@gjsify/cli 0.59.0 → 0.59.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.gjs.mjs CHANGED
@@ -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:`,...t,`
9
9
  `+n)}profile(t){}profileEnd(t){}timeStamp(t){}},pe=new Console,log=(...t)=>pe.log(...t),info=(...t)=>pe.info(...t),me=__name$1((...t)=>pe.debug(...t),`debug`),warn=(...t)=>pe.warn(...t),error=(...t)=>pe.error(...t),dir=(t,n)=>pe.dir(t,n),dirxml=(...t)=>pe.dirxml(...t),table=(t,n)=>pe.table(t,n),clear=()=>pe.clear(),assert=(t,...n)=>pe.assert(t,...n),trace=(...t)=>pe.trace(...t),time=t=>pe.time(t),timeEnd=t=>pe.timeEnd(t),timeLog=(t,...n)=>pe.timeLog(t,...n),count=t=>pe.count(t),countReset=t=>pe.countReset(t),group=(...t)=>pe.group(...t),groupCollapsed=(...t)=>pe.groupCollapsed(...t),groupEnd=()=>pe.groupEnd(),profile=t=>{},profileEnd=t=>{},timeStamp=t=>{}}),ge,_e=__esmMin(()=>{he(),ge={log,info,debug:me,warn,error,dir,dirxml,table,time,timeEnd,timeLog,trace,assert,clear,count,countReset,group,groupCollapsed,groupEnd,profile,profileEnd,timeStamp}}),ve,ye=__esmMin(()=>{ve=__name$1(t=>{Promise.resolve().then(t)},`queueMicrotask`)});function isWindowsPath(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)}function lastPathSeparatorIndex(t){let n=t.lastIndexOf(`/`);return isWindowsPath(t)?Math.max(n,t.lastIndexOf(`\\`)):n}function splitPathComponents(t){return isWindowsPath(t)?t.split(/[\\/]/):t.split(`/`)}function pathToFileUrlHref(t,n){let S=n?.windows??isWindowsPath(t),C=S?t.replace(/\\/g,`/`):t;if(S&&C.startsWith(`//`)){let t=C.indexOf(`/`,2);return`file://${t===-1?C.slice(2):C.slice(2,t)}${encodePathForFileUrl(t===-1?``:C.slice(t))}`}return`${C.startsWith(`/`)?`file://`:`file:///`}${encodePathForFileUrl(C)}`}function encodePathForFileUrl(t){let n=``;for(let S of t)n+=be.test(S)?S:percentEncode$1(S);return n}function percentEncode$1(t){let n=``;for(let S of new TextEncoder().encode(t))n+=`%${S.toString(16).toUpperCase().padStart(2,`0`)}`;return n}var be,xe=__esmMin(()=>{be=/^[A-Za-z0-9!$&'()*+,\-./:;=@_]$/,__name$1(percentEncode$1,`percentEncode`)});function mapSysname(t){let n=t.trim();switch(n){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(n)?`cygwin`:/^(MINGW|MSYS|Windows)/i.test(n)?`win32`:void 0}}function mapMachine(t){let n=t.trim().toLowerCase();switch(n){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 n.startsWith(`arm`)?`arm`:void 0}}var Se=__esmMin(()=>{});function classOf(t){return Ce.call(t).slice(8,-1)}function throwDataCloneError(t){let n=globalThis.DOMException;if(typeof n==`function`)throw new n(t,`DataCloneError`);let S=Error(t);throw S.name=`DataCloneError`,S}function internalClone(t,n,S){if(t==null)return t;let C=typeof t;if(C===`boolean`||C===`number`||C===`string`||C===`bigint`)return t;C===`symbol`&&throwDataCloneError(`Symbol cannot be cloned`),C===`function`&&throwDataCloneError(`Function cannot be cloned`);let N=t;if(n.has(N))return n.get(N);let F=classOf(N);if(F===`Date`)return new Date(N.getTime());if(F===`RegExp`)return new RegExp(N.source,N.flags);if(F===`Boolean`||F===`Number`||F===`String`)return Object(N.valueOf());if(F===`BigInt`)return Object(BigInt.prototype.valueOf.call(N));if(N instanceof Error){let t=N,C=t.constructor?.name,F=new(C&&we[C]||we[t.name]||Error)(t.message);return F.name=t.name,`cause`in t&&Object.defineProperty(F,"cause",{value:internalClone(t.cause,n,S),writable:!0,enumerable:!1,configurable:!0}),F}if(F===`DOMException`){let t=globalThis.DOMException;if(typeof t==`function`){let n=N;return new t(n.message,n.name)}}if(F===`ArrayBuffer`){let t=N;if(S&&S.transferred.has(t)){let C=S.transferred.get(t);return n.set(N,C),C}(t.detached===!0||t.byteLength===0&&t.detached)&&throwDataCloneError(`ArrayBuffer is detached and cannot be cloned`);let C=t.slice(0);return n.set(N,C),C}if(F===`SharedArrayBuffer`||N&&typeof N==`object`&&N.constructor?.name===`SharedBuffer`)return N;if(F===`DataView`){let t=N,C=S?.viewSnapshots.get(N),F=internalClone(t.buffer,n,S),I=C?C.byteOffset:t.byteOffset,H=C?C.byteLength:t.byteLength,W=new DataView(F,I,H);return n.set(N,W),W}if(Te.has(F)){let t=N,C=S?.viewSnapshots.get(N),F=internalClone(t.buffer,n,S),I=t.constructor,H=new I(F,C?C.byteOffset:t.byteOffset,C?C.length:t.length);return n.set(N,H),H}if(F===`Map`){let t=new Map;n.set(N,t);for(let[C,F]of N)t.set(internalClone(C,n,S),internalClone(F,n,S));return t}if(F===`Set`){let t=new Set;n.set(N,t);for(let C of N)t.add(internalClone(C,n,S));return t}{let t=globalThis,n=t.Blob,S=t.File;if(typeof S==`function`&&N instanceof S){let t=N;return new S([N],t.name,{type:t.type,lastModified:t.lastModified})}if(typeof n==`function`&&N instanceof n)return new n([N],{type:N.type})}if(N instanceof WeakMap&&throwDataCloneError(`WeakMap cannot be cloned`),N instanceof WeakSet&&throwDataCloneError(`WeakSet cannot be cloned`),N instanceof WeakRef&&throwDataCloneError(`WeakRef cannot be cloned`),typeof globalThis.Promise==`function`&&N instanceof Promise&&throwDataCloneError(`Promise cannot be cloned`),F===`Array`){let t=N,C=[];n.set(N,C);for(let N=0;N<t.length;N++)N in t&&(C[N]=internalClone(t[N],n,S));return C}if(F===`Object`||typeof N==`object`){let t={};n.set(N,t);for(let C of Object.keys(N))t[C]=internalClone(N[C],n,S);return t}throwDataCloneError(`${F} cannot be cloned`)}function structuredClone$1(t,n){let S=n?.transfer;if(!S||S.length===0)return internalClone(t,new Map);let C=new Set;for(let t of S)if(classOf(t)===`ArrayBuffer`){let n=t;n.detached===!0&&throwDataCloneError(`ArrayBuffer in transfer list is detached`),C.add(n)}let N=new Map;C.size>0&&snapshotViewsBackedByTransferredBuffers(t,C,N,new Set);let F=new Map;for(let t of C){let n=t;typeof n.transfer!=`function`&&throwDataCloneError(`ArrayBuffer.prototype.transfer() not available — runtime is not SM140+`),F.set(t,n.transfer())}return internalClone(t,new Map,{transferred:F,viewSnapshots:N})}function snapshotViewsBackedByTransferredBuffers(t,n,S,C){if(typeof t!=`object`||!t)return;let N=t;if(C.has(N))return;C.add(N);let F=classOf(N);if(F===`DataView`){let t=N;n.has(t.buffer)&&S.set(N,{byteOffset:t.byteOffset,length:0,byteLength:t.byteLength});return}if(Te.has(F)){let t=N;n.has(t.buffer)&&S.set(N,{byteOffset:t.byteOffset,length:t.length,byteLength:t.byteLength});return}if(Array.isArray(N)){for(let t=0;t<N.length;t++)t in N&&snapshotViewsBackedByTransferredBuffers(N[t],n,S,C);return}if(F===`Map`){for(let[t,F]of N)snapshotViewsBackedByTransferredBuffers(t,n,S,C),snapshotViewsBackedByTransferredBuffers(F,n,S,C);return}if(F===`Set`){for(let t of N)snapshotViewsBackedByTransferredBuffers(t,n,S,C);return}if(F===`Object`)for(let t of Object.keys(N))snapshotViewsBackedByTransferredBuffers(N[t],n,S,C)}var Ce,we,Te,Ee=__esmMin(()=>{({toString:Ce}=Object.prototype),we={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Te=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(t,n){try{let[S,C]=t.file_get_contents(n);return!S||!C?null:new TextDecoder().decode(C)}catch{return null}}function shellOut(t,n){try{let[S,C]=t.spawn_command_line_sync(n);if(!S||!C)return null;let N=new TextDecoder().decode(C).trim();return N.length>0?N:null}catch{return null}}function hasProcfs(){let t=hostGlib();if(!t)return!1;try{return t.file_test(`/proc/self/status`,16)}catch{return!1}}function hostPid(){if(De!==null)return De>0?De:void 0;let t=hostGlib();if(!t)return;let n=0,S=hasProcfs()?readText(t,`/proc/self/stat`):null;if(S)n=parseInt(S,10);else{let S=shellOut(t,`sh -c 'echo $PPID'`);S&&(n=parseInt(S,10))}return De=Number.isInteger(n)&&n>0?n:0,De>0?De:void 0}function hostPpid(){let t=hostGlib();if(!t)return;let n=hasProcfs()?readText(t,`/proc/self/status`):null;if(n){let t=/PPid:\s+(\d+)/.exec(n);if(t){let n=parseInt(t[1],10);return Number.isInteger(n)?n:void 0}}let S=hostPid();if(S===void 0)return;let C=shellOut(t,`ps -o ppid= -p ${S}`);if(!C)return;let N=parseInt(C,10);return Number.isInteger(N)?N:void 0}function hostExecPath(){let t=hostGlib();if(t){if(hasProcfs())try{let n=t.file_read_link(`/proc/self/exe`);if(n)return n}catch{}try{let n=t.get_prgname();if(n){let S=t.find_program_in_path(n);if(S)return S}}catch{return}}}function readProcessMemory$4(){let t=hostGlib();if(!t)return null;let n=hasProcfs()?readText(t,`/proc/self/status`):null;if(n){let t=new Map;for(let S of n.split(`
10
- `)){let n=/^(\w+):\s+(\d+)(\s+kB)?/.exec(S);n&&t.set(n[1],parseInt(n[2],10)*(n[3]?1024:1))}if(t.size>0)return{virtual:t.get(`VmSize`)??0,resident:t.get(`VmRSS`)??0,data:t.get(`VmData`)??0,peak:t.get(`VmPeak`)??0}}let S=shellOut(t,`sh -c 'ps -o rss=,vsz= -p $PPID'`);if(!S)return null;let C=/^(\d+)\s+(\d+)$/.exec(S);return C?{virtual:parseInt(C[2],10)*1024,resident:parseInt(C[1],10)*1024,data:0,peak:0}:null}var De,Oe=__esmMin(()=>{De=null,__name$1(readProcessMemory$4,`readProcessMemory`)});function glib(){let t=globalThis;if(typeof t.process?.versions?.gjs==`string`||t.process===void 0)return t.imports?.gi?.GLib}function arm(t){je||(je=!0,t.runAsync().catch(()=>{}))}function ensureMainLoop(){let t=glib();if(t)return Ae?ke:(ke=new t.MainLoop(null,!1),Ae=!0,t.main_depth()===0&&arm(ke),ke)}function holdMainLoop(){let t=ensureMainLoop();return t&&arm(t),t}function quitMainLoop(){ke&&=(ke.quit(),Ae=!1,je=!1,null)}var ke,Ae,je,Me=__esmMin(()=>{ke=null,Ae=!1,je=!1});function hostGi(){return globalThis.imports?.gi}function directoryOf(t){return/^(.*)[\\/][^\\/]*$/.exec(t)?.[1]}function colocateNativeLibrary(t,n=hostGi()){try{let S=n?.GIRepository?.Repository?.dup_default?.(),C=S?.get_typelib_path(t),N=C?directoryOf(C):void 0;return!S||!N?!1:(S.prepend_library_path(N),!0)}catch{return!1}}function probeNativeLibrary(t,n=hostGi()){try{let S=n?.GIRepository?.Repository?.dup_default?.(),C=S?.get_typelib_path(t);if(!n||!S||!C)return null;let N=firstSymbol(S,t);if(!N||(n.GModule?.module_error(),N.info.get_typelib().symbol(N.name)[0]))return null;let F=directoryOf(C)??`.`,I=C.includes(`\\`)&&!C.includes(`/`)?`\\`:`/`;for(let H of S.get_shared_libraries(t)??[]){let S=`${F}${I}${H}`,W=n.GLib?.file_test(S,n.GLib.FileTest.EXISTS)?S:H,q=loaderError(n,t,C,W,N.name);if(q!==void 0)return{namespace:t,library:W,reason:q,missingDependency:missingLibraryDependency(q,W)}}let H=(S.get_shared_libraries(t)??[]).join(`, `)||`(none named)`;return{namespace:t,library:H,reason:`symbol ${N.name} not found in ${H}, and the loader reported no error`}}catch{return null}}function firstSymbol(t,n){let S=t.get_n_infos(n),C=null;for(let N=0;N<S;N++){let S=t.get_info(n,N),F=S.get_type_init_function_name?.();if(F)return{info:S,name:F};let I=S.get_symbol?.();I&&!C&&(C={info:S,name:I})}return C}function loaderError(t,n,S,C,N){let{GIRepository:F,GLib:I,GModule:H}=t;if(!F?.Repository||!F.Typelib||!I||!H)return;let[,W]=I.file_get_contents(S),q=new TextEncoder().encode(`${C}\0`),Y=new Uint8Array(W.length+q.length);Y.set(W),Y.set(q,W.length);let X=new DataView(Y.buffer);X.setUint32(40,Y.length,!0),X.setUint32(52,W.length,!0);let Z=new F.Repository,te=firstSymbol(Z,Z.load_typelib(F.Typelib.new_from_bytes(new I.Bytes(Y)),0));if(te&&(H.module_error(),!te.info.get_typelib().symbol(N)[0]))return H.module_error()??`${n}: ${C} could not be opened (the loader reported no error)`}function missingLibraryDependency(t,n){let S=/Library not loaded: (\S+)/.exec(t)?.[1]??/Error loading shared library ([^\s:]+): .*\(needed by /.exec(t)?.[1]??/(?:^|\s)([^\s:]+): cannot open shared object file/.exec(t)?.[1];if(!S)return;let C=S.replace(/^.*[\\/]/,``);if(!(n&&C===n.replace(/^.*[\\/]/,``)))return C}function openNativeLibrary(t,n=hostGi()){colocateNativeLibrary(t,n);let S=probeNativeLibrary(t,n);return S?new NativeLibraryLoadError(S):null}function loadOptionalNativeModule(t,n,S=hostGi()){if(!S)return{module:null,error:Error(`${t}: imports.gi is not available (not running on GJS)`)};try{let C=S[t];if(!C)return{module:null,error:Error(`${t}: typelib not found`)};let N=openNativeLibrary(t,S);if(N)return ge.debug(N.message),{module:null,error:N};for(let t of n)C[t];return{module:C,error:null}}catch(t){return{module:null,error:t instanceof Error?t:Error(String(t))}}}var NativeLibraryLoadError,Fe=__esmMin(()=>{_e(),NativeLibraryLoadError=class extends Error{failure;constructor(t,n){let S=t.missingDependency?`It needs ${t.missingDependency}, which the loader could not find: not installed, or not on its search path.`:`The loader could not open it.`;super(`${t.namespace}: the native library ${t.library} could not be loaded. ${S}\nLoader: ${t.reason.trim()}\n`+(n??"`gjsify system-check` lists the system libraries the installed @gjsify packages need, with the install command for this host.")),this.name=`NativeLibraryLoadError`,this.failure=t}}});function drainOnce(t){let n=Math.min(64,Ie.length);for(let S=0;S<n;S++){let n=Ie.shift();try{n()}catch(n){try{t.log_default_handler(`gjsify-nextTick`,t.LogLevelFlags.LEVEL_WARNING,String(n?.stack||n),null)}catch{}}}Ie.length>0?t.timeout_add(t.PRIORITY_DEFAULT,1,()=>(drainOnce(t),!1)):Le=!1}function tryGLibTimeout(t){let n=globalThis.imports?.gi?.GLib;return n?.timeout_add?(Ie.push(t),Le||(Le=!0,n.timeout_add(n.PRIORITY_DEFAULT,0,()=>(drainOnce(n),!1))),!0):!1}var Ie,Le,nextTick,Re=__esmMin(()=>{Ie=[],Le=!1,nextTick=(t,...n)=>{let S=n.length>0?()=>t(...n):t;if(!tryGLibTimeout(S)){if(typeof globalThis.process?.nextTick==`function`){globalThis.process.nextTick(t,...n);return}if(typeof queueMicrotask==`function`){queueMicrotask(S);return}Promise.resolve().then(S)}}}),ze=__esmMin(()=>{ie(),oe(),se(),ce(),ue(),ye(),xe(),Se(),Ee(),Oe(),Me(),Fe(),Re()});re(),ze(),registerGlobal(`Blob`,te),registerGlobal(`File`,ne);function atobPolyfill(t){if(typeof globalThis.atob==`function`)return globalThis.atob(t);let n=t.replace(/[=\s]/g,``),S=``,C=0,N=0;for(let t=0;t<n.length;t++)C=C<<6|Ve[n.charCodeAt(t)],N+=6,N>=8&&(N-=8,S+=String.fromCharCode(C>>N&255));return S}function btoaPolyfill(t){if(typeof globalThis.btoa==`function`)return globalThis.btoa(t);let n=``,S=0;for(;S+2<t.length;S+=3){let C=t.charCodeAt(S)<<16|t.charCodeAt(S+1)<<8|t.charCodeAt(S+2);n+=Be[C>>18&63]+Be[C>>12&63]+Be[C>>6&63]+Be[C&63]}if(S+1===t.length){let C=t.charCodeAt(S)<<16;n+=Be[C>>18&63]+Be[C>>12&63]+`==`}else if(S+2===t.length){let C=t.charCodeAt(S)<<16|t.charCodeAt(S+1)<<8;n+=Be[C>>18&63]+Be[C>>12&63]+Be[C>>6&63]+`=`}return n}function base64Decode$2(t){let n=t.replace(/[=\s]/g,``),S=new Uint8Array(n.length*3>>2),C=0,N=0,F=0;for(let t=0;t<n.length;t++)C=C<<6|Ve[n.charCodeAt(t)],N+=6,N>=8&&(N-=8,S[F++]=C>>N&255);return S.subarray(0,F)}function base64Encode$1(t){let n=``,S=t.length;for(let C=0;C<S;C+=3){let N=t[C],F=C+1<S?t[C+1]:0,I=C+2<S?t[C+2]:0;n+=Be[N>>2],n+=Be[(N&3)<<4|F>>4],n+=C+1<S?Be[(F&15)<<2|I>>6]:`=`,n+=C+2<S?Be[I&63]:`=`}return n}var Be,Ve,He=__esmMin(()=>{Be=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ve=new Uint8Array(256);for(let t=0;t<64;t++)Ve[Be.charCodeAt(t)]=t;__name$1(base64Decode$2,`base64Decode`),__name$1(base64Encode$1,`base64Encode`)});function normalizeEncoding(t){if(!t||t===`utf8`||t===`utf-8`)return`utf8`;switch((``+t).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(t){let n=(``+t).toLowerCase().replace(/-/g,``);if(!Ue.includes(n))throw TypeError(`Unknown encoding: ${t}`)}var Ue,Ge=__esmMin(()=>{Ue=[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`]});function encodeString(t,n){switch(n){case`utf8`:return textEncoder().encode(t);case`ascii`:{let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&127;return n}case`latin1`:{let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&255;return n}case`base64`:return base64Decode$2(t.replace(/-/g,`+`).replace(/_/g,`/`));case`base64url`:return encodeString(t.replace(/-/g,`+`).replace(/_/g,`/`),`base64`);case`hex`:{let n=t.length>>>1,S=new Uint8Array(n);for(let C=0;C<n;C++){let n=parseInt(t[C*2],16),N=parseInt(t[C*2+1],16);if(Number.isNaN(n)||Number.isNaN(N))break;S[C]=n<<4|N}return S}case`utf16le`:{let n=new Uint8Array(t.length*2);for(let S=0;S<t.length;S++){let C=t.charCodeAt(S);n[S*2]=C&255,n[S*2+1]=C>>8&255}return n}default:return textEncoder().encode(t)}}function decodeString(t,n,S,C){let N=S!==void 0||C!==void 0?t.subarray(S??0,C??t.length):t;switch(n){case`utf8`:return textDecoder().decode(N);case`ascii`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]&127);return t}case`latin1`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]);return t}case`base64`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]);return btoaPolyfill(t)}case`base64url`:return decodeString(N,`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);case`hex`:{let t=``;for(let n=0;n<N.length;n++)t+=N[n].toString(16).padStart(2,`0`);return t}case`utf16le`:{let t=``;for(let n=0;n+1<N.length;n+=2)t+=String.fromCharCode(N[n]|N[n+1]<<8);return t}default:return textDecoder().decode(N)}}function checkOffset(t,n,S){if(t+n>S)throw RangeError(`Attempt to access memory outside buffer bounds`)}var Ke,qe,textEncoder,textDecoder,Je=__esmMin(()=>{He(),textEncoder=()=>Ke??=new TextEncoder,textDecoder=()=>qe??=new TextDecoder}),Ye,Xe,Ze,Qe,$e,SlowBuffer,et=__esmMin(()=>{Je(),Ge(),Ye=typeof SharedArrayBuffer<`u`,Xe=class Buffer extends Uint8Array{static _isBuffer=!0;static alloc(t,n,S){if(typeof t!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof t}`);if(t<0)throw RangeError(`The value "${t}" is invalid for option "size"`);let C=new Buffer(t);return n!==void 0&&n!==0&&C.fill(n,0,t,S),C}static allocUnsafe(t){if(typeof t!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof t}`);return new Buffer(t)}static allocUnsafeSlow(t){return Buffer.allocUnsafe(t)}static from(t,n,S){if(typeof t==`string`){let S=normalizeEncoding(n);if(n&&typeof n==`string`){let t=(``+n).toLowerCase().replace(/-/g,``);[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`,``].includes(t)||checkEncoding(n)}let C=encodeString(t,S);return new Buffer(C.buffer,C.byteOffset,C.byteLength)}if(ArrayBuffer.isView(t)){let n=new Buffer(t.buffer,t.byteOffset,t.byteLength),S=new Buffer(n.length);return S.set(n),S}if(t instanceof ArrayBuffer){let C=n||0,N=S===void 0?t.byteLength-C:S;return new Buffer(t,C,N)}if(Ye&&t instanceof SharedArrayBuffer){let C=n||0,N=S===void 0?t.byteLength-C:S;return new Buffer(new Uint8Array(t,C,N))}if(typeof t==`object`&&t&&typeof t.viewBytes==`function`&&typeof t.byteLength==`number`&&t.constructor?.name===`SharedBuffer`){let C=t,N=n||0,F=S===void 0?C.byteLength-N:S,I=C.viewBytes(N,F);return new Buffer(I.buffer,I.byteOffset,I.byteLength)}if(Array.isArray(t)){let n=new Buffer(t.length);for(let S=0;S<t.length;S++)n[S]=t[S]&255;return n}throw TypeError(`The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array`)}static isBuffer(t){return t instanceof Buffer}static isEncoding(t){if(typeof t!=`string`)return!1;let n=t.toLowerCase().replace(/-/g,``);return[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`].includes(n)}static byteLength(t,n){if(typeof t!=`string`){if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer||Ye&&t instanceof SharedArrayBuffer)return t.byteLength;throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer`)}switch(normalizeEncoding(n)){case`utf8`:return new TextEncoder().encode(t).byteLength;case`ascii`:case`latin1`:return t.length;case`base64`:case`base64url`:{let n=t.length;for(;n>0&&(t[n-1]===`=`||t[n-1]===` `);)n--;return n*3>>>2}case`hex`:return t.length>>>1;case`utf16le`:return t.length*2;default:return new TextEncoder().encode(t).byteLength}}static compare(t,n){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array))throw TypeError(`Arguments must be Buffers or Uint8Arrays`);let S=Math.min(t.length,n.length);for(let C=0;C<S;C++){if(t[C]<n[C])return-1;if(t[C]>n[C])return 1}return t.length<n.length?-1:+(t.length>n.length)}static concat(t,n){if(t.length===0)return Buffer.alloc(0);if(n===void 0){n=0;for(let S=0;S<t.length;S++)n+=t[S].length}let S=Buffer.alloc(n),C=0;for(let N=0;N<t.length;N++){let F=t[N],I=Math.min(F.length,n-C);I<=0||(S.set(F.subarray(0,I),C),C+=I)}return S}static poolSize=65536;toString(t,n,S){let C=normalizeEncoding(t);return decodeString(this,C,n,S)}toJSON(){return{type:`Buffer`,data:Array.from(this)}}equals(t){if(!(t instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);if(this.length!==t.length)return!1;for(let n=0;n<this.length;n++)if(this[n]!==t[n])return!1;return!0}compare(t,n,S,C,N){if(!(t instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);let F=C!==void 0||N!==void 0?this.subarray(C??0,N??this.length):this,I=n!==void 0||S!==void 0?t.subarray(n??0,S??t.length):t;return Buffer.compare(F,I)}copy(t,n=0,S=0,C){let N=C??this.length,F=Math.min(N-S,t.length-n);return F<=0?0:(t.set(this.subarray(S,S+F),n),F)}slice(t,n){let S=t??0,C=n??this.length,N=super.subarray(S,C);return new Buffer(N.buffer,N.byteOffset,N.byteLength)}subarray(t,n){let S=super.subarray(t,n);return new Buffer(S.buffer,S.byteOffset,S.byteLength)}write(t,n,S,C){n??=0;let N=encodeString(t,normalizeEncoding(C||(typeof S==`string`?S:void 0))),F=S!==void 0&&typeof S==`number`?Math.min(S,this.length-n):this.length-n,I=Math.min(N.length,F);return this.set(N.subarray(0,I),n),I}fill(t,n,S,C){let N=n??0,F=S??this.length;if(typeof t==`number`)super.fill(t&255,N,F);else if(typeof t==`string`){let n=encodeString(t,normalizeEncoding(C));if(n.length===0)super.fill(0,N,F);else if(n.length===1)super.fill(n[0],N,F);else for(let t=N;t<F;t++)this[t]=n[(t-N)%n.length]}else if(t instanceof Uint8Array)if(t.length===0)super.fill(0,N,F);else for(let n=N;n<F;n++)this[n]=t[(n-N)%t.length];return this}indexOf(t,n,S){if(typeof t==`number`)return super.indexOf(t&255,n);let C=typeof t==`string`?encodeString(t,normalizeEncoding(S)):t,N=n??0;outer:for(let t=N;t<=this.length-C.length;t++){for(let n=0;n<C.length;n++)if(this[t+n]!==C[n])continue outer;return t}return-1}lastIndexOf(t,n,S){if(typeof t==`number`)return n===void 0?super.lastIndexOf(t&255):super.lastIndexOf(t&255,n);let C=typeof t==`string`?encodeString(t,normalizeEncoding(S)):t,N=n===void 0?this.length-C.length:Math.min(n,this.length-C.length);outer:for(let t=N;t>=0;t--){for(let n=0;n<C.length;n++)if(this[t+n]!==C[n])continue outer;return t}return-1}includes(t,n,S){return this.indexOf(t,n,S)!==-1}readUInt8(t=0){return checkOffset(t,1,this.length),this[t]}readUInt16BE(t=0){return checkOffset(t,2,this.length),this[t]<<8|this[t+1]}readUInt16LE(t=0){return checkOffset(t,2,this.length),this[t]|this[t+1]<<8}readUInt32BE(t=0){return checkOffset(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])}readUInt32LE(t=0){return checkOffset(t,4,this.length),this[t+3]*16777216+(this[t+2]<<16|this[t+1]<<8|this[t])>>>0}readInt8(t=0){return checkOffset(t,1,this.length),this[t]|(this[t]&128?4294967040:0)}readInt16BE(t=0){checkOffset(t,2,this.length);let n=this[t]<<8|this[t+1];return n&32768?n|4294901760:n}readInt16LE(t=0){checkOffset(t,2,this.length);let n=this[t]|this[t+1]<<8;return n&32768?n|4294901760:n}readInt32BE(t=0){return checkOffset(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]}readInt32LE(t=0){return checkOffset(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24}readFloatBE(t=0){return checkOffset(t,4,this.length),new DataView(this.buffer,this.byteOffset+t,4).getFloat32(0,!1)}readFloatLE(t=0){return checkOffset(t,4,this.length),new DataView(this.buffer,this.byteOffset+t,4).getFloat32(0,!0)}readDoubleBE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getFloat64(0,!1)}readDoubleLE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getFloat64(0,!0)}readBigInt64BE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigInt64(0,!1)}readBigInt64LE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigInt64(0,!0)}readBigUInt64BE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigUint64(0,!1)}readBigUInt64LE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigUint64(0,!0)}readUIntBE(t,n){checkOffset(t,n,this.length);let S=0;for(let C=0;C<n;C++)S=S*256+this[t+C];return S}readUIntLE(t,n){checkOffset(t,n,this.length);let S=0,C=1;for(let N=0;N<n;N++)S+=this[t+N]*C,C*=256;return S}readIntBE(t,n){checkOffset(t,n,this.length);let S=0;for(let C=0;C<n;C++)S=S*256+this[t+C];return S>=2**(8*n-1)&&(S-=2**(8*n)),S}readIntLE(t,n){checkOffset(t,n,this.length);let S=0,C=1;for(let N=0;N<n;N++)S+=this[t+N]*C,C*=256;return S>=2**(8*n-1)&&(S-=2**(8*n)),S}writeUInt8(t,n=0){return checkOffset(n,1,this.length),this[n]=t&255,n+1}writeUInt16BE(t,n=0){return checkOffset(n,2,this.length),this[n]=t>>>8&255,this[n+1]=t&255,n+2}writeUInt16LE(t,n=0){return checkOffset(n,2,this.length),this[n]=t&255,this[n+1]=t>>>8&255,n+2}writeUInt32BE(t,n=0){return checkOffset(n,4,this.length),this[n]=t>>>24&255,this[n+1]=t>>>16&255,this[n+2]=t>>>8&255,this[n+3]=t&255,n+4}writeUInt32LE(t,n=0){return checkOffset(n,4,this.length),this[n]=t&255,this[n+1]=t>>>8&255,this[n+2]=t>>>16&255,this[n+3]=t>>>24&255,n+4}writeInt8(t,n=0){return checkOffset(n,1,this.length),t<0&&(t=255+t+1),this[n]=t&255,n+1}writeInt16BE(t,n=0){return checkOffset(n,2,this.length),this[n]=t>>>8&255,this[n+1]=t&255,n+2}writeInt16LE(t,n=0){return checkOffset(n,2,this.length),this[n]=t&255,this[n+1]=t>>>8&255,n+2}writeInt32BE(t,n=0){return checkOffset(n,4,this.length),this[n]=t>>>24&255,this[n+1]=t>>>16&255,this[n+2]=t>>>8&255,this[n+3]=t&255,n+4}writeInt32LE(t,n=0){return checkOffset(n,4,this.length),this[n]=t&255,this[n+1]=t>>>8&255,this[n+2]=t>>>16&255,this[n+3]=t>>>24&255,n+4}writeFloatBE(t,n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).setFloat32(0,t,!1),n+4}writeFloatLE(t,n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).setFloat32(0,t,!0),n+4}writeDoubleBE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setFloat64(0,t,!1),n+8}writeDoubleLE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setFloat64(0,t,!0),n+8}writeBigInt64BE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigInt64(0,t,!1),n+8}writeBigInt64LE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigInt64(0,t,!0),n+8}writeBigUInt64BE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigUint64(0,t,!1),n+8}writeBigUInt64LE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigUint64(0,t,!0),n+8}swap16(){let t=this.length;if(t%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let n=0;n<t;n+=2){let t=this[n];this[n]=this[n+1],this[n+1]=t}return this}swap32(){let t=this.length;if(t%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let n=0;n<t;n+=4){let t=this[n],S=this[n+1];this[n]=this[n+3],this[n+1]=this[n+2],this[n+2]=S,this[n+3]=t}return this}swap64(){let t=this.length;if(t%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let n=0;n<t;n+=8){let t=this[n],S=this[n+1],C=this[n+2],N=this[n+3];this[n]=this[n+7],this[n+1]=this[n+6],this[n+2]=this[n+5],this[n+3]=this[n+4],this[n+4]=N,this[n+5]=C,this[n+6]=S,this[n+7]=t}return this}},Ze=2**31-1,Qe=2**28-16,$e={MAX_LENGTH:Ze,MAX_STRING_LENGTH:Qe},SlowBuffer=class extends Xe{constructor(t){super(t)}}}),tt=__exportAll$5({Blob:()=>te,Buffer:()=>Xe,File:()=>ne,INSPECT_MAX_BYTES:()=>50,SlowBuffer:()=>SlowBuffer,atob:()=>nt,atobPolyfill:()=>atobPolyfill,base64Decode:()=>base64Decode$2,base64Encode:()=>base64Encode$1,btoa:()=>rt,btoaPolyfill:()=>btoaPolyfill,checkEncoding:()=>checkEncoding,constants:()=>$e,default:()=>it,kMaxLength:()=>Ze,kStringMaxLength:()=>Qe,normalizeEncoding:()=>normalizeEncoding}),nt,rt,it,ot=__esmMin(()=>{He(),re(),Ge(),et(),nt=globalThis.atob,rt=globalThis.btoa,it={Buffer:Xe,SlowBuffer,Blob:te,File:ne,atob:nt,btoa:rt,kMaxLength:Ze,kStringMaxLength:Qe,constants:$e,INSPECT_MAX_BYTES:50}});ot(),`Buffer`in globalThis||Object.defineProperty(globalThis,"Buffer",{value:Xe,enumerable:!1,writable:!0,configurable:!0});var st,ct=__esmMin(()=>{st=t}),lt,ut=__esmMin(()=>{ct(),lt=st});ut(),typeof globalThis.btoa!=`function`&&Object.defineProperty(globalThis,"btoa",{value:function btoa(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&255;return lt.base64_encode(n)},enumerable:!0,writable:!0,configurable:!0}),typeof globalThis.atob!=`function`&&Object.defineProperty(globalThis,"atob",{value:function atob(t){let n=lt.base64_decode(t),S=``;for(let t=0;t<n.length;t++)S+=String.fromCharCode(n[t]);return S},enumerable:!0,writable:!0,configurable:!0}),ze(),typeof queueMicrotask!=`function`&&Object.defineProperty(globalThis,"queueMicrotask",{value:ve,enumerable:!0,writable:!0,configurable:!0});function getGjsGlobal(){return globalThis}function getGioNamespace(){let t=getGjsGlobal().imports?.gi;if(!t)return null;let n=null;try{n=t.GioUnix??null}catch{}if(!n)try{n=t.Gio??null}catch{}return n}var dt=__esmMin(()=>{});function getMonotonicTime(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t?.get_monotonic_time)return BigInt(t.get_monotonic_time())*1000n}catch{}return typeof performance?.now==`function`?BigInt(Math.round(performance.now()*1e6)):BigInt(Date.now())*1000000n}function hrtime(t){let n=getMonotonicTime()-ft,S=Number(n/1000000000n),C=Number(n%1000000000n);if(t){let n=S-t[0],N=C-t[1];return N<0&&(n--,N+=1e9),[n,N]}return[S,C]}function hrtimeBigint(){return getMonotonicTime()-ft}var ft,pt=__esmMin(()=>{dt(),ft=getMonotonicTime()});function probeUname(){if(mt!==void 0)return mt;mt=null;try{let t=getGjsGlobal().imports?.gi?.GLib;if(!t)return mt;let n=t.spawn_sync,S=t.SpawnFlags?.SEARCH_PATH;if(!n||S===void 0)return mt;let[C,N]=n(null,[`uname`,`-sm`],null,S,null);if(!C||!N)return mt;let F=new TextDecoder().decode(N).trim().split(/\s+/);if(F.length<2)return mt;let I=mapSysname(F[0]),H=mapMachine(F[F.length-1]);if(!I||!H)return mt;mt={platform:I,arch:H}}catch{}return mt}var mt,ht=__esmMin(()=>{dt(),ze()});function detectGjsVersion(){try{let t=getGjsGlobal().imports?.system;if(t?.version!==void 0){let n=Number(t.version);return`${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%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 t=detectGjsVersion(),n={node:`20.0.0`};return t&&(n.gjs=t),{version:`v20.0.0`,versions:n,title:`gjs`}}function detectPpid(){let t=runtimeProcess();return t&&typeof t.ppid==`number`?t.ppid:hostPpid()??0}function runtimeProcess(){let t=globalThis.process;return typeof t?.release?.name==`string`?t:void 0}function onGjs(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function detectPlatform$1(){let t=runtimeProcess();if(t)return t.platform;if(onGjs()){let t=probeUname();if(t)return t.platform}return`linux`}function detectArch(){let t=runtimeProcess();if(t)return t.arch;if(onGjs()){let t=probeUname();if(t)return t.arch}return`x64`}function getPid$1(){let t=runtimeProcess();return t&&typeof t.pid==`number`?t.pid:hostPid()??0}var gt=__esmMin(()=>{dt(),ht(),ze(),__name$1(detectPlatform$1,`detectPlatform`),__name$1(getPid$1,`getPid`)});function getEnvProxy(){if(typeof globalThis.process?.env==`object`)return globalThis.process.env;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t)return new Proxy({},{get(n,S){if(typeof S==`string`)return t.getenv(S)??void 0},set(n,S,C){return typeof S==`string`?(t.setenv(S,String(C),!0),!0):!1},deleteProperty(n,S){return typeof S==`string`?(t.unsetenv(S),!0):!1},has(n,S){return typeof S==`string`?t.getenv(S)!==null:!1},ownKeys(n){return t.listenv()},getOwnPropertyDescriptor(n,S){if(typeof S!=`string`)return;let C=t.getenv(S);if(C!==null)return{configurable:!0,enumerable:!0,writable:!0,value:C}}})}catch{}return{}}function getArgv(){if(globalThis.process?.argv!==void 0)return globalThis.process.argv;try{let t=getGjsGlobal().imports?.system;if(t?.programArgs)return[`gjs`,t.programInvocationName||``,...t.programArgs]}catch{}return[`gjs`]}function getExecPath(){let t=globalThis.process;return!isGjsHost()&&typeof t?.execPath==`string`?t.execPath:hostExecPath()??`/usr/bin/gjs`}function isGjsHost(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function getCwd(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t?.get_current_dir)return t.get_current_dir()}catch{}return`/`}function chdir(t){let n=getGjsGlobal().imports?.gi?.GLib;try{if(n?.chdir){if(!n.file_test(t,16)){let n=Error(`ENOENT: no such file or directory, chdir '${t}'`);throw n.code=`ENOENT`,n.syscall=`chdir`,n.path=t,n}n.chdir(t);return}}catch(t){if(t&&typeof t==`object`&&t.code===`ENOENT`)throw t}if(!n){let n=globalThis.process;if(n&&typeof n.chdir==`function`){n.chdir(t);return}}throw Error(`process.chdir() is not supported in this environment`)}var _t=__esmMin(()=>{dt(),ze()});function exitProcess(t){let n=getGjsGlobal().imports,S=n?.gi?.GLib,C=n?.system,N=S?.idle_add,F=S?.SOURCE_REMOVE,I=S?.PRIORITY_DEFAULT,H=S?.MainContext;if(C?.exit&&N&&typeof I==`number`&&typeof F==`boolean`&&typeof H?.default==`function`){N(I,()=>(C.exit(t),F));let n=H.default();for(;;)n.iteration(!0)}try{C?.exit&&C.exit(t)}catch{}let W=globalThis.process;throw W&&typeof W.exit==`function`&&W.exit(t),Error(`process.exit(${t})`)}var vt=__esmMin(()=>{dt()});function isGjs$1(){return getGjsGlobal().imports?.gi?.GLib!==void 0}function classifyKillFailure(t){if(/No such process/i.test(t))return`ESRCH`;if(/Operation not permitted/i.test(t))return`EPERM`}function killPid(t,n){let S=getGjsGlobal().imports?.gi?.GLib;if(S){let C=typeof n==`number`?String(n):n||`SIGTERM`,N=[`kill`,C.startsWith(`SIG`)?`-${C.slice(3)}`:`-${C}`,`--`,String(t)],F=S.environ_setenv(S.get_environ(),`LC_ALL`,`C`,!0),[,,I,H]=S.spawn_sync(null,N,F,4,null),W=!1;try{W=S.spawn_check_wait_status(H)}catch{W=!1}if(W)return!0;let q=I?new TextDecoder().decode(I).trim():``,Y=classifyKillFailure(q),X=Error(Y?`kill ${Y}`:`kill failed${q?`: ${q}`:``}`);throw Y&&(X.code=Y,X.errno=Y===`ESRCH`?-3:-1,X.syscall=`kill`),X}let C=globalThis.process;if(C&&typeof C.kill==`function`)return C.kill(t,n);throw Error(`process.kill() is not supported in this environment`)}function memoryUsage(){let t=readProcessMemory$4();if(t)return{rss:t.resident,heapTotal:t.resident,heapUsed:t.resident,external:0,arrayBuffers:0};if(!isGjs$1()){let t=globalThis.process;if(t&&typeof t.memoryUsage==`function`)return t.memoryUsage()}return{rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}}function cpuUsage(t){if(!isGjs$1()){let n=globalThis.process;if(n&&typeof n.cpuUsage==`function`)return n.cpuUsage(t)}return{user:0,system:0}}function readUmask(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let[n,S]=t.file_get_contents(`/proc/self/status`);if(n){let t=/^Umask:\s*([0-7]+)/m.exec(new TextDecoder().decode(S));if(t)return parseInt(t[1],8)}}}catch{}return 18}var yt=__esmMin(()=>{dt(),ze(),__name$1(isGjs$1,`isGjs`)});function resolveSignalAdd(){let t=getGjsGlobal().imports?.gi;if(!t)return null;for(let[n,S]of[[`GLibUnix`,`signal_add`],[`GLib`,`unix_signal_add`]])try{let C=t[n]?.[S];if(typeof C==`function`)return C}catch{}return null}function isDeliverableSignal(t){return typeof t==`string`&&t in bt}function armSignal(t,n){if(xt.has(t))return;let S=bt[t],C=resolveSignalAdd(),N=getGjsGlobal().imports?.gi?.GLib;if(S===void 0||C===null||!N)return;let F=N.PRIORITY_DEFAULT,I=C(F,S,()=>(n(t),!0));xt.set(t,I)}function disarmSignal(t){let n=xt.get(t);if(n===void 0)return;xt.delete(t);let S=getGjsGlobal().imports?.gi?.GLib;S&&typeof S.source_remove==`function`&&S.source_remove(n)}var bt,xt,St=__esmMin(()=>{dt(),bt={SIGHUP:1,SIGINT:2,SIGTERM:15},xt=new Map});function claimRawMode(t,n){Tt.set(t,n)}function releaseRawMode(t){Tt.delete(t)}function noteRawMode(t,n,S){let C=S(n);return n?C&&claimRawMode(t,()=>{S(!1)}):releaseRawMode(t),C}function restoreClaimedRawModes(){let t=[...Tt.entries()];Tt.clear();let n=0,S;for(let[,C]of t)try{C(),n+=1}catch(t){S??=t}if(S!==void 0)throw S;return n}var Ct,wt,Tt,Et=__esmMin(()=>{Ct=Symbol.for(`@gjsify/terminal-native:raw-mode-claims`),wt=globalThis,Tt=wt[Ct]??=new Map});function callableModule(){if(!Ot)return null;try{return Ot.Terminal.is_tty(2),Ot}catch{return null}}function nativeIsTty(t){try{return callableModule()?.Terminal.is_tty(t)??null}catch{return null}}function nativeTerminalSize(t){try{let[n,S,C]=callableModule()?.Terminal.get_size(t)??[!1,0,0];return!n||C<=0?null:{rows:S,columns:C}}catch{return null}}function nativeSetRawMode(t,n){try{return callableModule()?.Terminal.set_raw_mode(t,n)??null}catch{return null}}var Dt,Ot,kt,At=__esmMin(()=>{Et(),ze(),Dt=loadOptionalNativeModule(`GjsifyTerminal`,[`Terminal`,`ResizeWatcher`]),Ot=Dt.module,kt=Ot});function onceWrapper(){let{target:t,type:n,listener:S}=this;return this.wrapperFn&&t.removeListener(n,this.wrapperFn),S.apply(t,Array.from(arguments))}function _onceWrap(t,n,S){let C={target:t,type:n,listener:S,wrapperFn:void 0},N=onceWrapper.bind(C);return C.wrapperFn=N,N.listener=S,N}function arrayClone(t){switch(t.length){case 0:return[];case 1:return[t[0]];case 2:return[t[0],t[1]];case 3:return[t[0],t[1],t[2]];default:return t.slice()}}function checkListener(t){if(typeof t!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof t)}function validateNumber(t,n){if(typeof t!=`number`||t!==t)throw TypeError(`The "${n}" argument must be of type number. Received type ${typeof t}`)}function spliceOne(t,n){for(;n+1<t.length;n++)t[n]=t[n+1];t.pop()}function unwrapListeners(t){let n=Array.from({length:t.length});for(let S=0;S<n.length;++S)n[S]=t[S].listener??t[S];return n}function createAbortError$2(t){let n=Error(`The operation was aborted`);return n.name=`AbortError`,n.code=`ABORT_ERR`,t?.reason&&(n.cause=t.reason),n}var jt,Mt,Nt,Pt=__esmMin(()=>{_e(),jt=Symbol(`kCapture`),Mt=Symbol.for(`nodejs.rejection`),Nt=class EventEmitter{static defaultMaxListeners=10;static errorMonitor=Symbol(`events.errorMonitor`);static captureRejectionSymbol=Mt;static _captureRejections=!1;static get captureRejections(){return EventEmitter._captureRejections}static set captureRejections(t){if(typeof t!=`boolean`)throw TypeError(`The "captureRejections" argument must be of type boolean.`);EventEmitter._captureRejections=t}_events;_eventsCount;_maxListeners;[jt];constructor(t){this._events=Object.create(null),this._eventsCount=0,this._maxListeners=void 0,this[jt]=t?.captureRejections??EventEmitter._captureRejections}setMaxListeners(t){if(validateNumber(t,`n`),t<0)throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+t);return this._maxListeners=t,this}getMaxListeners(){return this._maxListeners??EventEmitter.defaultMaxListeners}emit(t,...n){let S=this._events,C=t===`error`;if(S!==void 0)C&&S[EventEmitter.errorMonitor]!==void 0&&this.emit(EventEmitter.errorMonitor,...n),C&&=S.error===void 0;else if(!C)return!1;if(C){let t;if(t=n.length>0?n[0]:Error(`Unhandled error.`),t instanceof Error)throw t;let S=Error(`Unhandled error. (`+t+`)`);throw S.context=t,S}let N=S[t];if(N===void 0)return!1;if(typeof N==`function`){let S=N.apply(this,n);S!=null&&this[jt]&&this._addCatch(S,t,n)}else{let S=arrayClone(N),C=S.length;for(let N=0;N<C;++N){let C=S[N].apply(this,n);C!=null&&this[jt]&&this._addCatch(C,t,n)}}return!0}_addCatch(t,n,S){typeof t?.then==`function`&&t.then(void 0,t=>{let C=this[Mt];if(typeof C==`function`)C.call(this,t,n,...S);else{let n=this[jt];try{this[jt]=!1,this.emit(`error`,t)}finally{this[jt]=n}}})}addListener(t,n){return this._addListener(t,n,!1)}on(t,n){return this._addListener(t,n,!1)}prependListener(t,n){return this._addListener(t,n,!0)}_addListener(t,n,S){checkListener(n);let C=this._events;C===void 0?(C=this._events=Object.create(null),this._eventsCount=0):C.newListener!==void 0&&(this.emit(`newListener`,t,n.listener??n),C=this._events);let N=C[t];N===void 0?(C[t]=n,++this._eventsCount):typeof N==`function`?C[t]=S?[n,N]:[N,n]:S?N.unshift(n):N.push(n);let F=this.getMaxListeners();if(F>0){let n=typeof C[t]==`function`?1:C[t].length;if(n>F&&!C[t].warned){typeof C[t]!=`function`&&(C[t].warned=!0);let S=Error(`Possible EventEmitter memory leak detected. ${n} ${String(t)} listeners added to [${this.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);S.name=`MaxListenersExceededWarning`,ge.warn(S.message)}}return this}once(t,n){return checkListener(n),this.on(t,_onceWrap(this,t,n)),this}prependOnceListener(t,n){return checkListener(n),this.prependListener(t,_onceWrap(this,t,n)),this}removeListener(t,n){checkListener(n);let S=this._events;if(S===void 0)return this;let C=S[t];if(C===void 0)return this;if(C===n||C.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete S[t],S.removeListener&&this.emit(`removeListener`,t,C.listener??n));else if(typeof C!=`function`){let N=-1;for(let t=C.length-1;t>=0;t--)if(C[t]===n||C[t].listener===n){N=t;break}if(N<0)return this;N===0?C.shift():spliceOne(C,N),C.length===1&&(S[t]=C[0]),S.removeListener!==void 0&&this.emit(`removeListener`,t,n.listener??n)}return this}off(t,n){return this.removeListener(t,n)}removeAllListeners(t){let n=this._events;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){let t=Object.keys(n);for(let n=0;n<t.length;++n){let S=t[n];S!==`removeListener`&&this.removeAllListeners(S)}return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}let S=n[t];if(typeof S==`function`)this.removeListener(t,S);else if(S!==void 0)for(let n=S.length-1;n>=0;n--)this.removeListener(t,S[n]);return this}listeners(t){let n=this._events;if(n===void 0)return[];let S=n[t];return S===void 0?[]:typeof S==`function`?[S.listener??S]:unwrapListeners(S)}rawListeners(t){let n=this._events;if(n===void 0)return[];let S=n[t];return S===void 0?[]:typeof S==`function`?[S]:arrayClone(S)}listenerCount(t){let n=this._events;if(n===void 0)return 0;let S=n[t];return S===void 0?0:typeof S==`function`?1:S.length}eventNames(){return(this._eventsCount??0)>0?Reflect.ownKeys(this._events):[]}static once(t,n,S){return new Promise((C,N)=>{let F=S?.signal;if(F?.aborted){N(createAbortError$2(F));return}if(typeof t.addEventListener==`function`){let S=t,handler=(...t)=>{F&&F.removeEventListener(`abort`,abortHandler),C(t)},errorHandler=t=>{F&&F.removeEventListener(`abort`,abortHandler),S.removeEventListener(`error`,errorHandler),N(t)},abortHandler=()=>{S.removeEventListener(n,handler),S.removeEventListener(`error`,errorHandler),N(createAbortError$2(F))};S.addEventListener(n,handler,{once:!0}),n!==`error`&&S.addEventListener(`error`,errorHandler,{once:!0}),F&&F.addEventListener(`abort`,abortHandler,{once:!0});return}let I=t,eventHandler=(...t)=>{F&&F.removeEventListener(`abort`,abortHandler),errorHandler!==void 0&&I.removeListener(`error`,errorHandler),C(t)},errorHandler;n!==`error`&&(errorHandler=t=>{I.removeListener(n,eventHandler),F&&F.removeEventListener(`abort`,abortHandler),N(t)},I.once(`error`,errorHandler)),I.once(n,eventHandler);let abortHandler=()=>{I.removeListener(n,eventHandler),errorHandler&&I.removeListener(`error`,errorHandler),N(createAbortError$2(F))};F&&F.addEventListener(`abort`,abortHandler,{once:!0})})}static on(t,n,S){let C=S?.signal;if(C?.aborted)throw createAbortError$2(C);let N=S?.highWaterMark??2**53-1,F=S?.lowWaterMark??1;validateNumber(N,`highWaterMark`),validateNumber(F,`lowWaterMark`);let I=[],H=[],W=null,q=!1,Y=!1,eventHandler=(...n)=>{if(H.length>0){let{resolve:t}=H.shift();t({value:n,done:!1})}else I.push(n),I.length>=N&&!Y&&(Y=!0,typeof t.pause==`function`&&t.pause())},errorHandler=t=>{if(W=t,H.length>0){let{reject:n}=H.shift();n(t)}X.return()},abortHandler=()=>{errorHandler(createAbortError$2(C))};t.on(n,eventHandler),n!==`error`&&t.on(`error`,errorHandler),C&&C.addEventListener(`abort`,abortHandler,{once:!0});let cleanup=()=>{t.removeListener(n,eventHandler),t.removeListener(`error`,errorHandler),C&&C.removeEventListener(`abort`,abortHandler),q=!0;for(let{resolve:t}of H)t({value:void 0,done:!0});H.length=0,I.length=0},X={next(){if(I.length>0){let n=I.shift();return Y&&I.length<F&&(Y=!1,typeof t.resume==`function`&&t.resume()),Promise.resolve({value:n,done:!1})}if(W){let t=Promise.reject(W);return W=null,t}return q?Promise.resolve({value:void 0,done:!0}):new Promise((t,n)=>{H.push({resolve:t,reject:n})})},return(){return cleanup(),Promise.resolve({value:void 0,done:!0})},throw(t){return q||(W=t,cleanup()),Promise.reject(t)},[Symbol.asyncIterator](){return this}};return X}static listenerCount(t,n){return t.listenerCount(n)}static getEventListeners(t,n){return typeof t.listeners==`function`?t.listeners(n):[]}static setMaxListeners(t,...n){if(validateNumber(t,`n`),t<0)throw RangeError(`The value of "n" is out of range.`);if(n.length===0)EventEmitter.defaultMaxListeners=t;else for(let S of n)typeof S.setMaxListeners==`function`&&S.setMaxListeners(t)}static getMaxListeners(t){return typeof t.getMaxListeners==`function`?t.getMaxListeners():EventEmitter.defaultMaxListeners}static addAbortListener(t,n){t.aborted&&Promise.resolve().then(()=>n());let handler=()=>n();return t.addEventListener(`abort`,handler,{once:!0}),{[Symbol.dispose](){t.removeEventListener(`abort`,handler)}}}},Nt.EventEmitter=Nt;for(let t of[`setMaxListeners`,`getMaxListeners`,`emit`,`addListener`,`on`,`prependListener`,`once`,`prependOnceListener`,`removeListener`,`off`,`removeAllListeners`,`listeners`,`rawListeners`,`listenerCount`,`eventNames`]){let n=Nt.prototype[t];typeof n==`function`&&Object.defineProperty(Nt.prototype,t,{enumerable:!0,configurable:!0,writable:!0,value:n})}Object.defineProperty(Nt.prototype,"_events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(Nt.prototype,"_eventsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(Nt.prototype,"_maxListeners",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),__name$1(createAbortError$2,`createAbortError`)}),Ft=__exportAll$5({EventEmitter:()=>It,addAbortListener:()=>Kt,captureRejectionSymbol:()=>Lt,default:()=>It,defaultMaxListeners:()=>zt,errorMonitor:()=>Rt,getEventListeners:()=>Wt,getMaxListeners:()=>Vt,listenerCount:()=>Gt,"module.exports":()=>It,on:()=>Ut,once:()=>Ht,setMaxListeners:()=>Bt}),It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt=__esmMin(()=>{Pt(),ze(),It=makeCallable(Nt),It.EventEmitter=It,Lt=It.captureRejectionSymbol,Rt=It.errorMonitor,zt=It.defaultMaxListeners,Bt=It.setMaxListeners,Vt=It.getMaxListeners,Ht=It.once,Ut=It.on,Wt=It.getEventListeners,Gt=It.listenerCount,Kt=It.addAbortListener});function normalizeAndValidateEncoding(t){return t&&checkEncoding(t),normalizeEncoding(t)}function utf8DecodeMaximalSubpart(t,n,S){let C=``,N=n;for(;N<S;){let n=t[N];if(n<=127){C+=String.fromCharCode(n),N++;continue}if(n>=194&&n<=223){N+1<S&&t[N+1]>=128&&t[N+1]<=191?(C+=String.fromCharCode((n&31)<<6|t[N+1]&63),N+=2):(C+=`�`,N++);continue}if(n>=224&&n<=239){let F,I;if(n===224?(F=160,I=191):n===237?(F=128,I=159):(F=128,I=191),N+1>=S){C+=`�`,N++;continue}let H=t[N+1];if(H<F||H>I){C+=`�`,N++;continue}if(N+2>=S){C+=`�`,N+=2;continue}let W=t[N+2];if(W<128||W>191){C+=`�`,N+=2;continue}let q=(n&15)<<12|(H&63)<<6|W&63;C+=String.fromCharCode(q),N+=3;continue}if(n>=240&&n<=244){let F,I;if(n===240?(F=144,I=191):n===244?(F=128,I=143):(F=128,I=191),N+1>=S){C+=`�`,N++;continue}let H=t[N+1];if(H<F||H>I){C+=`�`,N++;continue}if(N+2>=S){C+=`�`,N+=2;continue}let W=t[N+2];if(W<128||W>191){C+=`�`,N+=2;continue}if(N+3>=S){C+=`�`,N+=3;continue}let q=t[N+3];if(q<128||q>191){C+=`�`,N+=3;continue}let Y=(n&7)<<18|(H&63)<<12|(W&63)<<6|q&63;C+=String.fromCharCode(55296+(Y-65536>>10),56320+(Y-65536&1023)),N+=4;continue}C+=`�`,N++}return C}function utf8CharLength(t){return t&128?t>=194&&t<=223?2:t>=224&&t<=239?3:t>=240&&t<=244?4:0:1}function isValidContinuation(t,n,S,C){if(S===1){if(n===3)return t===224?C>=160&&C<=191:t===237?C>=128&&C<=159:C>=128&&C<=191;if(n===4)return t===240?C>=144&&C<=191:t===244?C>=128&&C<=143:C>=128&&C<=191}return C>=128&&C<=191}function writeUtf8(t,n){let S=0,C=``;if(t._lastNeed>0){for(;S<n.length&&t._lastNeed>0;){let N=n[S],F=t._lastTotal-t._lastNeed;if(isValidContinuation(t._lastLeadByte,t._lastTotal,F,N))t._lastChar[F]=N,t._lastNeed--,S++;else{C+=`�`,t._lastNeed=0,t._lastTotal=0,t._lastLeadByte=0;break}}if(t._lastNeed===0&&t._lastTotal>0&&(C+=utf8DecodeMaximalSubpart(t._lastChar,0,t._lastTotal),t._lastTotal=0,t._lastLeadByte=0),t._lastNeed>0)return C}let N=n.length;for(let C=0;C<Math.min(4,n.length-S);C++){let F=n.length-1-C;if(F<S)break;let I=n[F];if((I&192)!=128){let S=utf8CharLength(I);if(S>0&&I>=128){let C=n.length-F;if(C<S){let H=!0;for(let t=1;t<C;t++)if(!isValidContinuation(I,S,t,n[F+t])){H=!1;break}if(H){N=F;for(let S=0;S<C;S++)t._lastChar[S]=n[F+S];t._lastNeed=S-C,t._lastTotal=S,t._lastLeadByte=I}}}break}}return N>S&&(C+=utf8DecodeMaximalSubpart(n,S,N)),C}function writeUtf16le(t,n){let S=``,C=0;if(t._lastNeed>0){let N=t._lastTotal-t._lastNeed,F=Math.min(t._lastNeed,n.length);for(let S=0;S<F;S++)t._lastChar[N+S]=n[S];if(t._lastNeed-=F,C=F,t._lastNeed>0)return``;let I=t._lastTotal,H=0;for(;H+1<I;){let N=t._lastChar[H]|t._lastChar[H+1]<<8;if(H+=2,N>=55296&&N<=56319){if(H+1<I){let n=t._lastChar[H]|t._lastChar[H+1]<<8;if(n>=56320&&n<=57343){S+=String.fromCharCode(N,n),H+=2;continue}}if(C+1<n.length){let t=n[C]|n[C+1]<<8;if(t>=56320&&t<=57343){S+=String.fromCharCode(N,t),C+=2;continue}}else if(C>=n.length)return t._lastChar[0]=t._lastChar[H-2],t._lastChar[1]=t._lastChar[H-1],t._lastNeed=2,t._lastTotal=4,S}S+=String.fromCharCode(N)}t._lastTotal=0}for(;C+1<n.length;){let N=n[C]|n[C+1]<<8;if(C+=2,N>=55296&&N<=56319)if(C+1<n.length){let t=n[C]|n[C+1]<<8;if(t>=56320&&t<=57343){S+=String.fromCharCode(N,t),C+=2;continue}}else if(C<n.length)return S+=String.fromCharCode(N),t._lastChar[0]=n[C],t._lastNeed=1,t._lastTotal=2,S;else return t._lastChar[0]=n[C-2],t._lastChar[1]=n[C-1],t._lastNeed=2,t._lastTotal=4,S;S+=String.fromCharCode(N)}return C<n.length&&(t._lastChar[0]=n[C],t._lastNeed=1,t._lastTotal=2),S}function writeBase64(t,n){let S=0;if(t._lastNeed>0){let C=Math.min(t._lastNeed,n.length);for(let S=0;S<C;S++)t._lastChar[t._lastTotal-t._lastNeed+S]=n[S],t._lastNeed--;if(S=C,t._lastNeed>0)return``}let C=n.length-S,N=C-C%3,F=``;t._lastTotal>0&&t._lastNeed===0&&(F+=base64Encode$1(t._lastChar.subarray(0,t._lastTotal)),t._lastTotal=0),N>0&&(F+=base64Encode$1(n.subarray(S,S+N)));let I=C-N;if(I>0){for(let C=0;C<I;C++)t._lastChar[C]=n[S+N+C];t._lastNeed=3-I,t._lastTotal=3}return F}function decodeAscii(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]&127);return n}function decodeLatin1(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return n}function decodeHex(t){let n=``;for(let S=0;S<t.length;S++)n+=t[S].toString(16).padStart(2,`0`);return n}var Jt,Yt=__esmMin(()=>{ot(),Jt=function StringDecoder(t){this.encoding=normalizeAndValidateEncoding(t),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},Jt.prototype.write=function write(t){if(t.length===0)return``;switch(this.encoding){case`utf8`:return writeUtf8(this,t);case`utf16le`:return writeUtf16le(this,t);case`base64`:return writeBase64(this,t);case`ascii`:return decodeAscii(t);case`latin1`:return decodeLatin1(t);case`hex`:return decodeHex(t);default:return decodeAscii(t)}},Jt.prototype.end=function end(t){let n=``;if(t&&t.length>0&&(n=this.write(t)),this.encoding===`utf8`&&this._lastNeed>0)n+=`�`,this._lastNeed=0,this._lastTotal=0;else if(this.encoding===`utf16le`&&this._lastNeed>0){let t=this._lastTotal-this._lastNeed;for(let S=0;S+1<t;S+=2)n+=String.fromCharCode(this._lastChar[S]|this._lastChar[S+1]<<8);this._lastNeed=0,this._lastTotal=0}else if(this.encoding===`base64`&&this._lastNeed>0){let t=this._lastChar.subarray(0,this._lastTotal-this._lastNeed);n+=base64Encode$1(t),this._lastNeed=0,this._lastTotal=0}return n}}),Xt,ProcessWriteStream,ProcessReadStream,Zt=__esmMin(()=>{_e(),dt(),At(),qt(),ze(),Yt(),Xt=new TextEncoder,ProcessWriteStream=class extends It{fd;writable=!0;_outGio=null;constructor(t){super(),this.fd=t;let n=getGioNamespace();if(n){let t=n.UnixOutputStream??n.OutputStream;if(t)try{this._outGio=t.new(this.fd,!1)}catch{}}}write(t){if(this._outGio)try{let n=typeof t==`string`?Xt.encode(t):t;return this._outGio.write_all(n,null),!0}catch{}return this.fd===2?ge.error(t):ge.log(t),!0}get isTTY(){let t=nativeIsTty(this.fd);if(t!==null)return t;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t)return!!t.log_writer_supports_color(this.fd)}catch{}return!1}get columns(){let t=nativeTerminalSize(this.fd);if(t)return t.columns;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let n=parseInt(t.getenv(`COLUMNS`)??`0`,10);if(n>0)return n}}catch{}return 80}end(){}destroy(){}get rows(){let t=nativeTerminalSize(this.fd);if(t)return t.rows;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let n=parseInt(t.getenv(`LINES`)??`0`,10);if(n>0)return n}}catch{}return 24}},ProcessReadStream=class extends It{fd;isRaw=!1;_gio=null;_stdinGio=null;_reading=!1;_flowing=!1;_mainLoopHeld=!1;_pendingRead=!1;_decoder=null;constructor(t){super(),this.fd=t,this._gio=getGioNamespace()}get isTTY(){return nativeIsTty(this.fd)??!1}setRawMode(t){return noteRawMode(this.fd,t,t=>nativeSetRawMode(this.fd,t)===!0)?(this.isRaw=t,this):(noteRawMode(this.fd,t,t=>this._setRawModeViaStty(t)),this.isRaw=t,this)}_setRawModeViaStty(t){try{let n=globalThis.imports?.gi,S=n?.Gio??n?.Gio;if(!S)return!1;let C=S.SubprocessFlags?.STDIN_INHERIT??2,N=t?[`stty`,`-icanon`,`-echo`,`-icrnl`,`-isig`,`min`,`1`,`time`,`0`]:[`stty`,`icanon`,`echo`,`icrnl`,`isig`],F=new S.SubprocessLauncher({flags:C}).spawnv(N);return F.wait(null),F.get_successful()}catch{return!1}}setEncoding(t){return this._decoder=new Jt(t),this}_pushData(t){if(this._decoder){let n=this._decoder.write(t);n.length>0&&this.emit(`data`,n)}else this.emit(`data`,t)}on(t,n){let S=t===`data`&&this.listenerCount(`data`)===0;return super.on(t,n),S&&t===`data`&&this.resume(),this}addListener(t,n){return this.on(t,n)}once(t,n){return super.once(t,n),this}removeListener(t,n){return super.removeListener(t,n),t===`data`&&this.listenerCount(`data`)===0&&this.pause(),this}off(t,n){return this.removeListener(t,n)}removeAllListeners(t){let n=t===void 0||t===`data`?this.listenerCount(`data`)>0:!1;return super.removeAllListeners(t),n&&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 t=globalThis.imports?.gi,n=t?.GLib??t?.GLib;n?.idle_add?n.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 t=this._gio.UnixInputStream??this._gio.InputStream;if(!t){this._reading=!1;return}try{this._stdinGio=t.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,(t,n)=>{this._pendingRead=!1;try{let S=t.read_bytes_finish(n)?.get_data?.()??null;if(S&&S.byteLength>0)this._pushData(Buffer.from(S));else if(S!==null&&S.byteLength===0){if(this._reading=!1,this._decoder){let t=this._decoder.end();t.length>0&&this.emit(`data`,t)}this.emit(`end`);return}}catch{this._reading=!1;return}this._reading&&loop()})};loop()}}});function defineLazy(t,n,S){Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let C=S();return Object.defineProperty(t,n,{value:C,configurable:!0,enumerable:!0,writable:!1}),C}})}var Qt,Process,$t=__esmMin(()=>{_e(),gt(),_t(),vt(),pt(),yt(),St(),Zt(),At(),qt(),Qt=Date.now(),Process=class extends It{platform;arch;env;argv;argv0;execPath;pid;ppid;version;versions;title;execArgv;config;exitCode;constructor(){super(),this.on(`exit`,()=>{try{restoreClaimedRawModes()}catch(t){ge.error(`@gjsify/process: raw mode could not be restored:`,t)}}),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 t=detectVersionInfo();this.version=t.version,this.versions=t.versions,this.title=t.title,this.on(`newListener`,t=>{isDeliverableSignal(t)&&armSignal(t,t=>this.emit(t,t))}),this.on(`removeListener`,t=>{isDeliverableSignal(t)&&this.listenerCount(t)===0&&disarmSignal(t)})}cwd(){return getCwd()}chdir(t){chdir(t)}kill(t,n){return killPid(t,n)}exit(t){return this.exitCode=t??this.exitCode??0,this.emit(`exit`,this.exitCode),exitProcess(this.exitCode)}nextTick(t,...n){typeof queueMicrotask==`function`?queueMicrotask(()=>t(...n)):Promise.resolve().then(()=>t(...n))}hrtime(t){return hrtime(t)}uptime(){return(Date.now()-Qt)/1e3}memoryUsage(){return memoryUsage()}cpuUsage(t){return cpuUsage(t)}stdout=new ProcessWriteStream(1);stderr=new ProcessWriteStream(2);stdin=new ProcessReadStream(0);abort(){this.exit(1)}umask(t){let n=readUmask();return t!==void 0&&!this._umaskWarned&&(this._umaskWarned=!0,this.emitWarning(`process.umask(0${t.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`)),n}_umaskWarned=!1;emitWarning(t,n){ge.warn(typeof t==`string`?`(${n||`Warning`}): ${t}`:t.message)}},Process.prototype.hrtime.bigint=function(){return hrtimeBigint()}}),en,tn,nn,rn=__esmMin(()=>{if(pt(),$t(),At(),en=new Process,kt)try{let t=new kt.ResizeWatcher;t.connect(`resized`,(t,n,S)=>{en.stdout.emit(`resize`),en.stderr.emit(`resize`)}),t.start()}catch{}en.platform,en.arch,en.env,en.argv,en.argv0,en.execPath,en.pid,en.ppid,en.version,en.versions,en.cwd.bind(en),en.chdir.bind(en),en.exit.bind(en),en.nextTick.bind(en),Object.assign(en.hrtime.bind(en),{bigint:hrtimeBigint}),en.uptime.bind(en),en.memoryUsage.bind(en),en.cpuUsage.bind(en),en.kill.bind(en),en.abort.bind(en),en.umask.bind(en),en.emitWarning.bind(en),en.execArgv,en.config,tn=en.stdout,en.stderr,nn=en.stdin});ze(),rn(),typeof Promise.withResolvers!=`function`&&(Promise.withResolvers=function(){let t,n;return{promise:new Promise((S,C)=>{t=S,n=C}),resolve:t,reject:n}}),initErrorV8Methods(Error),`global`in globalThis||Object.defineProperty(globalThis,"global",{value:globalThis,writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(globalThis,"process",{value:en,enumerable:!1,writable:!0,configurable:!0}),ze(),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 an=getGLib()!==void 0;function reportTimerThrow(t,n){try{t.log_default_handler(`gjsify-timers`,t.LogLevelFlags.LEVEL_WARNING,`Uncaught exception in a timer callback: ${String(n)}\n${n?.stack??``}`,null)}catch{}}var GjsifyTimeout=class{_id=null;_refed=!0;_callback;_delay;_args;_repeat;constructor(t,n,S,C){this._callback=t,this._delay=n,this._args=S,this._repeat=C,this._schedule()}_schedule(){let t=getGLib();if(!t)return;let n=t.timeout_add.bind(t);this._id=n(t.PRIORITY_DEFAULT,this._delay,()=>{try{this._callback.apply(globalThis,this._args)}catch(n){reportTimerThrow(t,n)}return this._repeat?t.SOURCE_CONTINUE:(this._id=null,t.SOURCE_REMOVE)})}unref(){return this._refed=!1,this}ref(){return this._refed=!0,this}hasRef(){return this._refed}refresh(){return this._cancel(),this._schedule(),this}_cancel(){this._id!==null&&(getGLib()?.Source.remove(this._id),this._id=null)}close(){return this._cancel(),this}[Symbol.toPrimitive](){return this._id}[Symbol.dispose](){this._cancel()}};function removeById(t){t instanceof GjsifyTimeout||typeof t==`object`&&t&&`_cancel`in t?t._cancel():typeof t==`object`&&t&&typeof t.close==`function`?t.close():typeof t==`number`&&getGLib()?.Source.remove(t)}if(an){let setT=(t,n=0,...S)=>new GjsifyTimeout(t,Math.max(0,n|0),S,!1),setI=(t,n=0,...S)=>new GjsifyTimeout(t,Math.max(0,n|0),S,!0),t=globalThis;t.setTimeout=setT,t.clearTimeout=removeById,t.setInterval=setI,t.clearInterval=removeById}function setImmediate$1(t,...n){return setTimeout(t,0,...n)}__name$1(setImmediate$1,`setImmediate`);function clearImmediate(t){clearTimeout(t)}`setImmediate`in globalThis||Object.defineProperty(globalThis,"setImmediate",{value:setImmediate$1,enumerable:!0,writable:!0,configurable:!0}),`clearImmediate`in globalThis||Object.defineProperty(globalThis,"clearImmediate",{value:clearImmediate,enumerable:!0,writable:!0,configurable:!0});var on,sn,cn=__esmMin(()=>{on=Object.defineProperty,sn=__name$1((t,n)=>{let S={};for(var C in t)on(S,C,{get:t[C],enumerable:!0});return n||on(S,Symbol.toStringTag,{value:`Module`}),S},`__exportAll`)});function assertPath(t){if(typeof t!=`string`)throw TypeError(`The "path" argument must be of type string. Received type `+typeof t)}function isPosixPathSeparator(t){return t===47}function isPathSeparator(t){return t===47||t===92}function isWindowsDeviceRoot(t){return t>=65&&t<=90||t>=97&&t<=122}function normalizeString$1(t,n,S,C){let N=``,F=0,I=-1,H=0,W;for(let q=0;q<=t.length;++q){if(q<t.length)W=t.charCodeAt(q);else if(C(W))break;else W=47;if(C(W)){if(!(I===q-1||H===1))if(I!==q-1&&H===2){if(N.length<2||F!==2||N.charCodeAt(N.length-1)!==46||N.charCodeAt(N.length-2)!==46){if(N.length>2){let t=N.lastIndexOf(S);t===-1?(N=``,F=0):(N=N.slice(0,t),F=N.length-1-N.lastIndexOf(S)),I=q,H=0;continue}else if(N.length===2||N.length===1){N=``,F=0,I=q,H=0;continue}}n&&(N.length>0?N+=`${S}..`:N=`..`,F=2)}else N.length>0?N+=S+t.slice(I+1,q):N=t.slice(I+1,q),F=q-I-1;I=q,H=0}else W===46&&H!==-1?++H:H=-1}return N}function _format(t,n){if(typeof n!=`object`||!n)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof n);let S=n,C=S.dir||S.root,N=S.base||(S.name||``)+formatExt(S.ext);return C?C===S.root?C+N:C+t+N:N}function formatExt(t){return t?`${t[0]===`.`?``:`.`}${t}`:``}var ln=__esmMin(()=>{__name$1(normalizeString$1,`normalizeString`)});function posixCwd(){if(typeof globalThis.process?.cwd==`function`)return globalThis.process.cwd();try{let t=globalThis.imports?.gi?.GLib;if(t?.get_current_dir)return t.get_current_dir()}catch{}return`/`}function resolve$4(...t){let n=``,S=!1;for(let C=t.length-1;C>=-1&&!S;C--){let N;if(C>=0){if(N=t[C],assertPath(N),N.length===0)continue}else N=posixCwd();n=`${N}/${n}`,S=N.charCodeAt(0)===47}return n=normalizeString$1(n,!S,`/`,isPosixPathSeparator),S?n.length>0?`/${n}`:`/`:n.length>0?n:`.`}function normalize$2(t){if(assertPath(t),t.length===0)return`.`;let n=t.charCodeAt(0)===47,S=t.charCodeAt(t.length-1)===47,C=normalizeString$1(t,!n,`/`,isPosixPathSeparator);return C.length===0&&!n&&(C=`.`),C.length>0&&S&&(C+=`/`),n?`/${C}`:C}function isAbsolute$2(t){return assertPath(t),t.length>0&&t.charCodeAt(0)===47}function join$3(...t){if(t.length===0)return`.`;let n;for(let S=0;S<t.length;++S){let C=t[S];assertPath(C),C.length>0&&(n===void 0?n=C:n+=`/${C}`)}return n===void 0?`.`:normalize$2(n)}function relative$1(t,n){if(assertPath(t),assertPath(n),t===n||(t=resolve$4(t),n=resolve$4(n),t===n))return``;let S=t.length,C=S-1,N=1,F=n.length-N,I=C<F?C:F,H=-1,W=0;for(;W<=I;++W){if(W===I){if(F>I){if(n.charCodeAt(N+W)===47)return n.slice(N+W+1);if(W===0)return n.slice(N+W)}else C>I&&(t.charCodeAt(1+W)===47?H=W:W===0&&(H=0));break}let S=t.charCodeAt(1+W);if(S!==n.charCodeAt(N+W))break;S===47&&(H=W)}let q=``;for(W=1+H+1;W<=S;++W)(W===S||t.charCodeAt(W)===47)&&(q.length===0?q+=`..`:q+=`/..`);return q.length>0?q+n.slice(N+H):(N+=H,n.charCodeAt(N)===47&&++N,n.slice(N))}function toNamespacedPath$1(t){return t}function dirname$2(t){if(assertPath(t),t.length===0)return`.`;let n=t.charCodeAt(0)===47,S=-1,C=!0;for(let n=t.length-1;n>=1;--n)if(t.charCodeAt(n)===47){if(!C){S=n;break}}else C=!1;return S===-1?n?`/`:`.`:n&&S===1?`//`:t.slice(0,S)}function basename$2(t,n){n!==void 0&&assertPath(n),assertPath(t);let S=0,C=-1,N=!0;if(n!==void 0&&n.length>0&&n.length<=t.length){if(n.length===t.length&&n===t)return``;let F=n.length-1,I=-1;for(let H=t.length-1;H>=0;--H){let W=t.charCodeAt(H);if(W===47){if(!N){S=H+1;break}}else I===-1&&(N=!1,I=H+1),F>=0&&(W===n.charCodeAt(F)?--F===-1&&(C=H):(F=-1,C=I))}return S===C?C=I:C===-1&&(C=t.length),t.slice(S,C)}else{for(let n=t.length-1;n>=0;--n)if(t.charCodeAt(n)===47){if(!N){S=n+1;break}}else C===-1&&(N=!1,C=n+1);return C===-1?``:t.slice(S,C)}}function extname$2(t){assertPath(t);let n=-1,S=0,C=-1,N=!0,F=0;for(let I=t.length-1;I>=0;--I){let H=t.charCodeAt(I);if(H===47){if(!N){S=I+1;break}continue}C===-1&&(N=!1,C=I+1),H===46?n===-1?n=I:F!==1&&(F=1):n!==-1&&(F=-1)}return n===-1||C===-1||F===0||F===1&&n===C-1&&n===S+1?``:t.slice(n,C)}function format$3(t){if(typeof t!=`object`||!t)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof t);return _format(`/`,t)}function parse$5(t){assertPath(t);let n={root:``,dir:``,base:``,ext:``,name:``};if(t.length===0)return n;let S=t.charCodeAt(0)===47,C;S?(n.root=`/`,C=1):C=0;let N=-1,F=0,I=-1,H=!0,W=t.length-1,q=0;for(;W>=C;--W){let n=t.charCodeAt(W);if(n===47){if(!H){F=W+1;break}continue}I===-1&&(H=!1,I=W+1),n===46?N===-1?N=W:q!==1&&(q=1):N!==-1&&(q=-1)}return N===-1||I===-1||q===0||q===1&&N===I-1&&N===F+1?I!==-1&&(F===0&&S?n.base=n.name=t.slice(1,I):n.base=n.name=t.slice(F,I)):(F===0&&S?(n.name=t.slice(1,N),n.base=t.slice(1,I)):(n.name=t.slice(F,N),n.base=t.slice(F,I)),n.ext=t.slice(N,I)),F>0?n.dir=t.slice(0,F-1):S&&(n.dir=`/`),n}var un,dn=__esmMin(()=>{cn(),ln(),un=sn({basename:()=>basename$2,delimiter:()=>`:`,dirname:()=>dirname$2,extname:()=>extname$2,format:()=>format$3,isAbsolute:()=>isAbsolute$2,join:()=>join$3,normalize:()=>normalize$2,parse:()=>parse$5,relative:()=>relative$1,resolve:()=>resolve$4,sep:()=>`/`,toNamespacedPath:()=>toNamespacedPath$1}),__name$1(resolve$4,`resolve`),__name$1(normalize$2,`normalize`),__name$1(isAbsolute$2,`isAbsolute`),__name$1(join$3,`join`),__name$1(relative$1,`relative`),__name$1(toNamespacedPath$1,`toNamespacedPath`),__name$1(dirname$2,`dirname`),__name$1(basename$2,`basename`),__name$1(extname$2,`extname`),__name$1(format$3,`format`),__name$1(parse$5,`parse`)});function cwd$1(){return typeof globalThis.process?.cwd==`function`?globalThis.process.cwd():`/`}function resolve$3(...t){let n=``,S=``,C=!1;for(let N=t.length-1;N>=-1;N--){let F;if(N>=0){if(F=t[N],assertPath(F),F.length===0)continue}else n.length===0?F=cwd$1():(F=globalThis.process?.env?.[`=${n}`]||cwd$1(),F.slice(0,2).toLowerCase()!==n.toLowerCase()&&F.charCodeAt(2)===92&&(F=`${n}\\`));let I=F.length,H=0,W=``,q=!1,Y=F.charCodeAt(0);if(I===1)isPathSeparator(Y)&&(H=1,q=!0);else if(isPathSeparator(Y))if(q=!0,isPathSeparator(F.charCodeAt(1))){let t=matchUncRoot(F);t&&(W=t.device,H=t.rootEnd)}else H=1;else isWindowsDeviceRoot(Y)&&F.charCodeAt(1)===58&&(W=F.slice(0,2),H=2,I>2&&isPathSeparator(F.charCodeAt(2))&&(q=!0,H=3));if(W.length>0)if(n.length>0){if(W.toLowerCase()!==n.toLowerCase())continue}else n=W;if(C){if(n.length>0)break}else if(S=`${F.slice(H)}\\${S}`,C=q,q&&n.length>0)break}return S=normalizeString$1(S,!C,`\\`,isPathSeparator),C?`${n}\\${S}`:`${n}${S}`||`.`}function matchUncRoot(t){let n=t.length,S=2,C=S;for(;S<n&&!isPathSeparator(t.charCodeAt(S));)S++;if(S>=n||S===C)return;let N=t.slice(C,S);for(C=S;S<n&&isPathSeparator(t.charCodeAt(S));)S++;if(!(S>=n||S===C)){for(C=S;S<n&&!isPathSeparator(t.charCodeAt(S));)S++;return N===`.`||N===`?`?{device:`\\\\${N}`,rootEnd:4,shareOnly:!1}:{device:`\\\\${N}\\${t.slice(C,S)}`,rootEnd:S,shareOnly:S===n}}}function normalize$1(t){assertPath(t);let n=t.length;if(n===0)return`.`;let S=t.charCodeAt(0);if(n===1)return isPosixPathSeparator(S)?`\\`:t;let C=0,N,F=!1;if(isPathSeparator(S))if(F=!0,isPathSeparator(t.charCodeAt(1))){let n=matchUncRoot(t);if(n?.shareOnly)return`${n.device}\\`;if(n&&(N=n.device,C=n.rootEnd,N.length===3)){let n=t.slice(4,t.indexOf(`:`)+1);isWindowsReservedName(n,n.length-1)&&(N=`\\\\?\\${n}`,C=4+n.length)}}else C=1;else{let I=t.indexOf(`:`);I>0&&(isWindowsDeviceRoot(S)&&I===1?(N=t.slice(0,2),C=2,n>2&&isPathSeparator(t.charCodeAt(2))&&(F=!0,C=3)):isWindowsReservedName(t,I)&&(N=t.slice(0,I+1),C=I+1))}let I=C<n?normalizeString$1(t.slice(C),!F,`\\`,isPathSeparator):``;if(I.length===0&&!F&&(I=`.`),I.length>0&&isPathSeparator(t.charCodeAt(n-1))&&(I+=`\\`),!F&&N===void 0&&t.includes(`:`)){if(I.length>=2&&isWindowsDeviceRoot(I.charCodeAt(0))&&I.charCodeAt(1)===58)return`.\\${I}`;let S=t.indexOf(`:`);do if(S===n-1||isPathSeparator(t.charCodeAt(S+1)))return`.\\${I}`;while((S=t.indexOf(`:`,S+1))!==-1)}return isWindowsReservedName(t,t.indexOf(`:`))?`.\\${N??``}${I}`:N===void 0?F?`\\${I}`:I:F?`${N}\\${I}`:`${N}${I}`}function isWindowsReservedName(t,n){return pn.has(t.slice(0,n).toUpperCase())}function isAbsolute$1(t){assertPath(t);let n=t.length;if(n===0)return!1;let S=t.charCodeAt(0);return!!(isPathSeparator(S)||isWindowsDeviceRoot(S)&&n>2&&t.charCodeAt(1)===58&&isPathSeparator(t.charCodeAt(2)))}function join$2(...t){if(t.length===0)return`.`;let n,S;for(let C=0;C<t.length;++C){let N=t[C];assertPath(N),N.length>0&&(n===void 0?n=S=N:n+=`\\${N}`)}if(n===void 0)return`.`;let C=!0,N=0;if(isPathSeparator(S.charCodeAt(0))){++N;let t=S.length;t>1&&isPathSeparator(S.charCodeAt(1))&&(++N,t>2&&(isPathSeparator(S.charCodeAt(2))?++N:C=!1))}if(C){for(;N<n.length&&isPathSeparator(n.charCodeAt(N));++N);N>=2&&(n=`\\${n.slice(N)}`)}return n.split(/\\+/).some(t=>{let n=t.indexOf(`:`);return n!==-1&&isWindowsReservedName(t,n)})?n.replace(/\//g,`\\`):normalize$1(n)}function relative(t,n){if(assertPath(t),assertPath(n),t===n)return``;let S=resolve$3(t),C=resolve$3(n);if(S===C||(t=S.toLowerCase(),n=C.toLowerCase(),t===n))return``;let N=0;for(;N<t.length&&t.charCodeAt(N)===92;++N);let F=t.length;for(;F-1>N&&t.charCodeAt(F-1)===92;--F);let I=F-N,H=0;for(;H<n.length&&n.charCodeAt(H)===92;++H);let W=n.length;for(;W-1>H&&n.charCodeAt(W-1)===92;--W);let q=W-H,Y=I<q?I:q,X=-1,Z=0;for(;Z<=Y;++Z){if(Z===Y){if(q>Y){if(n.charCodeAt(H+Z)===92)return C.slice(H+Z+1);if(Z===2)return C.slice(H+Z)}I>Y&&(t.charCodeAt(N+Z)===92?X=Z:Z===2&&(X=3));break}let S=t.charCodeAt(N+Z);if(S!==n.charCodeAt(H+Z))break;S===92&&(X=Z)}if(Z!==Y&&X===-1)return C;let te=``;for(X===-1&&(X=0),Z=N+X+1;Z<=F;++Z)(Z===F||t.charCodeAt(Z)===92)&&(te.length===0?te+=`..`:te+=`\\..`);return te.length>0?te+C.slice(H+X,W):(H+=X,C.charCodeAt(H)===92&&++H,C.slice(H,W))}function toNamespacedPath(t){if(typeof t!=`string`||t.length===0)return t;let n=resolve$3(t);if(n.length<=2)return t;if(n.charCodeAt(0)===92){if(n.charCodeAt(1)===92){let t=n.charCodeAt(2);if(t!==63&&t!==46)return`\\\\?\\UNC\\${n.slice(2)}`}}else if(isWindowsDeviceRoot(n.charCodeAt(0))&&n.charCodeAt(1)===58&&n.charCodeAt(2)===92)return`\\\\?\\${n}`;return n}function dirname$1(t){assertPath(t);let n=t.length;if(n===0)return`.`;let S=-1,C=-1,N=!0,F=0,I=t.charCodeAt(0);if(n>1)if(isPathSeparator(I)){if(S=F=1,isPathSeparator(t.charCodeAt(1))){let C=2,N=C;for(;C<n&&!isPathSeparator(t.charCodeAt(C));++C);if(C<n&&C!==N){for(N=C;C<n&&isPathSeparator(t.charCodeAt(C));++C);if(C<n&&C!==N){for(N=C;C<n&&!isPathSeparator(t.charCodeAt(C));++C);if(C===n)return t;C!==N&&(S=F=C+1)}}}}else isWindowsDeviceRoot(I)&&t.charCodeAt(1)===58&&(S=F=2,n>2&&isPathSeparator(t.charCodeAt(2))&&(S=F=3));else if(isPathSeparator(I))return t;for(let S=n-1;S>=F;--S)if(isPathSeparator(t.charCodeAt(S))){if(!N){C=S;break}}else N=!1;if(C===-1){if(S===-1)return`.`;C=S}return t.slice(0,C)}function basename$1(t,n){n!==void 0&&assertPath(n),assertPath(t);let S=0,C=-1,N=!0;if(t.length>=2&&isWindowsDeviceRoot(t.charCodeAt(0))&&t.charCodeAt(1)===58&&(S=2),n!==void 0&&n.length>0&&n.length<=t.length){if(n.length===t.length&&n===t)return``;let F=n.length-1,I=-1;for(let H=t.length-1;H>=S;--H){let W=t.charCodeAt(H);if(isPathSeparator(W)){if(!N){S=H+1;break}}else I===-1&&(N=!1,I=H+1),F>=0&&(W===n.charCodeAt(F)?--F===-1&&(C=H):(F=-1,C=I))}return S===C?C=I:C===-1&&(C=t.length),t.slice(S,C)}else{for(let n=t.length-1;n>=S;--n)if(isPathSeparator(t.charCodeAt(n))){if(!N){S=n+1;break}}else C===-1&&(N=!1,C=n+1);return C===-1?``:t.slice(S,C)}}function extname$1(t){assertPath(t);let n=0,S=-1,C=0,N=-1,F=!0,I=0;t.length>=2&&t.charCodeAt(1)===58&&isWindowsDeviceRoot(t.charCodeAt(0))&&(n=C=2);for(let H=t.length-1;H>=n;--H){let n=t.charCodeAt(H);if(isPathSeparator(n)){if(!F){C=H+1;break}continue}N===-1&&(F=!1,N=H+1),n===46?S===-1?S=H:I!==1&&(I=1):S!==-1&&(I=-1)}return S===-1||N===-1||I===0||I===1&&S===N-1&&S===C+1?``:t.slice(S,N)}function format$2(t){if(typeof t!=`object`||!t)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof t);return _format(`\\`,t)}function parse$4(t){assertPath(t);let n={root:``,dir:``,base:``,ext:``,name:``};if(t.length===0)return n;let S=t.length,C=0,N=t.charCodeAt(0);if(S>1)if(isPathSeparator(N)){if(C=1,isPathSeparator(t.charCodeAt(1))){let n=2,N=n;for(;n<S&&!isPathSeparator(t.charCodeAt(n));++n);if(n<S&&n!==N){for(N=n;n<S&&isPathSeparator(t.charCodeAt(n));++n);if(n<S&&n!==N){for(N=n;n<S&&!isPathSeparator(t.charCodeAt(n));++n);n===S?C=n:n!==N&&(C=n+1)}}}}else isWindowsDeviceRoot(N)&&t.charCodeAt(1)===58&&(C=2,S>2&&isPathSeparator(t.charCodeAt(2))&&(C=3));else if(isPathSeparator(N))return n.root=n.dir=t,n;C>0&&(n.root=t.slice(0,C));let F=-1,I=C,H=-1,W=!0,q=t.length-1,Y=0;for(;q>=C;--q){if(N=t.charCodeAt(q),isPathSeparator(N)){if(!W){I=q+1;break}continue}H===-1&&(W=!1,H=q+1),N===46?F===-1?F=q:Y!==1&&(Y=1):F!==-1&&(Y=-1)}return F===-1||H===-1||Y===0||Y===1&&F===H-1&&F===I+1?H!==-1&&(n.base=n.name=t.slice(I,H)):(n.name=t.slice(I,F),n.base=t.slice(I,H),n.ext=t.slice(F,H)),I>0&&I!==C?n.dir=t.slice(0,I-1):n.dir=n.root,n}var fn,pn,mn=__esmMin(()=>{cn(),ln(),fn=sn({basename:()=>basename$1,delimiter:()=>`;`,dirname:()=>dirname$1,extname:()=>extname$1,format:()=>format$2,isAbsolute:()=>isAbsolute$1,join:()=>join$2,normalize:()=>normalize$1,parse:()=>parse$4,relative:()=>relative,resolve:()=>resolve$3,sep:()=>`\\`,toNamespacedPath:()=>toNamespacedPath}),__name$1(cwd$1,`cwd`),__name$1(resolve$3,`resolve`),__name$1(normalize$1,`normalize`),pn=new Set([`CON`,`PRN`,`AUX`,`NUL`,...[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`¹`,`²`,`³`].flatMap(t=>[`COM${t}`,`LPT${t}`])]),__name$1(isAbsolute$1,`isAbsolute`),__name$1(join$2,`join`),__name$1(dirname$1,`dirname`),__name$1(basename$1,`basename`),__name$1(extname$1,`extname`),__name$1(format$2,`format`),__name$1(parse$4,`parse`)});function selectFlavour(t){return t===`win32`?fn:un}var hn=__esmMin(()=>{dn(),mn()}),gn=__exportAll$5({basename:()=>Tn,default:()=>An,delimiter:()=>kn,dirname:()=>wn,extname:()=>$,format:()=>En,isAbsolute:()=>bn,join:()=>xn,normalize:()=>yn,parse:()=>Dn,posix:()=>un,relative:()=>Sn,resolve:()=>vn,sep:()=>On,toNamespacedPath:()=>Cn,win32:()=>fn}),_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,$,En,Dn,On,kn,An,jn=__esmMin(()=>{dn(),mn(),hn(),ze(),_n=selectFlavour(hostOs()),{resolve:vn,normalize:yn,isAbsolute:bn,join:xn,relative:Sn,toNamespacedPath:Cn,dirname:wn,basename:Tn,extname:$,format:En,parse:Dn,sep:On,delimiter:kn}=_n,An={resolve:_n.resolve,normalize:_n.normalize,isAbsolute:_n.isAbsolute,join:_n.join,relative:_n.relative,toNamespacedPath:_n.toNamespacedPath,dirname:_n.dirname,basename:_n.basename,extname:_n.extname,format:_n.format,parse:_n.parse,sep:_n.sep,delimiter:_n.delimiter,posix:un,win32:fn}}),Mn=__exportAll$5({URL:()=>Bn,URLSearchParams:()=>Fn,default:()=>Vn,domainToASCII:()=>domainToASCII,domainToUnicode:()=>domainToUnicode,fileURLToPath:()=>fileURLToPath,format:()=>format$1,parse:()=>parse$3,pathToFileURL:()=>pathToFileURL,resolve:()=>resolve$2});function platformOrShapeIsWindows(t){return hostOs()===void 0?isWindowsPath(t):isWin32()}function parseFormUrlencoded(t){let n=[];if(!t)return n;for(let S of t.split(`&`)){if(S===``)continue;let t=S.indexOf(`=`);t===-1?n.push([decodeComponent(S),``]):n.push([decodeComponent(S.slice(0,t)),decodeComponent(S.slice(t+1))])}return n}function decodeComponent(t){try{return decodeURIComponent(t.replace(/\+/g,` `))}catch{return t}}function percentEncodeUtf8(t){let n=``;for(let S of new TextEncoder().encode(t))n+=`%${S.toString(16).toUpperCase().padStart(2,`0`)}`;return n}function encodeComponent(t){let n=``;for(let S of t)S===` `?n+=`+`:/^[A-Za-z0-9*\-._]$/.test(S)?n+=S:n+=percentEncodeUtf8(S);return n}function isSpecialScheme(t){return In.has(t)}function defaultPort(t){return In.get(t)??null}function percentEncode(t,n){let S=``;for(let C of t){let t=C.codePointAt(0);S+=t<=32||t>126||n.includes(C)?percentEncodeUtf8(C):C}return S}function encodeQuery(t,n){return percentEncode(t,n?`"#<>'`:`"#<>`)}function isSchemeChar(t){return t>=`a`&&t<=`z`||t>=`A`&&t<=`Z`||t>=`0`&&t<=`9`||t===`+`||t===`-`||t===`.`}function isAsciiDigit(t){return t!==void 0&&t>=`0`&&t<=`9`}function isHexDigit$1(t){return t!==void 0&&/^[0-9A-Fa-f]$/.test(t)}function digitPrefix(t){let n=``;for(let S of t){if(!isAsciiDigit(S))break;n+=S}return n}function hasForbiddenDomainCodePoint(t){for(let n of t){let t=n.codePointAt(0);if(t<=31||t===127||n===`%`||zn.has(n))return!0}return!1}function parseIPv6(t){let n=[0,0,0,0,0,0,0,0],S=0,C=null,N=0,at=()=>t[N];if(at()===`:`){if(t[N+1]!==`:`)return;N+=2,S++,C=S}for(;N<t.length;){if(S===8)return;if(at()===`:`){if(C!==null)return;N++,S++,C=S;continue}let F=0,I=0;for(;I<4&&isHexDigit$1(at());)F=F*16+Number.parseInt(at(),16),N++,I++;if(at()===`.`){if(I===0||(N-=I,S>6))return;let C=0;for(;N<t.length;){let t=null;if(C>0)if(at()===`.`&&C<4)N++;else return;if(!isAsciiDigit(at()))return;for(;isAsciiDigit(at());){let n=Number(at());if(t===null)t=n;else if(t===0)return;else t=t*10+n;if(t>255)return;N++}n[S]=n[S]*256+t,C++,(C===2||C===4)&&S++}if(C!==4)return;break}if(at()===`:`){if(N++,N>=t.length)return}else if(N<t.length)return;n[S]=F,S++}if(C!==null){let t=S-C;for(S=7;S!==0&&t>0;){let N=n[C+t-1];n[C+t-1]=n[S],n[S]=N,S--,t--}}else if(S!==8)return;return serializeIPv6(n)}function serializeIPv6(t){let n=null,S=1,C=-1,N=0;for(let F=0;F<8;F++){if(t[F]!==0){C=-1,N=0;continue}C===-1&&(C=F),N++,N>S&&(S=N,n=C)}let F=``,I=!1;for(let S=0;S<8;S++)if(!(I&&t[S]===0)){if(I=!1,n===S){F+=S===0?`::`:`:`,I=!0;continue}F+=t[S].toString(16),S!==7&&(F+=`:`)}return F}function parseHost(t,n){if(t.startsWith(`[`)){if(!t.endsWith(`]`))return;let n=parseIPv6(t.slice(1,-1));return n===void 0?void 0:`[${n}]`}if(n){for(let n of t)if(zn.has(n))return;return percentEncode(t,``)}if(!hasForbiddenDomainCodePoint(t))return t.toLowerCase()}function parseHostSetterValue(t,n,S,C,N){let F=t.replace(Rn,``),I=isSpecialScheme(n);if(n===`file`){let t=F.length;for(let n=0;n<F.length;n++){let S=F[n];if(S===`/`||S===`\\`||S===`?`||S===`#`){t=n;break}}let n=F.slice(0,t);if(n===``)return{host:``};let S=parseHost(n,!1);return S===void 0?void 0:{host:S===`localhost`?``:S}}let H=!1,W=``;for(let t=0;t<F.length;t++){let S=F[t];if(S===`:`&&!H){if(W===``||N)return;let S=parseHost(W,!I);if(S===void 0)return;let C=digitPrefix(F.slice(t+1));if(C===``)return{host:S};let H=Number(C);return H>65535?{host:S}:{host:S,port:H===defaultPort(n)?null:H}}if(S===`/`||S===`?`||S===`#`||I&&S===`\\`)break;S===`[`?H=!0:S===`]`&&(H=!1),W+=S}if(W===``&&(I||S||C))return;let q=parseHost(W,!I);return q===void 0?void 0:{host:q}}function isDoubleDotSegment(t){let n=t.toLowerCase();return n===`..`||n===`.%2e`||n===`%2e.`||n===`%2e%2e`}function isSingleDotSegment(t){let n=t.toLowerCase();return n===`.`||n===`%2e`}function parsePathSetterValue(t,n,S){let C=t.replace(Rn,``);if(n&&(C=C.replace(/\\/g,`/`)),C===``)return n||S?`/`:``;let N=[],F=(C.startsWith(`/`)?C.slice(1):C).split(`/`);for(let t=0;t<F.length;t++){let n=F[t],S=t===F.length-1;isDoubleDotSegment(n)?(N.pop(),S&&N.push(``)):isSingleDotSegment(n)?S&&N.push(``):N.push(percentEncode(n,'"#<>?^`{}'))}return`/`+N.join(`/`)}function bracketIPv6Host(t){return t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t}function parse$3(t,n,S){if(typeof t!=`string`)throw TypeError(`The "url" argument must be of type string. Received type `+typeof t);let C={protocol:null,slashes:null,auth:null,host:null,port:null,hostname:null,hash:null,search:null,query:null,pathname:null,path:null,href:t},N=t.trim(),F=N.indexOf(`#`);F!==-1&&(C.hash=N.slice(F),N=N.slice(0,F));let I=N.indexOf(`?`);I!==-1&&(C.search=N.slice(I),C.query=n?Object.fromEntries(new Fn(N.slice(I+1))):N.slice(I+1),N=N.slice(0,I));let H=/^([a-z][a-z0-9.+-]*:)/i.exec(N);if(H&&(C.protocol=H[1].toLowerCase(),N=N.slice(C.protocol.length)),(S||C.protocol)&&N.startsWith(`//`)&&(C.slashes=!0,N=N.slice(2)),C.slashes||C.protocol&&![`javascript:`,`data:`,`mailto:`].includes(C.protocol)){let t=-1;for(let n=0;n<N.length;n++){let S=N[n];if(S===`/`||S===`\\`){t=n;break}}let n=t===-1?N:N.slice(0,t);N=t===-1?``:N.slice(t);let S=n.lastIndexOf(`@`);S===-1?parseHostPort(n,C):(C.auth=decodeURIComponent(n.slice(0,S)),parseHostPort(n.slice(S+1),C))}return C.pathname=N||(C.slashes?`/`:null),(C.pathname!==null||C.search!==null)&&(C.path=(C.pathname||``)+(C.search||``)),C.href=format$1(C),C}function parseHostPort(t,n){if(!t)return;let S=t.indexOf(`[`);if(S!==-1){let C=t.indexOf(`]`,S);if(C!==-1){let N=t.slice(C+1);N.startsWith(`:`)&&(n.port=N.slice(1)),n.hostname=t.slice(S,C+1),n.host=n.hostname+(n.port?`:`+n.port:``);return}}let C=t.lastIndexOf(`:`);if(C!==-1){let S=t.slice(C+1);/^\d*$/.test(S)?(n.port=S||null,n.hostname=t.slice(0,C).toLowerCase()):n.hostname=t.toLowerCase()}else n.hostname=t.toLowerCase();n.host=n.hostname+(n.port?`:`+n.port:``)}function format$1(t){if(typeof t==`string`)return t;if(t instanceof Bn)return t.href;let n=t,S=``;if(n.protocol&&(S+=n.protocol),(n.slashes||n.protocol&&![`javascript:`,`data:`,`mailto:`].includes(n.protocol||``))&&(S+=`//`),n.auth&&(S+=encodeURIComponent(n.auth)+`@`),n.host?S+=n.host:(n.hostname&&(S+=n.hostname),n.port&&(S+=`:`+n.port)),n.pathname&&(S+=n.pathname),n.search)S+=n.search;else if(n.query&&typeof n.query==`object`){let t=new Fn(n.query).toString();t&&(S+=`?`+t)}return n.hash&&(S+=n.hash),S}function resolve$2(t,n){return new Bn(n,new Bn(t,`resolve://`)).href.replace(/^resolve:\/\//,``)}function fileURLToPath(t,n){if(typeof t==`string`&&(t=new Bn(t)),!(t instanceof Bn))throw TypeError(`The "url" argument must be of type string or URL. Received type `+typeof t);if(t.protocol!==`file:`)throw TypeError(`The URL must be of scheme file`);let S=t.pathname,C=n?.windows??platformOrShapeIsWindows(S.slice(1));for(let t=0;t<S.length;t++){if(S[t]!==`%`)continue;let n=S.codePointAt(t+2)|32,N=S[t+1]===`2`&&n===102,F=S[t+1]===`5`&&n===99;if(C&&(N||F))throw TypeError(`File URL path must not include encoded \\ or / characters`);if(N)throw TypeError(`File URL path must not include encoded / characters`)}if(t.hostname!==``&&t.hostname!==`localhost`){if(!C)throw TypeError(`File URL host must be "localhost" or empty on ${hostOs()??`this platform`}`);return`\\\\${t.hostname}${decodeURIComponent(S).replace(/\//g,`\\`)}`}if(C){let t=decodeURIComponent(S);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t.replace(/\//g,`\\`)}return decodeURIComponent(S)}function pathToFileURL(t,n){let S=n?.windows??platformOrShapeIsWindows(t),C=S&&t.startsWith(`\\\\`)?t:(S?fn:un).resolve(currentDir(),t);if(S&&C.startsWith(`\\\\`))return uncPathToFileURL(C);let N=t.charCodeAt(t.length-1);return(N===47||S&&N===92)&&C[C.length-1]!==On&&(C+=`/`),new Bn(pathToFileUrlHref(C,{windows:S}))}function currentDir(){return typeof globalThis.process?.cwd==`function`?globalThis.process.cwd():lt.get_current_dir()}function uncPathToFileURL(t){let n=t.startsWith(`\\\\?\\UNC\\`)?8:2,S=t.indexOf(`\\`,n);if(S===-1)throw invalidPathValue(t,`Missing UNC resource path`);if(S===2)throw invalidPathValue(t,`Empty UNC servername`);let C=t.slice(n,S);return new Bn(`file://${C===`?`?``:C}${encodePathForFileUrl(t.slice(S).replace(/\\/g,`/`))}`)}function invalidPathValue(t,n){let S=TypeError(`The argument 'path' ${n}. Received '${t}'`);return S.code=`ERR_INVALID_ARG_VALUE`,S}function domainToASCII(t){try{return new Bn(`http://${t}`).hostname}catch{return``}}function domainToUnicode(t){try{return new Bn(`http://${t}`).hostname}catch{return``}}var Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn=__esmMin(()=>{ut(),ze(),jn(),Nn=lt.UriFlags.HAS_PASSWORD|lt.UriFlags.ENCODED|lt.UriFlags.SCHEME_NORMALIZE,Pn=new WeakMap,Fn=class URLSearchParams{_entries=[];constructor(t){if(t)if(typeof t==`string`)this._entries=parseFormUrlencoded(t.startsWith(`?`)?t.slice(1):t);else if(Array.isArray(t))for(let[n,S]of t)this._entries.push([String(n),String(S)]);else if(t instanceof URLSearchParams)this._entries=t._entries.map(([t,n])=>[t,n]);else for(let n of Object.keys(t))this._entries.push([n,String(t[n])])}get(t){for(let[n,S]of this._entries)if(n===t)return S;return null}getAll(t){return this._entries.filter(([n])=>n===t).map(([,t])=>t)}set(t,n){let S=!1;if(this._entries=this._entries.filter(([n])=>n===t?S?!1:(S=!0,!0):!0),S){for(let S=0;S<this._entries.length;S++)if(this._entries[S][0]===t){this._entries[S][1]=n;break}}else this._entries.push([t,n]);Pn.get(this)?.()}has(t,n){return n===void 0?this._entries.some(([n])=>n===t):this._entries.some(([S,C])=>S===t&&C===n)}delete(t,n){this._entries=n===void 0?this._entries.filter(([n])=>n!==t):this._entries.filter(([S,C])=>!(S===t&&C===n)),Pn.get(this)?.()}append(t,n){this._entries.push([t,n]),Pn.get(this)?.()}sort(){this._entries.sort((t,n)=>t[0]<n[0]?-1:+(t[0]>n[0])),Pn.get(this)?.()}toString(){return this._entries.map(([t,n])=>encodeComponent(t)+`=`+encodeComponent(n)).join(`&`)}forEach(t){for(let[n,S]of this._entries)t(S,n,this)}*entries(){yield*this._entries}*keys(){for(let[t]of this._entries)yield t}*values(){for(let[,t]of this._entries)yield t}[Symbol.iterator](){return this.entries()}get size(){return this._entries.length}},In=new Map([[`ftp`,21],[`file`,null],[`http`,80],[`https`,443],[`ws`,80],[`wss`,443]]),Ln='"#/:;<=>?@[\\]^`{|}',Rn=/[\t\n\r]/g,__name$1(isHexDigit$1,`isHexDigit`),zn=new Set([`\0`,` `,`
10
+ `)){let n=/^(\w+):\s+(\d+)(\s+kB)?/.exec(S);n&&t.set(n[1],parseInt(n[2],10)*(n[3]?1024:1))}if(t.size>0)return{virtual:t.get(`VmSize`)??0,resident:t.get(`VmRSS`)??0,data:t.get(`VmData`)??0,peak:t.get(`VmPeak`)??0}}let S=shellOut(t,`sh -c 'ps -o rss=,vsz= -p $PPID'`);if(!S)return null;let C=/^(\d+)\s+(\d+)$/.exec(S);return C?{virtual:parseInt(C[2],10)*1024,resident:parseInt(C[1],10)*1024,data:0,peak:0}:null}var De,Oe=__esmMin(()=>{De=null,__name$1(readProcessMemory$4,`readProcessMemory`)});function glib(){let t=globalThis;if(typeof t.process?.versions?.gjs==`string`||t.process===void 0)return t.imports?.gi?.GLib}function arm(t){je||(je=!0,t.runAsync().catch(()=>{}))}function ensureMainLoop(){let t=glib();if(t)return Ae?ke:(ke=new t.MainLoop(null,!1),Ae=!0,t.main_depth()===0&&arm(ke),ke)}function holdMainLoop(){let t=ensureMainLoop();return t&&arm(t),t}function quitMainLoop(){ke&&=(ke.quit(),Ae=!1,je=!1,null)}var ke,Ae,je,Me=__esmMin(()=>{ke=null,Ae=!1,je=!1});function hostGi(){return globalThis.imports?.gi}function directoryOf(t){return/^(.*)[\\/][^\\/]*$/.exec(t)?.[1]}function colocateNativeLibrary(t,n=hostGi()){try{let S=n?.GIRepository?.Repository?.dup_default?.(),C=S?.get_typelib_path(t),N=C?directoryOf(C):void 0;return!S||!N?!1:(S.prepend_library_path(N),!0)}catch{return!1}}function probeNativeLibrary(t,n=hostGi()){try{let S=n?.GIRepository?.Repository?.dup_default?.(),C=S?.get_typelib_path(t);if(!n||!S||!C)return null;let N=firstSymbol(S,t);if(!N||(n.GModule?.module_error(),N.info.get_typelib().symbol(N.name)[0]))return null;let F=directoryOf(C)??`.`,I=C.includes(`\\`)&&!C.includes(`/`)?`\\`:`/`;for(let H of S.get_shared_libraries(t)??[]){let S=`${F}${I}${H}`,W=n.GLib?.file_test(S,n.GLib.FileTest.EXISTS)?S:H,q=loaderError(n,t,C,W,N.name);if(q!==void 0)return{namespace:t,library:W,reason:q,missingDependency:missingLibraryDependency(q,W)}}let H=(S.get_shared_libraries(t)??[]).join(`, `)||`(none named)`;return{namespace:t,library:H,reason:`symbol ${N.name} not found in ${H}, and the loader reported no error`}}catch{return null}}function firstSymbol(t,n){let S=t.get_n_infos(n),C=null;for(let N=0;N<S;N++){let S=t.get_info(n,N),F=S.get_type_init_function_name?.();if(F)return{info:S,name:F};let I=S.get_symbol?.();I&&!C&&(C={info:S,name:I})}return C}function loaderError(t,n,S,C,N){let{GIRepository:F,GLib:I,GModule:H}=t;if(!F?.Repository||!F.Typelib||!I||!H)return;let[,W]=I.file_get_contents(S),q=new TextEncoder().encode(`${C}\0`),Y=new Uint8Array(W.length+q.length);Y.set(W),Y.set(q,W.length);let X=new DataView(Y.buffer);X.setUint32(40,Y.length,!0),X.setUint32(52,W.length,!0);let Z=new F.Repository,te=firstSymbol(Z,Z.load_typelib(F.Typelib.new_from_bytes(new I.Bytes(Y)),0));if(te&&(H.module_error(),!te.info.get_typelib().symbol(N)[0]))return H.module_error()??`${n}: ${C} could not be opened (the loader reported no error)`}function missingLibraryDependency(t,n){let S=/Library not loaded: (\S+)/.exec(t)?.[1]??/Error loading shared library ([^\s:]+): .*\(needed by /.exec(t)?.[1]??/(?:^|\s)([^\s:]+): cannot open shared object file/.exec(t)?.[1];if(!S)return;let C=S.replace(/^.*[\\/]/,``);if(!(n&&C===n.replace(/^.*[\\/]/,``)))return C}function openNativeLibrary(t,n=hostGi()){colocateNativeLibrary(t,n);let S=probeNativeLibrary(t,n);return S?new NativeLibraryLoadError(S):null}function loadOptionalNativeModule(t,n,S=hostGi()){if(!S)return{module:null,error:Error(`${t}: imports.gi is not available (not running on GJS)`)};try{let C=S[t];if(!C)return{module:null,error:Error(`${t}: typelib not found`)};let N=openNativeLibrary(t,S);if(N)return ge.debug(N.message),{module:null,error:N};for(let t of n)C[t];return{module:C,error:null}}catch(t){return{module:null,error:t instanceof Error?t:Error(String(t))}}}var NativeLibraryLoadError,Fe=__esmMin(()=>{_e(),NativeLibraryLoadError=class extends Error{failure;constructor(t,n){let S=t.missingDependency?`It needs ${t.missingDependency}, which the loader could not find: not installed, or not on its search path.`:`The loader could not open it.`;super(`${t.namespace}: the native library ${t.library} could not be loaded. ${S}\nLoader: ${t.reason.trim()}\n`+(n??"`gjsify system-check` lists the system libraries the installed @gjsify packages need, with the install command for this host.")),this.name=`NativeLibraryLoadError`,this.failure=t}}});function drainOnce(t){let n=Math.min(64,Ie.length);for(let S=0;S<n;S++){let n=Ie.shift();try{n()}catch(n){try{t.log_default_handler(`gjsify-nextTick`,t.LogLevelFlags.LEVEL_WARNING,String(n?.stack||n),null)}catch{}}}Ie.length>0?t.timeout_add(t.PRIORITY_DEFAULT,1,()=>(drainOnce(t),!1)):Le=!1}function tryGLibTimeout(t){let n=globalThis.imports?.gi?.GLib;return n?.timeout_add?(Ie.push(t),Le||(Le=!0,n.timeout_add(n.PRIORITY_DEFAULT,0,()=>(drainOnce(n),!1))),!0):!1}var Ie,Le,nextTick,Re=__esmMin(()=>{Ie=[],Le=!1,nextTick=(t,...n)=>{let S=n.length>0?()=>t(...n):t;if(!tryGLibTimeout(S)){if(typeof globalThis.process?.nextTick==`function`){globalThis.process.nextTick(t,...n);return}if(typeof queueMicrotask==`function`){queueMicrotask(S);return}Promise.resolve().then(S)}}}),ze=__esmMin(()=>{ie(),oe(),se(),ce(),ue(),ye(),xe(),Se(),Ee(),Oe(),Me(),Fe(),Re()});re(),ze(),registerGlobal(`Blob`,te),registerGlobal(`File`,ne);function atobPolyfill(t){if(typeof globalThis.atob==`function`)return globalThis.atob(t);let n=t.replace(/[=\s]/g,``),S=``,C=0,N=0;for(let t=0;t<n.length;t++)C=C<<6|Ve[n.charCodeAt(t)],N+=6,N>=8&&(N-=8,S+=String.fromCharCode(C>>N&255));return S}function btoaPolyfill(t){if(typeof globalThis.btoa==`function`)return globalThis.btoa(t);let n=``,S=0;for(;S+2<t.length;S+=3){let C=t.charCodeAt(S)<<16|t.charCodeAt(S+1)<<8|t.charCodeAt(S+2);n+=Be[C>>18&63]+Be[C>>12&63]+Be[C>>6&63]+Be[C&63]}if(S+1===t.length){let C=t.charCodeAt(S)<<16;n+=Be[C>>18&63]+Be[C>>12&63]+`==`}else if(S+2===t.length){let C=t.charCodeAt(S)<<16|t.charCodeAt(S+1)<<8;n+=Be[C>>18&63]+Be[C>>12&63]+Be[C>>6&63]+`=`}return n}function base64Decode$2(t){let n=t.replace(/[=\s]/g,``),S=new Uint8Array(n.length*3>>2),C=0,N=0,F=0;for(let t=0;t<n.length;t++)C=C<<6|Ve[n.charCodeAt(t)],N+=6,N>=8&&(N-=8,S[F++]=C>>N&255);return S.subarray(0,F)}function base64Encode$1(t){let n=``,S=t.length;for(let C=0;C<S;C+=3){let N=t[C],F=C+1<S?t[C+1]:0,I=C+2<S?t[C+2]:0;n+=Be[N>>2],n+=Be[(N&3)<<4|F>>4],n+=C+1<S?Be[(F&15)<<2|I>>6]:`=`,n+=C+2<S?Be[I&63]:`=`}return n}var Be,Ve,He=__esmMin(()=>{Be=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ve=new Uint8Array(256);for(let t=0;t<64;t++)Ve[Be.charCodeAt(t)]=t;__name$1(base64Decode$2,`base64Decode`),__name$1(base64Encode$1,`base64Encode`)});function normalizeEncoding(t){if(!t||t===`utf8`||t===`utf-8`)return`utf8`;switch((``+t).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(t){let n=(``+t).toLowerCase().replace(/-/g,``);if(!Ue.includes(n))throw TypeError(`Unknown encoding: ${t}`)}var Ue,Ge=__esmMin(()=>{Ue=[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`]});function encodeString(t,n){switch(n){case`utf8`:return textEncoder().encode(t);case`ascii`:{let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&127;return n}case`latin1`:{let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&255;return n}case`base64`:return base64Decode$2(t.replace(/-/g,`+`).replace(/_/g,`/`));case`base64url`:return encodeString(t.replace(/-/g,`+`).replace(/_/g,`/`),`base64`);case`hex`:{let n=t.length>>>1,S=new Uint8Array(n);for(let C=0;C<n;C++){let n=parseInt(t[C*2],16),N=parseInt(t[C*2+1],16);if(Number.isNaN(n)||Number.isNaN(N))break;S[C]=n<<4|N}return S}case`utf16le`:{let n=new Uint8Array(t.length*2);for(let S=0;S<t.length;S++){let C=t.charCodeAt(S);n[S*2]=C&255,n[S*2+1]=C>>8&255}return n}default:return textEncoder().encode(t)}}function decodeString(t,n,S,C){let N=S!==void 0||C!==void 0?t.subarray(S??0,C??t.length):t;switch(n){case`utf8`:return textDecoder().decode(N);case`ascii`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]&127);return t}case`latin1`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]);return t}case`base64`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]);return btoaPolyfill(t)}case`base64url`:return decodeString(N,`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);case`hex`:{let t=``;for(let n=0;n<N.length;n++)t+=N[n].toString(16).padStart(2,`0`);return t}case`utf16le`:{let t=``;for(let n=0;n+1<N.length;n+=2)t+=String.fromCharCode(N[n]|N[n+1]<<8);return t}default:return textDecoder().decode(N)}}function checkOffset(t,n,S){if(t+n>S)throw RangeError(`Attempt to access memory outside buffer bounds`)}var Ke,qe,textEncoder,textDecoder,Je=__esmMin(()=>{He(),textEncoder=()=>Ke??=new TextEncoder,textDecoder=()=>qe??=new TextDecoder}),Ye,Xe,Ze,Qe,$e,SlowBuffer,et=__esmMin(()=>{Je(),Ge(),Ye=typeof SharedArrayBuffer<`u`,Xe=class Buffer extends Uint8Array{static _isBuffer=!0;static alloc(t,n,S){if(typeof t!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof t}`);if(t<0)throw RangeError(`The value "${t}" is invalid for option "size"`);let C=new Buffer(t);return n!==void 0&&n!==0&&C.fill(n,0,t,S),C}static allocUnsafe(t){if(typeof t!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof t}`);return new Buffer(t)}static allocUnsafeSlow(t){return Buffer.allocUnsafe(t)}static from(t,n,S){if(typeof t==`string`){let S=normalizeEncoding(n);if(n&&typeof n==`string`){let t=(``+n).toLowerCase().replace(/-/g,``);[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`,``].includes(t)||checkEncoding(n)}let C=encodeString(t,S);return new Buffer(C.buffer,C.byteOffset,C.byteLength)}if(ArrayBuffer.isView(t)){let n=new Buffer(t.buffer,t.byteOffset,t.byteLength),S=new Buffer(n.length);return S.set(n),S}if(t instanceof ArrayBuffer){let C=n||0,N=S===void 0?t.byteLength-C:S;return new Buffer(t,C,N)}if(Ye&&t instanceof SharedArrayBuffer){let C=n||0,N=S===void 0?t.byteLength-C:S;return new Buffer(new Uint8Array(t,C,N))}if(typeof t==`object`&&t&&typeof t.viewBytes==`function`&&typeof t.byteLength==`number`&&t.constructor?.name===`SharedBuffer`){let C=t,N=n||0,F=S===void 0?C.byteLength-N:S,I=C.viewBytes(N,F);return new Buffer(I.buffer,I.byteOffset,I.byteLength)}if(Array.isArray(t)){let n=new Buffer(t.length);for(let S=0;S<t.length;S++)n[S]=t[S]&255;return n}throw TypeError(`The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array`)}static isBuffer(t){return t instanceof Buffer}static isEncoding(t){if(typeof t!=`string`)return!1;let n=t.toLowerCase().replace(/-/g,``);return[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`].includes(n)}static byteLength(t,n){if(typeof t!=`string`){if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer||Ye&&t instanceof SharedArrayBuffer)return t.byteLength;throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer`)}switch(normalizeEncoding(n)){case`utf8`:return new TextEncoder().encode(t).byteLength;case`ascii`:case`latin1`:return t.length;case`base64`:case`base64url`:{let n=t.length;for(;n>0&&(t[n-1]===`=`||t[n-1]===` `);)n--;return n*3>>>2}case`hex`:return t.length>>>1;case`utf16le`:return t.length*2;default:return new TextEncoder().encode(t).byteLength}}static compare(t,n){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array))throw TypeError(`Arguments must be Buffers or Uint8Arrays`);let S=Math.min(t.length,n.length);for(let C=0;C<S;C++){if(t[C]<n[C])return-1;if(t[C]>n[C])return 1}return t.length<n.length?-1:+(t.length>n.length)}static concat(t,n){if(t.length===0)return Buffer.alloc(0);if(n===void 0){n=0;for(let S=0;S<t.length;S++)n+=t[S].length}let S=Buffer.alloc(n),C=0;for(let N=0;N<t.length;N++){let F=t[N],I=Math.min(F.length,n-C);I<=0||(S.set(F.subarray(0,I),C),C+=I)}return S}static poolSize=65536;toString(t,n,S){let C=normalizeEncoding(t);return decodeString(this,C,n,S)}toJSON(){return{type:`Buffer`,data:Array.from(this)}}equals(t){if(!(t instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);if(this.length!==t.length)return!1;for(let n=0;n<this.length;n++)if(this[n]!==t[n])return!1;return!0}compare(t,n,S,C,N){if(!(t instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);let F=C!==void 0||N!==void 0?this.subarray(C??0,N??this.length):this,I=n!==void 0||S!==void 0?t.subarray(n??0,S??t.length):t;return Buffer.compare(F,I)}copy(t,n=0,S=0,C){let N=C??this.length,F=Math.min(N-S,t.length-n);return F<=0?0:(t.set(this.subarray(S,S+F),n),F)}slice(t,n){let S=t??0,C=n??this.length,N=super.subarray(S,C);return new Buffer(N.buffer,N.byteOffset,N.byteLength)}subarray(t,n){let S=super.subarray(t,n);return new Buffer(S.buffer,S.byteOffset,S.byteLength)}write(t,n,S,C){n??=0;let N=encodeString(t,normalizeEncoding(C||(typeof S==`string`?S:void 0))),F=S!==void 0&&typeof S==`number`?Math.min(S,this.length-n):this.length-n,I=Math.min(N.length,F);return this.set(N.subarray(0,I),n),I}fill(t,n,S,C){let N=n??0,F=S??this.length;if(typeof t==`number`)super.fill(t&255,N,F);else if(typeof t==`string`){let n=encodeString(t,normalizeEncoding(C));if(n.length===0)super.fill(0,N,F);else if(n.length===1)super.fill(n[0],N,F);else for(let t=N;t<F;t++)this[t]=n[(t-N)%n.length]}else if(t instanceof Uint8Array)if(t.length===0)super.fill(0,N,F);else for(let n=N;n<F;n++)this[n]=t[(n-N)%t.length];return this}indexOf(t,n,S){if(typeof t==`number`)return super.indexOf(t&255,n);let C=typeof t==`string`?encodeString(t,normalizeEncoding(S)):t,N=n??0;outer:for(let t=N;t<=this.length-C.length;t++){for(let n=0;n<C.length;n++)if(this[t+n]!==C[n])continue outer;return t}return-1}lastIndexOf(t,n,S){if(typeof t==`number`)return n===void 0?super.lastIndexOf(t&255):super.lastIndexOf(t&255,n);let C=typeof t==`string`?encodeString(t,normalizeEncoding(S)):t,N=n===void 0?this.length-C.length:Math.min(n,this.length-C.length);outer:for(let t=N;t>=0;t--){for(let n=0;n<C.length;n++)if(this[t+n]!==C[n])continue outer;return t}return-1}includes(t,n,S){return this.indexOf(t,n,S)!==-1}readUInt8(t=0){return checkOffset(t,1,this.length),this[t]}readUInt16BE(t=0){return checkOffset(t,2,this.length),this[t]<<8|this[t+1]}readUInt16LE(t=0){return checkOffset(t,2,this.length),this[t]|this[t+1]<<8}readUInt32BE(t=0){return checkOffset(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])}readUInt32LE(t=0){return checkOffset(t,4,this.length),this[t+3]*16777216+(this[t+2]<<16|this[t+1]<<8|this[t])>>>0}readInt8(t=0){return checkOffset(t,1,this.length),this[t]|(this[t]&128?4294967040:0)}readInt16BE(t=0){checkOffset(t,2,this.length);let n=this[t]<<8|this[t+1];return n&32768?n|4294901760:n}readInt16LE(t=0){checkOffset(t,2,this.length);let n=this[t]|this[t+1]<<8;return n&32768?n|4294901760:n}readInt32BE(t=0){return checkOffset(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]}readInt32LE(t=0){return checkOffset(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24}readFloatBE(t=0){return checkOffset(t,4,this.length),new DataView(this.buffer,this.byteOffset+t,4).getFloat32(0,!1)}readFloatLE(t=0){return checkOffset(t,4,this.length),new DataView(this.buffer,this.byteOffset+t,4).getFloat32(0,!0)}readDoubleBE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getFloat64(0,!1)}readDoubleLE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getFloat64(0,!0)}readBigInt64BE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigInt64(0,!1)}readBigInt64LE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigInt64(0,!0)}readBigUInt64BE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigUint64(0,!1)}readBigUInt64LE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigUint64(0,!0)}readUIntBE(t,n){checkOffset(t,n,this.length);let S=0;for(let C=0;C<n;C++)S=S*256+this[t+C];return S}readUIntLE(t,n){checkOffset(t,n,this.length);let S=0,C=1;for(let N=0;N<n;N++)S+=this[t+N]*C,C*=256;return S}readIntBE(t,n){checkOffset(t,n,this.length);let S=0;for(let C=0;C<n;C++)S=S*256+this[t+C];return S>=2**(8*n-1)&&(S-=2**(8*n)),S}readIntLE(t,n){checkOffset(t,n,this.length);let S=0,C=1;for(let N=0;N<n;N++)S+=this[t+N]*C,C*=256;return S>=2**(8*n-1)&&(S-=2**(8*n)),S}writeUInt8(t,n=0){return checkOffset(n,1,this.length),this[n]=t&255,n+1}writeUInt16BE(t,n=0){return checkOffset(n,2,this.length),this[n]=t>>>8&255,this[n+1]=t&255,n+2}writeUInt16LE(t,n=0){return checkOffset(n,2,this.length),this[n]=t&255,this[n+1]=t>>>8&255,n+2}writeUInt32BE(t,n=0){return checkOffset(n,4,this.length),this[n]=t>>>24&255,this[n+1]=t>>>16&255,this[n+2]=t>>>8&255,this[n+3]=t&255,n+4}writeUInt32LE(t,n=0){return checkOffset(n,4,this.length),this[n]=t&255,this[n+1]=t>>>8&255,this[n+2]=t>>>16&255,this[n+3]=t>>>24&255,n+4}writeInt8(t,n=0){return checkOffset(n,1,this.length),t<0&&(t=255+t+1),this[n]=t&255,n+1}writeInt16BE(t,n=0){return checkOffset(n,2,this.length),this[n]=t>>>8&255,this[n+1]=t&255,n+2}writeInt16LE(t,n=0){return checkOffset(n,2,this.length),this[n]=t&255,this[n+1]=t>>>8&255,n+2}writeInt32BE(t,n=0){return checkOffset(n,4,this.length),this[n]=t>>>24&255,this[n+1]=t>>>16&255,this[n+2]=t>>>8&255,this[n+3]=t&255,n+4}writeInt32LE(t,n=0){return checkOffset(n,4,this.length),this[n]=t&255,this[n+1]=t>>>8&255,this[n+2]=t>>>16&255,this[n+3]=t>>>24&255,n+4}writeFloatBE(t,n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).setFloat32(0,t,!1),n+4}writeFloatLE(t,n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).setFloat32(0,t,!0),n+4}writeDoubleBE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setFloat64(0,t,!1),n+8}writeDoubleLE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setFloat64(0,t,!0),n+8}writeBigInt64BE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigInt64(0,t,!1),n+8}writeBigInt64LE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigInt64(0,t,!0),n+8}writeBigUInt64BE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigUint64(0,t,!1),n+8}writeBigUInt64LE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigUint64(0,t,!0),n+8}readUint8(t=0){return this.readUInt8(t)}readUint16BE(t=0){return this.readUInt16BE(t)}readUint16LE(t=0){return this.readUInt16LE(t)}readUint32BE(t=0){return this.readUInt32BE(t)}readUint32LE(t=0){return this.readUInt32LE(t)}readUintBE(t,n){return this.readUIntBE(t,n)}readUintLE(t,n){return this.readUIntLE(t,n)}readBigUint64BE(t=0){return this.readBigUInt64BE(t)}readBigUint64LE(t=0){return this.readBigUInt64LE(t)}writeUint8(t,n=0){return this.writeUInt8(t,n)}writeUint16BE(t,n=0){return this.writeUInt16BE(t,n)}writeUint16LE(t,n=0){return this.writeUInt16LE(t,n)}writeUint32BE(t,n=0){return this.writeUInt32BE(t,n)}writeUint32LE(t,n=0){return this.writeUInt32LE(t,n)}writeBigUint64BE(t,n=0){return this.writeBigUInt64BE(t,n)}writeBigUint64LE(t,n=0){return this.writeBigUInt64LE(t,n)}swap16(){let t=this.length;if(t%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let n=0;n<t;n+=2){let t=this[n];this[n]=this[n+1],this[n+1]=t}return this}swap32(){let t=this.length;if(t%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let n=0;n<t;n+=4){let t=this[n],S=this[n+1];this[n]=this[n+3],this[n+1]=this[n+2],this[n+2]=S,this[n+3]=t}return this}swap64(){let t=this.length;if(t%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let n=0;n<t;n+=8){let t=this[n],S=this[n+1],C=this[n+2],N=this[n+3];this[n]=this[n+7],this[n+1]=this[n+6],this[n+2]=this[n+5],this[n+3]=this[n+4],this[n+4]=N,this[n+5]=C,this[n+6]=S,this[n+7]=t}return this}},Ze=2**31-1,Qe=2**28-16,$e={MAX_LENGTH:Ze,MAX_STRING_LENGTH:Qe},SlowBuffer=class extends Xe{constructor(t){super(t)}}}),tt=__exportAll$5({Blob:()=>te,Buffer:()=>Xe,File:()=>ne,INSPECT_MAX_BYTES:()=>50,SlowBuffer:()=>SlowBuffer,atob:()=>nt,atobPolyfill:()=>atobPolyfill,base64Decode:()=>base64Decode$2,base64Encode:()=>base64Encode$1,btoa:()=>rt,btoaPolyfill:()=>btoaPolyfill,checkEncoding:()=>checkEncoding,constants:()=>$e,default:()=>it,kMaxLength:()=>Ze,kStringMaxLength:()=>Qe,normalizeEncoding:()=>normalizeEncoding}),nt,rt,it,ot=__esmMin(()=>{He(),re(),Ge(),et(),nt=globalThis.atob,rt=globalThis.btoa,it={Buffer:Xe,SlowBuffer,Blob:te,File:ne,atob:nt,btoa:rt,kMaxLength:Ze,kStringMaxLength:Qe,constants:$e,INSPECT_MAX_BYTES:50}});ot(),`Buffer`in globalThis||Object.defineProperty(globalThis,"Buffer",{value:Xe,enumerable:!1,writable:!0,configurable:!0});var st,ct=__esmMin(()=>{st=t}),lt,ut=__esmMin(()=>{ct(),lt=st});ut(),typeof globalThis.btoa!=`function`&&Object.defineProperty(globalThis,"btoa",{value:function btoa(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&255;return lt.base64_encode(n)},enumerable:!0,writable:!0,configurable:!0}),typeof globalThis.atob!=`function`&&Object.defineProperty(globalThis,"atob",{value:function atob(t){let n=lt.base64_decode(t),S=``;for(let t=0;t<n.length;t++)S+=String.fromCharCode(n[t]);return S},enumerable:!0,writable:!0,configurable:!0}),ze(),typeof queueMicrotask!=`function`&&Object.defineProperty(globalThis,"queueMicrotask",{value:ve,enumerable:!0,writable:!0,configurable:!0});function getGjsGlobal(){return globalThis}function getGioNamespace(){let t=getGjsGlobal().imports?.gi;if(!t)return null;let n=null;try{n=t.GioUnix??null}catch{}if(!n)try{n=t.Gio??null}catch{}return n}var dt=__esmMin(()=>{});function getMonotonicTime(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t?.get_monotonic_time)return BigInt(t.get_monotonic_time())*1000n}catch{}return typeof performance?.now==`function`?BigInt(Math.round(performance.now()*1e6)):BigInt(Date.now())*1000000n}function hrtime(t){let n=getMonotonicTime()-ft,S=Number(n/1000000000n),C=Number(n%1000000000n);if(t){let n=S-t[0],N=C-t[1];return N<0&&(n--,N+=1e9),[n,N]}return[S,C]}function hrtimeBigint(){return getMonotonicTime()-ft}var ft,pt=__esmMin(()=>{dt(),ft=getMonotonicTime()});function probeUname(){if(mt!==void 0)return mt;mt=null;try{let t=getGjsGlobal().imports?.gi?.GLib;if(!t)return mt;let n=t.spawn_sync,S=t.SpawnFlags?.SEARCH_PATH;if(!n||S===void 0)return mt;let[C,N]=n(null,[`uname`,`-sm`],null,S,null);if(!C||!N)return mt;let F=new TextDecoder().decode(N).trim().split(/\s+/);if(F.length<2)return mt;let I=mapSysname(F[0]),H=mapMachine(F[F.length-1]);if(!I||!H)return mt;mt={platform:I,arch:H}}catch{}return mt}var mt,ht=__esmMin(()=>{dt(),ze()});function detectGjsVersion(){try{let t=getGjsGlobal().imports?.system;if(t?.version!==void 0){let n=Number(t.version);return`${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%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 t=detectGjsVersion(),n={node:`20.0.0`};return t&&(n.gjs=t),{version:`v20.0.0`,versions:n,title:`gjs`}}function detectPpid(){let t=runtimeProcess();return t&&typeof t.ppid==`number`?t.ppid:hostPpid()??0}function runtimeProcess(){let t=globalThis.process;return typeof t?.release?.name==`string`?t:void 0}function onGjs(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function detectPlatform$1(){let t=runtimeProcess();if(t)return t.platform;if(onGjs()){let t=probeUname();if(t)return t.platform}return`linux`}function detectArch(){let t=runtimeProcess();if(t)return t.arch;if(onGjs()){let t=probeUname();if(t)return t.arch}return`x64`}function getPid$1(){let t=runtimeProcess();return t&&typeof t.pid==`number`?t.pid:hostPid()??0}var gt=__esmMin(()=>{dt(),ht(),ze(),__name$1(detectPlatform$1,`detectPlatform`),__name$1(getPid$1,`getPid`)});function getEnvProxy(){if(typeof globalThis.process?.env==`object`)return globalThis.process.env;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t)return new Proxy({},{get(n,S){if(typeof S==`string`)return t.getenv(S)??void 0},set(n,S,C){return typeof S==`string`?(t.setenv(S,String(C),!0),!0):!1},deleteProperty(n,S){return typeof S==`string`?(t.unsetenv(S),!0):!1},has(n,S){return typeof S==`string`?t.getenv(S)!==null:!1},ownKeys(n){return t.listenv()},getOwnPropertyDescriptor(n,S){if(typeof S!=`string`)return;let C=t.getenv(S);if(C!==null)return{configurable:!0,enumerable:!0,writable:!0,value:C}}})}catch{}return{}}function getArgv(){if(globalThis.process?.argv!==void 0)return globalThis.process.argv;try{let t=getGjsGlobal().imports?.system;if(t?.programArgs)return[`gjs`,t.programInvocationName||``,...t.programArgs]}catch{}return[`gjs`]}function getExecPath(){let t=globalThis.process;return!isGjsHost()&&typeof t?.execPath==`string`?t.execPath:hostExecPath()??`/usr/bin/gjs`}function isGjsHost(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function getCwd(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t?.get_current_dir)return t.get_current_dir()}catch{}return`/`}function chdir(t){let n=getGjsGlobal().imports?.gi?.GLib;try{if(n?.chdir){if(!n.file_test(t,16)){let n=Error(`ENOENT: no such file or directory, chdir '${t}'`);throw n.code=`ENOENT`,n.syscall=`chdir`,n.path=t,n}n.chdir(t);return}}catch(t){if(t&&typeof t==`object`&&t.code===`ENOENT`)throw t}if(!n){let n=globalThis.process;if(n&&typeof n.chdir==`function`){n.chdir(t);return}}throw Error(`process.chdir() is not supported in this environment`)}var _t=__esmMin(()=>{dt(),ze()});function exitProcess(t){let n=getGjsGlobal().imports,S=n?.gi?.GLib,C=n?.system,N=S?.idle_add,F=S?.SOURCE_REMOVE,I=S?.PRIORITY_DEFAULT,H=S?.MainContext;if(C?.exit&&N&&typeof I==`number`&&typeof F==`boolean`&&typeof H?.default==`function`){N(I,()=>(C.exit(t),F));let n=H.default();for(;;)n.iteration(!0)}try{C?.exit&&C.exit(t)}catch{}let W=globalThis.process;throw W&&typeof W.exit==`function`&&W.exit(t),Error(`process.exit(${t})`)}var vt=__esmMin(()=>{dt()});function isGjs$1(){return getGjsGlobal().imports?.gi?.GLib!==void 0}function classifyKillFailure(t){if(/No such process/i.test(t))return`ESRCH`;if(/Operation not permitted/i.test(t))return`EPERM`}function killPid(t,n){let S=getGjsGlobal().imports?.gi?.GLib;if(S){let C=typeof n==`number`?String(n):n||`SIGTERM`,N=[`kill`,C.startsWith(`SIG`)?`-${C.slice(3)}`:`-${C}`,`--`,String(t)],F=S.environ_setenv(S.get_environ(),`LC_ALL`,`C`,!0),[,,I,H]=S.spawn_sync(null,N,F,4,null),W=!1;try{W=S.spawn_check_wait_status(H)}catch{W=!1}if(W)return!0;let q=I?new TextDecoder().decode(I).trim():``,Y=classifyKillFailure(q),X=Error(Y?`kill ${Y}`:`kill failed${q?`: ${q}`:``}`);throw Y&&(X.code=Y,X.errno=Y===`ESRCH`?-3:-1,X.syscall=`kill`),X}let C=globalThis.process;if(C&&typeof C.kill==`function`)return C.kill(t,n);throw Error(`process.kill() is not supported in this environment`)}function memoryUsage(){let t=readProcessMemory$4();if(t)return{rss:t.resident,heapTotal:t.resident,heapUsed:t.resident,external:0,arrayBuffers:0};if(!isGjs$1()){let t=globalThis.process;if(t&&typeof t.memoryUsage==`function`)return t.memoryUsage()}return{rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}}function cpuUsage(t){if(!isGjs$1()){let n=globalThis.process;if(n&&typeof n.cpuUsage==`function`)return n.cpuUsage(t)}return{user:0,system:0}}function readUmask(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let[n,S]=t.file_get_contents(`/proc/self/status`);if(n){let t=/^Umask:\s*([0-7]+)/m.exec(new TextDecoder().decode(S));if(t)return parseInt(t[1],8)}}}catch{}return 18}var yt=__esmMin(()=>{dt(),ze(),__name$1(isGjs$1,`isGjs`)});function resolveSignalAdd(){let t=getGjsGlobal().imports?.gi;if(!t)return null;for(let[n,S]of[[`GLibUnix`,`signal_add`],[`GLib`,`unix_signal_add`]])try{let C=t[n]?.[S];if(typeof C==`function`)return C}catch{}return null}function isDeliverableSignal(t){return typeof t==`string`&&t in bt}function armSignal(t,n){if(xt.has(t))return;let S=bt[t],C=resolveSignalAdd(),N=getGjsGlobal().imports?.gi?.GLib;if(S===void 0||C===null||!N)return;let F=N.PRIORITY_DEFAULT,I=C(F,S,()=>(n(t),!0));xt.set(t,I)}function disarmSignal(t){let n=xt.get(t);if(n===void 0)return;xt.delete(t);let S=getGjsGlobal().imports?.gi?.GLib;S&&typeof S.source_remove==`function`&&S.source_remove(n)}var bt,xt,St=__esmMin(()=>{dt(),bt={SIGHUP:1,SIGINT:2,SIGTERM:15},xt=new Map});function claimRawMode(t,n){Tt.set(t,n)}function releaseRawMode(t){Tt.delete(t)}function noteRawMode(t,n,S){let C=S(n);return n?C&&claimRawMode(t,()=>{S(!1)}):releaseRawMode(t),C}function restoreClaimedRawModes(){let t=[...Tt.entries()];Tt.clear();let n=0,S;for(let[,C]of t)try{C(),n+=1}catch(t){S??=t}if(S!==void 0)throw S;return n}var Ct,wt,Tt,Et=__esmMin(()=>{Ct=Symbol.for(`@gjsify/terminal-native:raw-mode-claims`),wt=globalThis,Tt=wt[Ct]??=new Map});function callableModule(){if(!Ot)return null;try{return Ot.Terminal.is_tty(2),Ot}catch{return null}}function nativeIsTty(t){try{return callableModule()?.Terminal.is_tty(t)??null}catch{return null}}function nativeTerminalSize(t){try{let[n,S,C]=callableModule()?.Terminal.get_size(t)??[!1,0,0];return!n||C<=0?null:{rows:S,columns:C}}catch{return null}}function nativeSetRawMode(t,n){try{return callableModule()?.Terminal.set_raw_mode(t,n)??null}catch{return null}}var Dt,Ot,kt,At=__esmMin(()=>{Et(),ze(),Dt=loadOptionalNativeModule(`GjsifyTerminal`,[`Terminal`,`ResizeWatcher`]),Ot=Dt.module,kt=Ot});function onceWrapper(){let{target:t,type:n,listener:S}=this;return this.wrapperFn&&t.removeListener(n,this.wrapperFn),S.apply(t,Array.from(arguments))}function _onceWrap(t,n,S){let C={target:t,type:n,listener:S,wrapperFn:void 0},N=onceWrapper.bind(C);return C.wrapperFn=N,N.listener=S,N}function arrayClone(t){switch(t.length){case 0:return[];case 1:return[t[0]];case 2:return[t[0],t[1]];case 3:return[t[0],t[1],t[2]];default:return t.slice()}}function checkListener(t){if(typeof t!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof t)}function validateNumber(t,n){if(typeof t!=`number`||t!==t)throw TypeError(`The "${n}" argument must be of type number. Received type ${typeof t}`)}function spliceOne(t,n){for(;n+1<t.length;n++)t[n]=t[n+1];t.pop()}function unwrapListeners(t){let n=Array.from({length:t.length});for(let S=0;S<n.length;++S)n[S]=t[S].listener??t[S];return n}function createAbortError$2(t){let n=Error(`The operation was aborted`);return n.name=`AbortError`,n.code=`ABORT_ERR`,t?.reason&&(n.cause=t.reason),n}var jt,Mt,Nt,Pt=__esmMin(()=>{_e(),jt=Symbol(`kCapture`),Mt=Symbol.for(`nodejs.rejection`),Nt=class EventEmitter{static defaultMaxListeners=10;static errorMonitor=Symbol(`events.errorMonitor`);static captureRejectionSymbol=Mt;static _captureRejections=!1;static get captureRejections(){return EventEmitter._captureRejections}static set captureRejections(t){if(typeof t!=`boolean`)throw TypeError(`The "captureRejections" argument must be of type boolean.`);EventEmitter._captureRejections=t}_events;_eventsCount;_maxListeners;[jt];constructor(t){this._events=Object.create(null),this._eventsCount=0,this._maxListeners=void 0,this[jt]=t?.captureRejections??EventEmitter._captureRejections}setMaxListeners(t){if(validateNumber(t,`n`),t<0)throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+t);return this._maxListeners=t,this}getMaxListeners(){return this._maxListeners??EventEmitter.defaultMaxListeners}emit(t,...n){let S=this._events,C=t===`error`;if(S!==void 0)C&&S[EventEmitter.errorMonitor]!==void 0&&this.emit(EventEmitter.errorMonitor,...n),C&&=S.error===void 0;else if(!C)return!1;if(C){let t;if(t=n.length>0?n[0]:Error(`Unhandled error.`),t instanceof Error)throw t;let S=Error(`Unhandled error. (`+t+`)`);throw S.context=t,S}let N=S[t];if(N===void 0)return!1;if(typeof N==`function`){let S=N.apply(this,n);S!=null&&this[jt]&&this._addCatch(S,t,n)}else{let S=arrayClone(N),C=S.length;for(let N=0;N<C;++N){let C=S[N].apply(this,n);C!=null&&this[jt]&&this._addCatch(C,t,n)}}return!0}_addCatch(t,n,S){typeof t?.then==`function`&&t.then(void 0,t=>{let C=this[Mt];if(typeof C==`function`)C.call(this,t,n,...S);else{let n=this[jt];try{this[jt]=!1,this.emit(`error`,t)}finally{this[jt]=n}}})}addListener(t,n){return this._addListener(t,n,!1)}on(t,n){return this._addListener(t,n,!1)}prependListener(t,n){return this._addListener(t,n,!0)}_addListener(t,n,S){checkListener(n);let C=this._events;C===void 0?(C=this._events=Object.create(null),this._eventsCount=0):C.newListener!==void 0&&(this.emit(`newListener`,t,n.listener??n),C=this._events);let N=C[t];N===void 0?(C[t]=n,++this._eventsCount):typeof N==`function`?C[t]=S?[n,N]:[N,n]:S?N.unshift(n):N.push(n);let F=this.getMaxListeners();if(F>0){let n=typeof C[t]==`function`?1:C[t].length;if(n>F&&!C[t].warned){typeof C[t]!=`function`&&(C[t].warned=!0);let S=Error(`Possible EventEmitter memory leak detected. ${n} ${String(t)} listeners added to [${this.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);S.name=`MaxListenersExceededWarning`,ge.warn(S.message)}}return this}once(t,n){return checkListener(n),this.on(t,_onceWrap(this,t,n)),this}prependOnceListener(t,n){return checkListener(n),this.prependListener(t,_onceWrap(this,t,n)),this}removeListener(t,n){checkListener(n);let S=this._events;if(S===void 0)return this;let C=S[t];if(C===void 0)return this;if(C===n||C.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete S[t],S.removeListener&&this.emit(`removeListener`,t,C.listener??n));else if(typeof C!=`function`){let N=-1;for(let t=C.length-1;t>=0;t--)if(C[t]===n||C[t].listener===n){N=t;break}if(N<0)return this;N===0?C.shift():spliceOne(C,N),C.length===1&&(S[t]=C[0]),S.removeListener!==void 0&&this.emit(`removeListener`,t,n.listener??n)}return this}off(t,n){return this.removeListener(t,n)}removeAllListeners(t){let n=this._events;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){let t=Object.keys(n);for(let n=0;n<t.length;++n){let S=t[n];S!==`removeListener`&&this.removeAllListeners(S)}return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}let S=n[t];if(typeof S==`function`)this.removeListener(t,S);else if(S!==void 0)for(let n=S.length-1;n>=0;n--)this.removeListener(t,S[n]);return this}listeners(t){let n=this._events;if(n===void 0)return[];let S=n[t];return S===void 0?[]:typeof S==`function`?[S.listener??S]:unwrapListeners(S)}rawListeners(t){let n=this._events;if(n===void 0)return[];let S=n[t];return S===void 0?[]:typeof S==`function`?[S]:arrayClone(S)}listenerCount(t){let n=this._events;if(n===void 0)return 0;let S=n[t];return S===void 0?0:typeof S==`function`?1:S.length}eventNames(){return(this._eventsCount??0)>0?Reflect.ownKeys(this._events):[]}static once(t,n,S){return new Promise((C,N)=>{let F=S?.signal;if(F?.aborted){N(createAbortError$2(F));return}if(typeof t.addEventListener==`function`){let S=t,handler=(...t)=>{F&&F.removeEventListener(`abort`,abortHandler),C(t)},errorHandler=t=>{F&&F.removeEventListener(`abort`,abortHandler),S.removeEventListener(`error`,errorHandler),N(t)},abortHandler=()=>{S.removeEventListener(n,handler),S.removeEventListener(`error`,errorHandler),N(createAbortError$2(F))};S.addEventListener(n,handler,{once:!0}),n!==`error`&&S.addEventListener(`error`,errorHandler,{once:!0}),F&&F.addEventListener(`abort`,abortHandler,{once:!0});return}let I=t,eventHandler=(...t)=>{F&&F.removeEventListener(`abort`,abortHandler),errorHandler!==void 0&&I.removeListener(`error`,errorHandler),C(t)},errorHandler;n!==`error`&&(errorHandler=t=>{I.removeListener(n,eventHandler),F&&F.removeEventListener(`abort`,abortHandler),N(t)},I.once(`error`,errorHandler)),I.once(n,eventHandler);let abortHandler=()=>{I.removeListener(n,eventHandler),errorHandler&&I.removeListener(`error`,errorHandler),N(createAbortError$2(F))};F&&F.addEventListener(`abort`,abortHandler,{once:!0})})}static on(t,n,S){let C=S?.signal;if(C?.aborted)throw createAbortError$2(C);let N=S?.highWaterMark??2**53-1,F=S?.lowWaterMark??1;validateNumber(N,`highWaterMark`),validateNumber(F,`lowWaterMark`);let I=[],H=[],W=null,q=!1,Y=!1,eventHandler=(...n)=>{if(H.length>0){let{resolve:t}=H.shift();t({value:n,done:!1})}else I.push(n),I.length>=N&&!Y&&(Y=!0,typeof t.pause==`function`&&t.pause())},errorHandler=t=>{if(W=t,H.length>0){let{reject:n}=H.shift();n(t)}X.return()},abortHandler=()=>{errorHandler(createAbortError$2(C))};t.on(n,eventHandler),n!==`error`&&t.on(`error`,errorHandler),C&&C.addEventListener(`abort`,abortHandler,{once:!0});let cleanup=()=>{t.removeListener(n,eventHandler),t.removeListener(`error`,errorHandler),C&&C.removeEventListener(`abort`,abortHandler),q=!0;for(let{resolve:t}of H)t({value:void 0,done:!0});H.length=0,I.length=0},X={next(){if(I.length>0){let n=I.shift();return Y&&I.length<F&&(Y=!1,typeof t.resume==`function`&&t.resume()),Promise.resolve({value:n,done:!1})}if(W){let t=Promise.reject(W);return W=null,t}return q?Promise.resolve({value:void 0,done:!0}):new Promise((t,n)=>{H.push({resolve:t,reject:n})})},return(){return cleanup(),Promise.resolve({value:void 0,done:!0})},throw(t){return q||(W=t,cleanup()),Promise.reject(t)},[Symbol.asyncIterator](){return this}};return X}static listenerCount(t,n){return t.listenerCount(n)}static getEventListeners(t,n){return typeof t.listeners==`function`?t.listeners(n):[]}static setMaxListeners(t,...n){if(validateNumber(t,`n`),t<0)throw RangeError(`The value of "n" is out of range.`);if(n.length===0)EventEmitter.defaultMaxListeners=t;else for(let S of n)typeof S.setMaxListeners==`function`&&S.setMaxListeners(t)}static getMaxListeners(t){return typeof t.getMaxListeners==`function`?t.getMaxListeners():EventEmitter.defaultMaxListeners}static addAbortListener(t,n){t.aborted&&Promise.resolve().then(()=>n());let handler=()=>n();return t.addEventListener(`abort`,handler,{once:!0}),{[Symbol.dispose](){t.removeEventListener(`abort`,handler)}}}},Nt.EventEmitter=Nt;for(let t of[`setMaxListeners`,`getMaxListeners`,`emit`,`addListener`,`on`,`prependListener`,`once`,`prependOnceListener`,`removeListener`,`off`,`removeAllListeners`,`listeners`,`rawListeners`,`listenerCount`,`eventNames`]){let n=Nt.prototype[t];typeof n==`function`&&Object.defineProperty(Nt.prototype,t,{enumerable:!0,configurable:!0,writable:!0,value:n})}Object.defineProperty(Nt.prototype,"_events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(Nt.prototype,"_eventsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(Nt.prototype,"_maxListeners",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),__name$1(createAbortError$2,`createAbortError`)}),Ft=__exportAll$5({EventEmitter:()=>It,addAbortListener:()=>Kt,captureRejectionSymbol:()=>Lt,default:()=>It,defaultMaxListeners:()=>zt,errorMonitor:()=>Rt,getEventListeners:()=>Wt,getMaxListeners:()=>Vt,listenerCount:()=>Gt,"module.exports":()=>It,on:()=>Ut,once:()=>Ht,setMaxListeners:()=>Bt}),It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt=__esmMin(()=>{Pt(),ze(),It=makeCallable(Nt),It.EventEmitter=It,Lt=It.captureRejectionSymbol,Rt=It.errorMonitor,zt=It.defaultMaxListeners,Bt=It.setMaxListeners,Vt=It.getMaxListeners,Ht=It.once,Ut=It.on,Wt=It.getEventListeners,Gt=It.listenerCount,Kt=It.addAbortListener});function normalizeAndValidateEncoding(t){return t&&checkEncoding(t),normalizeEncoding(t)}function utf8DecodeMaximalSubpart(t,n,S){let C=``,N=n;for(;N<S;){let n=t[N];if(n<=127){C+=String.fromCharCode(n),N++;continue}if(n>=194&&n<=223){N+1<S&&t[N+1]>=128&&t[N+1]<=191?(C+=String.fromCharCode((n&31)<<6|t[N+1]&63),N+=2):(C+=`�`,N++);continue}if(n>=224&&n<=239){let F,I;if(n===224?(F=160,I=191):n===237?(F=128,I=159):(F=128,I=191),N+1>=S){C+=`�`,N++;continue}let H=t[N+1];if(H<F||H>I){C+=`�`,N++;continue}if(N+2>=S){C+=`�`,N+=2;continue}let W=t[N+2];if(W<128||W>191){C+=`�`,N+=2;continue}let q=(n&15)<<12|(H&63)<<6|W&63;C+=String.fromCharCode(q),N+=3;continue}if(n>=240&&n<=244){let F,I;if(n===240?(F=144,I=191):n===244?(F=128,I=143):(F=128,I=191),N+1>=S){C+=`�`,N++;continue}let H=t[N+1];if(H<F||H>I){C+=`�`,N++;continue}if(N+2>=S){C+=`�`,N+=2;continue}let W=t[N+2];if(W<128||W>191){C+=`�`,N+=2;continue}if(N+3>=S){C+=`�`,N+=3;continue}let q=t[N+3];if(q<128||q>191){C+=`�`,N+=3;continue}let Y=(n&7)<<18|(H&63)<<12|(W&63)<<6|q&63;C+=String.fromCharCode(55296+(Y-65536>>10),56320+(Y-65536&1023)),N+=4;continue}C+=`�`,N++}return C}function utf8CharLength(t){return t&128?t>=194&&t<=223?2:t>=224&&t<=239?3:t>=240&&t<=244?4:0:1}function isValidContinuation(t,n,S,C){if(S===1){if(n===3)return t===224?C>=160&&C<=191:t===237?C>=128&&C<=159:C>=128&&C<=191;if(n===4)return t===240?C>=144&&C<=191:t===244?C>=128&&C<=143:C>=128&&C<=191}return C>=128&&C<=191}function writeUtf8(t,n){let S=0,C=``;if(t._lastNeed>0){for(;S<n.length&&t._lastNeed>0;){let N=n[S],F=t._lastTotal-t._lastNeed;if(isValidContinuation(t._lastLeadByte,t._lastTotal,F,N))t._lastChar[F]=N,t._lastNeed--,S++;else{C+=`�`,t._lastNeed=0,t._lastTotal=0,t._lastLeadByte=0;break}}if(t._lastNeed===0&&t._lastTotal>0&&(C+=utf8DecodeMaximalSubpart(t._lastChar,0,t._lastTotal),t._lastTotal=0,t._lastLeadByte=0),t._lastNeed>0)return C}let N=n.length;for(let C=0;C<Math.min(4,n.length-S);C++){let F=n.length-1-C;if(F<S)break;let I=n[F];if((I&192)!=128){let S=utf8CharLength(I);if(S>0&&I>=128){let C=n.length-F;if(C<S){let H=!0;for(let t=1;t<C;t++)if(!isValidContinuation(I,S,t,n[F+t])){H=!1;break}if(H){N=F;for(let S=0;S<C;S++)t._lastChar[S]=n[F+S];t._lastNeed=S-C,t._lastTotal=S,t._lastLeadByte=I}}}break}}return N>S&&(C+=utf8DecodeMaximalSubpart(n,S,N)),C}function writeUtf16le(t,n){let S=``,C=0;if(t._lastNeed>0){let N=t._lastTotal-t._lastNeed,F=Math.min(t._lastNeed,n.length);for(let S=0;S<F;S++)t._lastChar[N+S]=n[S];if(t._lastNeed-=F,C=F,t._lastNeed>0)return``;let I=t._lastTotal,H=0;for(;H+1<I;){let N=t._lastChar[H]|t._lastChar[H+1]<<8;if(H+=2,N>=55296&&N<=56319){if(H+1<I){let n=t._lastChar[H]|t._lastChar[H+1]<<8;if(n>=56320&&n<=57343){S+=String.fromCharCode(N,n),H+=2;continue}}if(C+1<n.length){let t=n[C]|n[C+1]<<8;if(t>=56320&&t<=57343){S+=String.fromCharCode(N,t),C+=2;continue}}else if(C>=n.length)return t._lastChar[0]=t._lastChar[H-2],t._lastChar[1]=t._lastChar[H-1],t._lastNeed=2,t._lastTotal=4,S}S+=String.fromCharCode(N)}t._lastTotal=0}for(;C+1<n.length;){let N=n[C]|n[C+1]<<8;if(C+=2,N>=55296&&N<=56319)if(C+1<n.length){let t=n[C]|n[C+1]<<8;if(t>=56320&&t<=57343){S+=String.fromCharCode(N,t),C+=2;continue}}else if(C<n.length)return S+=String.fromCharCode(N),t._lastChar[0]=n[C],t._lastNeed=1,t._lastTotal=2,S;else return t._lastChar[0]=n[C-2],t._lastChar[1]=n[C-1],t._lastNeed=2,t._lastTotal=4,S;S+=String.fromCharCode(N)}return C<n.length&&(t._lastChar[0]=n[C],t._lastNeed=1,t._lastTotal=2),S}function writeBase64(t,n){let S=0;if(t._lastNeed>0){let C=Math.min(t._lastNeed,n.length);for(let S=0;S<C;S++)t._lastChar[t._lastTotal-t._lastNeed+S]=n[S],t._lastNeed--;if(S=C,t._lastNeed>0)return``}let C=n.length-S,N=C-C%3,F=``;t._lastTotal>0&&t._lastNeed===0&&(F+=base64Encode$1(t._lastChar.subarray(0,t._lastTotal)),t._lastTotal=0),N>0&&(F+=base64Encode$1(n.subarray(S,S+N)));let I=C-N;if(I>0){for(let C=0;C<I;C++)t._lastChar[C]=n[S+N+C];t._lastNeed=3-I,t._lastTotal=3}return F}function decodeAscii(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]&127);return n}function decodeLatin1(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return n}function decodeHex(t){let n=``;for(let S=0;S<t.length;S++)n+=t[S].toString(16).padStart(2,`0`);return n}var Jt,Yt=__esmMin(()=>{ot(),Jt=function StringDecoder(t){this.encoding=normalizeAndValidateEncoding(t),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},Jt.prototype.write=function write(t){if(t.length===0)return``;switch(this.encoding){case`utf8`:return writeUtf8(this,t);case`utf16le`:return writeUtf16le(this,t);case`base64`:return writeBase64(this,t);case`ascii`:return decodeAscii(t);case`latin1`:return decodeLatin1(t);case`hex`:return decodeHex(t);default:return decodeAscii(t)}},Jt.prototype.end=function end(t){let n=``;if(t&&t.length>0&&(n=this.write(t)),this.encoding===`utf8`&&this._lastNeed>0)n+=`�`,this._lastNeed=0,this._lastTotal=0;else if(this.encoding===`utf16le`&&this._lastNeed>0){let t=this._lastTotal-this._lastNeed;for(let S=0;S+1<t;S+=2)n+=String.fromCharCode(this._lastChar[S]|this._lastChar[S+1]<<8);this._lastNeed=0,this._lastTotal=0}else if(this.encoding===`base64`&&this._lastNeed>0){let t=this._lastChar.subarray(0,this._lastTotal-this._lastNeed);n+=base64Encode$1(t),this._lastNeed=0,this._lastTotal=0}return n}}),Xt,ProcessWriteStream,ProcessReadStream,Zt=__esmMin(()=>{_e(),dt(),At(),qt(),ze(),Yt(),Xt=new TextEncoder,ProcessWriteStream=class extends It{fd;writable=!0;_outGio=null;constructor(t){super(),this.fd=t;let n=getGioNamespace();if(n){let t=n.UnixOutputStream??n.OutputStream;if(t)try{this._outGio=t.new(this.fd,!1)}catch{}}}write(t){if(this._outGio)try{let n=typeof t==`string`?Xt.encode(t):t;return this._outGio.write_all(n,null),!0}catch{}return this.fd===2?ge.error(t):ge.log(t),!0}get isTTY(){let t=nativeIsTty(this.fd);if(t!==null)return t;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t)return!!t.log_writer_supports_color(this.fd)}catch{}return!1}get columns(){let t=nativeTerminalSize(this.fd);if(t)return t.columns;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let n=parseInt(t.getenv(`COLUMNS`)??`0`,10);if(n>0)return n}}catch{}return 80}end(){}destroy(){}get rows(){let t=nativeTerminalSize(this.fd);if(t)return t.rows;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let n=parseInt(t.getenv(`LINES`)??`0`,10);if(n>0)return n}}catch{}return 24}},ProcessReadStream=class extends It{fd;isRaw=!1;_gio=null;_stdinGio=null;_reading=!1;_flowing=!1;_mainLoopHeld=!1;_pendingRead=!1;_decoder=null;constructor(t){super(),this.fd=t,this._gio=getGioNamespace()}get isTTY(){return nativeIsTty(this.fd)??!1}setRawMode(t){return noteRawMode(this.fd,t,t=>nativeSetRawMode(this.fd,t)===!0)?(this.isRaw=t,this):(noteRawMode(this.fd,t,t=>this._setRawModeViaStty(t)),this.isRaw=t,this)}_setRawModeViaStty(t){try{let n=globalThis.imports?.gi,S=n?.Gio??n?.Gio;if(!S)return!1;let C=S.SubprocessFlags?.STDIN_INHERIT??2,N=t?[`stty`,`-icanon`,`-echo`,`-icrnl`,`-isig`,`min`,`1`,`time`,`0`]:[`stty`,`icanon`,`echo`,`icrnl`,`isig`],F=new S.SubprocessLauncher({flags:C}).spawnv(N);return F.wait(null),F.get_successful()}catch{return!1}}setEncoding(t){return this._decoder=new Jt(t),this}_pushData(t){if(this._decoder){let n=this._decoder.write(t);n.length>0&&this.emit(`data`,n)}else this.emit(`data`,t)}on(t,n){let S=t===`data`&&this.listenerCount(`data`)===0;return super.on(t,n),S&&t===`data`&&this.resume(),this}addListener(t,n){return this.on(t,n)}once(t,n){return super.once(t,n),this}removeListener(t,n){return super.removeListener(t,n),t===`data`&&this.listenerCount(`data`)===0&&this.pause(),this}off(t,n){return this.removeListener(t,n)}removeAllListeners(t){let n=t===void 0||t===`data`?this.listenerCount(`data`)>0:!1;return super.removeAllListeners(t),n&&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 t=globalThis.imports?.gi,n=t?.GLib??t?.GLib;n?.idle_add?n.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 t=this._gio.UnixInputStream??this._gio.InputStream;if(!t){this._reading=!1;return}try{this._stdinGio=t.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,(t,n)=>{this._pendingRead=!1;try{let S=t.read_bytes_finish(n)?.get_data?.()??null;if(S&&S.byteLength>0)this._pushData(Buffer.from(S));else if(S!==null&&S.byteLength===0){if(this._reading=!1,this._decoder){let t=this._decoder.end();t.length>0&&this.emit(`data`,t)}this.emit(`end`);return}}catch{this._reading=!1;return}this._reading&&loop()})};loop()}}});function defineLazy(t,n,S){Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let C=S();return Object.defineProperty(t,n,{value:C,configurable:!0,enumerable:!0,writable:!1}),C}})}var Qt,Process,$t=__esmMin(()=>{_e(),gt(),_t(),vt(),pt(),yt(),St(),Zt(),At(),qt(),Qt=Date.now(),Process=class extends It{platform;arch;env;argv;argv0;execPath;pid;ppid;version;versions;title;execArgv;config;exitCode;constructor(){super(),this.on(`exit`,()=>{try{restoreClaimedRawModes()}catch(t){ge.error(`@gjsify/process: raw mode could not be restored:`,t)}}),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 t=detectVersionInfo();this.version=t.version,this.versions=t.versions,this.title=t.title,this.on(`newListener`,t=>{isDeliverableSignal(t)&&armSignal(t,t=>this.emit(t,t))}),this.on(`removeListener`,t=>{isDeliverableSignal(t)&&this.listenerCount(t)===0&&disarmSignal(t)})}cwd(){return getCwd()}chdir(t){chdir(t)}kill(t,n){return killPid(t,n)}exit(t){return this.exitCode=t??this.exitCode??0,this.emit(`exit`,this.exitCode),exitProcess(this.exitCode)}nextTick(t,...n){typeof queueMicrotask==`function`?queueMicrotask(()=>t(...n)):Promise.resolve().then(()=>t(...n))}hrtime(t){return hrtime(t)}uptime(){return(Date.now()-Qt)/1e3}memoryUsage(){return memoryUsage()}cpuUsage(t){return cpuUsage(t)}stdout=new ProcessWriteStream(1);stderr=new ProcessWriteStream(2);stdin=new ProcessReadStream(0);abort(){this.exit(1)}umask(t){let n=readUmask();return t!==void 0&&!this._umaskWarned&&(this._umaskWarned=!0,this.emitWarning(`process.umask(0${t.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`)),n}_umaskWarned=!1;emitWarning(t,n){ge.warn(typeof t==`string`?`(${n||`Warning`}): ${t}`:t.message)}},Process.prototype.hrtime.bigint=function(){return hrtimeBigint()}}),en,tn,nn,rn=__esmMin(()=>{if(pt(),$t(),At(),en=new Process,kt)try{let t=new kt.ResizeWatcher;t.connect(`resized`,(t,n,S)=>{en.stdout.emit(`resize`),en.stderr.emit(`resize`)}),t.start()}catch{}en.platform,en.arch,en.env,en.argv,en.argv0,en.execPath,en.pid,en.ppid,en.version,en.versions,en.cwd.bind(en),en.chdir.bind(en),en.exit.bind(en),en.nextTick.bind(en),Object.assign(en.hrtime.bind(en),{bigint:hrtimeBigint}),en.uptime.bind(en),en.memoryUsage.bind(en),en.cpuUsage.bind(en),en.kill.bind(en),en.abort.bind(en),en.umask.bind(en),en.emitWarning.bind(en),en.execArgv,en.config,tn=en.stdout,en.stderr,nn=en.stdin});ze(),rn(),typeof Promise.withResolvers!=`function`&&(Promise.withResolvers=function(){let t,n;return{promise:new Promise((S,C)=>{t=S,n=C}),resolve:t,reject:n}}),initErrorV8Methods(Error),`global`in globalThis||Object.defineProperty(globalThis,"global",{value:globalThis,writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(globalThis,"process",{value:en,enumerable:!1,writable:!0,configurable:!0}),ze(),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 an=getGLib()!==void 0;function reportTimerThrow(t,n){try{t.log_default_handler(`gjsify-timers`,t.LogLevelFlags.LEVEL_WARNING,`Uncaught exception in a timer callback: ${String(n)}\n${n?.stack??``}`,null)}catch{}}var GjsifyTimeout=class{_id=null;_refed=!0;_callback;_delay;_args;_repeat;constructor(t,n,S,C){this._callback=t,this._delay=n,this._args=S,this._repeat=C,this._schedule()}_schedule(){let t=getGLib();if(!t)return;let n=t.timeout_add.bind(t);this._id=n(t.PRIORITY_DEFAULT,this._delay,()=>{try{this._callback.apply(globalThis,this._args)}catch(n){reportTimerThrow(t,n)}return this._repeat?t.SOURCE_CONTINUE:(this._id=null,t.SOURCE_REMOVE)})}unref(){return this._refed=!1,this}ref(){return this._refed=!0,this}hasRef(){return this._refed}refresh(){return this._cancel(),this._schedule(),this}_cancel(){this._id!==null&&(getGLib()?.Source.remove(this._id),this._id=null)}close(){return this._cancel(),this}[Symbol.toPrimitive](){return this._id}[Symbol.dispose](){this._cancel()}};function removeById(t){t instanceof GjsifyTimeout||typeof t==`object`&&t&&`_cancel`in t?t._cancel():typeof t==`object`&&t&&typeof t.close==`function`?t.close():typeof t==`number`&&getGLib()?.Source.remove(t)}if(an){let setT=(t,n=0,...S)=>new GjsifyTimeout(t,Math.max(0,n|0),S,!1),setI=(t,n=0,...S)=>new GjsifyTimeout(t,Math.max(0,n|0),S,!0),t=globalThis;t.setTimeout=setT,t.clearTimeout=removeById,t.setInterval=setI,t.clearInterval=removeById}function setImmediate$1(t,...n){return setTimeout(t,0,...n)}__name$1(setImmediate$1,`setImmediate`);function clearImmediate(t){clearTimeout(t)}`setImmediate`in globalThis||Object.defineProperty(globalThis,"setImmediate",{value:setImmediate$1,enumerable:!0,writable:!0,configurable:!0}),`clearImmediate`in globalThis||Object.defineProperty(globalThis,"clearImmediate",{value:clearImmediate,enumerable:!0,writable:!0,configurable:!0});var on,sn,cn=__esmMin(()=>{on=Object.defineProperty,sn=__name$1((t,n)=>{let S={};for(var C in t)on(S,C,{get:t[C],enumerable:!0});return n||on(S,Symbol.toStringTag,{value:`Module`}),S},`__exportAll`)});function assertPath(t){if(typeof t!=`string`)throw TypeError(`The "path" argument must be of type string. Received type `+typeof t)}function isPosixPathSeparator(t){return t===47}function isPathSeparator(t){return t===47||t===92}function isWindowsDeviceRoot(t){return t>=65&&t<=90||t>=97&&t<=122}function normalizeString$1(t,n,S,C){let N=``,F=0,I=-1,H=0,W;for(let q=0;q<=t.length;++q){if(q<t.length)W=t.charCodeAt(q);else if(C(W))break;else W=47;if(C(W)){if(!(I===q-1||H===1))if(I!==q-1&&H===2){if(N.length<2||F!==2||N.charCodeAt(N.length-1)!==46||N.charCodeAt(N.length-2)!==46){if(N.length>2){let t=N.lastIndexOf(S);t===-1?(N=``,F=0):(N=N.slice(0,t),F=N.length-1-N.lastIndexOf(S)),I=q,H=0;continue}else if(N.length===2||N.length===1){N=``,F=0,I=q,H=0;continue}}n&&(N.length>0?N+=`${S}..`:N=`..`,F=2)}else N.length>0?N+=S+t.slice(I+1,q):N=t.slice(I+1,q),F=q-I-1;I=q,H=0}else W===46&&H!==-1?++H:H=-1}return N}function _format(t,n){if(typeof n!=`object`||!n)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof n);let S=n,C=S.dir||S.root,N=S.base||(S.name||``)+formatExt(S.ext);return C?C===S.root?C+N:C+t+N:N}function formatExt(t){return t?`${t[0]===`.`?``:`.`}${t}`:``}var ln=__esmMin(()=>{__name$1(normalizeString$1,`normalizeString`)});function posixCwd(){if(typeof globalThis.process?.cwd==`function`)return globalThis.process.cwd();try{let t=globalThis.imports?.gi?.GLib;if(t?.get_current_dir)return t.get_current_dir()}catch{}return`/`}function resolve$4(...t){let n=``,S=!1;for(let C=t.length-1;C>=-1&&!S;C--){let N;if(C>=0){if(N=t[C],assertPath(N),N.length===0)continue}else N=posixCwd();n=`${N}/${n}`,S=N.charCodeAt(0)===47}return n=normalizeString$1(n,!S,`/`,isPosixPathSeparator),S?n.length>0?`/${n}`:`/`:n.length>0?n:`.`}function normalize$2(t){if(assertPath(t),t.length===0)return`.`;let n=t.charCodeAt(0)===47,S=t.charCodeAt(t.length-1)===47,C=normalizeString$1(t,!n,`/`,isPosixPathSeparator);return C.length===0&&!n&&(C=`.`),C.length>0&&S&&(C+=`/`),n?`/${C}`:C}function isAbsolute$2(t){return assertPath(t),t.length>0&&t.charCodeAt(0)===47}function join$3(...t){if(t.length===0)return`.`;let n;for(let S=0;S<t.length;++S){let C=t[S];assertPath(C),C.length>0&&(n===void 0?n=C:n+=`/${C}`)}return n===void 0?`.`:normalize$2(n)}function relative$1(t,n){if(assertPath(t),assertPath(n),t===n||(t=resolve$4(t),n=resolve$4(n),t===n))return``;let S=t.length,C=S-1,N=1,F=n.length-N,I=C<F?C:F,H=-1,W=0;for(;W<=I;++W){if(W===I){if(F>I){if(n.charCodeAt(N+W)===47)return n.slice(N+W+1);if(W===0)return n.slice(N+W)}else C>I&&(t.charCodeAt(1+W)===47?H=W:W===0&&(H=0));break}let S=t.charCodeAt(1+W);if(S!==n.charCodeAt(N+W))break;S===47&&(H=W)}let q=``;for(W=1+H+1;W<=S;++W)(W===S||t.charCodeAt(W)===47)&&(q.length===0?q+=`..`:q+=`/..`);return q.length>0?q+n.slice(N+H):(N+=H,n.charCodeAt(N)===47&&++N,n.slice(N))}function toNamespacedPath$1(t){return t}function dirname$2(t){if(assertPath(t),t.length===0)return`.`;let n=t.charCodeAt(0)===47,S=-1,C=!0;for(let n=t.length-1;n>=1;--n)if(t.charCodeAt(n)===47){if(!C){S=n;break}}else C=!1;return S===-1?n?`/`:`.`:n&&S===1?`//`:t.slice(0,S)}function basename$2(t,n){n!==void 0&&assertPath(n),assertPath(t);let S=0,C=-1,N=!0;if(n!==void 0&&n.length>0&&n.length<=t.length){if(n.length===t.length&&n===t)return``;let F=n.length-1,I=-1;for(let H=t.length-1;H>=0;--H){let W=t.charCodeAt(H);if(W===47){if(!N){S=H+1;break}}else I===-1&&(N=!1,I=H+1),F>=0&&(W===n.charCodeAt(F)?--F===-1&&(C=H):(F=-1,C=I))}return S===C?C=I:C===-1&&(C=t.length),t.slice(S,C)}else{for(let n=t.length-1;n>=0;--n)if(t.charCodeAt(n)===47){if(!N){S=n+1;break}}else C===-1&&(N=!1,C=n+1);return C===-1?``:t.slice(S,C)}}function extname$2(t){assertPath(t);let n=-1,S=0,C=-1,N=!0,F=0;for(let I=t.length-1;I>=0;--I){let H=t.charCodeAt(I);if(H===47){if(!N){S=I+1;break}continue}C===-1&&(N=!1,C=I+1),H===46?n===-1?n=I:F!==1&&(F=1):n!==-1&&(F=-1)}return n===-1||C===-1||F===0||F===1&&n===C-1&&n===S+1?``:t.slice(n,C)}function format$3(t){if(typeof t!=`object`||!t)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof t);return _format(`/`,t)}function parse$5(t){assertPath(t);let n={root:``,dir:``,base:``,ext:``,name:``};if(t.length===0)return n;let S=t.charCodeAt(0)===47,C;S?(n.root=`/`,C=1):C=0;let N=-1,F=0,I=-1,H=!0,W=t.length-1,q=0;for(;W>=C;--W){let n=t.charCodeAt(W);if(n===47){if(!H){F=W+1;break}continue}I===-1&&(H=!1,I=W+1),n===46?N===-1?N=W:q!==1&&(q=1):N!==-1&&(q=-1)}return N===-1||I===-1||q===0||q===1&&N===I-1&&N===F+1?I!==-1&&(F===0&&S?n.base=n.name=t.slice(1,I):n.base=n.name=t.slice(F,I)):(F===0&&S?(n.name=t.slice(1,N),n.base=t.slice(1,I)):(n.name=t.slice(F,N),n.base=t.slice(F,I)),n.ext=t.slice(N,I)),F>0?n.dir=t.slice(0,F-1):S&&(n.dir=`/`),n}var un,dn=__esmMin(()=>{cn(),ln(),un=sn({basename:()=>basename$2,delimiter:()=>`:`,dirname:()=>dirname$2,extname:()=>extname$2,format:()=>format$3,isAbsolute:()=>isAbsolute$2,join:()=>join$3,normalize:()=>normalize$2,parse:()=>parse$5,relative:()=>relative$1,resolve:()=>resolve$4,sep:()=>`/`,toNamespacedPath:()=>toNamespacedPath$1}),__name$1(resolve$4,`resolve`),__name$1(normalize$2,`normalize`),__name$1(isAbsolute$2,`isAbsolute`),__name$1(join$3,`join`),__name$1(relative$1,`relative`),__name$1(toNamespacedPath$1,`toNamespacedPath`),__name$1(dirname$2,`dirname`),__name$1(basename$2,`basename`),__name$1(extname$2,`extname`),__name$1(format$3,`format`),__name$1(parse$5,`parse`)});function cwd$1(){return typeof globalThis.process?.cwd==`function`?globalThis.process.cwd():`/`}function resolve$3(...t){let n=``,S=``,C=!1;for(let N=t.length-1;N>=-1;N--){let F;if(N>=0){if(F=t[N],assertPath(F),F.length===0)continue}else n.length===0?F=cwd$1():(F=globalThis.process?.env?.[`=${n}`]||cwd$1(),F.slice(0,2).toLowerCase()!==n.toLowerCase()&&F.charCodeAt(2)===92&&(F=`${n}\\`));let I=F.length,H=0,W=``,q=!1,Y=F.charCodeAt(0);if(I===1)isPathSeparator(Y)&&(H=1,q=!0);else if(isPathSeparator(Y))if(q=!0,isPathSeparator(F.charCodeAt(1))){let t=matchUncRoot(F);t&&(W=t.device,H=t.rootEnd)}else H=1;else isWindowsDeviceRoot(Y)&&F.charCodeAt(1)===58&&(W=F.slice(0,2),H=2,I>2&&isPathSeparator(F.charCodeAt(2))&&(q=!0,H=3));if(W.length>0)if(n.length>0){if(W.toLowerCase()!==n.toLowerCase())continue}else n=W;if(C){if(n.length>0)break}else if(S=`${F.slice(H)}\\${S}`,C=q,q&&n.length>0)break}return S=normalizeString$1(S,!C,`\\`,isPathSeparator),C?`${n}\\${S}`:`${n}${S}`||`.`}function matchUncRoot(t){let n=t.length,S=2,C=S;for(;S<n&&!isPathSeparator(t.charCodeAt(S));)S++;if(S>=n||S===C)return;let N=t.slice(C,S);for(C=S;S<n&&isPathSeparator(t.charCodeAt(S));)S++;if(!(S>=n||S===C)){for(C=S;S<n&&!isPathSeparator(t.charCodeAt(S));)S++;return N===`.`||N===`?`?{device:`\\\\${N}`,rootEnd:4,shareOnly:!1}:{device:`\\\\${N}\\${t.slice(C,S)}`,rootEnd:S,shareOnly:S===n}}}function normalize$1(t){assertPath(t);let n=t.length;if(n===0)return`.`;let S=t.charCodeAt(0);if(n===1)return isPosixPathSeparator(S)?`\\`:t;let C=0,N,F=!1;if(isPathSeparator(S))if(F=!0,isPathSeparator(t.charCodeAt(1))){let n=matchUncRoot(t);if(n?.shareOnly)return`${n.device}\\`;if(n&&(N=n.device,C=n.rootEnd,N.length===3)){let n=t.slice(4,t.indexOf(`:`)+1);isWindowsReservedName(n,n.length-1)&&(N=`\\\\?\\${n}`,C=4+n.length)}}else C=1;else{let I=t.indexOf(`:`);I>0&&(isWindowsDeviceRoot(S)&&I===1?(N=t.slice(0,2),C=2,n>2&&isPathSeparator(t.charCodeAt(2))&&(F=!0,C=3)):isWindowsReservedName(t,I)&&(N=t.slice(0,I+1),C=I+1))}let I=C<n?normalizeString$1(t.slice(C),!F,`\\`,isPathSeparator):``;if(I.length===0&&!F&&(I=`.`),I.length>0&&isPathSeparator(t.charCodeAt(n-1))&&(I+=`\\`),!F&&N===void 0&&t.includes(`:`)){if(I.length>=2&&isWindowsDeviceRoot(I.charCodeAt(0))&&I.charCodeAt(1)===58)return`.\\${I}`;let S=t.indexOf(`:`);do if(S===n-1||isPathSeparator(t.charCodeAt(S+1)))return`.\\${I}`;while((S=t.indexOf(`:`,S+1))!==-1)}return isWindowsReservedName(t,t.indexOf(`:`))?`.\\${N??``}${I}`:N===void 0?F?`\\${I}`:I:F?`${N}\\${I}`:`${N}${I}`}function isWindowsReservedName(t,n){return pn.has(t.slice(0,n).toUpperCase())}function isAbsolute$1(t){assertPath(t);let n=t.length;if(n===0)return!1;let S=t.charCodeAt(0);return!!(isPathSeparator(S)||isWindowsDeviceRoot(S)&&n>2&&t.charCodeAt(1)===58&&isPathSeparator(t.charCodeAt(2)))}function join$2(...t){if(t.length===0)return`.`;let n,S;for(let C=0;C<t.length;++C){let N=t[C];assertPath(N),N.length>0&&(n===void 0?n=S=N:n+=`\\${N}`)}if(n===void 0)return`.`;let C=!0,N=0;if(isPathSeparator(S.charCodeAt(0))){++N;let t=S.length;t>1&&isPathSeparator(S.charCodeAt(1))&&(++N,t>2&&(isPathSeparator(S.charCodeAt(2))?++N:C=!1))}if(C){for(;N<n.length&&isPathSeparator(n.charCodeAt(N));++N);N>=2&&(n=`\\${n.slice(N)}`)}return n.split(/\\+/).some(t=>{let n=t.indexOf(`:`);return n!==-1&&isWindowsReservedName(t,n)})?n.replace(/\//g,`\\`):normalize$1(n)}function relative(t,n){if(assertPath(t),assertPath(n),t===n)return``;let S=resolve$3(t),C=resolve$3(n);if(S===C||(t=S.toLowerCase(),n=C.toLowerCase(),t===n))return``;let N=0;for(;N<t.length&&t.charCodeAt(N)===92;++N);let F=t.length;for(;F-1>N&&t.charCodeAt(F-1)===92;--F);let I=F-N,H=0;for(;H<n.length&&n.charCodeAt(H)===92;++H);let W=n.length;for(;W-1>H&&n.charCodeAt(W-1)===92;--W);let q=W-H,Y=I<q?I:q,X=-1,Z=0;for(;Z<=Y;++Z){if(Z===Y){if(q>Y){if(n.charCodeAt(H+Z)===92)return C.slice(H+Z+1);if(Z===2)return C.slice(H+Z)}I>Y&&(t.charCodeAt(N+Z)===92?X=Z:Z===2&&(X=3));break}let S=t.charCodeAt(N+Z);if(S!==n.charCodeAt(H+Z))break;S===92&&(X=Z)}if(Z!==Y&&X===-1)return C;let te=``;for(X===-1&&(X=0),Z=N+X+1;Z<=F;++Z)(Z===F||t.charCodeAt(Z)===92)&&(te.length===0?te+=`..`:te+=`\\..`);return te.length>0?te+C.slice(H+X,W):(H+=X,C.charCodeAt(H)===92&&++H,C.slice(H,W))}function toNamespacedPath(t){if(typeof t!=`string`||t.length===0)return t;let n=resolve$3(t);if(n.length<=2)return t;if(n.charCodeAt(0)===92){if(n.charCodeAt(1)===92){let t=n.charCodeAt(2);if(t!==63&&t!==46)return`\\\\?\\UNC\\${n.slice(2)}`}}else if(isWindowsDeviceRoot(n.charCodeAt(0))&&n.charCodeAt(1)===58&&n.charCodeAt(2)===92)return`\\\\?\\${n}`;return n}function dirname$1(t){assertPath(t);let n=t.length;if(n===0)return`.`;let S=-1,C=-1,N=!0,F=0,I=t.charCodeAt(0);if(n>1)if(isPathSeparator(I)){if(S=F=1,isPathSeparator(t.charCodeAt(1))){let C=2,N=C;for(;C<n&&!isPathSeparator(t.charCodeAt(C));++C);if(C<n&&C!==N){for(N=C;C<n&&isPathSeparator(t.charCodeAt(C));++C);if(C<n&&C!==N){for(N=C;C<n&&!isPathSeparator(t.charCodeAt(C));++C);if(C===n)return t;C!==N&&(S=F=C+1)}}}}else isWindowsDeviceRoot(I)&&t.charCodeAt(1)===58&&(S=F=2,n>2&&isPathSeparator(t.charCodeAt(2))&&(S=F=3));else if(isPathSeparator(I))return t;for(let S=n-1;S>=F;--S)if(isPathSeparator(t.charCodeAt(S))){if(!N){C=S;break}}else N=!1;if(C===-1){if(S===-1)return`.`;C=S}return t.slice(0,C)}function basename$1(t,n){n!==void 0&&assertPath(n),assertPath(t);let S=0,C=-1,N=!0;if(t.length>=2&&isWindowsDeviceRoot(t.charCodeAt(0))&&t.charCodeAt(1)===58&&(S=2),n!==void 0&&n.length>0&&n.length<=t.length){if(n.length===t.length&&n===t)return``;let F=n.length-1,I=-1;for(let H=t.length-1;H>=S;--H){let W=t.charCodeAt(H);if(isPathSeparator(W)){if(!N){S=H+1;break}}else I===-1&&(N=!1,I=H+1),F>=0&&(W===n.charCodeAt(F)?--F===-1&&(C=H):(F=-1,C=I))}return S===C?C=I:C===-1&&(C=t.length),t.slice(S,C)}else{for(let n=t.length-1;n>=S;--n)if(isPathSeparator(t.charCodeAt(n))){if(!N){S=n+1;break}}else C===-1&&(N=!1,C=n+1);return C===-1?``:t.slice(S,C)}}function extname$1(t){assertPath(t);let n=0,S=-1,C=0,N=-1,F=!0,I=0;t.length>=2&&t.charCodeAt(1)===58&&isWindowsDeviceRoot(t.charCodeAt(0))&&(n=C=2);for(let H=t.length-1;H>=n;--H){let n=t.charCodeAt(H);if(isPathSeparator(n)){if(!F){C=H+1;break}continue}N===-1&&(F=!1,N=H+1),n===46?S===-1?S=H:I!==1&&(I=1):S!==-1&&(I=-1)}return S===-1||N===-1||I===0||I===1&&S===N-1&&S===C+1?``:t.slice(S,N)}function format$2(t){if(typeof t!=`object`||!t)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof t);return _format(`\\`,t)}function parse$4(t){assertPath(t);let n={root:``,dir:``,base:``,ext:``,name:``};if(t.length===0)return n;let S=t.length,C=0,N=t.charCodeAt(0);if(S>1)if(isPathSeparator(N)){if(C=1,isPathSeparator(t.charCodeAt(1))){let n=2,N=n;for(;n<S&&!isPathSeparator(t.charCodeAt(n));++n);if(n<S&&n!==N){for(N=n;n<S&&isPathSeparator(t.charCodeAt(n));++n);if(n<S&&n!==N){for(N=n;n<S&&!isPathSeparator(t.charCodeAt(n));++n);n===S?C=n:n!==N&&(C=n+1)}}}}else isWindowsDeviceRoot(N)&&t.charCodeAt(1)===58&&(C=2,S>2&&isPathSeparator(t.charCodeAt(2))&&(C=3));else if(isPathSeparator(N))return n.root=n.dir=t,n;C>0&&(n.root=t.slice(0,C));let F=-1,I=C,H=-1,W=!0,q=t.length-1,Y=0;for(;q>=C;--q){if(N=t.charCodeAt(q),isPathSeparator(N)){if(!W){I=q+1;break}continue}H===-1&&(W=!1,H=q+1),N===46?F===-1?F=q:Y!==1&&(Y=1):F!==-1&&(Y=-1)}return F===-1||H===-1||Y===0||Y===1&&F===H-1&&F===I+1?H!==-1&&(n.base=n.name=t.slice(I,H)):(n.name=t.slice(I,F),n.base=t.slice(I,H),n.ext=t.slice(F,H)),I>0&&I!==C?n.dir=t.slice(0,I-1):n.dir=n.root,n}var fn,pn,mn=__esmMin(()=>{cn(),ln(),fn=sn({basename:()=>basename$1,delimiter:()=>`;`,dirname:()=>dirname$1,extname:()=>extname$1,format:()=>format$2,isAbsolute:()=>isAbsolute$1,join:()=>join$2,normalize:()=>normalize$1,parse:()=>parse$4,relative:()=>relative,resolve:()=>resolve$3,sep:()=>`\\`,toNamespacedPath:()=>toNamespacedPath}),__name$1(cwd$1,`cwd`),__name$1(resolve$3,`resolve`),__name$1(normalize$1,`normalize`),pn=new Set([`CON`,`PRN`,`AUX`,`NUL`,...[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`¹`,`²`,`³`].flatMap(t=>[`COM${t}`,`LPT${t}`])]),__name$1(isAbsolute$1,`isAbsolute`),__name$1(join$2,`join`),__name$1(dirname$1,`dirname`),__name$1(basename$1,`basename`),__name$1(extname$1,`extname`),__name$1(format$2,`format`),__name$1(parse$4,`parse`)});function selectFlavour(t){return t===`win32`?fn:un}var hn=__esmMin(()=>{dn(),mn()}),gn=__exportAll$5({basename:()=>Tn,default:()=>An,delimiter:()=>kn,dirname:()=>wn,extname:()=>$,format:()=>En,isAbsolute:()=>bn,join:()=>xn,normalize:()=>yn,parse:()=>Dn,posix:()=>un,relative:()=>Sn,resolve:()=>vn,sep:()=>On,toNamespacedPath:()=>Cn,win32:()=>fn}),_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,$,En,Dn,On,kn,An,jn=__esmMin(()=>{dn(),mn(),hn(),ze(),_n=selectFlavour(hostOs()),{resolve:vn,normalize:yn,isAbsolute:bn,join:xn,relative:Sn,toNamespacedPath:Cn,dirname:wn,basename:Tn,extname:$,format:En,parse:Dn,sep:On,delimiter:kn}=_n,An={resolve:_n.resolve,normalize:_n.normalize,isAbsolute:_n.isAbsolute,join:_n.join,relative:_n.relative,toNamespacedPath:_n.toNamespacedPath,dirname:_n.dirname,basename:_n.basename,extname:_n.extname,format:_n.format,parse:_n.parse,sep:_n.sep,delimiter:_n.delimiter,posix:un,win32:fn}}),Mn=__exportAll$5({URL:()=>Bn,URLSearchParams:()=>Fn,default:()=>Vn,domainToASCII:()=>domainToASCII,domainToUnicode:()=>domainToUnicode,fileURLToPath:()=>fileURLToPath,format:()=>format$1,parse:()=>parse$3,pathToFileURL:()=>pathToFileURL,resolve:()=>resolve$2});function platformOrShapeIsWindows(t){return hostOs()===void 0?isWindowsPath(t):isWin32()}function parseFormUrlencoded(t){let n=[];if(!t)return n;for(let S of t.split(`&`)){if(S===``)continue;let t=S.indexOf(`=`);t===-1?n.push([decodeComponent(S),``]):n.push([decodeComponent(S.slice(0,t)),decodeComponent(S.slice(t+1))])}return n}function decodeComponent(t){try{return decodeURIComponent(t.replace(/\+/g,` `))}catch{return t}}function percentEncodeUtf8(t){let n=``;for(let S of new TextEncoder().encode(t))n+=`%${S.toString(16).toUpperCase().padStart(2,`0`)}`;return n}function encodeComponent(t){let n=``;for(let S of t)S===` `?n+=`+`:/^[A-Za-z0-9*\-._]$/.test(S)?n+=S:n+=percentEncodeUtf8(S);return n}function isSpecialScheme(t){return In.has(t)}function defaultPort(t){return In.get(t)??null}function percentEncode(t,n){let S=``;for(let C of t){let t=C.codePointAt(0);S+=t<=32||t>126||n.includes(C)?percentEncodeUtf8(C):C}return S}function encodeQuery(t,n){return percentEncode(t,n?`"#<>'`:`"#<>`)}function isSchemeChar(t){return t>=`a`&&t<=`z`||t>=`A`&&t<=`Z`||t>=`0`&&t<=`9`||t===`+`||t===`-`||t===`.`}function isAsciiDigit(t){return t!==void 0&&t>=`0`&&t<=`9`}function isHexDigit$1(t){return t!==void 0&&/^[0-9A-Fa-f]$/.test(t)}function digitPrefix(t){let n=``;for(let S of t){if(!isAsciiDigit(S))break;n+=S}return n}function hasForbiddenDomainCodePoint(t){for(let n of t){let t=n.codePointAt(0);if(t<=31||t===127||n===`%`||zn.has(n))return!0}return!1}function parseIPv6(t){let n=[0,0,0,0,0,0,0,0],S=0,C=null,N=0,at=()=>t[N];if(at()===`:`){if(t[N+1]!==`:`)return;N+=2,S++,C=S}for(;N<t.length;){if(S===8)return;if(at()===`:`){if(C!==null)return;N++,S++,C=S;continue}let F=0,I=0;for(;I<4&&isHexDigit$1(at());)F=F*16+Number.parseInt(at(),16),N++,I++;if(at()===`.`){if(I===0||(N-=I,S>6))return;let C=0;for(;N<t.length;){let t=null;if(C>0)if(at()===`.`&&C<4)N++;else return;if(!isAsciiDigit(at()))return;for(;isAsciiDigit(at());){let n=Number(at());if(t===null)t=n;else if(t===0)return;else t=t*10+n;if(t>255)return;N++}n[S]=n[S]*256+t,C++,(C===2||C===4)&&S++}if(C!==4)return;break}if(at()===`:`){if(N++,N>=t.length)return}else if(N<t.length)return;n[S]=F,S++}if(C!==null){let t=S-C;for(S=7;S!==0&&t>0;){let N=n[C+t-1];n[C+t-1]=n[S],n[S]=N,S--,t--}}else if(S!==8)return;return serializeIPv6(n)}function serializeIPv6(t){let n=null,S=1,C=-1,N=0;for(let F=0;F<8;F++){if(t[F]!==0){C=-1,N=0;continue}C===-1&&(C=F),N++,N>S&&(S=N,n=C)}let F=``,I=!1;for(let S=0;S<8;S++)if(!(I&&t[S]===0)){if(I=!1,n===S){F+=S===0?`::`:`:`,I=!0;continue}F+=t[S].toString(16),S!==7&&(F+=`:`)}return F}function parseHost(t,n){if(t.startsWith(`[`)){if(!t.endsWith(`]`))return;let n=parseIPv6(t.slice(1,-1));return n===void 0?void 0:`[${n}]`}if(n){for(let n of t)if(zn.has(n))return;return percentEncode(t,``)}if(!hasForbiddenDomainCodePoint(t))return t.toLowerCase()}function parseHostSetterValue(t,n,S,C,N){let F=t.replace(Rn,``),I=isSpecialScheme(n);if(n===`file`){let t=F.length;for(let n=0;n<F.length;n++){let S=F[n];if(S===`/`||S===`\\`||S===`?`||S===`#`){t=n;break}}let n=F.slice(0,t);if(n===``)return{host:``};let S=parseHost(n,!1);return S===void 0?void 0:{host:S===`localhost`?``:S}}let H=!1,W=``;for(let t=0;t<F.length;t++){let S=F[t];if(S===`:`&&!H){if(W===``||N)return;let S=parseHost(W,!I);if(S===void 0)return;let C=digitPrefix(F.slice(t+1));if(C===``)return{host:S};let H=Number(C);return H>65535?{host:S}:{host:S,port:H===defaultPort(n)?null:H}}if(S===`/`||S===`?`||S===`#`||I&&S===`\\`)break;S===`[`?H=!0:S===`]`&&(H=!1),W+=S}if(W===``&&(I||S||C))return;let q=parseHost(W,!I);return q===void 0?void 0:{host:q}}function isDoubleDotSegment(t){let n=t.toLowerCase();return n===`..`||n===`.%2e`||n===`%2e.`||n===`%2e%2e`}function isSingleDotSegment(t){let n=t.toLowerCase();return n===`.`||n===`%2e`}function parsePathSetterValue(t,n,S){let C=t.replace(Rn,``);if(n&&(C=C.replace(/\\/g,`/`)),C===``)return n||S?`/`:``;let N=[],F=(C.startsWith(`/`)?C.slice(1):C).split(`/`);for(let t=0;t<F.length;t++){let n=F[t],S=t===F.length-1;isDoubleDotSegment(n)?(N.pop(),S&&N.push(``)):isSingleDotSegment(n)?S&&N.push(``):N.push(percentEncode(n,'"#<>?^`{}'))}return`/`+N.join(`/`)}function bracketIPv6Host(t){return t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t}function parse$3(t,n,S){if(typeof t!=`string`)throw TypeError(`The "url" argument must be of type string. Received type `+typeof t);let C={protocol:null,slashes:null,auth:null,host:null,port:null,hostname:null,hash:null,search:null,query:null,pathname:null,path:null,href:t},N=t.trim(),F=N.indexOf(`#`);F!==-1&&(C.hash=N.slice(F),N=N.slice(0,F));let I=N.indexOf(`?`);I!==-1&&(C.search=N.slice(I),C.query=n?Object.fromEntries(new Fn(N.slice(I+1))):N.slice(I+1),N=N.slice(0,I));let H=/^([a-z][a-z0-9.+-]*:)/i.exec(N);if(H&&(C.protocol=H[1].toLowerCase(),N=N.slice(C.protocol.length)),(S||C.protocol)&&N.startsWith(`//`)&&(C.slashes=!0,N=N.slice(2)),C.slashes||C.protocol&&![`javascript:`,`data:`,`mailto:`].includes(C.protocol)){let t=-1;for(let n=0;n<N.length;n++){let S=N[n];if(S===`/`||S===`\\`){t=n;break}}let n=t===-1?N:N.slice(0,t);N=t===-1?``:N.slice(t);let S=n.lastIndexOf(`@`);S===-1?parseHostPort(n,C):(C.auth=decodeURIComponent(n.slice(0,S)),parseHostPort(n.slice(S+1),C))}return C.pathname=N||(C.slashes?`/`:null),(C.pathname!==null||C.search!==null)&&(C.path=(C.pathname||``)+(C.search||``)),C.href=format$1(C),C}function parseHostPort(t,n){if(!t)return;let S=t.indexOf(`[`);if(S!==-1){let C=t.indexOf(`]`,S);if(C!==-1){let N=t.slice(C+1);N.startsWith(`:`)&&(n.port=N.slice(1)),n.hostname=t.slice(S,C+1),n.host=n.hostname+(n.port?`:`+n.port:``);return}}let C=t.lastIndexOf(`:`);if(C!==-1){let S=t.slice(C+1);/^\d*$/.test(S)?(n.port=S||null,n.hostname=t.slice(0,C).toLowerCase()):n.hostname=t.toLowerCase()}else n.hostname=t.toLowerCase();n.host=n.hostname+(n.port?`:`+n.port:``)}function format$1(t){if(typeof t==`string`)return t;if(t instanceof Bn)return t.href;let n=t,S=``;if(n.protocol&&(S+=n.protocol),(n.slashes||n.protocol&&![`javascript:`,`data:`,`mailto:`].includes(n.protocol||``))&&(S+=`//`),n.auth&&(S+=encodeURIComponent(n.auth)+`@`),n.host?S+=n.host:(n.hostname&&(S+=n.hostname),n.port&&(S+=`:`+n.port)),n.pathname&&(S+=n.pathname),n.search)S+=n.search;else if(n.query&&typeof n.query==`object`){let t=new Fn(n.query).toString();t&&(S+=`?`+t)}return n.hash&&(S+=n.hash),S}function resolve$2(t,n){return new Bn(n,new Bn(t,`resolve://`)).href.replace(/^resolve:\/\//,``)}function fileURLToPath(t,n){if(typeof t==`string`&&(t=new Bn(t)),!(t instanceof Bn))throw TypeError(`The "url" argument must be of type string or URL. Received type `+typeof t);if(t.protocol!==`file:`)throw TypeError(`The URL must be of scheme file`);let S=t.pathname,C=n?.windows??platformOrShapeIsWindows(S.slice(1));for(let t=0;t<S.length;t++){if(S[t]!==`%`)continue;let n=S.codePointAt(t+2)|32,N=S[t+1]===`2`&&n===102,F=S[t+1]===`5`&&n===99;if(C&&(N||F))throw TypeError(`File URL path must not include encoded \\ or / characters`);if(N)throw TypeError(`File URL path must not include encoded / characters`)}if(t.hostname!==``&&t.hostname!==`localhost`){if(!C)throw TypeError(`File URL host must be "localhost" or empty on ${hostOs()??`this platform`}`);return`\\\\${t.hostname}${decodeURIComponent(S).replace(/\//g,`\\`)}`}if(C){let t=decodeURIComponent(S);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t.replace(/\//g,`\\`)}return decodeURIComponent(S)}function pathToFileURL(t,n){let S=n?.windows??platformOrShapeIsWindows(t),C=S&&t.startsWith(`\\\\`)?t:(S?fn:un).resolve(currentDir(),t);if(S&&C.startsWith(`\\\\`))return uncPathToFileURL(C);let N=t.charCodeAt(t.length-1);return(N===47||S&&N===92)&&C[C.length-1]!==On&&(C+=`/`),new Bn(pathToFileUrlHref(C,{windows:S}))}function currentDir(){return typeof globalThis.process?.cwd==`function`?globalThis.process.cwd():lt.get_current_dir()}function uncPathToFileURL(t){let n=t.startsWith(`\\\\?\\UNC\\`)?8:2,S=t.indexOf(`\\`,n);if(S===-1)throw invalidPathValue(t,`Missing UNC resource path`);if(S===2)throw invalidPathValue(t,`Empty UNC servername`);let C=t.slice(n,S);return new Bn(`file://${C===`?`?``:C}${encodePathForFileUrl(t.slice(S).replace(/\\/g,`/`))}`)}function invalidPathValue(t,n){let S=TypeError(`The argument 'path' ${n}. Received '${t}'`);return S.code=`ERR_INVALID_ARG_VALUE`,S}function domainToASCII(t){try{return new Bn(`http://${t}`).hostname}catch{return``}}function domainToUnicode(t){try{return new Bn(`http://${t}`).hostname}catch{return``}}var Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn=__esmMin(()=>{ut(),ze(),jn(),Nn=lt.UriFlags.HAS_PASSWORD|lt.UriFlags.ENCODED|lt.UriFlags.SCHEME_NORMALIZE,Pn=new WeakMap,Fn=class URLSearchParams{_entries=[];constructor(t){if(t)if(typeof t==`string`)this._entries=parseFormUrlencoded(t.startsWith(`?`)?t.slice(1):t);else if(Array.isArray(t))for(let[n,S]of t)this._entries.push([String(n),String(S)]);else if(t instanceof URLSearchParams)this._entries=t._entries.map(([t,n])=>[t,n]);else for(let n of Object.keys(t))this._entries.push([n,String(t[n])])}get(t){for(let[n,S]of this._entries)if(n===t)return S;return null}getAll(t){return this._entries.filter(([n])=>n===t).map(([,t])=>t)}set(t,n){let S=!1;if(this._entries=this._entries.filter(([n])=>n===t?S?!1:(S=!0,!0):!0),S){for(let S=0;S<this._entries.length;S++)if(this._entries[S][0]===t){this._entries[S][1]=n;break}}else this._entries.push([t,n]);Pn.get(this)?.()}has(t,n){return n===void 0?this._entries.some(([n])=>n===t):this._entries.some(([S,C])=>S===t&&C===n)}delete(t,n){this._entries=n===void 0?this._entries.filter(([n])=>n!==t):this._entries.filter(([S,C])=>!(S===t&&C===n)),Pn.get(this)?.()}append(t,n){this._entries.push([t,n]),Pn.get(this)?.()}sort(){this._entries.sort((t,n)=>t[0]<n[0]?-1:+(t[0]>n[0])),Pn.get(this)?.()}toString(){return this._entries.map(([t,n])=>encodeComponent(t)+`=`+encodeComponent(n)).join(`&`)}forEach(t){for(let[n,S]of this._entries)t(S,n,this)}*entries(){yield*this._entries}*keys(){for(let[t]of this._entries)yield t}*values(){for(let[,t]of this._entries)yield t}[Symbol.iterator](){return this.entries()}get size(){return this._entries.length}},In=new Map([[`ftp`,21],[`file`,null],[`http`,80],[`https`,443],[`ws`,80],[`wss`,443]]),Ln='"#/:;<=>?@[\\]^`{|}',Rn=/[\t\n\r]/g,__name$1(isHexDigit$1,`isHexDigit`),zn=new Set([`\0`,` `,`
11
11
  `,`\r`,` `,`#`,`/`,`:`,`<`,`>`,`?`,`@`,`[`,`\\`,`]`,`^`,`|`]),Bn=class URL{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(t,n){let S=t instanceof URL?t.href:String(t),C;try{if(n!==void 0){let t=n instanceof URL?n.href:String(n);C=lt.Uri.parse(t,Nn).parse_relative(S,Nn)}else C=lt.Uri.parse(S,Nn)}catch{throw TypeError(`Invalid URL: ${S}`)}if(!C)throw TypeError(`Invalid URL: ${S}`);this.#e=C.get_scheme();let N=isSpecialScheme(this.#e);this.#t=C.get_user()??``,this.#n=C.get_password()??``;let F=C.get_host(),I=F===null?null:bracketIPv6Host(F.toLowerCase());this.#r=I===null?N?``:null:this.#e===`file`&&I===`localhost`?``:I;let H=C.get_port();this.#i=H===-1||H===defaultPort(this.#e)?null:H,this.#a=C.get_path()??``,N&&this.#a===``&&(this.#a=`/`),this.#o=this.#r===null&&!this.#a.startsWith(`/`),this.#r===null&&!this.#o&&this.#a.startsWith(`/.//`)&&(this.#a=this.#a.slice(2)),this.#s=C.get_fragment()??null,this.#l=C.get_query()??null,this.#c=new Fn,this.#c._entries=parseFormUrlencoded(this.#l??``),Pn.set(this.#c,()=>{let t=this.#c.toString();this.#l=t===``?null:t})}get protocol(){return this.#e+`:`}set protocol(t){let n=String(t).replace(Rn,``)+`:`;if(!/^[A-Za-z]/.test(n))return;let S=``;for(let t of n){if(t===`:`)break;if(!isSchemeChar(t))return;S+=t.toLowerCase()}isSpecialScheme(this.#e)===isSpecialScheme(S)&&(S===`file`&&(this.#t!==``||this.#n!==``||this.#i!==null)||this.#e===`file`&&(this.#r===null||this.#r===``)||(this.#e=S,this.#i!==null&&this.#i===defaultPort(S)&&(this.#i=null)))}get hostname(){return this.#r??``}set hostname(t){if(this.#o)return;let n=parseHostSetterValue(String(t),this.#e,this.#t!==``||this.#n!==``,this.#i!==null,!0);n!==void 0&&(this.#r=n.host)}get port(){return this.#i===null?``:String(this.#i)}set port(t){if(this.#u())return;let n=String(t);if(n===``){this.#i=null;return}let S=digitPrefix(n.replace(Rn,``));if(S===``)return;let C=Number(S);C>65535||(this.#i=C===defaultPort(this.#e)?null:C)}get host(){let t=this.hostname,n=this.port;return n?`${t}:${n}`:t}set host(t){if(this.#o)return;let n=parseHostSetterValue(String(t),this.#e,this.#t!==``||this.#n!==``,this.#i!==null,!1);n!==void 0&&(this.#r=n.host,n.port!==void 0&&(this.#i=n.port))}get pathname(){return this.#a}set pathname(t){this.#o||(this.#a=parsePathSetterValue(String(t),isSpecialScheme(this.#e),this.#r===null))}get search(){return this.#l?`?`+this.#l:``}set search(t){let n=String(t);if(n===``){this.#l=null,this.#c._entries=[];return}let S=(n.startsWith(`?`)?n.slice(1):n).replace(Rn,``);this.#l=encodeQuery(S,isSpecialScheme(this.#e)),this.#c._entries=parseFormUrlencoded(S)}get hash(){return this.#s?`#`+this.#s:``}set hash(t){let n=String(t);if(n===``){this.#s=null;return}let S=(n.startsWith(`#`)?n.slice(1):n).replace(Rn,``);this.#s=percentEncode(S,'"<>`')}get origin(){return isSpecialScheme(this.#e)&&this.#e!==`file`?`${this.protocol}//${this.host}`:`null`}get username(){return this.#t}set username(t){this.#u()||(this.#t=percentEncode(String(t),Ln))}get password(){return this.#n}set password(t){this.#u()||(this.#n=percentEncode(String(t),Ln))}#u(){return this.#r===null||this.#r===``||this.#e===`file`}get href(){let t=this.#e+`:`;return this.#r===null?!this.#o&&this.#a.startsWith(`//`)&&(t+=`/.`):(t+=`//`,(this.#t!==``||this.#n!==``)&&(t+=this.#t,this.#n!==``&&(t+=`:`+this.#n),t+=`@`),t+=this.#r,this.#i!==null&&(t+=`:`+this.#i)),t+=this.#a,t+=this.#l===null?``:`?${this.#l}`,t+=this.#s===null?``:`#${this.#s}`,t}set href(t){let n=new URL(String(t));this.#e=n.#e,this.#t=n.#t,this.#n=n.#n,this.#r=n.#r,this.#i=n.#i,this.#a=n.#a,this.#o=n.#o,this.#l=n.#l,this.#s=n.#s,this.#c._entries=parseFormUrlencoded(this.#l??``)}get searchParams(){return this.#c}toString(){return this.href}toJSON(){return this.href}static _objectURLPaths=new Map;static _objectURLCounter=0;static createObjectURL(t){let n=t?._tmpPath;if(typeof n==`string`&&n.length>0){let t=`file://${n}`;return URL._objectURLPaths.set(t,n),t}return`file:///dev/null`}static revokeObjectURL(t){let n=URL._objectURLPaths.get(t);n&&(lt.unlink(n),URL._objectURLPaths.delete(t))}},__name$1(parse$3,`parse`),__name$1(format$1,`format`),__name$1(resolve$2,`resolve`),Vn={URL:Bn,URLSearchParams:Fn,parse:parse$3,format:format$1,resolve:resolve$2,fileURLToPath,pathToFileURL,domainToASCII,domainToUnicode}});Hn(),typeof globalThis.URL!=`function`&&Object.defineProperty(globalThis,"URL",{value:Bn,enumerable:!1,writable:!0,configurable:!0}),typeof globalThis.URLSearchParams!=`function`&&Object.defineProperty(globalThis,"URLSearchParams",{value:Fn,enumerable:!1,writable:!0,configurable:!0});var Un=__exportAll$5({PerformanceEntry:()=>qn,PerformanceMark:()=>Yn,PerformanceMeasure:()=>Xn,PerformanceObserver:()=>Kn,PerformanceObserverEntryList:()=>Jn,default:()=>Zn,eventLoopUtilization:()=>eventLoopUtilization,monitorEventLoopDelay:()=>monitorEventLoopDelay,performance:()=>Wn,timerify:()=>timerify});function eventLoopUtilization(t,n){return{idle:0,active:0,utilization:0}}function timerify(t){let wrapped=function(...n){let S=Wn.now(),C=t.apply(this,n);return Wn.now()-S,C};return Object.defineProperty(wrapped,"name",{value:t.name}),wrapped}function monitorEventLoopDelay(t){let n=new Map;return{enable(){},disable(){},reset(){},percentile(t){return 0},get min(){return 0},get max(){return 0},get mean(){return 0},get stddev(){return 0},get percentiles(){return n}}}var Wn,PerformanceObserverStub,PerformanceEntryStub,PerformanceObserverEntryListStub,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn=__esmMin(()=>{if(globalThis.performance)Wn=globalThis.performance;else{let t,_now;try{let n=globalThis.imports?.gi?.GLib;if(!n)throw Error(`GJS imports.gi.GLib not available`);t=n.get_monotonic_time(),_now=()=>(n.get_monotonic_time()-t)/1e3}catch{let n=Date.now();t=0,_now=()=>Date.now()-n}let n=[],S=Date.now()-_now();Wn={timeOrigin:S,now:_now,mark(t){let S={name:t,entryType:`mark`,startTime:_now(),duration:0};return n.push(S),S},measure(t,S,C){let N=0,F=_now();if(S){let t=n.find(t=>t.entryType===`mark`&&t.name===S);t&&(N=t.startTime)}if(C){let t=n.find(t=>t.entryType===`mark`&&t.name===C);t&&(F=t.startTime)}let I={name:t,entryType:`measure`,startTime:N,duration:F-N};return n.push(I),I},getEntries(){return[...n]},getEntriesByName(t){return n.filter(n=>n.name===t)},getEntriesByType(t){return n.filter(n=>n.entryType===t)},clearMarks(t){for(let S=n.length-1;S>=0;S--)n[S].entryType===`mark`&&(!t||n[S].name===t)&&n.splice(S,1)},clearMeasures(t){for(let S=n.length-1;S>=0;S--)n[S].entryType===`measure`&&(!t||n[S].name===t)&&n.splice(S,1)},clearResourceTimings(){},setResourceTimingBufferSize(){},toJSON(){return{timeOrigin:S}}}}PerformanceObserverStub=class{_callback;constructor(t){this._callback=t}observe(t){}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(t){return[]}getEntriesByType(t){return[]}},Gn=globalThis,Kn=Gn.PerformanceObserver||PerformanceObserverStub,qn=Gn.PerformanceEntry||PerformanceEntryStub,Jn=Gn.PerformanceObserverEntryList||PerformanceObserverEntryListStub,Yn=Gn.PerformanceMark||class PerformanceMark extends PerformanceEntryStub{},Xn=Gn.PerformanceMeasure||class PerformanceMeasure extends PerformanceEntryStub{},Zn={performance:Wn,PerformanceObserver:Kn,PerformanceEntry:qn,PerformanceObserverEntryList:Jn,PerformanceMark:Yn,PerformanceMeasure:Xn,eventLoopUtilization,timerify,monitorEventLoopDelay}});Qn();const $n=globalThis;globalThis.performance===void 0&&($n.performance=Wn),typeof $n.PerformanceObserver!=`function`&&($n.PerformanceObserver=Kn);const er={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(t,n){super(t),this.name=n||`Error`,this.code=Object.hasOwn(er,this.name)?er[this.name]:0}};const tr=globalThis.DOMException===void 0?_DOMExceptionPolyfill:globalThis.DOMException;_e();const nr=Symbol(`type`),rr=Symbol(`bubbles`),ir=Symbol(`cancelable`),ar=Symbol(`composed`),sr=Symbol(`target`),cr=Symbol(`currentTarget`),lr=Symbol(`eventPhase`),ur=Symbol(`defaultPrevented`),dr=Symbol(`isTrusted`),fr=Symbol(`timeStamp`),pr=Symbol(`stop`),mr=Symbol(`immediateStop`),hr=Symbol(`dispatching`),gr=Symbol(`inPassiveListener`);var Event=class{[nr];[rr];[ir];[ar];[sr]=null;[cr]=null;[lr]=0;[ur]=!1;[dr]=!1;[fr];[pr]=!1;[mr]=!1;[hr]=!1;[gr]=!1;get type(){return this[nr]}get bubbles(){return this[rr]}get cancelable(){return this[ir]}get composed(){return this[ar]}get target(){return this[sr]}get currentTarget(){return this[cr]}get eventPhase(){return this[lr]}get defaultPrevented(){return this[ur]}get timeStamp(){return this[fr]}get cancelBubble(){return this[pr]}set cancelBubble(t){t&&this.stopPropagation()}get returnValue(){return!this[ur]}set returnValue(t){t||this.preventDefault()}get srcElement(){return this[sr]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(t,n){this[nr]=t,this[rr]=n?.bubbles??!1,this[ir]=n?.cancelable??!1,this[ar]=n?.composed??!1,this[fr]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[dr],enumerable:!0,configurable:!1})}composedPath(){return this[cr]?[this[cr]]:[]}preventDefault(){this[ir]&&!this[gr]&&(this[ur]=!0)}stopPropagation(){this[pr]=!0}stopImmediatePropagation(){this[pr]=!0,this[mr]=!0}},EventTarget=class{#e=new Map;get[Symbol.toStringTag](){return`EventTarget`}addEventListener(t,n,S){if(n===null)return;let C=typeof S==`boolean`?S:S?.capture??!1,N=typeof S==`object`?S?.once??!1:!1,F=typeof S==`object`?S?.passive??!1:!1,I=this.#e.get(t);I||(I=[],this.#e.set(t,I));for(let t of I)if(t.listener===n&&t.capture===C)return;let H={listener:n,capture:C,once:N,passive:F,removed:!1};I.push(H),typeof S==`object`&&S?.signal&&S.signal.addEventListener(`abort`,()=>{this.removeEventListener(t,n,{capture:C})},{once:!0})}removeEventListener(t,n,S){if(n===null)return;let C=typeof S==`boolean`?S:S?.capture??!1,N=this.#e.get(t);if(!N)return;let F=N.findIndex(t=>t.listener===n&&t.capture===C);F!==-1&&(N[F].removed=!0,N.splice(F,1),N.length===0&&this.#e.delete(t))}dispatchEvent(t){let n=t;if(n[hr])throw new tr(`The event is already being dispatched.`,`InvalidStateError`);n[hr]=!0,n[sr]=this,n[cr]=this,n[lr]=Event.AT_TARGET;try{let S=this.#e.get(t.type);if(S){let C=[...S];for(let S of C)if(!S.removed){if(n[mr]||n[pr])break;S.once&&this.removeEventListener(t.type,S.listener,{capture:S.capture});try{S.passive&&(n[gr]=!0),typeof S.listener==`function`?S.listener.call(this,t):typeof S.listener.handleEvent==`function`&&S.listener.handleEvent.call(S.listener,t)}catch(t){reportListenerException(t)}finally{n[gr]=!1}}}}finally{n[lr]=Event.NONE,n[cr]=null,n[hr]=!1}return!t.defaultPrevented}};function reportListenerException(t){try{let n=globalThis;if(typeof n.reportError==`function`)n.reportError(t);else if(t instanceof Error){let n=`${t.name}: ${t.message}`;ge.error(t.stack?`${n}\n${t.stack}`:n)}else ge.error(String(t))}catch{}}for(let[t,n]of[[`NONE`,0],[`CAPTURING_PHASE`,1],[`AT_TARGET`,2],[`BUBBLING_PHASE`,3]])Object.defineProperty(Event.prototype,t,{value:n,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Event,t,{value:n,writable:!1,enumerable:!0,configurable:!1});const _r=Symbol(`abort`),vr=Symbol(`internal`);var yr=class AbortSignal extends EventTarget{#e=!1;#t=void 0;onabort=null;constructor(t){if(super(),t!==vr)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}[_r](t){if(this.#e)return;this.#e=!0,this.#t=t??new tr(`The operation was aborted.`,`AbortError`);let n=new Event(`abort`);typeof this.onabort==`function`&&this.onabort.call(this,n),this.dispatchEvent(n)}static abort(t){let n=new AbortSignal(vr);return n[_r](t),n}static timeout(t){let n=new AbortSignal(vr);return setTimeout(()=>{n[_r](new tr(`The operation timed out.`,`TimeoutError`))},t),n}static any(t){let n=new AbortSignal(vr);for(let S of t)if(S.aborted)return n[_r](S.reason),n;let onAbort=()=>{if(!n.aborted){let S=t.find(t=>t.aborted);n[_r](S?.reason)}};for(let n of t)n.addEventListener(`abort`,onAbort,{once:!0});return n}},br=class AbortController{signal;constructor(){this.signal=new yr(vr)}get[Symbol.toStringTag](){return`AbortController`}abort(t){if(!(this instanceof AbortController))throw TypeError(`'abort' called on an object that is not a valid instance of AbortController.`);this.signal[_r](t)}};const Sr=globalThis;globalThis.AbortController===void 0&&(Sr.AbortController=br),globalThis.AbortSignal===void 0&&(Sr.AbortSignal=yr);const Cr=Symbol(`kState`),wr=Symbol(`kType`);function isBrandCheck(t){return n=>typeof n==`object`&&!!n&&n[Cr]!==void 0&&n[wr]===t}function dequeueValue(t){let n=t[Cr].queue.shift();if(n===void 0)throw Error(`dequeueValue called on an empty queue`);let{value:S,size:C}=n;return t[Cr].queueTotalSize=Math.max(0,t[Cr].queueTotalSize-C),S}function resetQueue(t){t[Cr].queue=[],t[Cr].queueTotalSize=0}function peekQueueValue(t){return t[Cr].queue[0].value}function enqueueValueWithSize(t,n,S){if(S=+S,typeof S!=`number`||S<0||Number.isNaN(S)||S===1/0)throw RangeError(`Invalid size: ${S}`);t[Cr].queue.push({value:n,size:S}),t[Cr].queueTotalSize+=S}function extractHighWaterMark(t,n){if(t===void 0)return n;if(t=+t,typeof t!=`number`||Number.isNaN(t)||t<0)throw RangeError(`Invalid highWaterMark: ${t}`);return t}function extractSizeAlgorithm(t){if(t===void 0)return()=>1;if(typeof t!=`function`)throw TypeError(`strategy.size must be a function`);return t}function transferArrayBuffer(t){return typeof ArrayBuffer.prototype.transfer==`function`?t.transfer():t.slice(0)}function isDetachedBuffer(t){if(typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||t.byteLength!==0)return!1;try{return t.slice(0,0),!1}catch{return!0}}function typedArrayConstructorByTag(t){switch(t){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(t){switch(t){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(t){t.then(()=>{},()=>{})}function createPromiseCallback(t,n,S){if(typeof n!=`function`)throw TypeError(`${t} must be a function`);return async(...t)=>n.call(S,...t)}async function nonOpFlush(){}function nonOpStart(){}async function nonOpPull(){}async function nonOpCancel(){}async function nonOpWrite(){}const Tr={__proto__:Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),next:void 0,return:void 0};function createAsyncFromSyncIterator(t){let n={[Symbol.iterator]:()=>t.iterator},S=(async function*(){return yield*n})();return{iterator:S,nextMethod:S.next,done:!1}}function getIterator(t,n=`sync`,S){if(S===void 0)if(n===`async`){if(S=t[Symbol.asyncIterator],S==null){let n=t[Symbol.iterator];if(n===void 0)throw TypeError(`Object is not iterable`);return createAsyncFromSyncIterator(getIterator(t,`sync`,n))}}else S=t[Symbol.iterator];if(S===void 0)throw TypeError(`Object is not iterable`);let C=S.call(t);if(typeof C!=`object`||!C)throw TypeError(`The iterator method must return an object`);return{iterator:C,nextMethod:C.next,done:!1}}function iteratorNext(t,n){let S;if(S=n===void 0?t.nextMethod.call(t.iterator):t.nextMethod.call(t.iterator,n),typeof S!=`object`||!S)throw TypeError(`The iterator.next() method must return an object`);return S}const Er=typeof globalThis.AbortController==`function`?globalThis.AbortController:class AbortControllerShim{signal={aborted:!1,reason:void 0,addEventListener(){},removeEventListener(){}};abort(t){this.signal.aborted=!0,this.signal.reason=t}},Dr=Symbol(`kAbort`),Or=Symbol(`kCloseSentinel`),kr=Symbol(`kError`),Ar=Symbol(`kSkipThrow`);var WritableStream=class{[wr]=`WritableStream`;[Cr];constructor(t={},n={}){if(t!=null&&typeof t!=`object`)throw TypeError(`sink must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`strategy must be an object`);let S=t?.type;if(S!==void 0)throw RangeError(`Invalid type: ${S}`);this[Cr]=createWritableStreamState();let C=extractSizeAlgorithm(n?.size),N=extractHighWaterMark(n?.highWaterMark,1);setupWritableStreamDefaultControllerFromSink(this,t,N,C)}get locked(){if(!jr(this))throw TypeError(`Invalid this`);return isWritableStreamLocked(this)}abort(t){return jr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){return jr(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(!jr(this))throw TypeError(`Invalid this`);return new WritableStreamDefaultWriter(this)}get[Symbol.toStringTag](){return`WritableStream`}},WritableStreamDefaultWriter=class{[wr]=`WritableStreamDefaultWriter`;[Cr];constructor(t){if(!jr(t))throw TypeError(`Expected a WritableStream`);this[Cr]={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,t)}get closed(){return Mr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}get desiredSize(){if(!Mr(this))throw TypeError(`Invalid this`);if(this[Cr].stream===void 0)throw TypeError(`Writer is not bound to a WritableStream`);return writableStreamDefaultWriterGetDesiredSize(this)}get ready(){return Mr(this)?this[Cr].ready.promise:Promise.reject(TypeError(`Invalid this`))}abort(t){return Mr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){if(!Mr(this))return Promise.reject(TypeError(`Invalid this`));let{stream:t}=this[Cr];return t===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamCloseQueuedOrInFlight(t)?Promise.reject(TypeError(`Failure to close WritableStream`)):writableStreamDefaultWriterClose(this)}releaseLock(){if(!Mr(this))throw TypeError(`Invalid this`);let{stream:t}=this[Cr];t!==void 0&&writableStreamDefaultWriterRelease(this)}write(t){return Mr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterWrite(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`WritableStreamDefaultWriter`}},WritableStreamDefaultController=class{[wr]=`WritableStreamDefaultController`;[Cr];constructor(t){if(t!==Ar)throw TypeError(`Illegal constructor`)}[Dr](t){let n=this[Cr].abortAlgorithm(t);return writableStreamDefaultControllerClearAlgorithms(this),n}[kr](){resetQueue(this)}get signal(){if(!Nr(this))throw TypeError(`Invalid this`);return this[Cr].abortController.signal}error(t){if(!Nr(this))throw TypeError(`Invalid this`);this[Cr].stream[Cr].state===`writable`&&writableStreamDefaultControllerError(this,t)}get[Symbol.toStringTag](){return`WritableStreamDefaultController`}};const jr=isBrandCheck(`WritableStream`),Mr=isBrandCheck(`WritableStreamDefaultWriter`),Nr=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(t){return t[Cr].writer!==void 0}function setupWritableStreamDefaultWriter(t,n){if(isWritableStreamLocked(n))throw TypeError(`WritableStream is locked`);switch(t[Cr].stream=n,n[Cr].writer=t,n[Cr].state){case`writable`:!writableStreamCloseQueuedOrInFlight(n)&&n[Cr].backpressure?t[Cr].ready=Promise.withResolvers():t[Cr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Cr].close=Promise.withResolvers();break;case`erroring`:t[Cr].ready={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise),t[Cr].close=Promise.withResolvers();break;case`closed`:t[Cr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Cr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;default:t[Cr].ready={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},t[Cr].close={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise),setPromiseHandled(t[Cr].close.promise)}}function writableStreamAbort(t,n){let{state:S,controller:C}=t[Cr];if(S===`closed`||S===`errored`)return Promise.resolve();if(C[Cr].abortController.abort(n),t[Cr].pendingAbortRequest.abort.promise!==void 0)return t[Cr].pendingAbortRequest.abort.promise;let N=!1;S===`erroring`&&(N=!0,n=void 0);let F=Promise.withResolvers();return t[Cr].pendingAbortRequest={abort:F,reason:n,wasAlreadyErroring:N},N||writableStreamStartErroring(t,n),F.promise}function writableStreamClose(t){let{state:n,writer:S,backpressure:C,controller:N}=t[Cr];if(n===`closed`||n===`errored`)return Promise.reject(TypeError(`WritableStream is closed`));t[Cr].closeRequest=Promise.withResolvers();let{promise:F}=t[Cr].closeRequest;return S!==void 0&&C&&n===`writable`&&S[Cr].ready.resolve?.(),writableStreamDefaultControllerClose(N),F}function writableStreamUpdateBackpressure(t,n){let{writer:S}=t[Cr];S!==void 0&&t[Cr].backpressure!==n&&(n?S[Cr].ready=Promise.withResolvers():S[Cr].ready.resolve?.()),t[Cr].backpressure=n}function writableStreamStartErroring(t,n){let{controller:S,writer:C}=t[Cr];t[Cr].state=`erroring`,t[Cr].storedError=n,C!==void 0&&writableStreamDefaultWriterEnsureReadyPromiseRejected(C,n),!writableStreamHasOperationMarkedInFlight(t)&&S[Cr].started&&writableStreamFinishErroring(t)}function writableStreamRejectCloseAndClosedPromiseIfNeeded(t){t[Cr].closeRequest.promise!==void 0&&(t[Cr].closeRequest.reject?.(t[Cr].storedError),t[Cr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}),setPromiseHandled(t[Cr].close.promise),t[Cr].close.reject?.(t[Cr].storedError);let{writer:n}=t[Cr];n!==void 0&&(setPromiseHandled(n[Cr].close.promise),n[Cr].close.reject?.(t[Cr].storedError))}function writableStreamMarkFirstWriteRequestInFlight(t){let n=t[Cr].writeRequests.shift();t[Cr].inFlightWriteRequest=n}function writableStreamMarkCloseRequestInFlight(t){t[Cr].inFlightCloseRequest=t[Cr].closeRequest,t[Cr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamHasOperationMarkedInFlight(t){return t[Cr].inFlightWriteRequest.promise!==void 0||t[Cr].inFlightCloseRequest.promise!==void 0}function writableStreamFinishInFlightWriteWithError(t,n){t[Cr].inFlightWriteRequest.reject?.(n),t[Cr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0},writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightWrite(t){t[Cr].inFlightWriteRequest.resolve?.(),t[Cr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamFinishInFlightCloseWithError(t,n){t[Cr].inFlightCloseRequest.reject?.(n),t[Cr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Cr].pendingAbortRequest.abort.promise!==void 0&&(t[Cr].pendingAbortRequest.abort.reject?.(n),t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1}),writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightClose(t){t[Cr].inFlightCloseRequest.resolve?.(),t[Cr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Cr].state===`erroring`&&(t[Cr].storedError=void 0,t[Cr].pendingAbortRequest.abort.promise!==void 0&&(t[Cr].pendingAbortRequest.abort.resolve?.(),t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1})),t[Cr].state=`closed`,t[Cr].writer!==void 0&&t[Cr].writer[Cr].close.resolve?.(),t[Cr].close.resolve?.()}function writableStreamFinishErroring(t){t[Cr].state=`errored`,t[Cr].controller[kr]();let n=t[Cr].storedError;for(let S of t[Cr].writeRequests)S.reject?.(n);if(t[Cr].writeRequests=[],t[Cr].pendingAbortRequest.abort.promise===void 0){writableStreamRejectCloseAndClosedPromiseIfNeeded(t);return}let S=t[Cr].pendingAbortRequest;if(t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1},S.wasAlreadyErroring){S.abort.reject?.(n),writableStreamRejectCloseAndClosedPromiseIfNeeded(t);return}t[Cr].controller[Dr](S.reason).then(()=>{S.abort.resolve?.(),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)},n=>{S.abort.reject?.(n),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)})}function writableStreamDealWithRejection(t,n){if(t[Cr].state===`writable`){writableStreamStartErroring(t,n);return}writableStreamFinishErroring(t)}function writableStreamCloseQueuedOrInFlight(t){return t[Cr].closeRequest.promise!==void 0||t[Cr].inFlightCloseRequest.promise!==void 0}function writableStreamAddWriteRequest(t){let{promise:n,resolve:S,reject:C}=Promise.withResolvers();return t[Cr].writeRequests.push({promise:n,resolve:S,reject:C}),n}function writableStreamDefaultWriterWrite(t,n){let{stream:S}=t[Cr],{controller:C}=S[Cr],N=writableStreamDefaultControllerGetChunkSize(C,n);if(S!==t[Cr].stream)return Promise.reject(TypeError(`Mismatched WritableStreams`));let{state:F}=S[Cr];if(F===`errored`)return Promise.reject(S[Cr].storedError);if(writableStreamCloseQueuedOrInFlight(S)||F===`closed`)return Promise.reject(TypeError(`WritableStream is closed`));if(F===`erroring`)return Promise.reject(S[Cr].storedError);let I=writableStreamAddWriteRequest(S);return writableStreamDefaultControllerWrite(C,n,N),I}function writableStreamDefaultWriterRelease(t){let{stream:n}=t[Cr],S=TypeError(`Writer has been released`);writableStreamDefaultWriterEnsureReadyPromiseRejected(t,S),writableStreamDefaultWriterEnsureClosedPromiseRejected(t,S),n[Cr].writer=void 0,t[Cr].stream=void 0}function writableStreamDefaultWriterGetDesiredSize(t){let{stream:n}=t[Cr];switch(n[Cr].state){case`errored`:case`erroring`:return null;case`closed`:return 0}return writableStreamDefaultControllerGetDesiredSize(n[Cr].controller)}function writableStreamDefaultWriterEnsureReadyPromiseRejected(t,n){t[Cr].ready.reject?(t[Cr].ready.reject(n),t[Cr].ready.resolve=void 0,t[Cr].ready.reject=void 0):t[Cr].ready={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise)}function writableStreamDefaultWriterEnsureClosedPromiseRejected(t,n){t[Cr].close.reject?(t[Cr].close.reject(n),t[Cr].close.resolve=void 0,t[Cr].close.reject=void 0):t[Cr].close={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise)}function writableStreamDefaultWriterCloseWithErrorPropagation(t){let{stream:n}=t[Cr],{state:S}=n[Cr];return writableStreamCloseQueuedOrInFlight(n)||S===`closed`?Promise.resolve():S===`errored`?Promise.reject(n[Cr].storedError):writableStreamDefaultWriterClose(t)}function writableStreamDefaultWriterClose(t){return writableStreamClose(t[Cr].stream)}function writableStreamDefaultWriterAbort(t,n){return writableStreamAbort(t[Cr].stream,n)}function writableStreamDefaultControllerWrite(t,n,S){try{enqueueValueWithSize(t,n,S)}catch(n){writableStreamDefaultControllerErrorIfNeeded(t,n);return}let{stream:C}=t[Cr];!writableStreamCloseQueuedOrInFlight(C)&&C[Cr].state===`writable`&&writableStreamUpdateBackpressure(C,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerProcessWrite(t,n){let{stream:S,writeAlgorithm:C}=t[Cr];writableStreamMarkFirstWriteRequestInFlight(S),C(n,t).then(()=>{writableStreamFinishInFlightWrite(S);let{state:n}=S[Cr];dequeueValue(t),!writableStreamCloseQueuedOrInFlight(S)&&n===`writable`&&writableStreamUpdateBackpressure(S,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)},n=>{S[Cr].state===`writable`&&writableStreamDefaultControllerClearAlgorithms(t),writableStreamFinishInFlightWriteWithError(S,n)})}function writableStreamDefaultControllerProcessClose(t){let{closeAlgorithm:n,stream:S}=t[Cr];writableStreamMarkCloseRequestInFlight(S),dequeueValue(t);let C=n();writableStreamDefaultControllerClearAlgorithms(t),C.then(()=>writableStreamFinishInFlightClose(S),t=>writableStreamFinishInFlightCloseWithError(S,t))}function writableStreamDefaultControllerGetDesiredSize(t){return t[Cr].highWaterMark-t[Cr].queueTotalSize}function writableStreamDefaultControllerGetChunkSize(t,n){let{sizeAlgorithm:S}=t[Cr];if(S===void 0)return 1;try{return S(n)}catch(n){return writableStreamDefaultControllerErrorIfNeeded(t,n),1}}function writableStreamDefaultControllerErrorIfNeeded(t,n){t[Cr].stream[Cr].state===`writable`&&writableStreamDefaultControllerError(t,n)}function writableStreamDefaultControllerError(t,n){writableStreamDefaultControllerClearAlgorithms(t),writableStreamStartErroring(t[Cr].stream,n)}function writableStreamDefaultControllerClose(t){enqueueValueWithSize(t,Or,0),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerClearAlgorithms(t){t[Cr].writeAlgorithm=void 0,t[Cr].closeAlgorithm=void 0,t[Cr].abortAlgorithm=void 0,t[Cr].sizeAlgorithm=void 0}function writableStreamDefaultControllerGetBackpressure(t){return writableStreamDefaultControllerGetDesiredSize(t)<=0}function writableStreamDefaultControllerAdvanceQueueIfNeeded(t){let{queue:n,started:S,stream:C}=t[Cr];if(!S||C[Cr].inFlightWriteRequest.promise!==void 0)return;if(C[Cr].state===`erroring`){writableStreamFinishErroring(C);return}if(!n.length)return;let N=peekQueueValue(t);N===Or?writableStreamDefaultControllerProcessClose(t):writableStreamDefaultControllerProcessWrite(t,N)}function setupWritableStreamDefaultControllerFromSink(t,n,S,C){let N=new WritableStreamDefaultController(Ar),F=n?.start,I=n?.write,H=n?.close,W=n?.abort;setupWritableStreamDefaultController(t,N,F?F.bind(n,N):nonOpStart,I?createPromiseCallback(`sink.write`,I,n):nonOpWrite,H?createPromiseCallback(`sink.close`,H,n):nonOpCancel,W?createPromiseCallback(`sink.abort`,W,n):nonOpCancel,S,C)}function setupWritableStreamDefaultController(t,n,S,C,N,F,I,H){n[Cr]={abortAlgorithm:F,closeAlgorithm:N,highWaterMark:I,queue:[],queueTotalSize:0,abortController:new Er,sizeAlgorithm:H,started:!1,stream:t,writeAlgorithm:C},t[Cr].controller=n,writableStreamUpdateBackpressure(t,writableStreamDefaultControllerGetBackpressure(n));let W=S();new Promise(t=>t(W)).then(()=>{n[Cr].started=!0,writableStreamDefaultControllerAdvanceQueueIfNeeded(n)},S=>{n[Cr].started=!0,writableStreamDealWithRejection(t,S)})}function createWritableStream(t,n,S,C,N=1,F=()=>1){let I=Object.create(WritableStream.prototype);return I[wr]=`WritableStream`,I[Cr]=createWritableStreamState(),setupWritableStreamDefaultController(I,new WritableStreamDefaultController(Ar),t,n,S,C,N,F),I}ze();const Pr=Symbol(`kCancel`),Fr=Symbol(`kClose`),Ir=Symbol(`kChunk`),Lr=Symbol(`kError`),Rr=Symbol(`kPull`),zr=Symbol(`kRelease`),Br=Symbol(`kSkipThrow`);let Vr,Hr;function lazyReadableReleasedError(){return Vr||(Vr=TypeError(`Reader released`),Vr)}function lazyReadableReleasingError(){return Hr||(Hr=TypeError(`Releasing reader`),Hr)}function createAbortError$1(){if(typeof globalThis.DOMException==`function`)return new DOMException(`The operation was aborted`,`AbortError`);let t=Error(`The operation was aborted`);return t.name=`AbortError`,t}__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`)}[wr]=`ReadableStream`;[Cr];constructor(t={},n={}){if(t!=null&&typeof t!=`object`)throw TypeError(`source must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`strategy must be an object`);this[Cr]=createReadableStreamState();let S=n?.size,C=n?.highWaterMark,N=t?.type;if(N!==void 0){if(`${N}`==`bytes`){if(S!==void 0)throw RangeError(`strategy.size must not be set for a byte stream`);setupReadableByteStreamControllerFromSource(this,t,extractHighWaterMark(C,0));return}throw RangeError(`Invalid type: ${N}`)}setupReadableStreamDefaultControllerFromSource(this,t,extractHighWaterMark(C,1),extractSizeAlgorithm(S))}get locked(){if(!Ur(this))throw TypeError(`Invalid this`);return isReadableStreamLocked(this)}static from(t){return readableStreamFromIterable(t)}cancel(t=void 0){return Ur(this)?isReadableStreamLocked(this)?Promise.reject(TypeError(`ReadableStream is locked`)):readableStreamCancel(this,t):Promise.reject(TypeError(`Invalid this`))}getReader(t={}){if(!Ur(this))throw TypeError(`Invalid this`);if(t!=null&&typeof t!=`object`)throw TypeError(`options must be an object`);let n=t?.mode;if(n===void 0)return new ReadableStreamDefaultReader(this);if(`${n}`==`byob`)return new ReadableStreamBYOBReader(this);throw RangeError(`Invalid mode: ${n}`)}pipeThrough(t,n={}){if(!Ur(this))throw TypeError(`Invalid this`);let S=t?.readable;if(!Ur(S))throw TypeError(`transform.readable must be a ReadableStream`);let C=t?.writable;if(!jr(C))throw TypeError(`transform.writable must be a WritableStream`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let N=n?.preventAbort,F=n?.preventCancel,I=n?.preventClose,H=n?.signal;if(H!==void 0&&!(H instanceof Object&&`aborted`in H))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(C))throw TypeError(`The WritableStream is locked`);return setPromiseHandled(readableStreamPipeTo(this,C,!!I,!!N,!!F,H)),S}pipeTo(t,n={}){try{if(!Ur(this))throw TypeError(`Invalid this`);if(!jr(t))throw TypeError(`destination must be a WritableStream`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let S=n?.preventAbort,C=n?.preventCancel,N=n?.preventClose,F=n?.signal;if(F!==void 0&&!(F instanceof Object&&`aborted`in F))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(t))throw TypeError(`The WritableStream is locked`);return readableStreamPipeTo(this,t,!!N,!!S,!!C,F)}catch(t){return Promise.reject(t)}}tee(){if(!Ur(this))throw TypeError(`Invalid this`);let t=this[Cr].controller;return Kr(t)?readableByteStreamTee(this):readableStreamDefaultTee(this,!1)}values(t={}){if(!Ur(this))throw TypeError(`Invalid this`);if(t!=null&&typeof t!=`object`)throw TypeError(`options must be an object`);let n=!!t?.preventCancel,S=new ReadableStreamDefaultReader(this),C={done:!1,current:void 0},N=!1;function nextSteps(){if(C.done)return Promise.resolve({done:!0,value:void 0});if(S[Cr].stream===void 0)return Promise.reject(TypeError(`The reader is not bound to a ReadableStream`));let{promise:t,resolve:n,reject:N}=Promise.withResolvers();return readableStreamDefaultReaderRead(S,{[Ir](t){C.current=void 0,n({value:t,done:!1})},[Fr](){C.current=void 0,C.done=!0,readableStreamReaderGenericRelease(S),n({done:!0,value:void 0})},[Lr](t){C.current=void 0,C.done=!0,readableStreamReaderGenericRelease(S),N(t)}}),t}async function returnSteps(t){if(C.done)return{done:!0,value:t};if(C.done=!0,S[Cr].stream===void 0)throw TypeError(`The reader is not bound to a ReadableStream`);if(!n){let n=readableStreamReaderGenericCancel(S,t);return readableStreamReaderGenericRelease(S),await n,{done:!0,value:t}}return readableStreamReaderGenericRelease(S),{done:!0,value:t}}return Object.setPrototypeOf({next(){return N||=(C.current=Promise.resolve(),!0),C.current=C.current===void 0?nextSteps():C.current.then(nextSteps,nextSteps),C.current},return(t){return N=!0,C.current=C.current===void 0?returnSteps(t):C.current.then(()=>returnSteps(t),()=>returnSteps(t)),C.current},[Symbol.asyncIterator](){return this}},Tr)}[Symbol.asyncIterator](){return this.values()}get[Symbol.toStringTag](){return`ReadableStream`}},DefaultReadRequest=class{[Cr];constructor(){this[Cr]=Promise.withResolvers()}[Ir](t){this[Cr].resolve?.({value:t,done:!1})}[Fr](){this[Cr].resolve?.({value:void 0,done:!0})}[Lr](t){this[Cr].reject?.(t)}get promise(){return this[Cr].promise}},ReadableStreamDefaultReader=class{[wr]=`ReadableStreamDefaultReader`;[Cr];constructor(t){if(!Ur(t))throw TypeError(`Expected a ReadableStream`);this[Cr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamDefaultReader(this,t)}read(){if(!Gr(this))return Promise.reject(TypeError(`Invalid this`));if(this[Cr].stream===void 0)return Promise.reject(TypeError(`The reader is not attached to a stream`));let t=this[Cr].stream,n=t[Cr].controller;if(t[Cr].state===`readable`&&Wr(n)&&n[Cr].queue.length>0){t[Cr].disturbed=!0;let S=dequeueValue(n);return n[Cr].closeRequested&&!n[Cr].queue.length?(readableStreamDefaultControllerClearAlgorithms(n),readableStreamClose(t)):readableStreamDefaultControllerCallPullIfNeeded(n),Promise.resolve({value:S,done:!1})}let S=new DefaultReadRequest;return readableStreamDefaultReaderRead(this,S),S.promise}releaseLock(){if(!Gr(this))throw TypeError(`Invalid this`);this[Cr].stream!==void 0&&readableStreamDefaultReaderRelease(this)}get closed(){return Gr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return Gr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`The reader is not attached to a stream`)):readableStreamReaderGenericCancel(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamDefaultReader`}},ReadableStreamDefaultController=class{[wr]=`ReadableStreamDefaultController`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get desiredSize(){return readableStreamDefaultControllerGetDesiredSize(this)}close(){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerClose(this)}enqueue(t=void 0){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerEnqueue(this,t)}error(t=void 0){readableStreamDefaultControllerError(this,t)}[Pr](t){return readableStreamDefaultControllerCancelSteps(this,t)}[Rr](t){readableStreamDefaultControllerPullSteps(this,t)}[zr](){}get[Symbol.toStringTag](){return`ReadableStreamDefaultController`}};const Ur=isBrandCheck(`ReadableStream`),Wr=isBrandCheck(`ReadableStreamDefaultController`),Gr=isBrandCheck(`ReadableStreamDefaultReader`);function isReadableStreamLocked(t){return t[Cr].reader!==void 0}function readableStreamCancel(t,n){switch(t[Cr].disturbed=!0,t[Cr].state){case`closed`:return Promise.resolve();case`errored`:return Promise.reject(t[Cr].storedError)}readableStreamClose(t);let S=t[Cr].reader;if(S!==void 0&&readableStreamHasBYOBReader(t)){let t=S[Cr].readIntoRequests;S[Cr].readIntoRequests=[];for(let n=0;n<t.length;n++)t[n][Fr](void 0)}return t[Cr].controller[Pr](n).then(()=>{})}function readableStreamClose(t){t[Cr].state=`closed`,t[Cr].closedPromise.resolve();let{reader:n}=t[Cr];if(n!==void 0&&(n[Cr].close.resolve?.(),readableStreamHasDefaultReader(t))){for(let t=0;t<n[Cr].readRequests.length;t++)n[Cr].readRequests[t][Fr]();n[Cr].readRequests=[]}}function readableStreamError(t,n){t[Cr].state=`errored`,t[Cr].storedError=n,setPromiseHandled(t[Cr].closedPromise.promise),t[Cr].closedPromise.reject(n);let{reader:S}=t[Cr];if(S!==void 0){if(setPromiseHandled(S[Cr].close.promise),S[Cr].close.reject?.(n),readableStreamHasDefaultReader(t)){for(let t=0;t<S[Cr].readRequests.length;t++)S[Cr].readRequests[t][Lr](n);S[Cr].readRequests=[]}else if(readableStreamHasBYOBReader(t)){for(let t=0;t<S[Cr].readIntoRequests.length;t++)S[Cr].readIntoRequests[t][Lr](n);S[Cr].readIntoRequests=[]}}}function readableStreamHasDefaultReader(t){let{reader:n}=t[Cr];return n===void 0?!1:n[Cr]!==void 0&&n[wr]===`ReadableStreamDefaultReader`}function readableStreamGetNumReadRequests(t){return t[Cr].reader[Cr].readRequests.length}function readableStreamFulfillReadRequest(t,n,S){let{reader:C}=t[Cr],N=C[Cr].readRequests.shift();S?N[Fr]():N[Ir](n)}function readableStreamAddReadRequest(t,n){t[Cr].reader[Cr].readRequests.push(n)}function readableStreamReaderGenericCancel(t,n){let{stream:S}=t[Cr];return readableStreamCancel(S,n)}function readableStreamReaderGenericInitialize(t,n){switch(t[Cr].stream=n,n[Cr].reader=t,n[Cr].state){case`readable`:t[Cr].close=Promise.withResolvers();break;case`closed`:t[Cr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;case`errored`:t[Cr].close={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise);break}}function readableStreamReaderGenericRelease(t){let{stream:n}=t[Cr],S=lazyReadableReleasedError();n[Cr].state===`readable`?t[Cr].close.reject?.(S):t[Cr].close={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise),n[Cr].controller[zr](),n[Cr].reader=void 0,t[Cr].stream=void 0}function readableStreamDefaultReaderRelease(t){readableStreamReaderGenericRelease(t),readableStreamDefaultReaderErrorReadRequests(t,lazyReadableReleasingError())}function readableStreamDefaultReaderErrorReadRequests(t,n){for(let S=0;S<t[Cr].readRequests.length;++S)t[Cr].readRequests[S][Lr](n);t[Cr].readRequests=[]}function readableStreamDefaultReaderRead(t,n){let{stream:S}=t[Cr];switch(S[Cr].disturbed=!0,S[Cr].state){case`closed`:n[Fr]();break;case`errored`:n[Lr](S[Cr].storedError);break;case`readable`:S[Cr].controller[Rr](n);break}}function setupReadableStreamDefaultReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);readableStreamReaderGenericInitialize(t,n),t[Cr].readRequests=[]}function readableStreamDefaultControllerClose(t){readableStreamDefaultControllerCanCloseOrEnqueue(t)&&(t[Cr].closeRequested=!0,t[Cr].queue.length||(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(t[Cr].stream)))}function readableStreamDefaultControllerEnqueue(t,n){if(!readableStreamDefaultControllerCanCloseOrEnqueue(t))return;let{stream:S}=t[Cr];if(isReadableStreamLocked(S)&&readableStreamGetNumReadRequests(S))readableStreamFulfillReadRequest(S,n,!1);else try{enqueueValueWithSize(t,n,t[Cr].sizeAlgorithm(n))}catch(n){throw readableStreamDefaultControllerError(t,n),n}readableStreamDefaultControllerCallPullIfNeeded(t)}function readableStreamDefaultControllerCanCloseOrEnqueue(t){let{stream:n}=t[Cr];return!t[Cr].closeRequested&&n[Cr].state===`readable`}function readableStreamDefaultControllerGetDesiredSize(t){let{stream:n,highWaterMark:S,queueTotalSize:C}=t[Cr];switch(n[Cr].state){case`errored`:return null;case`closed`:return 0;default:return S-C}}function readableStreamDefaultControllerHasBackpressure(t){return!readableStreamDefaultControllerShouldCallPull(t)}function readableStreamDefaultControllerShouldCallPull(t){let{stream:n}=t[Cr];if(!readableStreamDefaultControllerCanCloseOrEnqueue(t)||!t[Cr].started)return!1;if(isReadableStreamLocked(n)&&readableStreamGetNumReadRequests(n))return!0;let S=readableStreamDefaultControllerGetDesiredSize(t);return S!==null&&S>0}function readableStreamDefaultControllerCallPullIfNeeded(t){if(readableStreamDefaultControllerShouldCallPull(t)){if(t[Cr].pulling){t[Cr].pullAgain=!0;return}t[Cr].pulling=!0,t[Cr].pullAlgorithm(t).then(()=>{t[Cr].pulling=!1,t[Cr].pullAgain&&(t[Cr].pullAgain=!1,readableStreamDefaultControllerCallPullIfNeeded(t))},n=>readableStreamDefaultControllerError(t,n))}}function readableStreamDefaultControllerClearAlgorithms(t){t[Cr].pullAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0,t[Cr].sizeAlgorithm=void 0}function readableStreamDefaultControllerError(t,n){let{stream:S}=t[Cr];S[Cr].state===`readable`&&(resetQueue(t),readableStreamDefaultControllerClearAlgorithms(t),readableStreamError(S,n))}function readableStreamDefaultControllerCancelSteps(t,n){resetQueue(t);let S=t[Cr].cancelAlgorithm?.(n)??Promise.resolve();return readableStreamDefaultControllerClearAlgorithms(t),S}function readableStreamDefaultControllerPullSteps(t,n){let{stream:S,queue:C}=t[Cr];if(C.length){let N=dequeueValue(t);t[Cr].closeRequested&&!C.length?(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(S)):readableStreamDefaultControllerCallPullIfNeeded(t),n[Ir](N);return}readableStreamAddReadRequest(S,n),readableStreamDefaultControllerCallPullIfNeeded(t)}function setupReadableStreamDefaultController(t,n,S,C,N,F,I){n[Cr]={cancelAlgorithm:N,closeRequested:!1,highWaterMark:F,pullAgain:!1,pullAlgorithm:C,pulling:!1,queue:[],queueTotalSize:0,started:!1,sizeAlgorithm:I,stream:t},t[Cr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Cr].started=!0,readableStreamDefaultControllerCallPullIfNeeded(n)},t=>readableStreamDefaultControllerError(n,t))}function setupReadableStreamDefaultControllerFromSource(t,n,S,C){let N=new ReadableStreamDefaultController(Br),F=n?.start,I=n?.pull,H=n?.cancel;setupReadableStreamDefaultController(t,N,F?F.bind(n,N):nonOpStart,I?createPromiseCallback(`source.pull`,I,n):nonOpPull,H?createPromiseCallback(`source.cancel`,H,n):nonOpCancel,S,C)}function createReadableStream(t,n,S,C=1,N=()=>1){let F=Object.create(ReadableStream$1.prototype);return F[wr]=`ReadableStream`,F[Cr]=createReadableStreamState(),setupReadableStreamDefaultController(F,new ReadableStreamDefaultController(Br),t,n,S,C,N),F}function readableStreamFromIterable(t){let n,S=getIterator(t,`async`),C=nonOpStart;async function pullAlgorithm(){let t=iteratorNext(S);return Promise.resolve(t).then(t=>{if(typeof t!=`object`||!t)throw TypeError(`The promise returned by the iterator.next() method must fulfill with an object`);t.done?readableStreamDefaultControllerClose(n[Cr].controller):readableStreamDefaultControllerEnqueue(n[Cr].controller,t.value)})}async function cancelAlgorithm(t){let n=S.iterator,C=n.return;if(C===void 0)return Promise.resolve();let N=C.call(n,t);return Promise.resolve(N).then(t=>{if(typeof t!=`object`||!t)throw TypeError(`The promise returned by the iterator.return() method must fulfill with an object`)})}return n=createReadableStream(C,pullAlgorithm,cancelAlgorithm,0),n}function readableStreamPipeTo(t,n,S,C,N,F){let I,H;try{I=new ReadableStreamDefaultReader(t),H=new WritableStreamDefaultWriter(n)}catch(t){return Promise.reject(t)}t[Cr].disturbed=!0;let W=!1,{promise:q,resolve:Y,reject:X}=Promise.withResolvers(),Z={currentWrite:Promise.resolve()},te;function finalize(t,n){writableStreamDefaultWriterRelease(H),readableStreamReaderGenericRelease(I),F!==void 0&&te&&(F.removeEventListener(`abort`,te),te=void 0),t?X(n):Y()}async function waitForCurrentWrite(){let t=Z.currentWrite;await t,t!==Z.currentWrite&&await waitForCurrentWrite()}function shutdownWithAnAction(t,S,C){if(W)return;if(W=!0,n[Cr].state===`writable`&&!writableStreamCloseQueuedOrInFlight(n)){waitForCurrentWrite().then(complete,t=>finalize(!0,t));return}complete();function complete(){t().then(()=>finalize(!!S,C),t=>finalize(!0,t))}}function shutdown(t,S){if(!W){if(W=!0,n[Cr].state===`writable`&&!writableStreamCloseQueuedOrInFlight(n)){waitForCurrentWrite().then(()=>finalize(!!t,S),t=>finalize(!0,t));return}finalize(!!t,S)}}function abortAlgorithm(){let S;S=F.reason&&F.reason.name===`AbortError`?createAbortError$1():F.reason;let I=[];C||I.push(()=>n[Cr].state===`writable`?writableStreamAbort(n,S):Promise.resolve()),N||I.push(()=>t[Cr].state===`readable`?readableStreamCancel(t,S):Promise.resolve()),shutdownWithAnAction(()=>Promise.all(I.map(t=>t())).then(()=>void 0),!0,S)}function watchErrored(t,n,S){t[Cr].state===`errored`?S(t[Cr].storedError):n.then(void 0,S)}function watchClosed(t,n,S){t[Cr].state===`closed`?S():n.then(S,()=>{})}class PipeToReadRequest{[Ir](t){ve(()=>{Z.currentWrite=writableStreamDefaultWriterWrite(H,t),setPromiseHandled(Z.currentWrite),ne.resolve(!1)})}[Fr](){ne.resolve(!0)}[Lr](t){ne.reject(t)}}let ne={resolve:null,reject:null};async function step(){if(W||n[Cr].backpressure&&(await H[Cr].ready.promise,W))return!0;let S=t[Cr].controller;if(t[Cr].state===`readable`&&Wr(S)&&S[Cr].queue.length>0){for(;S[Cr].queue.length>0;){if(W)return!0;let C=dequeueValue(S);if(S[Cr].closeRequested&&!S[Cr].queue.length&&(readableStreamDefaultControllerClearAlgorithms(S),readableStreamClose(t)),Z.currentWrite=writableStreamDefaultWriterWrite(H,C),setPromiseHandled(Z.currentWrite),n[Cr].backpressure||n[Cr].state!==`writable`||writableStreamCloseQueuedOrInFlight(n))break}return readableStreamDefaultControllerCallPullIfNeeded(S),t[Cr].state===`closed`}let{promise:C,resolve:N,reject:F}=Promise.withResolvers();return ne={resolve:N,reject:F},readableStreamDefaultReaderRead(I,new PipeToReadRequest),C}async function run(){for(;!await step(););}if(F!==void 0){if(F.aborted)return abortAlgorithm(),q;te=abortAlgorithm,F.addEventListener(`abort`,te,{once:!0})}if(setPromiseHandled(run()),watchErrored(t,I[Cr].close.promise,t=>{if(!C)return shutdownWithAnAction(()=>writableStreamAbort(n,t),!0,t);shutdown(!0,t)}),watchErrored(n,H[Cr].close.promise,n=>{if(!N)return shutdownWithAnAction(()=>readableStreamCancel(t,n),!0,n);shutdown(!0,n)}),watchClosed(t,I[Cr].close.promise,()=>{if(!S)return shutdownWithAnAction(()=>writableStreamDefaultWriterCloseWithErrorPropagation(H));shutdown()}),writableStreamCloseQueuedOrInFlight(n)||n[Cr].state===`closed`){let n=TypeError(`Destination WritableStream is closed`);N?shutdown(!0,n):shutdownWithAnAction(()=>readableStreamCancel(t,n),!0,n)}return q}function readableStreamDefaultTee(t,n){let S=new ReadableStreamDefaultReader(t),C=!1,N=!1,F=!1,I,H,W,q,Y=Promise.withResolvers();async function pullAlgorithm(){C||(C=!0,readableStreamDefaultReaderRead(S,{[Ir](t){ve(()=>{C=!1;let S=t,I=t;if(!F&&n)try{I=structuredClone(I)}catch{}N||readableStreamDefaultControllerEnqueue(W[Cr].controller,S),F||readableStreamDefaultControllerEnqueue(q[Cr].controller,I)})},[Fr](){ve(()=>{C=!1,N||readableStreamDefaultControllerClose(W[Cr].controller),F||readableStreamDefaultControllerClose(q[Cr].controller),(!N||!F)&&Y.resolve(void 0)})},[Lr](){C=!1}}))}function cancel1Algorithm(n){if(N=!0,I=n,F){let n=[I,H];Y.resolve(readableStreamCancel(t,n))}return Y.promise}function cancel2Algorithm(n){if(F=!0,H=n,N){let n=[I,H];Y.resolve(readableStreamCancel(t,n))}return Y.promise}return W=createReadableStream(nonOpStart,pullAlgorithm,cancel1Algorithm),q=createReadableStream(nonOpStart,pullAlgorithm,cancel2Algorithm),S[Cr].close.promise.then(void 0,t=>{readableStreamDefaultControllerError(W[Cr].controller,t),readableStreamDefaultControllerError(q[Cr].controller,t),(!N||!F)&&Y.resolve(void 0)}),[W,q]}var BYOBReadIntoRequest=class{[Cr];constructor(){this[Cr]=Promise.withResolvers()}[Ir](t){this[Cr].resolve?.({value:t,done:!1})}[Fr](t){this[Cr].resolve?.({value:t,done:!0})}[Lr](t){this[Cr].reject?.(t)}get promise(){return this[Cr].promise}},ReadableStreamBYOBReader=class{[wr]=`ReadableStreamBYOBReader`;[Cr];constructor(t){if(!Ur(t))throw TypeError(`Expected a ReadableStream`);this[Cr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamBYOBReader(this,t)}read(t,n={}){if(!qr(this))return Promise.reject(TypeError(`Invalid this`));if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))return Promise.reject(TypeError(`view must be an ArrayBufferView`));let S=t.buffer,C=t.byteLength;if(C===0)return Promise.reject(TypeError(`view must have non-zero byteLength`));if(S.byteLength===0)return isDetachedBuffer(S)?Promise.reject(TypeError(`view's buffer has been detached`)):Promise.reject(TypeError(`view's buffer must have non-zero byteLength`));let N=n?.min??1;if(typeof N!=`number`||N<1||!Number.isInteger(N)||Number.isNaN(N))return Promise.reject(TypeError(`options.min must be a positive integer`));let F=t[Symbol.toStringTag];if(F!==void 0&&F!==`DataView`){if(N>t.length)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`))}else if(N>C)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`));if(this[Cr].stream===void 0)return Promise.reject(TypeError(`Reader has no associated stream`));let I=new BYOBReadIntoRequest;return readableStreamBYOBReaderRead(this,t,N,I),I.promise}releaseLock(){if(!qr(this))throw TypeError(`Invalid this`);this[Cr].stream!==void 0&&readableStreamBYOBReaderRelease(this)}get closed(){return qr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return qr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Reader has no associated stream`)):readableStreamReaderGenericCancel(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamBYOBReader`}},ReadableStreamBYOBRequest=class{[wr]=`ReadableStreamBYOBRequest`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get view(){if(!Jr(this))throw TypeError(`Invalid this`);return this[Cr].view}respond(t){if(!Jr(this))throw TypeError(`Invalid this`);if(this[Cr].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(t=+t,!Number.isInteger(t)||t<0||!Number.isFinite(t))throw RangeError(`bytesWritten must be a non-negative integer`);let n=this[Cr].view;if(isDetachedBuffer(n.buffer))throw TypeError(`The BYOB request's buffer has been detached`);readableByteStreamControllerRespond(this[Cr].controller,t)}respondWithNewView(t){if(!Jr(this))throw TypeError(`Invalid this`);if(this[Cr].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))throw TypeError(`view must be an ArrayBufferView`);if(isDetachedBuffer(t.buffer))throw TypeError(`The given view's buffer has been detached`);readableByteStreamControllerRespondWithNewView(this[Cr].controller,t)}get[Symbol.toStringTag](){return`ReadableStreamBYOBRequest`}},ReadableByteStreamController=class{[wr]=`ReadableByteStreamController`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get byobRequest(){if(!Kr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetBYOBRequest(this)}get desiredSize(){if(!Kr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetDesiredSize(this)}close(){if(!Kr(this))throw TypeError(`Invalid this`);if(this[Cr].closeRequested)throw TypeError(`Close already requested`);if(this[Cr].stream[Cr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerClose(this)}enqueue(t){if(!Kr(this))throw TypeError(`Invalid this`);if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))throw TypeError(`chunk must be an ArrayBufferView`);if(t.byteLength===0)throw TypeError(`chunk length must be non-zero`);if(t.buffer.byteLength===0)throw TypeError(`chunk's buffer length must be non-zero`);if(this[Cr].closeRequested)throw TypeError(`Cannot enqueue after close has been requested`);if(this[Cr].stream[Cr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerEnqueue(this,t)}error(t=void 0){if(!Kr(this))throw TypeError(`Invalid this`);readableByteStreamControllerError(this,t)}[Pr](t){return readableByteStreamControllerCancelSteps(this,t)}[Rr](t){readableByteStreamControllerPullSteps(this,t)}[zr](){if(this[Cr].pendingPullIntos.length>0){let t=this[Cr].pendingPullIntos[0];t.readerType=`none`,this[Cr].pendingPullIntos=[t]}}get[Symbol.toStringTag](){return`ReadableByteStreamController`}};const Kr=isBrandCheck(`ReadableByteStreamController`),qr=isBrandCheck(`ReadableStreamBYOBReader`),Jr=isBrandCheck(`ReadableStreamBYOBRequest`);function readableStreamHasBYOBReader(t){let{reader:n}=t[Cr];return n===void 0?!1:n[Cr]!==void 0&&n[wr]===`ReadableStreamBYOBReader`}function readableStreamGetNumReadIntoRequests(t){return t[Cr].reader[Cr].readIntoRequests.length}function readableStreamAddReadIntoRequest(t,n){t[Cr].reader[Cr].readIntoRequests.push(n)}function readableStreamFulfillReadIntoRequest(t,n,S){let{reader:C}=t[Cr],N=C[Cr].readIntoRequests.shift();S?N[Fr](n):N[Ir](n)}function setupReadableStreamBYOBReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);if(!Kr(n[Cr].controller))throw TypeError(`Cannot use a BYOB reader with a non-byte stream`);readableStreamReaderGenericInitialize(t,n),t[Cr].readIntoRequests=[]}function readableStreamBYOBReaderRead(t,n,S,C){let{stream:N}=t[Cr];N[Cr].disturbed=!0,N[Cr].state===`errored`?C[Lr](N[Cr].storedError):readableByteStreamControllerPullInto(N[Cr].controller,n,S,C)}function readableStreamBYOBReaderRelease(t){readableStreamReaderGenericRelease(t);let n=TypeError(`Reader was released`);for(let S=0;S<t[Cr].readIntoRequests.length;S++)t[Cr].readIntoRequests[S][Lr](n);t[Cr].readIntoRequests=[]}function readableByteStreamControllerClearAlgorithms(t){t[Cr].pullAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0}function readableByteStreamControllerClearPendingPullIntos(t){readableByteStreamControllerInvalidateBYOBRequest(t),t[Cr].pendingPullIntos=[]}function readableByteStreamControllerInvalidateBYOBRequest(t){let n=t[Cr].byobRequest;n!=null&&(n[Cr].controller=void 0,n[Cr].view=null,t[Cr].byobRequest=null)}function readableByteStreamControllerError(t,n){let{stream:S}=t[Cr];S[Cr].state===`readable`&&(readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t),readableByteStreamControllerClearAlgorithms(t),readableStreamError(S,n))}function readableByteStreamControllerGetDesiredSize(t){let n=t[Cr].stream[Cr].state;return n===`errored`?null:n===`closed`?0:t[Cr].highWaterMark-t[Cr].queueTotalSize}function readableByteStreamControllerShouldCallPull(t){let{stream:n}=t[Cr];if(n[Cr].state!==`readable`||t[Cr].closeRequested||!t[Cr].started)return!1;if(readableStreamHasDefaultReader(n)&&readableStreamGetNumReadRequests(n)>0||readableStreamHasBYOBReader(n)&&readableStreamGetNumReadIntoRequests(n)>0)return!0;let S=readableByteStreamControllerGetDesiredSize(t);return S!==null&&S>0}function readableByteStreamControllerCallPullIfNeeded(t){if(readableByteStreamControllerShouldCallPull(t)){if(t[Cr].pulling){t[Cr].pullAgain=!0;return}t[Cr].pulling=!0,t[Cr].pullAlgorithm(t).then(()=>{t[Cr].pulling=!1,t[Cr].pullAgain&&(t[Cr].pullAgain=!1,readableByteStreamControllerCallPullIfNeeded(t))},n=>readableByteStreamControllerError(t,n))}}function readableByteStreamControllerHandleQueueDrain(t){t[Cr].queueTotalSize===0&&t[Cr].closeRequested?(readableByteStreamControllerClearAlgorithms(t),readableStreamClose(t[Cr].stream)):readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerEnqueueChunkToQueue(t,n,S,C){t[Cr].queue.push({buffer:n,byteOffset:S,byteLength:C}),t[Cr].queueTotalSize+=C}function readableByteStreamControllerEnqueueClonedChunkToQueue(t,n,S,C){let N;try{N=n.slice(S,S+C)}catch(n){readableByteStreamControllerError(t,n);return}readableByteStreamControllerEnqueueChunkToQueue(t,N,0,C)}function readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,n){n.bytesFilled>0&&readableByteStreamControllerEnqueueClonedChunkToQueue(t,n.buffer,n.byteOffset,n.bytesFilled),readableByteStreamControllerShiftPendingPullInto(t)}function readableByteStreamControllerShiftPendingPullInto(t){return t[Cr].pendingPullIntos.shift()}function readableByteStreamControllerFillHeadPullIntoDescriptor(t,n,S){S.bytesFilled+=n}function readableByteStreamControllerConvertPullIntoDescriptor(t){let n=t.bytesFilled,S=t.elementSize,C=transferArrayBuffer(t.buffer);return t.buffer=C,new t.viewConstructor(C,t.byteOffset,n/S)}function readableByteStreamControllerCommitPullIntoDescriptor(t,n){let S=!1;t[Cr].state===`closed`&&(S=!0);let C=readableByteStreamControllerConvertPullIntoDescriptor(n);n.readerType==="default"?readableStreamFulfillReadRequest(t,C,S):readableStreamFulfillReadIntoRequest(t,C,S)}function readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,n){let S=Math.min(t[Cr].queueTotalSize,n.byteLength-n.bytesFilled),C=n.bytesFilled+S,N=S,F=!1,I=C-C%n.elementSize;I>=n.minimumFill&&(N=I-n.bytesFilled,F=!0);let H=t[Cr].queue;for(;N>0;){let S=H[0],C=Math.min(N,S.byteLength),F=n.byteOffset+n.bytesFilled,I=new Uint8Array(n.buffer,F,C),W=new Uint8Array(S.buffer,S.byteOffset,C);I.set(W),S.byteLength===C?H.shift():(S.byteOffset+=C,S.byteLength-=C),t[Cr].queueTotalSize-=C,readableByteStreamControllerFillHeadPullIntoDescriptor(t,C,n),N-=C}return F}function readableByteStreamControllerFillReadRequestFromQueue(t,n){let S=t[Cr].queue.shift();t[Cr].queueTotalSize-=S.byteLength,readableByteStreamControllerHandleQueueDrain(t);let C=new Uint8Array(S.buffer,S.byteOffset,S.byteLength);n[Ir](C)}function readableByteStreamControllerProcessReadRequestsUsingQueue(t){let n=t[Cr].stream[Cr].reader;for(;n[Cr].readRequests.length!==0;){if(t[Cr].queueTotalSize===0)return;readableByteStreamControllerFillReadRequestFromQueue(t,n[Cr].readRequests.shift())}}function readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t){for(;t[Cr].pendingPullIntos.length!==0;){if(t[Cr].queueTotalSize===0)return;let n=t[Cr].pendingPullIntos[0];readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,n)&&(readableByteStreamControllerShiftPendingPullInto(t),readableByteStreamControllerCommitPullIntoDescriptor(t[Cr].stream,n))}}function readableByteStreamControllerGetBYOBRequest(t){if(t[Cr].byobRequest===null&&t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0],S=new Uint8Array(n.buffer,n.byteOffset+n.bytesFilled,n.byteLength-n.bytesFilled),C=new ReadableStreamBYOBRequest(Br);C[Cr]={controller:t,view:S},t[Cr].byobRequest=C}return t[Cr].byobRequest}function readableByteStreamControllerEnqueue(t,n){let{stream:S}=t[Cr];if(t[Cr].closeRequested||S[Cr].state!==`readable`)return;let C=n.buffer,N=n.byteLength,F=n.byteOffset;if(isDetachedBuffer(C))throw TypeError(`chunk's buffer is detached`);let I=transferArrayBuffer(C);if(t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0];if(isDetachedBuffer(n.buffer))throw TypeError(`BYOB request's buffer has been detached`);readableByteStreamControllerInvalidateBYOBRequest(t),n.buffer=transferArrayBuffer(n.buffer),n.readerType===`none`&&readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,n)}readableStreamHasDefaultReader(S)?(readableByteStreamControllerProcessReadRequestsUsingQueue(t),readableStreamGetNumReadRequests(S)===0?readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N):(t[Cr].pendingPullIntos.length!==0&&readableByteStreamControllerShiftPendingPullInto(t),readableStreamFulfillReadRequest(S,new Uint8Array(I,F,N),!1))):readableStreamHasBYOBReader(S)?(readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t)):readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerClose(t){let{stream:n}=t[Cr];if(!(t[Cr].closeRequested||n[Cr].state!==`readable`)){if(t[Cr].queueTotalSize>0){t[Cr].closeRequested=!0;return}if(t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0];if(n.bytesFilled%n.elementSize!==0){let n=TypeError(`Insufficient bytes to fill elements in the given buffer`);throw readableByteStreamControllerError(t,n),n}}readableByteStreamControllerClearAlgorithms(t),readableStreamClose(n)}}function readableByteStreamControllerPullInto(t,n,S,C){let N=t[Cr].stream,F=n[Symbol.toStringTag],I,H;if(F===void 0||F===`DataView`)I=DataView,H=1;else{let t=typedArrayConstructorByTag(F);if(!t){C[Lr](TypeError(`Unsupported typed array: ${F}`));return}I=t,H=elementSizeByTag(F)}let W=n.buffer,q=n.byteLength,Y=n.byteOffset,X=S*H,Z;try{Z=transferArrayBuffer(W)}catch(t){C[Lr](t);return}let te={buffer:Z,bufferByteLength:Z.byteLength,byteOffset:Y,byteLength:q,bytesFilled:0,minimumFill:X,elementSize:H,viewConstructor:I,readerType:`byob`};if(t[Cr].pendingPullIntos.length!==0){t[Cr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C);return}if(N[Cr].state===`closed`){let t=new I(te.buffer,te.byteOffset,0);C[Fr](t);return}if(t[Cr].queueTotalSize>0){if(readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,te)){let n=readableByteStreamControllerConvertPullIntoDescriptor(te);readableByteStreamControllerHandleQueueDrain(t),C[Ir](n);return}if(t[Cr].closeRequested){let n=TypeError(`Insufficient bytes to fill elements in the given buffer`);readableByteStreamControllerError(t,n),C[Lr](n);return}}t[Cr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespond(t,n){let S=t[Cr].pendingPullIntos[0];if(t[Cr].stream[Cr].state===`closed`){if(n!==0)throw TypeError(`bytesWritten must be 0 when calling respond() on a closed stream`)}else{if(n===0)throw TypeError(`bytesWritten must be greater than 0 when calling respond() on a readable stream`);if(S.bytesFilled+n>S.byteLength)throw RangeError(`bytesWritten out of range`)}S.buffer=transferArrayBuffer(S.buffer),readableByteStreamControllerRespondInternal(t,n)}function readableByteStreamControllerRespondWithNewView(t,n){let S=t[Cr].pendingPullIntos[0],C=t[Cr].stream[Cr].state,N=n.byteLength,F=n.byteOffset,I=n.buffer;if(C===`closed`){if(N!==0)throw TypeError(`view's length must be 0 when calling respondWithNewView() on a closed stream`)}else if(N===0)throw TypeError(`view's length must be greater than 0 when calling respondWithNewView() on a readable stream`);if(S.byteOffset+S.bytesFilled!==F)throw RangeError(`The region specified by view does not match byobRequest`);if(S.bufferByteLength!==I.byteLength)throw RangeError(`The buffer of view has different capacity than byobRequest`);if(S.bytesFilled+N>S.byteLength)throw RangeError(`The region specified by view is larger than byobRequest`);S.buffer=transferArrayBuffer(I),readableByteStreamControllerRespondInternal(t,N)}function readableByteStreamControllerRespondInternal(t,n){let S=t[Cr].pendingPullIntos[0];readableByteStreamControllerInvalidateBYOBRequest(t),t[Cr].stream[Cr].state===`closed`?readableByteStreamControllerRespondInClosedState(t,S):readableByteStreamControllerRespondInReadableState(t,n,S),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespondInClosedState(t,n){n.readerType===`none`&&readableByteStreamControllerShiftPendingPullInto(t);let S=t[Cr].stream;if(readableStreamHasBYOBReader(S))for(;readableStreamGetNumReadIntoRequests(S)>0;)readableByteStreamControllerCommitPullIntoDescriptor(S,readableByteStreamControllerShiftPendingPullInto(t))}function readableByteStreamControllerRespondInReadableState(t,n,S){if(readableByteStreamControllerFillHeadPullIntoDescriptor(t,n,S),S.readerType===`none`){readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,S),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t);return}if(S.bytesFilled<S.minimumFill)return;readableByteStreamControllerShiftPendingPullInto(t);let C=S.bytesFilled%S.elementSize;if(C>0){let n=S.byteOffset+S.bytesFilled;readableByteStreamControllerEnqueueClonedChunkToQueue(t,S.buffer,n-C,C)}S.bytesFilled-=C,readableByteStreamControllerCommitPullIntoDescriptor(t[Cr].stream,S),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t)}function readableByteStreamControllerCancelSteps(t,n){readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t);let S=t[Cr].cancelAlgorithm?.(n)??Promise.resolve();return readableByteStreamControllerClearAlgorithms(t),S}function readableByteStreamControllerPullSteps(t,n){let S=t[Cr].stream;if(t[Cr].queueTotalSize>0){readableByteStreamControllerFillReadRequestFromQueue(t,n);return}let C=t[Cr].autoAllocateChunkSize;if(C!==void 0){let S;try{S=new ArrayBuffer(C)}catch(t){n[Lr](t);return}let N={buffer:S,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:`default`};t[Cr].pendingPullIntos.push(N)}readableStreamAddReadRequest(S,n),readableByteStreamControllerCallPullIfNeeded(t)}function setupReadableByteStreamController(t,n,S,C,N,F,I){n[Cr]={cancelAlgorithm:N,closeRequested:!1,highWaterMark:F,pullAgain:!1,pullAlgorithm:C,pulling:!1,queue:[],queueTotalSize:0,started:!1,stream:t,byobRequest:null,pendingPullIntos:[],autoAllocateChunkSize:I},t[Cr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Cr].started=!0,readableByteStreamControllerCallPullIfNeeded(n)},t=>readableByteStreamControllerError(n,t))}function setupReadableByteStreamControllerFromSource(t,n,S){let C=new ReadableByteStreamController(Br),N=n?.start,F=n?.pull,I=n?.cancel,H=n?.autoAllocateChunkSize;if(H!==void 0&&(H===0||!Number.isInteger(H)||H<0))throw TypeError(`autoAllocateChunkSize must be a positive integer`);setupReadableByteStreamController(t,C,N?N.bind(n,C):nonOpStart,F?createPromiseCallback(`source.pull`,F,n):nonOpPull,I?createPromiseCallback(`source.cancel`,I,n):nonOpCancel,S,H)}function readableByteStreamTee(t){let n=new ReadableStreamDefaultReader(t),S=!1,C=!1,N=!1,F,I,H=Promise.withResolvers(),W,q,Y,X;function pullAlgorithm(){return S?Promise.resolve():(S=!0,n.read().then(t=>{if(S=!1,t.done){C||Y.close(),N||X.close();return}let n=t.value,F=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength));C||Y.enqueue(F),N||X.enqueue(new Uint8Array(F))},()=>{}),Promise.resolve())}return W=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(n){if(C=!0,F=n,N){let n=readableStreamCancel(t,[F,I]);return H.resolve(),n}return H.promise}}),q=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(n){if(N=!0,I=n,C){let n=readableStreamCancel(t,[F,I]);return H.resolve(),n}return H.promise}}),Y=W[Cr].controller,X=q[Cr].controller,n.closed.catch(t=>{Y.error(t),X.error(t),(!C||!N)&&H.resolve()}),[W,q]}const Yr=Symbol(`kSkipThrow`);var TransformStream=class{[wr]=`TransformStream`;[Cr];constructor(t={},n={},S={}){if(t!=null&&typeof t!=`object`)throw TypeError(`transformer must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`writableStrategy must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`readableStrategy must be an object`);let C=t?.readableType,N=t?.writableType,F=t?.start;if(C!==void 0)throw RangeError(`Invalid readableType: ${C}`);if(N!==void 0)throw RangeError(`Invalid writableType: ${N}`);let I=extractHighWaterMark(S?.highWaterMark,0),H=extractSizeAlgorithm(S?.size),W=extractHighWaterMark(n?.highWaterMark,1),q=extractSizeAlgorithm(n?.size),Y=Promise.withResolvers();initializeTransformStream(this,Y,W,q,I,H),setupTransformStreamDefaultControllerFromTransformer(this,t),F===void 0?Y.resolve():Y.resolve(F.call(t,this[Cr].controller))}get readable(){if(!Xr(this))throw TypeError(`Invalid this`);return this[Cr].readable}get writable(){if(!Xr(this))throw TypeError(`Invalid this`);return this[Cr].writable}get[Symbol.toStringTag](){return`TransformStream`}},TransformStreamDefaultController=class{[wr]=`TransformStreamDefaultController`;[Cr];constructor(t){if(t!==Yr)throw TypeError(`Illegal constructor`)}get desiredSize(){if(!Zr(this))throw TypeError(`Invalid this`);let{stream:t}=this[Cr],{readable:n}=t[Cr],S=n[Cr].controller;return readableStreamDefaultControllerGetDesiredSize(S)}enqueue(t){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerEnqueue(this,t)}error(t){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerError(this,t)}terminate(){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerTerminate(this)}get[Symbol.toStringTag](){return`TransformStreamDefaultController`}};const Xr=isBrandCheck(`TransformStream`),Zr=isBrandCheck(`TransformStreamDefaultController`);async function defaultTransformAlgorithm(t,n){transformStreamDefaultControllerEnqueue(n,t)}function initializeTransformStream(t,n,S,C,N,F){let startAlgorithm=()=>n.promise,I=createWritableStream(startAlgorithm,n=>transformStreamDefaultSinkWriteAlgorithm(t,n),()=>transformStreamDefaultSinkCloseAlgorithm(t),n=>transformStreamDefaultSinkAbortAlgorithm(t,n),S,C);t[Cr]={readable:createReadableStream(startAlgorithm,()=>transformStreamDefaultSourcePullAlgorithm(t),n=>transformStreamDefaultSourceCancelAlgorithm(t,n),N,F),writable:I,controller:void 0,backpressure:void 0,backpressureChange:{promise:void 0,resolve:void 0,reject:void 0}},transformStreamSetBackpressure(t,!0)}function transformStreamError(t,n){let{readable:S}=t[Cr];readableStreamDefaultControllerError(S[Cr].controller,n),transformStreamErrorWritableAndUnblockWrite(t,n)}function transformStreamErrorWritableAndUnblockWrite(t,n){let{controller:S,writable:C}=t[Cr];transformStreamDefaultControllerClearAlgorithms(S),writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t)}function transformStreamUnblockWrite(t){t[Cr].backpressure&&transformStreamSetBackpressure(t,!1)}function transformStreamSetBackpressure(t,n){t[Cr].backpressureChange.promise!==void 0&&t[Cr].backpressureChange.resolve?.(),t[Cr].backpressureChange=Promise.withResolvers(),t[Cr].backpressure=n}function setupTransformStreamDefaultController(t,n,S,C,N){n[Cr]={stream:t,transformAlgorithm:S,flushAlgorithm:C,cancelAlgorithm:N,finishPromise:void 0},t[Cr].controller=n}function setupTransformStreamDefaultControllerFromTransformer(t,n){let S=new TransformStreamDefaultController(Yr),C=n?.transform,N=n?.flush,F=n?.cancel;setupTransformStreamDefaultController(t,S,C?createPromiseCallback(`transformer.transform`,C,n):defaultTransformAlgorithm,N?createPromiseCallback(`transformer.flush`,N,n):nonOpFlush,F?createPromiseCallback(`transformer.cancel`,F,n):nonOpCancel)}function transformStreamDefaultControllerClearAlgorithms(t){t[Cr].transformAlgorithm=void 0,t[Cr].flushAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0}function transformStreamDefaultControllerEnqueue(t,n){let{stream:S}=t[Cr],{readable:C}=S[Cr],N=C[Cr].controller;if(!readableStreamDefaultControllerCanCloseOrEnqueue(N))throw TypeError(`Unable to enqueue`);try{readableStreamDefaultControllerEnqueue(N,n)}catch(t){throw transformStreamErrorWritableAndUnblockWrite(S,t),C[Cr].storedError}readableStreamDefaultControllerHasBackpressure(N)!==S[Cr].backpressure&&transformStreamSetBackpressure(S,!0)}function transformStreamDefaultControllerError(t,n){transformStreamError(t[Cr].stream,n)}async function transformStreamDefaultControllerPerformTransform(t,n){try{let S=t[Cr].transformAlgorithm;if(S===void 0)return;await S(n,t)}catch(n){throw transformStreamError(t[Cr].stream,n),n}}function transformStreamDefaultControllerTerminate(t){let{stream:n}=t[Cr],{readable:S}=n[Cr];readableStreamDefaultControllerClose(S[Cr].controller),transformStreamErrorWritableAndUnblockWrite(n,TypeError(`TransformStream has been terminated`))}function transformStreamDefaultSinkWriteAlgorithm(t,n){let{controller:S}=t[Cr];return t[Cr].backpressure?t[Cr].backpressureChange.promise.then(()=>{let{writable:C}=t[Cr];if(C[Cr].state===`erroring`)throw C[Cr].storedError;return transformStreamDefaultControllerPerformTransform(S,n)}):transformStreamDefaultControllerPerformTransform(S,n)}async function transformStreamDefaultSinkAbortAlgorithm(t,n){let{controller:S,readable:C}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Cr].finishPromise=N;let H=S[Cr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Cr].state===`errored`?I(C[Cr].storedError):(readableStreamDefaultControllerError(C[Cr].controller,n),F())},t=>{readableStreamDefaultControllerError(C[Cr].controller,t),I(t)}),S[Cr].finishPromise}function transformStreamDefaultSinkCloseAlgorithm(t){let{readable:n,controller:S}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:C,resolve:N,reject:F}=Promise.withResolvers();S[Cr].finishPromise=C;let I=S[Cr].flushAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(S),I.then(()=>{n[Cr].state===`errored`?F(n[Cr].storedError):(readableStreamDefaultControllerClose(n[Cr].controller),N())},t=>{readableStreamDefaultControllerError(n[Cr].controller,t),F(t)}),S[Cr].finishPromise}function transformStreamDefaultSourcePullAlgorithm(t){return transformStreamSetBackpressure(t,!1),t[Cr].backpressureChange.promise}function transformStreamDefaultSourceCancelAlgorithm(t,n){let{controller:S,writable:C}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Cr].finishPromise=N;let H=S[Cr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Cr].state===`errored`?I(C[Cr].storedError):(writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t),F())},n=>{writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t),I(n)}),S[Cr].finishPromise}const Qr=Object.defineProperty(t=>t.byteLength,"name",{value:`size`}),$r=Object.defineProperty(()=>1,"name",{value:`size`});var ByteLengthQueuingStrategy=class{#e;constructor(t){if(typeof t!=`object`||!t)throw TypeError(`init must be an object`);if(t.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+t.highWaterMark}get highWaterMark(){return this.#e}get size(){return Qr}get[Symbol.toStringTag](){return`ByteLengthQueuingStrategy`}},CountQueuingStrategy=class{#e;constructor(t){if(typeof t!=`object`||!t)throw TypeError(`init must be an object`);if(t.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+t.highWaterMark}get highWaterMark(){return this.#e}get size(){return $r}get[Symbol.toStringTag](){return`CountQueuingStrategy`}},TextEncoderStream=class{#e=null;#t=new TextEncoder;#n;constructor(){this.#n=new TransformStream({transform:(t,n)=>{if(t=String(t),t===``)return;this.#e!==null&&(t=this.#e+t);let S=t.charCodeAt(t.length-1);55296<=S&&S<=56319?(this.#e=t.slice(-1),t=t.slice(0,-1)):this.#e=null,t&&n.enqueue(this.#t.encode(t))},flush:t=>{this.#e!==null&&t.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 ei=hasStreamingSupport();function incompleteUtf8Tail$1(t){let n=t.length;if(n===0)return 0;for(let S=1;S<=Math.min(3,n);S++){let C=t[n-S];if(!(C&128))return 0;if((C&192)!=128){let t;if((C&224)==192)t=2;else if((C&240)==224)t=3;else if((C&248)==240)t=4;else return 0;return S<t?S:0}}return 0}__name$1(incompleteUtf8Tail$1,`incompleteUtf8Tail`);var TextDecoderStream=class{#e;#t;constructor(t,n){if(this.#e=new TextDecoder(t,n),ei)this.#t=new TransformStream({transform:(t,n)=>{let S=toUint8Array$3(t),C=this.#e.decode(S,{stream:!0});C&&n.enqueue(C)},flush:t=>{let n=this.#e.decode();n&&t.enqueue(n)},cancel:()=>{this.#e.decode()}});else{let t=new Uint8Array;this.#t=new TransformStream({transform:(n,S)=>{let C=toUint8Array$3(n),N;t.length>0?(N=new Uint8Array(t.length+C.length),N.set(t,0),N.set(C,t.length)):N=C;let F=incompleteUtf8Tail$1(N),I;if(F>0?(I=N.slice(0,N.length-F),t=N.slice(N.length-F)):(I=N,t=new Uint8Array),I.length>0){let t=this.#e.decode(I);t&&S.enqueue(t)}},flush:n=>{if(t.length>0){let S=this.#e.decode(t);S&&n.enqueue(S),t=new Uint8Array}},cancel:()=>{t=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(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw TypeError(`chunk must be a BufferSource`)}__name$1(toUint8Array$3,`toUint8Array`);function isNativeStreamUsable$3(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}__name$1(isNativeStreamUsable$3,`isNativeStreamUsable`);const ti=isNativeStreamUsable$3(globalThis.ReadableStream,`getReader`)?globalThis.ReadableStream:ReadableStream$1,ni=isNativeStreamUsable$3(globalThis.WritableStream,`getWriter`)?globalThis.WritableStream:WritableStream,ri=isNativeStreamUsable$3(globalThis.TransformStream,`readable`)?globalThis.TransformStream:TransformStream,ii=typeof globalThis.ByteLengthQueuingStrategy==`function`?globalThis.ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,ai=typeof globalThis.CountQueuingStrategy==`function`?globalThis.CountQueuingStrategy:CountQueuingStrategy,oi=typeof globalThis.TextEncoderStream==`function`?globalThis.TextEncoderStream:TextEncoderStream,si=typeof globalThis.TextDecoderStream==`function`?globalThis.TextDecoderStream:TextDecoderStream;var ci,li=__esmMin(()=>{ci=n}),di,fi=__esmMin(()=>{li(),di=ci});function getGioFormat(t){switch(t){case`gzip`:return di.ZlibCompressorFormat.GZIP;case`deflate`:return di.ZlibCompressorFormat.ZLIB;case`deflate-raw`:return di.ZlibCompressorFormat.RAW}}function concat$2(t){let n=t.reduce((t,n)=>t+n.length,0),S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}function assertLevel(t){if(!(t>=-1&&t<=9))throw RangeError(`The value of "level" is out of range. It must be >= -1 and <= 9. Received ${t}`)}function compressWithGio(t,n,S=-1){assertLevel(S);let C=new di.ZlibCompressor({format:getGioFormat(n),level:Math.trunc(S)}),N=new di.ConverterOutputStream({base_stream:di.MemoryOutputStream.new_resizable(),converter:C});N.write_bytes(new lt.Bytes(t),null),N.close(null);let F=N.get_base_stream().steal_as_bytes();return new Uint8Array(F.get_data()??[])}function decompressStreamWithGio(t,n){let S=new di.ZlibDecompressor({format:getGioFormat(n)}),C=di.MemoryInputStream.new_from_bytes(new lt.Bytes(t)),N=new di.ConverterInputStream({base_stream:C,converter:S}),F=[];for(;;){let t=N.read_bytes(mi,null);if(t.get_size()===0)break;F.push(new Uint8Array(t.get_data()))}return N.close(null),concat$2(F)}function findGzipMemberEnd(t){let n=new di.ZlibDecompressor({format:di.ZlibCompressorFormat.GZIP}),S=new Uint8Array(262144),C=0;for(;;){let N=t.subarray(C,C+pi);try{let[t,F,I]=n.convert(N,S,di.ConverterFlags.NONE);if(C+=F,t===di.ConverterResult.FINISHED||F===0&&I===0)return C}catch{return C}}}function gunzipWithGio(t){let n=[],S=0;for(;S<t.length&&!(t.length-S<2||t[S]!==31||t[S+1]!==139);){let C=t.subarray(S),N=findGzipMemberEnd(C);if(N<=0)break;n.push(decompressStreamWithGio(C.subarray(0,N),`gzip`)),S+=N}return n.length===0?decompressStreamWithGio(t,`gzip`):concat$2(n)}var pi,mi,hi=__esmMin(()=>{fi(),ut(),pi=256*1024,mi=1024*1024,__name$1(concat$2,`concat`)}),gi=__esmMin(()=>{ze()}),_i,vi,yi=__esmMin(()=>{_i=Object.defineProperty,vi=__name$1((t,n)=>{let S={};for(var C in t)_i(S,C,{get:t[C],enumerable:!0});return n||_i(S,Symbol.toStringTag,{value:`Module`}),S},`__exportAll`)});function _setPipeImpl(t){bi=t}var bi,Stream_,xi=__esmMin(()=>{qt(),Stream_=class extends It{constructor(t){super(t)}pipe(t,n){return bi(this,t,n)}}});function finished$1(t,n,S){let C;C=typeof n==`function`?n:S;let N=!1;function done(t){N||(N=!0,C(t))}let onFinish=()=>done(),onEnd=()=>done(),onError=t=>done(t),onClose=()=>{let n=t,S=t;!n.writableFinished&&!S.readableEnded&&done(Error(`premature close`))};t.on(`finish`,onFinish),t.on(`end`,onEnd),t.on(`error`,onError),t.on(`close`,onClose);let F=t,I=typeof t.write==`function`,H=typeof t.read==`function`,W=F.writableFinished===!0,q=F.readableEnded===!0;if(F.destroyed===!0){let t=F._err;ve(t?()=>done(t):I&&W||H&&q?()=>done():()=>done(Error(`premature close`)))}else(I&&!H&&W||!I&&H&&q||I&&H&&W&&q)&&ve(()=>done());return function cleanup(){t.removeListener(`finish`,onFinish),t.removeListener(`end`,onEnd),t.removeListener(`error`,onError),t.removeListener(`close`,onClose)}}function addAbortSignal(t,n){if(!(t instanceof AbortSignal))throw TypeError(`The first argument must be an AbortSignal`);if(!(n instanceof Stream_))throw TypeError(`The second argument must be a Stream`);let S=n;if(t.aborted)S.destroy(Error(`The operation was aborted`));else{let onAbort=()=>{S.destroy(Error(`The operation was aborted`))};t.addEventListener(`abort`,onAbort,{once:!0}),n.once(`close`,()=>{t.removeEventListener(`abort`,onAbort)})}return n}function isReadable(t){if(t==null)return!1;let n=t;return typeof n.readable!=`boolean`||typeof n.read!=`function`||n.destroyed===!0||n.readableEnded===!0?!1:n.readable===!0}function isWritable(t){if(t==null)return!1;let n=t;return typeof n.writable!=`boolean`||typeof n.write!=`function`||n.destroyed===!0||n.writableEnded===!0?!1:n.writable===!0}function isDestroyed(t){return t==null?!1:t.destroyed===!0}function isDisturbed(t){if(t==null)return!1;let n=t;return n.readableDidRead===!0||n.readableFlowing!==null&&n.readableFlowing!==void 0}function isErrored(t){if(t==null)return!1;let n=t;return n.destroyed===!0&&typeof n.readable==`boolean`&&n.readable===!1||n.destroyed===!0&&typeof n.writable==`boolean`&&n.writable===!1}var Si=__esmMin(()=>{xi(),ze(),__name$1(finished$1,`finished`)});function getDefaultHighWaterMark(t){return t?wi:Ci}function setDefaultHighWaterMark(t,n){if(typeof n!=`number`||n<0||Number.isNaN(n))throw TypeError(`Invalid highWaterMark: ${n}`);t?wi=n:Ci=n}function validateHighWaterMark(t,n){if(n!==void 0&&(typeof n!=`number`||Number.isNaN(n))){let S=TypeError(`The value of "${t}" is invalid. Received ${n}`);throw S.code=`ERR_INVALID_ARG_VALUE`,S}}var Ci,wi,Ti=__esmMin(()=>{Ci=16384,wi=16});function createAbortError(){let t=Error(`The operation was aborted`);return t.name=`AbortError`,t.code=`ABORT_ERR`,t}async function streamAsyncDispose(t,n){let S;t.destroyed||(S=n?void 0:createAbortError(),t.destroy(S)),await new Promise((n,C)=>{finished$1(t,t=>{t&&t!==S?C(t):n()})})}var Ei,Di=__esmMin(()=>{Si(),Ei=Symbol.asyncDispose??Symbol.for(`Symbol.asyncDispose`)});function chunkLength(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}function sliceChunk(t,n,S){if(typeof t==`string`)return S===void 0?t.slice(n):t.slice(n,S);let C=t.slice;return typeof C==`function`?C.call(t,n,S):t}var Oi,ki,Ai,ji=__esmMin(()=>{xi(),Di(),Ti(),ze(),Oi=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;_constructImpl;constructor(t){super(t),this.readableHighWaterMark=t?.highWaterMark??getDefaultHighWaterMark(t?.objectMode??!1),this.readableEncoding=t?.encoding??null,this.readableObjectMode=t?.objectMode??!1,this._readableState.highWaterMark=this.readableHighWaterMark,this._readableState.objectMode=this.readableObjectMode,t?.read&&(this._readImpl=t.read),t?.destroy&&(this._destroy=t.destroy),t?.construct&&(this._constructImpl=t.construct),(this._constructImpl||this._construct!==Readable_.prototype._construct)&&(this._readableState.constructed=!1,nextTick(()=>{this._construct(t=>{this._readableState.constructed=!0,t?this.destroy(t):this.readableFlowing===!0&&this._flow()})}))}_construct(t){this._constructImpl?this._constructImpl.call(this,t):t()}_read(t){this._readImpl&&this._readImpl.call(this,t)}read(t){if(!this._readableState.constructed)return null;if(this._buffer.length===0){if(this._readableState.ended)return null;this._readableState.reading=!0,this._read(t??this.readableHighWaterMark),this._readableState.reading=!1}if(this._buffer.length===0||t===0)return null;if(this.readableObjectMode){if(t===void 0){let t=this._buffer.shift();return--this.readableLength,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),t}if(t>this.readableLength)return null;let n=this._buffer.shift();return--this.readableLength,n}if(t!=null)return t>this.readableLength?null:this._readBytes(t);let n=this._buffer.splice(0);if(this.readableLength=0,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),n.length===1)return n[0];if(n.length===0)return null;if(typeof n[0]==`string`)return n.join(``);let S=globalThis.Buffer;return S?.concat?S.concat(n):n}_readBytes(t){let n=0,S=[];for(;n<t&&this._buffer.length>0;){let C=this._buffer[0],N=chunkLength(C);if(n+N<=t)S.push(this._buffer.shift()),n+=N,this.readableLength-=N;else{let N=t-n;S.push(sliceChunk(C,0,N)),this._buffer[0]=sliceChunk(C,N),this.readableLength-=N,n+=N}}if(S.length===1)return S[0];let C=globalThis.Buffer;return C?.concat?C.concat(S):S}push(t,n){if(t===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 t==`string`||ArrayBuffer.isView(t))){let n=Object.assign(TypeError(`Invalid non-string/buffer chunk type: ${typeof t}`),{code:`ERR_INVALID_ARG_TYPE`});return nextTick(()=>this.emit(`error`,n)),!1}return this._buffer.push(t),this.readableLength+=this.readableObjectMode?1:chunkLength(t),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(t,n){return super.on(t,n),t===`data`&&this.readableFlowing!==!1&&this.listenerCount(`readable`)===0&&this.resume(),t===`readable`&&(this.readableFlowing=!1,this._buffer.length>0||this._readableState.ended?this._scheduleReadable():this._readableState.reading||nextTick(()=>{this.destroyed||this.read(0)})),this}removeListener(t,n){let S=super.removeListener(t,n);return t===`readable`&&nextTick(()=>this._updateReadableListening()),S}removeAllListeners(t){let n=t===void 0?super.removeAllListeners():super.removeAllListeners(t);return(t===`readable`||t===void 0)&&nextTick(()=>this._updateReadableListening()),n}_updateReadableListening(){this.listenerCount(`readable`)>0||(this.listenerCount(`data`)>0?this.resume():this.readableFlowing=null)}unshift(t){this._buffer.unshift(t),this.readableLength+=this.readableObjectMode?1:chunkLength(t)}setEncoding(t){return this.readableEncoding=t,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 t=this._buffer.shift();if(this.readableLength-=this.readableObjectMode?1:chunkLength(t),this.readableEncoding&&typeof t!=`string`){let n=globalThis.Buffer;n?.isBuffer&&n.isBuffer(t)?t=t.toString(this.readableEncoding):t instanceof Uint8Array&&(t=new TextDecoder(this.readableEncoding).decode(t))}this.emit(`data`,t)}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(t){if(t){let n=this._pipeDests.findIndex(n=>n.dest===t);if(n!==-1){this._pipeDests[n].cleanup(),this._pipeDests.splice(n,1);let S=this._readableState.pipes.indexOf(t);S!==-1&&this._readableState.pipes.splice(S,1),t.emit(`unpipe`,this),this._pipeDests.length===0&&(this.readableFlowing=!1)}}else{for(let t of this._pipeDests)t.cleanup(),t.dest.emit(`unpipe`,this);this._pipeDests=[],this._readableState.pipes=[],this.readableFlowing=!1}return this}_destroy(t,n){n(t??void 0)}destroy(t){if(this.destroyed)return this;this.destroyed=!0,this.readable=!1,this.readableAborted=!this.readableEnded,t&&(this._err=t);let n=!1,cb=t=>{n||(n=!0,t&&nextTick(()=>this.emit(`error`,t)),nextTick(()=>this.emit(`close`)))};try{this._destroy(t??null,cb)}catch(t){cb(t)}return this}static toWeb(t){return new ReadableStream({start(n){t.on(`data`,t=>{typeof t==`string`?n.enqueue(new TextEncoder().encode(t)):t instanceof Uint8Array?n.enqueue(t):t&&typeof t.length==`number`&&n.enqueue(new Uint8Array(t))}),t.on(`end`,()=>{n.close()}),t.on(`error`,t=>{n.error(t)})},cancel(){t.destroy()}})}static fromWeb(t,n){let S=t.getReader();return new Readable_({...n,read(){S.read().then(({done:t,value:n})=>{t?this.push(null):this.push(n)},t=>{this.destroy(t)})},destroy(t,n){S.cancel(t?.message).then(()=>n(null),n)}})}[Symbol.asyncIterator](){let t=this,n=[],S=!1,C=null,N=null,F=null;return t.on(`data`,t=>{if(N){let n=N;N=null,F=null,n({value:t,done:!1})}else n.push(t)}),t.on(`end`,()=>{if(S=!0,N){let t=N;N=null,F=null,t({value:void 0,done:!0})}}),t.on(`error`,t=>{if(C=t,S=!0,F){let n=F;N=null,F=null,n(t)}}),{next(){return C?Promise.reject(C):n.length>0?Promise.resolve({value:n.shift(),done:!1}):S?Promise.resolve({value:void 0,done:!0}):new Promise((t,n)=>{N=t,F=n})},return(){return t.destroy(),Promise.resolve({value:void 0,done:!0})},[Symbol.asyncIterator](){return this}}}static from(t,n){let S=new Readable_({objectMode:!0,...n,read(){}});return typeof t==`string`||ArrayBuffer.isView(t)?(S.push(t),S.push(null),S):((async()=>{try{for await(let n of t)S.push(n)||await new Promise(t=>S.once(`drain`,t));S.push(null)}catch(t){S.destroy(t)}})(),S)}},Oi.prototype[Ei]=function(){return streamAsyncDispose(this,this.readableEnded)},ki=Object.getOwnPropertyDescriptor(Oi.prototype,`on`),Ai=Object.getOwnPropertyDescriptor(Oi.prototype,`removeListener`),Object.defineProperty(Oi.prototype,"addListener",{...ki}),Object.defineProperty(Oi.prototype,"off",{...Ai})});function writeAfterEndError(){let t=Error(`write after end`);return t.code=`ERR_STREAM_WRITE_AFTER_END`,t}var Mi=__esmMin(()=>{});function chunkLen$1(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var Duplex_,Ni=__esmMin(()=>{Mi(),Ti(),ji(),ze(),Duplex_=class extends Oi{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(t){super(t),validateHighWaterMark(`writableHighWaterMark`,t?.writableHighWaterMark),validateHighWaterMark(`readableHighWaterMark`,t?.readableHighWaterMark),this.writableObjectMode=t?.writableObjectMode??t?.objectMode??!1,this.writableHighWaterMark=t?.highWaterMark??t?.writableHighWaterMark??getDefaultHighWaterMark(this.writableObjectMode),this._writableState.highWaterMark=this.writableHighWaterMark,this._writableState.objectMode=this.writableObjectMode,t?.highWaterMark===void 0&&t?.readableHighWaterMark!==void 0&&(this.readableHighWaterMark=t.readableHighWaterMark,this._readableState.highWaterMark=t.readableHighWaterMark),t?.readableObjectMode!==void 0&&(this.readableObjectMode=t.readableObjectMode,this._readableState.objectMode=t.readableObjectMode,t?.readableHighWaterMark===void 0&&t?.highWaterMark===void 0&&(this.readableHighWaterMark=getDefaultHighWaterMark(t.readableObjectMode),this._readableState.highWaterMark=this.readableHighWaterMark)),this.allowHalfOpen=t?.allowHalfOpen!==!1,this._decodeStrings=t?.decodeStrings!==!1,t?.write&&(this._writeImpl=t.write),t?.final&&(this._finalImpl=t.final),this.allowHalfOpen||this.once(`end`,()=>{this.writableEnded||nextTick(()=>this.end())})}_write(t,n,S){this._writeImpl?this._writeImpl.call(this,t,n,S):S()}_final(t){this._finalImpl?this._finalImpl.call(this,t):t()}destroy(t){return this.destroyed?this:(this.writable=!1,super.destroy(t))}write(t,n,S){let C,N;if(typeof n==`function`?(C=n,N=this._defaultEncoding):(N=n??this._defaultEncoding,C=S??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof t==`string`){let n=globalThis.Buffer;n&&(t=n.from(t,N),N=`buffer`)}if(typeof t!=`string`&&!this.writableObjectMode){let n=globalThis.Buffer;(n&&n.isBuffer(t)||t instanceof Uint8Array)&&(N=`buffer`)}if(this.writableEnded){let t=writeAfterEndError();return nextTick(()=>{C(t),this.emit(`error`,t)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen$1(t),this.writableCorked>0)return this._duplexCorkedBuffer.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;let F=this.writableLength<this.writableHighWaterMark;return F||(this.writableNeedDrain=!0),this._duplexDoWrite(t,N,C),F}_duplexDoWrite(t,n,S){if(this._duplexWriting){this._duplexWriteQueue.push({chunk:t,encoding:n,callback:S});return}this._duplexWriting=!0,this._duplexStartWrite(t,n,S)}_duplexStartWrite(t,n,S){this._pendingWrites++,this._write(t,n,n=>{this._pendingWrites--,this.writableLength-=this.writableObjectMode?1:chunkLen$1(t),nextTick(n?()=>{if(S(n),this._duplexWriting=!1,this.destroyed||this.emit(`error`,n),this._duplexWriteQueue.length>0){let t=this._duplexWriteQueue.shift();this._duplexWriting=!0,this._duplexStartWrite(t.chunk,t.encoding,t.callback)}}:()=>{if(S(),this._duplexWriteQueue.length>0){let t=this._duplexWriteQueue.shift();this._duplexStartWrite(t.chunk,t.encoding,t.callback);return}if(this._duplexWriting=!1,this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._pendingWrites===0&&this._pendingEndCb){let t=this._pendingEndCb;this._pendingEndCb=null,t()}})})}end(t,n,S){typeof t==`function`&&(S=t,t=void 0),typeof n==`function`&&(S=n,n=void 0),t!=null&&this.write(t,n),this.writableEnded=!0;let doFinal=()=>{this._final(t=>{this.writableFinished=!0,this._doPrefinishHooks(()=>{nextTick(()=>{t&&this.emit(`error`,t),this.emit(`finish`),nextTick(()=>this.emit(`close`)),S&&S()})})})};return this._pendingWrites>0||this._duplexWriting||this._duplexWriteQueue.length>0?this._pendingEndCb=doFinal:doFinal(),this}_doPrefinishHooks(t){t()}cork(){this.writableCorked++}uncork(){if(this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._duplexCorkedBuffer.length>0)){let t=this._duplexCorkedBuffer.splice(0);for(let{chunk:n,encoding:S,callback:C}of t)this._write(n,S,t=>{this.writableLength-=this.writableObjectMode?1:chunkLen$1(n),t?(C(t),this.destroyed||this.emit(`error`,t)):C()});this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,nextTick(()=>this.emit(`drain`)))}}setDefaultEncoding(t){return this._defaultEncoding=t,this}},__name$1(chunkLen$1,`chunkLen`)});function pipe(t,n,S){let C=t,N=S?.end!==!1,F=!1,ondrain=()=>{F=!1,n.removeListener(`drain`,ondrain);let t=C;typeof t.resume==`function`&&t.resume()},ondata=t=>{if(n.writable){let S=C;n.write(t)===!1&&typeof S.pause==`function`&&(S.pause(),F||(F=!0,n.on(`drain`,ondrain)))}};C.on(`data`,ondata);let I=!1,onend=()=>{I||(I=!0,N&&n.end())},onclose=()=>{if(!I&&(I=!0,N&&!(C instanceof Oi))){let t=n;typeof t.destroy==`function`&&t.destroy()}};N&&(C.on(`end`,onend),C.on(`close`,onclose));let cleanup=()=>{C.removeListener(`data`,ondata),F&&n.removeListener(`drain`,ondrain),C.removeListener(`end`,onend),C.removeListener(`close`,onclose),C.removeListener(`end`,cleanup),C.removeListener(`close`,cleanup),n.removeListener(`close`,cleanup)};return C.on(`end`,cleanup),C.on(`close`,cleanup),n.on(`close`,cleanup),C instanceof Oi&&(C._pipeDests.push({dest:n,cleanup}),C._readableState.pipes.push(n)),n.emit(`pipe`,C),n}var Pi=__esmMin(()=>{xi(),ji(),_setPipeImpl(pipe)});function chunkLen(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var Fi,Ii=__esmMin(()=>{Mi(),xi(),Di(),Ti(),ze(),Fi=class Writable_ extends Stream_{static[Symbol.hasInstance](t){let n=this;return n.prototype!==void 0&&Object.prototype.isPrototypeOf.call(n.prototype,t)?!0:n.prototype!==Writable_.prototype||t==null?!1:typeof t.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;_constructImpl;_decodeStrings;_defaultEncoding=`utf8`;_autoDestroy;constructor(t){super(t),this.writableHighWaterMark=t?.highWaterMark??getDefaultHighWaterMark(t?.objectMode??!1),this.writableObjectMode=t?.objectMode??!1,this._decodeStrings=t?.decodeStrings!==!1,this._autoDestroy=t?.autoDestroy!==!1,t?.write&&(this._writeImpl=t.write),t?.writev&&(this._writev=t.writev),t?.final&&(this._finalImpl=t.final),t?.destroy&&(this._destroy=t.destroy),t?.construct&&(this._constructImpl=t.construct),(this._constructImpl||this._construct!==Writable_.prototype._construct)&&(this._writableState.constructed=!1,nextTick(()=>{this._construct(t=>{this._writableState.constructed=!0,t?this.destroy(t):this._maybeFlush()})}))}_construct(t){this._constructImpl?this._constructImpl.call(this,t):t()}_write(t,n,S){this._writeImpl?this._writeImpl.call(this,t,n,S):S()}_final(t){this._finalImpl?this._finalImpl.call(this,t):t()}_destroy(t,n){n(t)}_maybeFlush(){let t=this._pendingConstruct.splice(0);if(t.length>0){let[n,...S]=t;this._writeBuffer.push(...S),this._doWrite(n.chunk,n.encoding,n.callback)}if(this._pendingEnd){let{chunk:t,encoding:n,callback:S}=this._pendingEnd;this._pendingEnd=null,this._doEnd(t,n,S)}}_doWrite(t,n,S){this._writableState.writing=!0;let C=!0;this._write(t,n,n=>{if(this.writableLength-=this.writableObjectMode?1:chunkLen(t),C){nextTick(()=>{if(n){S(n),this.emit(`error`,n);return}S(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}),n||this._drainWriteBuffer();return}nextTick(n?()=>{S(n),this.emit(`error`,n),this._drainWriteBuffer()}:()=>{S(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._drainWriteBuffer()})}),C=!1}_drainWriteBuffer(){if(this._writeBuffer.length>0){let t=this._writeBuffer.shift();this._doWrite(t.chunk,t.encoding,t.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(t=>{this.writableFinished=!0,this._writableState.finished=!0,nextTick(()=>{t&&this.emit(`error`,t),this.emit(`finish`),this._autoDestroy?this.destroy():nextTick(()=>this.emit(`close`)),this._endCallback&&this._endCallback()})}))}write(t,n,S){let C,N;if(typeof n==`function`?(C=n,N=this._defaultEncoding):(N=n??this._defaultEncoding,C=S??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof t==`string`){let n=globalThis.Buffer;n&&(t=n.from(t,N),N=`buffer`)}if(typeof t!=`string`&&!this.writableObjectMode){let n=globalThis.Buffer;(n&&n.isBuffer(t)||t instanceof Uint8Array)&&(N=`buffer`)}if(this.writableEnded){let t=writeAfterEndError();return nextTick(()=>{C(t),this.emit(`error`,t)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen(t),this.writableCorked>0)return this._corkedBuffer.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;if(!this._writableState.constructed)return this._pendingConstruct.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;let F=this.writableLength<this.writableHighWaterMark;return F||(this.writableNeedDrain=!0),this._writableState.writing?this._writeBuffer.push({chunk:t,encoding:N,callback:C}):this._doWrite(t,N,C),F}_doEnd(t,n,S){t!=null&&this.write(t,n),this.writableEnded=!0,this._writableState.ended=!0,this._ending=!0,this._endCallback=S,this._maybeFinish()}end(t,n,S){return typeof t==`function`&&(S=t,t=void 0),typeof n==`function`&&(S=n,n=void 0),this.writableEnded?(S&&nextTick(S),this):this._writableState.constructed?(this._doEnd(t,n,S),this):(this._pendingEnd={chunk:t,encoding:n,callback:S},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 t=this._corkedBuffer.splice(0),n=t.map(t=>({chunk:t.chunk,encoding:t.encoding}));this._writev.call(this,n,n=>{for(let n of t)this.writableLength-=this.writableObjectMode?1:chunkLen(n.chunk);if(n){for(let S of t)S.callback(n);this.emit(`error`,n)}else{for(let n of t)n.callback();this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}})}else{let t=this._corkedBuffer.splice(0);if(t.length>0){let[n,...S]=t;this._writeBuffer.push(...S),this._doWrite(n.chunk,n.encoding,n.callback)}}}setDefaultEncoding(t){return this._defaultEncoding=t,this}destroy(t){if(this.destroyed)return this;this.destroyed=!0,this.writable=!1,t&&(this._err=t);let n=!1,cb=t=>{n||(n=!0,t&&nextTick(()=>this.emit(`error`,t)),nextTick(()=>this.emit(`close`)))};try{this._destroy(t??null,cb)}catch(t){cb(t)}return this}},Fi.prototype[Ei]=function(){return streamAsyncDispose(this,this.writableFinished)}}),Li,Ri=__esmMin(()=>{Ni(),ze(),Li=class Transform_ extends Duplex_{constructor(t){super({...t,write:void 0,final:void 0});let n=this;t?.transform&&(n._transform=t.transform),t?.flush&&(n._flush=t.flush),t?.final&&(n._final=t.final)}_transform(t,n,S){throw Object.assign(Error(`The _transform() method is not implemented`),{code:`ERR_METHOD_NOT_IMPLEMENTED`})}_flush(t){t()}_write(t,n,S){let C=!1;try{this._transform(t,n,(t,n)=>{if(C){let t=Object.assign(Error(`Callback called multiple times`),{code:`ERR_MULTIPLE_CALLBACK`});nextTick(()=>this.emit(`error`,t));return}if(C=!0,t){S(t);return}n!=null&&this.push(n),S()})}catch(t){if(t?.code===`ERR_METHOD_NOT_IMPLEMENTED`)throw t;S(t)}}_final(t){this._flush((n,S)=>{if(n){t(n);return}S!=null&&this.push(S),this.push(null),t()})}_doPrefinishHooks(t){let n=Transform_.prototype._final;this._final===n?t():n.call(this,t)}}}),PassThrough_,zi=__esmMin(()=>{Ri(),PassThrough_=class extends Li{constructor(t){super({...t,transform(t,n,S){S(null,t)}})}}});function pipeline$1(...t){let n=t,S=typeof n[n.length-1]==`function`?n.pop():void 0,C=n;if(C.length<2)throw Error(`pipeline requires at least 2 streams`);let N=null;function onError(t){if(!N){N=t;for(let t of C)typeof t.destroy==`function`&&t.destroy();S&&S(t)}}let F=C[0];for(let t=1;t<C.length;t++){let n=C[t];F.pipe(n),F.on(`error`,onError),F=n}let I=C[C.length-1];return I.on(`error`,onError),I.on(`finish`,()=>{S&&!N&&S(null)}),I}var Bi=__esmMin(()=>{__name$1(pipeline$1,`pipeline`)});function pipeline(...t){return new Promise((n,S)=>{let cb=t=>{t?S(t):n()};pipeline$1(...t,cb)})}function finished(t,n){return new Promise((S,C)=>{n&&typeof n!=`function`?finished$1(t,n,t=>{t?C(t):S()}):finished$1(t,t=>{t?C(t):S()})})}var Vi,Hi,Ui=__esmMin(()=>{yi(),Si(),Bi(),Vi=vi({default:()=>Hi,finished:()=>finished,pipeline:()=>pipeline}),Hi={pipeline,finished}}),Wi=__exportAll$5({Duplex:()=>Ji,PassThrough:()=>Xi,Readable:()=>Ki,Stream:()=>Gi,Transform:()=>Yi,Writable:()=>qi,addAbortSignal:()=>addAbortSignal,default:()=>Zi,finished:()=>finished$1,getDefaultHighWaterMark:()=>getDefaultHighWaterMark,isDestroyed:()=>isDestroyed,isDisturbed:()=>isDisturbed,isErrored:()=>isErrored,isReadable:()=>isReadable,isWritable:()=>isWritable,"module.exports":()=>Zi,pipeline:()=>pipeline$1,promises:()=>Vi,setDefaultHighWaterMark:()=>setDefaultHighWaterMark}),Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi=__esmMin(()=>{gi(),xi(),Si(),Ti(),ji(),Ni(),Pi(),Ii(),Ri(),zi(),Bi(),Ui(),Gi=makeCallable(Stream_),Ki=makeCallable(Oi),qi=makeCallable(Fi),Ji=makeCallable(Duplex_),Yi=makeCallable(Li),Xi=makeCallable(PassThrough_),Zi=Object.assign(Gi,{Stream:Gi,Readable:Ki,Writable:qi,Duplex:Ji,Transform:Yi,PassThrough:Xi,pipeline:pipeline$1,finished:finished$1,addAbortSignal,isReadable,isWritable,isDestroyed,isDisturbed,isErrored,getDefaultHighWaterMark,setDefaultHighWaterMark,promises:Vi})});function toUint8Array$2(t){return typeof t==`string`?new TextEncoder().encode(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function concat$1(t){let n=t.reduce((t,n)=>t+n.length,0),S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}function createGzip(t){return new Gzip(t)}function createGunzip(t){return new Gunzip(t)}function createDeflate(t){return new Deflate(t)}function createInflate(t){return new Inflate(t)}function createDeflateRaw(t){return new DeflateRaw(t)}function createInflateRaw(t){return new InflateRaw(t)}function createUnzip(t){return new Unzip(t)}function createBrotliCompress(t){throw Error(`createBrotliCompress is not supported on GJS (no Brotli in GLib)`)}function createBrotliDecompress(t){throw Error(`createBrotliDecompress is not supported on GJS (no Brotli in GLib)`)}function createZstdCompress(t){let n=Error(`createZstdCompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}function createZstdDecompress(t){let n=Error(`createZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}var ZlibBase,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,$i=__esmMin(()=>{hi(),Qi(),__name$1(toUint8Array$2,`toUint8Array`),__name$1(concat$1,`concat`),ZlibBase=class extends Yi{_mode;_chunks=[];constructor(t,n){super(n),this._mode=t}_transform(t,n,S){this._chunks.push(toUint8Array$2(t)),S()}_flush(t){let n=concat$1(this._chunks);this._chunks=[];try{this.push(Buffer.from(this._run(n))),t()}catch(n){t(n instanceof Error?n:Error(String(n)))}}_run(t){let n=this._mode;switch(n.kind){case`compress`:return compressWithGio(t,n.format);case`decompress`:return decompressStreamWithGio(t,n.format);case`gunzip`:return gunzipWithGio(t);case`unzip`:return t.length>=2&&t[0]===31&&t[1]===139?gunzipWithGio(t):decompressStreamWithGio(t,`deflate`)}}},Gzip=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`gzip`},t)}},Gunzip=class extends ZlibBase{constructor(t){super({kind:`gunzip`},t)}},Deflate=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`deflate`},t)}},Inflate=class extends ZlibBase{constructor(t){super({kind:`decompress`,format:`deflate`},t)}},DeflateRaw=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`deflate-raw`},t)}},InflateRaw=class extends ZlibBase{constructor(t){super({kind:`decompress`,format:`deflate-raw`},t)}},Unzip=class extends ZlibBase{constructor(t){super({kind:`unzip`},t)}},BrotliCompress=class extends Yi{constructor(){throw super(),Error(`BrotliCompress is not supported on GJS (no Brotli in GLib)`)}},BrotliDecompress=class extends Yi{constructor(){throw super(),Error(`BrotliDecompress is not supported on GJS (no Brotli in GLib)`)}},ZstdCompress=class extends Yi{constructor(){super();let t=Error(`ZstdCompress is not supported on GJS (no Zstd in GLib)`);throw t.code=`ERR_UNSUPPORTED_OPERATION`,t}},ZstdDecompress=class extends Yi{constructor(){super();let t=Error(`ZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw t.code=`ERR_UNSUPPORTED_OPERATION`,t}}}),ea=__exportAll$5({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:()=>na,createBrotliCompress:()=>createBrotliCompress,createBrotliDecompress:()=>createBrotliDecompress,createDeflate:()=>createDeflate,createDeflateRaw:()=>createDeflateRaw,createGunzip:()=>createGunzip,createGzip:()=>createGzip,createInflate:()=>createInflate,createInflateRaw:()=>createInflateRaw,createUnzip:()=>createUnzip,createZstdCompress:()=>createZstdCompress,createZstdDecompress:()=>createZstdDecompress,default:()=>ra,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(t,n){return n===`gzip`?gunzipWithGio(t):decompressStreamWithGio(t,n)}async function runWebTransform(t,n){let S=new ReadableStream({start(n){n.enqueue(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),n.close()}}),C=[],N=S.pipeThrough(n).getReader();for(;;){let{done:t,value:n}=await N.read();if(t)break;C.push(n)}let F=C.reduce((t,n)=>t+n.length,0),I=new Uint8Array(F),H=0;for(let t of C)I.set(t,H),H+=t.length;return I}async function compressWithWeb(t,n){return runWebTransform(t,new CompressionStream(n))}async function decompressWithWeb(t,n){return runWebTransform(t,new DecompressionStream(n))}function requestedLevel(t){let n=t?.level;if(!(n===void 0||n===-1))return assertLevel(n),n}async function compress(t,n,S){return S===void 0&&hasWebCompression()?compressWithWeb(t,n):compressWithGio(t,n,S)}async function decompress(t,n){if(hasWebCompression())try{return await decompressWithWeb(t,n)}catch(S){if(n!==`gzip`)throw S;return decompressWithGio(t,n)}return decompressWithGio(t,n)}function toUint8Array$1(t){return typeof t==`string`?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function gzip$1(t,n,S){let C=typeof n==`function`?n:S,N=typeof n==`function`?void 0:n;compress(toUint8Array$1(t),`gzip`,requestedLevel(N)).then(t=>C(null,t),t=>C(t instanceof Error?t:Error(String(t)),new Uint8Array))}function gunzip$1(t,n,S){let C=typeof n==`function`?n:S;decompress(toUint8Array$1(t),`gzip`).then(t=>C(null,t),t=>C(t instanceof Error?t:Error(String(t)),new Uint8Array))}function deflate(t,n,S){let C=typeof n==`function`?n:S,N=typeof n==`function`?void 0:n;compress(toUint8Array$1(t),`deflate`,requestedLevel(N)).then(t=>C(null,t),t=>C(t instanceof Error?t:Error(String(t)),new Uint8Array))}function inflate(t,n,S){let C=typeof n==`function`?n:S;decompress(toUint8Array$1(t),`deflate`).then(t=>C(null,t),t=>C(t instanceof Error?t:Error(String(t)),new Uint8Array))}function deflateRaw(t,n,S){let C=typeof n==`function`?n:S,N=typeof n==`function`?void 0:n;compress(toUint8Array$1(t),`deflate-raw`,requestedLevel(N)).then(t=>C(null,t),t=>C(t instanceof Error?t:Error(String(t)),new Uint8Array))}function inflateRaw(t,n,S){let C=typeof n==`function`?n:S;decompress(toUint8Array$1(t),`deflate-raw`).then(t=>C(null,t),t=>C(t instanceof Error?t:Error(String(t)),new Uint8Array))}function gzipSync(t,n){return compressWithGio(toUint8Array$1(t),`gzip`,n?.level??-1)}function gunzipSync(t,n){return decompressWithGio(toUint8Array$1(t),`gzip`)}function deflateSync(t,n){return compressWithGio(toUint8Array$1(t),`deflate`,n?.level??-1)}function inflateSync(t,n){return decompressWithGio(toUint8Array$1(t),`deflate`)}function deflateRawSync(t,n){return compressWithGio(toUint8Array$1(t),`deflate-raw`,n?.level??-1)}function inflateRawSync(t,n){return decompressWithGio(toUint8Array$1(t),`deflate-raw`)}function brotliCompress(t,n,S){(typeof n==`function`?n:S)(Error(`brotliCompress: Brotli is not supported in this environment`),ta)}function brotliDecompress(t,n,S){(typeof n==`function`?n:S)(Error(`brotliDecompress: Brotli is not supported in this environment`),ta)}function brotliCompressSync(t,n){throw Error(`brotliCompressSync: Brotli is not supported in this environment`)}function brotliDecompressSync(t,n){throw Error(`brotliDecompressSync: Brotli is not supported in this environment`)}function zstdCompress(t,n,S){let C=typeof n==`function`?n:S,N=Error(`zstdCompress: Zstd is not supported in this environment`);N.code=`ERR_UNSUPPORTED_OPERATION`,C(N,ta)}function zstdDecompress(t,n,S){let C=typeof n==`function`?n:S,N=Error(`zstdDecompress: Zstd is not supported in this environment`);N.code=`ERR_UNSUPPORTED_OPERATION`,C(N,ta)}function zstdCompressSync(t,n){let S=Error(`zstdCompressSync: Zstd is not supported in this environment`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}function zstdDecompressSync(t,n){let S=Error(`zstdDecompressSync: Zstd is not supported in this environment`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}var hasWebCompression,ta,na,ra,ia=__esmMin(()=>{hi(),$i(),hasWebCompression=()=>globalThis.CompressionStream!==void 0,__name$1(toUint8Array$1,`toUint8Array`),__name$1(gzip$1,`gzip`),__name$1(gunzip$1,`gunzip`),ta=new Uint8Array,na={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},ra={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:na}});const aa=new Set([`gzip`,`deflate`,`deflate-raw`]);function validateFormat(t){if(!aa.has(t))throw TypeError(`Unsupported compression format: '${t}'. Supported formats: 'gzip', 'deflate', 'deflate-raw'.`);return t}const oa=typeof globalThis.CompressionStream==`function`&&typeof globalThis.DecompressionStream==`function`;let sa=!1,ca,la,ua,da,fa,pa;async function loadZlib(){if(sa)return;let t=await Promise.resolve().then(()=>(ia(),ea));ca=t.gzipSync,la=t.gunzipSync,ua=t.deflateSync,da=t.inflateSync,fa=t.deflateRawSync,pa=t.inflateRawSync,sa=!0}function getCompressFn(t){switch(t){case`gzip`:return t=>ca(t);case`deflate`:return t=>ua(t);case`deflate-raw`:return t=>fa(t)}}function getDecompressFn(t){switch(t){case`gzip`:return t=>la(t);case`deflate`:return t=>da(t);case`deflate-raw`:return t=>pa(t)}}function concatChunks$1(t){if(t.length===1)return t[0];let n=0;for(let S of t)n+=S.length;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}__name$1(concatChunks$1,`concatChunks`);let ma,ha;if(oa)ma=globalThis.CompressionStream,ha=globalThis.DecompressionStream;else{let t=loadZlib();ma=class CompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new ri({transform(t){C.push(t)},async flush(n){try{await t;let N=getCompressFn(S)(concatChunks$1(C));N.length>0&&n.enqueue(N)}catch(t){n.error(t)}}});this.readable=N.readable,this.writable=N.writable}},ha=class DecompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new ri({transform(t){C.push(t)},async flush(n){try{await t;let N=getDecompressFn(S)(concatChunks$1(C));N.length>0&&n.enqueue(N)}catch(t){n.error(t)}}});this.readable=N.readable,this.writable=N.writable}}}const ga=globalThis;globalThis.CompressionStream===void 0&&(ga.CompressionStream=ma),globalThis.DecompressionStream===void 0&&(ga.DecompressionStream=ha);const _a=globalThis;globalThis.DOMException===void 0&&(_a.DOMException=tr);var va,__name,ya=__esmMin(()=>{va=Object.defineProperty,__name=(t,n)=>va(t,`name`,{value:n,configurable:!0})});function validateHeaderName(t){if(typeof t!=`string`||!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let n=TypeError(`Header name must be a valid HTTP token ["${t}"]`);throw Object.defineProperty(n,"code",{value:`ERR_INVALID_HTTP_TOKEN`}),n}}function validateHeaderValue(t,n){if(n===void 0){let n=TypeError(`Header "${t}" value must not be undefined`);throw Object.defineProperty(n,"code",{value:`ERR_HTTP_INVALID_HEADER_VALUE`}),n}if(typeof n==`string`&&/[^\t -~€-ÿ]/.test(n)){let n=TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:`ERR_INVALID_CHAR`}),n}}const ba=Symbol(`Headers.headers`);function isBoxedPrimitive$2(t){return t instanceof String||t instanceof Number||t instanceof Boolean||typeof Symbol<`u`&&t instanceof Symbol||typeof BigInt<`u`&&t instanceof BigInt}__name$1(isBoxedPrimitive$2,`isBoxedPrimitive`);var xa=class Headers{[ba];constructor(t){if(this[ba]=new Map,t!=null){if(t instanceof Headers){for(let[n,S]of t[ba])this[ba].set(n,[...S]);return}if(typeof t==`object`&&!isBoxedPrimitive$2(t)){let n=t[Symbol.iterator];if(n==null)for(let[n,S]of Object.entries(t))validateHeaderName(n),validateHeaderValue(n,String(S)),this.append(n,String(S));else{if(typeof n!=`function`)throw TypeError(`Header pairs must be iterable`);for(let n of t){if(typeof n!=`object`||isBoxedPrimitive$2(n))throw TypeError(`Each header pair must be an iterable object`);let t=[...n];if(t.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);validateHeaderName(t[0]),validateHeaderValue(t[0],String(t[1])),this.append(t[0],String(t[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(t,n){validateHeaderName(t),validateHeaderValue(t,n);let S=String(t).toLowerCase(),C=String(n),N=this[ba].get(S);N?N.push(C):this[ba].set(S,[C])}set(t,n){validateHeaderName(t),validateHeaderValue(t,n);let S=String(t).toLowerCase();this[ba].set(S,[String(n)])}delete(t){this[ba].delete(String(t).toLowerCase())}has(t){return this[ba].has(String(t).toLowerCase())}get(t){let n=this[ba].get(String(t).toLowerCase());if(!n||n.length===0)return null;let S=n.join(`, `);return/^content-encoding$/i.test(t)&&(S=S.toLowerCase()),S}getAll(t){return this[ba].get(String(t).toLowerCase())??[]}getSetCookie(){return this[ba].get(`set-cookie`)??[]}forEach(t,n){for(let S of this.keys())Reflect.apply(t,n,[this.get(S),S,this])}*keys(){let t=[...this[ba].keys()].sort(),n=new Set;for(let S of t)n.has(S)||(n.add(S),yield S)}*values(){for(let t of this.keys())yield this.get(t)}*entries(){for(let t of this.keys())yield[t,this.get(t)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let t={};for(let n of this.keys())t[n]=this.getAll(n);return t}_appendToSoupMessage(t,n,S=t.MessageHeadersType.REQUEST){let C=n?n.get_request_headers():new t.MessageHeaders(S);for(let[t,n]of this.entries())C.append(t,n);return C}static _newFromSoupMessage(t,n,S=t.MessageHeadersType.RESPONSE){let C=new Headers,N;return N=S===t.MessageHeadersType.RESPONSE?n.get_response_headers():n.get_request_headers(),N.foreach((t,n)=>{C.append(t,n)}),C}[Symbol.for(`nodejs.util.inspect.custom`)](){let t={};for(let n of this.keys()){let S=this.getAll(n);n===`host`?t[n]=S[0]:t[n]=S.length>1?S:S[0]}return t}};Object.defineProperties(xa.prototype,[`get`,`entries`,`forEach`,`values`].reduce((t,n)=>(t[n]={enumerable:!0},t),{}));var Sa=__esmMin(()=>{ot()});Sa();var FetchBaseError=class extends Error{type;constructor(t,n){super(t),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{code;errno;erroredSysCall;constructor(t,n,S){super(t,n),S&&(this.code=this.errno=S.code,this.erroredSysCall=S.syscall)}};Hn();const Ca=Symbol.toStringTag,isURLSearchParameters=t=>typeof t==`object`&&typeof t.append==`function`&&typeof t.delete==`function`&&typeof t.get==`function`&&typeof t.getAll==`function`&&typeof t.has==`function`&&typeof t.set==`function`&&typeof t.sort==`function`&&t[Ca]===`URLSearchParams`,isBlob=t=>{if(!t||typeof t!=`object`)return!1;let n=t;return typeof n.arrayBuffer==`function`&&typeof n.type==`string`&&typeof n.stream==`function`&&typeof n.constructor==`function`&&/^(Blob|File)$/.test(n[Ca])},isAbortSignal=t=>{if(typeof t!=`object`||!t)return!1;let n=t;return n[Ca]===`AbortSignal`||n[Ca]===`EventTarget`},isDomainOrSubdomain=(t,n)=>{let S=new Bn(n).hostname,C=new Bn(t).hostname;return S===C||S.endsWith(`.${C}`)},isSameProtocol=(t,n)=>new Bn(n).protocol===new Bn(t).protocol;var wa,Ta,File,Ea=__esmMin(()=>{wa=Symbol(`File.name`),Ta=Symbol(`File.lastModified`),File=class extends Blob{[wa];[Ta];webkitRelativePath=``;constructor(t,n,S){super(t,S),this[wa]=String(n),this[Ta]=S?.lastModified??Date.now()}get name(){return this[wa]}get lastModified(){return this[Ta]}get[Symbol.toStringTag](){return`File`}}});function generateBoundary(){let t=`----formdata-`;for(let n=0;n<24;n++)t+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*62));return t}function escape(t){return t.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`)}function formDataToBlob(t,n){n??=generateBoundary();let S=[],C=`--${n}\r\nContent-Disposition: form-data; name="`;for(let[n,N]of t.entries())if(typeof N==`string`)S.push(`${C}${escape(n)}"\r\n\r\n${N.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
12
12
  `)}\r\n`);else{let t=N instanceof File?N:new File([N],`blob`,{type:N.type});S.push(`${C}${escape(n)}"; filename="${escape(t.name)}"\r\nContent-Type: ${t.type||`application/octet-stream`}\r\n\r\n`),S.push(t),S.push(`\r
13
13
  `)}return S.push(`--${n}--`),new Blob(S,{type:`multipart/form-data; boundary=${n}`})}var Da=__esmMin(()=>{Ea()});function normalizeValue(t,n,S){return typeof n==`string`?n:(n instanceof Blob&&!(n instanceof File)&&(n=new File([n],S??`blob`,{type:n.type})),n instanceof File&&S!==void 0&&(n=new File([n],S,{type:n.type,lastModified:n.lastModified})),n)}var Oa,FormData,ka=__esmMin(()=>{Ea(),Oa=Symbol(`FormData.entries`),FormData=class{[Oa]=[];constructor(){}append(t,n,S){this[Oa].push({name:String(t),value:normalizeValue(t,n,S)})}delete(t){let n=String(t);this[Oa]=this[Oa].filter(t=>t.name!==n)}get(t){let n=String(t),S=this[Oa].find(t=>t.name===n);return S?S.value:null}getAll(t){let n=String(t);return this[Oa].filter(t=>t.name===n).map(t=>t.value)}has(t){let n=String(t);return this[Oa].some(t=>t.name===n)}set(t,n,S){let C=String(t),N=normalizeValue(C,n,S),F=!1;this[Oa]=this[Oa].filter(t=>t.name===C?F?!1:(F=!0,t.value=N,!0):!0),F||this[Oa].push({name:C,value:N})}forEach(t,n){for(let S of this[Oa])t.call(n,S.value,S.name,this)}*entries(){for(let t of this[Oa])yield[t.name,t.value]}*keys(){for(let t of this[Oa])yield t.name}*values(){for(let t of this[Oa])yield t.value}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`FormData`}}}),Aa=__esmMin(()=>{Da(),ka()}),ja=__exportAll$5({toFormData:()=>toFormData});function _fileName(t){let n=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!n)return;let S=n[2]||n[3]||``,C=S.slice(S.lastIndexOf(`\\`)+1);return C=C.replace(/%22/g,`"`),C=C.replace(/&#(\d{4});/g,(t,n)=>String.fromCharCode(n)),C}async function toFormData(t,n){if(!/multipart/i.test(n))throw TypeError(`Failed to fetch`);let S=n.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!S)throw TypeError(`no or bad content-type header, no multipart boundary`);let C=new MultipartParser(S[1]||S[2]),N,F,I,H,W,q,Y=[],X=new FormData,onPartData=t=>{I+=Z.decode(t,{stream:!0})},appendToFile=t=>{Y.push(t)},appendFileToFormData=()=>{let t=new ne(Y,q,{type:W});X.append(H,t)},appendEntryToFormData=()=>{X.append(H,I)},Z=new TextDecoder(`utf-8`);Z.decode(),C.onPartBegin=function(){C.onPartData=onPartData,C.onPartEnd=appendEntryToFormData,N=``,F=``,I=``,H=``,W=``,q=null,Y.length=0},C.onHeaderField=function(t){N+=Z.decode(t,{stream:!0})},C.onHeaderValue=function(t){F+=Z.decode(t,{stream:!0})},C.onHeaderEnd=function(){if(F+=Z.decode(),N=N.toLowerCase(),N===`content-disposition`){let t=F.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);t&&(H=t[2]||t[3]||``),q=_fileName(F),q&&(C.onPartData=appendToFile,C.onPartEnd=appendFileToFormData)}else N===`content-type`&&(W=F);F=``,N=``};for await(let n of t)C.write(n);return C.end(),X}var Ma,Na,lower,noop,MultipartParser,Pa=__esmMin(()=>{Aa(),Ma=1,Na={PART_BOUNDARY:Ma,LAST_BOUNDARY:Ma*=2},lower=t=>t|32,noop=(...t)=>{},MultipartParser=class{index=0;flags=0;boundary;lookbehind;state=0;onHeaderEnd=noop;onHeaderField=noop;onHeadersEnd=noop;onHeaderValue=noop;onPartBegin=noop;onPartData=noop;onPartEnd=noop;boundaryChars={};constructor(t){t=`\r
@@ -145,7 +145,7 @@ fi
145
145
  `)}`:``;n.fail(N(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(C).length,Object.keys(C).join(`, `)+S))}},F.unknownArguments=function unknownArguments(S,C,I,H,W=!0){let q=t.getInternalMethods().getCommandInstance().getCommands(),Y=[],X=t.getInternalMethods().getContext();if(Object.keys(S).forEach(n=>{!pp.includes(n)&&!Object.prototype.hasOwnProperty.call(I,n)&&!Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),n)&&!F.isValidAndSomeAliasIsNotNew(n,C)&&Y.push(n)}),W&&(X.commands.length>0||q.length>0||H)&&S._.slice(X.commands.length).forEach(t=>{q.includes(``+t)||Y.push(``+t)}),W){let n=t.getDemandedCommands()._?.max||0,C=X.commands.length+n;C<S._.length&&S._.slice(C).forEach(t=>{t=String(t),!X.commands.includes(t)&&!Y.includes(t)&&Y.push(t)})}Y.length&&n.fail(N(`Unknown argument: %s`,`Unknown arguments: %s`,Y.length,Y.map(t=>t.trim()?t:`"${t}"`).join(`, `)))},F.unknownCommands=function unknownCommands(S){let C=t.getInternalMethods().getCommandInstance().getCommands(),F=[],I=t.getInternalMethods().getContext();return(I.commands.length>0||C.length>0)&&S._.slice(I.commands.length).forEach(t=>{C.includes(``+t)||F.push(``+t)}),F.length>0?(n.fail(N(`Unknown command: %s`,`Unknown commands: %s`,F.length,F.join(`, `))),!0):!1},F.isValidAndSomeAliasIsNotNew=function isValidAndSomeAliasIsNotNew(n,S){if(!Object.prototype.hasOwnProperty.call(S,n))return!1;let C=t.parsed.newAliases;return[n,...S[n]].some(t=>!Object.prototype.hasOwnProperty.call(C,t)||!C[n])},F.limitedChoices=function limitedChoices(S){let N=t.getOptions(),F={};if(!Object.keys(N.choices).length)return;Object.keys(S).forEach(t=>{pp.indexOf(t)===-1&&Object.prototype.hasOwnProperty.call(N.choices,t)&&[].concat(S[t]).forEach(n=>{N.choices[t].indexOf(n)===-1&&n!==void 0&&(F[t]=(F[t]||[]).concat(n))})});let I=Object.keys(F);if(!I.length)return;let H=C(`Invalid values:`);I.forEach(t=>{H+=`\n ${C(`Argument: %s, Given: %s, Choices: %s`,t,n.stringifiedValues(F[t]),n.stringifiedValues(N.choices[t]))}`}),n.fail(H)};let I={};F.implies=function implies(n,C){argsert(`<string|object> [array|number|string]`,[n,C],arguments.length),typeof n==`object`?Object.keys(n).forEach(t=>{F.implies(t,n[t])}):(t.global(n),I[n]||(I[n]=[]),Array.isArray(C)?C.forEach(t=>F.implies(n,t)):(assertNotStrictEqual(C,void 0,S),I[n].push(C)))},F.getImplied=function getImplied(){return I};function keyExists(t,n){let S=Number(n);return n=isNaN(S)?n:S,typeof n==`number`?n=t._.length>=n:n.match(/^--no-.+/)?(n=n.match(/^--no-(.+)/)[1],n=!Object.prototype.hasOwnProperty.call(t,n)):n=Object.prototype.hasOwnProperty.call(t,n),n}F.implications=function implications(t){let S=[];if(Object.keys(I).forEach(n=>{let C=n;(I[n]||[]).forEach(n=>{let N=C,F=n;N=keyExists(t,N),n=keyExists(t,n),N&&!n&&S.push(` ${C} -> ${F}`)})}),S.length){let t=`${C(`Implications failed:`)}\n`;S.forEach(n=>{t+=n}),n.fail(t)}};let H={};F.conflicts=function conflicts(n,S){argsert(`<string|object> [array|string]`,[n,S],arguments.length),typeof n==`object`?Object.keys(n).forEach(t=>{F.conflicts(t,n[t])}):(t.global(n),H[n]||(H[n]=[]),Array.isArray(S)?S.forEach(t=>F.conflicts(n,t)):H[n].push(S))},F.getConflicting=()=>H,F.conflicting=function conflictingFn(N){Object.keys(N).forEach(t=>{H[t]&&H[t].forEach(S=>{S&&N[t]!==void 0&&N[S]!==void 0&&n.fail(C(`Arguments %s and %s are mutually exclusive`,t,S))})}),t.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(H).forEach(t=>{H[t].forEach(F=>{F&&N[S.Parser.camelCase(t)]!==void 0&&N[S.Parser.camelCase(F)]!==void 0&&n.fail(C(`Arguments %s and %s are mutually exclusive`,t,F))})})},F.recommendCommands=function recommendCommands(t,S){S=S.sort((t,n)=>n.length-t.length);let N=null,F=1/0;for(let n=0,C;(C=S[n])!==void 0;n++){let n=levenshtein(t,C);n<=3&&n<F&&(F=n,N=C)}N&&n.fail(C(`Did you mean %s?`,N))},F.reset=function reset(t){return I=objFilter(I,n=>!t[n]),H=objFilter(H,n=>!t[n]),F};let W=[];return F.freeze=function freeze(){W.push({implied:I,conflicting:H})},F.unfreeze=function unfreeze(){let t=W.pop();assertNotStrictEqual(t,void 0,S),{implied:I,conflicting:H}=t},F}var pp,mp=__esmMin(()=>{$f(),Yf(),fp(),ip(),pp=[`$0`,`--`,`_`]});function YargsFactory(t){return(n=[],S=t.process.cwd(),C)=>{let N=new YargsInstance(n,S,C,t);return Object.defineProperty(N,"argv",{get:()=>N.parse(),enumerable:!0}),N.help(),N.version(),N}}function isYargsInstance(t){return!!t&&typeof t.getInternalMethods==`function`}var __classPrivateFieldSet,__classPrivateFieldGet,hp,gp,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,YargsInstance,Fm=__esmMin(()=>{_e(),rp(),Yf(),_l(),op(),$f(),dp(),mp(),ip(),bl(),ep(),Xf(),tp(),ap(),__classPrivateFieldSet=function(t,n,S,C,N){if(C===`m`)throw TypeError(`Private method is not writable`);if(C===`a`&&!N)throw TypeError(`Private accessor was defined without a setter`);if(typeof n==`function`?t!==n||!N:!n.has(t))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return C===`a`?N.call(t,S):N?N.value=S:n.set(t,S),S},__classPrivateFieldGet=function(t,n,S,C){if(S===`a`&&!C)throw TypeError(`Private accessor was defined without a getter`);if(typeof n==`function`?t!==n||!C:!n.has(t))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return S===`m`?C:S===`a`?C.call(t):C?C.value:n.get(t)},Zp=Symbol(`copyDoubleDash`),Qp=Symbol(`copyDoubleDash`),$p=Symbol(`deleteFromParserHintObject`),em=Symbol(`emitWarning`),tm=Symbol(`freeze`),nm=Symbol(`getDollarZero`),im=Symbol(`getParserConfiguration`),am=Symbol(`getUsageConfiguration`),om=Symbol(`guessLocale`),sm=Symbol(`guessVersion`),cm=Symbol(`parsePositionalNumbers`),lm=Symbol(`pkgUp`),um=Symbol(`populateParserHintArray`),dm=Symbol(`populateParserHintSingleValueDictionary`),fm=Symbol(`populateParserHintArrayDictionary`),pm=Symbol(`populateParserHintDictionary`),mm=Symbol(`sanitizeKey`),hm=Symbol(`setKey`),gm=Symbol(`unfreeze`),_m=Symbol(`validateAsync`),vm=Symbol(`getCommandInstance`),ym=Symbol(`getContext`),bm=Symbol(`getHasOutput`),xm=Symbol(`getLoggerInstance`),Sm=Symbol(`getParseContext`),Cm=Symbol(`getUsageInstance`),wm=Symbol(`getValidationInstance`),Tm=Symbol(`hasParseCallback`),Em=Symbol(`isGlobalContext`),Dm=Symbol(`postProcess`),Om=Symbol(`rebase`),km=Symbol(`reset`),Am=Symbol(`runYargsParserAndExecuteCommands`),jm=Symbol(`runValidation`),Mm=Symbol(`setHasOutput`),Nm=Symbol(`kTrackManuallySetKeys`),Pm=`en_US`,YargsInstance=class{constructor(t=[],n,S,C){this.customScriptName=!1,this.parsed=!1,hp.set(this,void 0),gp.set(this,void 0),vp.set(this,{commands:[],fullCommands:[]}),yp.set(this,null),bp.set(this,null),xp.set(this,`show-hidden`),Sp.set(this,null),Cp.set(this,!0),wp.set(this,{}),Tp.set(this,!0),Ep.set(this,[]),Dp.set(this,void 0),Op.set(this,{}),kp.set(this,!1),Ap.set(this,null),jp.set(this,!0),Mp.set(this,void 0),Np.set(this,``),Pp.set(this,void 0),Fp.set(this,void 0),Ip.set(this,{}),Lp.set(this,null),Rp.set(this,null),zp.set(this,{}),Bp.set(this,{}),Vp.set(this,void 0),Hp.set(this,!1),Up.set(this,void 0),Wp.set(this,!1),Gp.set(this,!1),Kp.set(this,!1),qp.set(this,void 0),Jp.set(this,{}),Yp.set(this,null),Xp.set(this,void 0),__classPrivateFieldSet(this,Up,C,`f`),__classPrivateFieldSet(this,Vp,t,`f`),__classPrivateFieldSet(this,gp,n,`f`),__classPrivateFieldSet(this,Fp,S,`f`),__classPrivateFieldSet(this,Dp,new GlobalMiddleware(this),`f`),this.$0=this[nm](),this[km](),__classPrivateFieldSet(this,hp,__classPrivateFieldGet(this,hp,`f`),`f`),__classPrivateFieldSet(this,qp,__classPrivateFieldGet(this,qp,`f`),`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`),`f`),__classPrivateFieldSet(this,Pp,__classPrivateFieldGet(this,Pp,`f`),`f`),__classPrivateFieldGet(this,Pp,`f`).showHiddenOpt=__classPrivateFieldGet(this,xp,`f`),__classPrivateFieldSet(this,Mp,this[Qp](),`f`),__classPrivateFieldGet(this,Up,`f`).y18n.setLocale(Pm)}addHelpOpt(t,n){return argsert(`[string|boolean] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,Ap,`f`)&&(this[$p](__classPrivateFieldGet(this,Ap,`f`)),__classPrivateFieldSet(this,Ap,null,`f`)),t===!1&&n===void 0?this:(__classPrivateFieldSet(this,Ap,typeof t==`string`?t:`help`,`f`),this.boolean(__classPrivateFieldGet(this,Ap,`f`)),this.describe(__classPrivateFieldGet(this,Ap,`f`),n||__classPrivateFieldGet(this,qp,`f`).deferY18nLookup(`Show help`)),this)}help(t,n){return this.addHelpOpt(t,n)}addShowHiddenOpt(t,n){if(argsert(`[string|boolean] [string]`,[t,n],arguments.length),t===!1&&n===void 0)return this;let S=typeof t==`string`?t:__classPrivateFieldGet(this,xp,`f`);return this.boolean(S),this.describe(S,n||__classPrivateFieldGet(this,qp,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,Pp,`f`).showHiddenOpt=S,this}showHidden(t,n){return this.addShowHiddenOpt(t,n)}alias(t,n){return argsert(`<object|string|array> [string|array]`,[t,n],arguments.length),this[fm](this.alias.bind(this),`alias`,t,n),this}array(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`array`,t),this[Nm](t),this}boolean(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`boolean`,t),this[Nm](t),this}check(t,n){return argsert(`<function> [boolean]`,[t,n],arguments.length),this.middleware((n,S)=>maybeAsyncResult(()=>t(n,S.getOptions()),S=>(S?(typeof S==`string`||S instanceof Error)&&__classPrivateFieldGet(this,qp,`f`).fail(S.toString(),S):__classPrivateFieldGet(this,qp,`f`).fail(__classPrivateFieldGet(this,Up,`f`).y18n.__(`Argument check failed: %s`,t.toString())),n),t=>(__classPrivateFieldGet(this,qp,`f`).fail(t.message?t.message:t.toString(),t),n)),!1,n),this}choices(t,n){return argsert(`<object|string|array> [string|array]`,[t,n],arguments.length),this[fm](this.choices.bind(this),`choices`,t,n),this}coerce(t,n){if(argsert(`<object|string|array> [function]`,[t,n],arguments.length),Array.isArray(t)){if(!n)throw new gl(`coerce callback must be provided`);for(let S of t)this.coerce(S,n);return this}else if(typeof t==`object`){for(let n of Object.keys(t))this.coerce(n,t[n]);return this}if(!n)throw new gl(`coerce callback must be provided`);let S=t;return __classPrivateFieldGet(this,Pp,`f`).key[S]=!0,__classPrivateFieldGet(this,Dp,`f`).addCoerceMiddleware((t,C)=>{let N=C.getAliases()[S]??[],F=[S,...N].filter(n=>Object.prototype.hasOwnProperty.call(t,n));return F.length===0?t:maybeAsyncResult(()=>n(t[F[0]]),n=>(F.forEach(S=>{t[S]=n}),t),t=>{throw new gl(t.message)})},S),this}conflicts(t,n){return argsert(`<string|object> [string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Xp,`f`).conflicts(t,n),this}config(t=`config`,n,S){return argsert(`[object|string] [string|function] [function]`,[t,n,S],arguments.length),typeof t==`object`&&!Array.isArray(t)?(t=applyExtends(t,__classPrivateFieldGet(this,gp,`f`),this[im]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Up,`f`)),__classPrivateFieldGet(this,Pp,`f`).configObjects=(__classPrivateFieldGet(this,Pp,`f`).configObjects||[]).concat(t),this):(typeof n==`function`&&(S=n,n=void 0),this.describe(t,n||__classPrivateFieldGet(this,qp,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(t)?t:[t]).forEach(t=>{__classPrivateFieldGet(this,Pp,`f`).config[t]=S||!0}),this)}completion(t,n,S){return argsert(`[string] [string|boolean|function] [function]`,[t,n,S],arguments.length),typeof n==`function`&&(S=n,n=void 0),__classPrivateFieldSet(this,bp,t||__classPrivateFieldGet(this,bp,`f`)||`completion`,`f`),!n&&n!==!1&&(n=`generate completion script`),this.command(__classPrivateFieldGet(this,bp,`f`),n),S&&__classPrivateFieldGet(this,yp,`f`).registerFunction(S),this}command(t,n,S,C,N,F){return argsert(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[t,n,S,C,N,F],arguments.length),__classPrivateFieldGet(this,hp,`f`).addHandler(t,n,S,C,N,F),this}commands(t,n,S,C,N,F){return this.command(t,n,S,C,N,F)}commandDir(t,n){argsert(`<string> [object]`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,Fp,`f`)||__classPrivateFieldGet(this,Up,`f`).require;return __classPrivateFieldGet(this,hp,`f`).addDirectory(t,S,__classPrivateFieldGet(this,Up,`f`).getCallerFile(),n),this}count(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`count`,t),this[Nm](t),this}default(t,n,S){return argsert(`<object|string|array> [*] [string]`,[t,n,S],arguments.length),S&&(assertSingleKey(t,__classPrivateFieldGet(this,Up,`f`)),__classPrivateFieldGet(this,Pp,`f`).defaultDescription[t]=S),typeof n==`function`&&(assertSingleKey(t,__classPrivateFieldGet(this,Up,`f`)),__classPrivateFieldGet(this,Pp,`f`).defaultDescription[t]||(__classPrivateFieldGet(this,Pp,`f`).defaultDescription[t]=__classPrivateFieldGet(this,qp,`f`).functionDescription(n)),n=n.call()),this[dm](this.default.bind(this),`default`,t,n),this}defaults(t,n,S){return this.default(t,n,S)}demandCommand(t=1,n,S,C){return argsert(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[t,n,S,C],arguments.length),typeof n!=`number`&&(S=n,n=1/0),this.global(`_`,!1),__classPrivateFieldGet(this,Pp,`f`).demandedCommands._={min:t,max:n,minMsg:S,maxMsg:C},this}demand(t,n,S){return Array.isArray(n)?(n.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,Up,`f`)),this.demandOption(t,S)}),n=1/0):typeof n!=`number`&&(S=n,n=1/0),typeof t==`number`?(assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,Up,`f`)),this.demandCommand(t,n,S,S)):Array.isArray(t)?t.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,Up,`f`)),this.demandOption(t,S)}):typeof S==`string`?this.demandOption(t,S):(S===!0||S===void 0)&&this.demandOption(t),this}demandOption(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[dm](this.demandOption.bind(this),`demandedOptions`,t,n),this}deprecateOption(t,n){return argsert(`<string> [string|boolean]`,[t,n],arguments.length),__classPrivateFieldGet(this,Pp,`f`).deprecatedOptions[t]=n,this}describe(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[hm](t,!0),__classPrivateFieldGet(this,qp,`f`).describe(t,n),this}detectLocale(t){return argsert(`<boolean>`,[t],arguments.length),__classPrivateFieldSet(this,Cp,t,`f`),this}env(t){return argsert(`[string|boolean]`,[t],arguments.length),t===!1?delete __classPrivateFieldGet(this,Pp,`f`).envPrefix:__classPrivateFieldGet(this,Pp,`f`).envPrefix=t||``,this}epilogue(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,qp,`f`).epilog(t),this}epilog(t){return this.epilogue(t)}example(t,n){return argsert(`<string|array> [string]`,[t,n],arguments.length),Array.isArray(t)?t.forEach(t=>this.example(...t)):__classPrivateFieldGet(this,qp,`f`).example(t,n),this}exit(t,n){__classPrivateFieldSet(this,kp,!0,`f`),__classPrivateFieldSet(this,Sp,n,`f`),__classPrivateFieldGet(this,Tp,`f`)&&__classPrivateFieldGet(this,Up,`f`).process.exit(t)}exitProcess(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Tp,t,`f`),this}fail(t){if(argsert(`<function|boolean>`,[t],arguments.length),typeof t==`boolean`&&t!==!1)throw new gl(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,qp,`f`).failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,n){return argsert(`<array> [function]`,[t,n],arguments.length),n?__classPrivateFieldGet(this,yp,`f`).getCompletion(t,n):new Promise((n,S)=>{__classPrivateFieldGet(this,yp,`f`).getCompletion(t,(t,C)=>{t?S(t):n(C)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,Pp,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,Pp,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,Pp,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,Cp,`f`)}getExitProcess(){return __classPrivateFieldGet(this,Tp,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,Op,`f`),__classPrivateFieldGet(this,Bp,`f`))}getHelp(){if(__classPrivateFieldSet(this,kp,!0,`f`),!__classPrivateFieldGet(this,qp,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[Am](__classPrivateFieldGet(this,Vp,`f`),void 0,void 0,0,!0);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,qp,`f`).help())}let t=__classPrivateFieldGet(this,hp,`f`).runDefaultBuilderOn(this);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,qp,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,qp,`f`).help())}getOptions(){return __classPrivateFieldGet(this,Pp,`f`)}getStrict(){return __classPrivateFieldGet(this,Wp,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,Gp,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,Kp,`f`)}global(t,n){return argsert(`<string|array> [boolean]`,[t,n],arguments.length),t=[].concat(t),n===!1?t.forEach(t=>{__classPrivateFieldGet(this,Pp,`f`).local.includes(t)||__classPrivateFieldGet(this,Pp,`f`).local.push(t)}):__classPrivateFieldGet(this,Pp,`f`).local=__classPrivateFieldGet(this,Pp,`f`).local.filter(n=>t.indexOf(n)===-1),this}group(t,n){argsert(`<string|array> <string>`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,Bp,`f`)[n]||__classPrivateFieldGet(this,Op,`f`)[n];__classPrivateFieldGet(this,Bp,`f`)[n]&&delete __classPrivateFieldGet(this,Bp,`f`)[n];let C={};return __classPrivateFieldGet(this,Op,`f`)[n]=(S||[]).concat(t).filter(t=>C[t]?!1:C[t]=!0),this}hide(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,Pp,`f`).hiddenOptions.push(t),this}implies(t,n){return argsert(`<string|object> [number|string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Xp,`f`).implies(t,n),this}locale(t){return argsert(`[string]`,[t],arguments.length),t===void 0?(this[om](),__classPrivateFieldGet(this,Up,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,Cp,!1,`f`),__classPrivateFieldGet(this,Up,`f`).y18n.setLocale(t),this)}middleware(t,n,S){return __classPrivateFieldGet(this,Dp,`f`).addMiddleware(t,!!n,S)}nargs(t,n){return argsert(`<string|object|array> [number]`,[t,n],arguments.length),this[dm](this.nargs.bind(this),`narg`,t,n),this}normalize(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`normalize`,t),this}number(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`number`,t),this[Nm](t),this}option(t,n){if(argsert(`<string|object> [object]`,[t,n],arguments.length),typeof t==`object`)Object.keys(t).forEach(n=>{this.options(n,t[n])});else{typeof n!=`object`&&(n={}),this[Nm](t),__classPrivateFieldGet(this,Yp,`f`)&&(t===`version`||n?.alias===`version`)&&this[em]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
146
146
  `),void 0,`versionWarning`),__classPrivateFieldGet(this,Pp,`f`).key[t]=!0,n.alias&&this.alias(t,n.alias);let S=n.deprecate||n.deprecated;S&&this.deprecateOption(t,S);let C=n.demand||n.required||n.require;C&&this.demand(t,C),n.demandOption&&this.demandOption(t,typeof n.demandOption==`string`?n.demandOption:void 0),n.conflicts&&this.conflicts(t,n.conflicts),`default`in n&&this.default(t,n.default),n.implies!==void 0&&this.implies(t,n.implies),n.nargs!==void 0&&this.nargs(t,n.nargs),n.config&&this.config(t,n.configParser),n.normalize&&this.normalize(t),n.choices&&this.choices(t,n.choices),n.coerce&&this.coerce(t,n.coerce),n.group&&this.group(t,n.group),(n.boolean||n.type===`boolean`)&&(this.boolean(t),n.alias&&this.boolean(n.alias)),(n.array||n.type===`array`)&&(this.array(t),n.alias&&this.array(n.alias)),(n.number||n.type===`number`)&&(this.number(t),n.alias&&this.number(n.alias)),(n.string||n.type===`string`)&&(this.string(t),n.alias&&this.string(n.alias)),(n.count||n.type===`count`)&&this.count(t),typeof n.global==`boolean`&&this.global(t,n.global),n.defaultDescription&&(__classPrivateFieldGet(this,Pp,`f`).defaultDescription[t]=n.defaultDescription),n.skipValidation&&this.skipValidation(t);let N=n.describe||n.description||n.desc,F=__classPrivateFieldGet(this,qp,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(F,t)||typeof N==`string`)&&this.describe(t,N),n.hidden&&this.hide(t),n.requiresArg&&this.requiresArg(t)}return this}options(t,n){return this.option(t,n)}parse(t,n,S){argsert(`[string|array] [function|boolean|object] [function]`,[t,n,S],arguments.length),this[tm](),t===void 0&&(t=__classPrivateFieldGet(this,Vp,`f`)),typeof n==`object`&&(__classPrivateFieldSet(this,Rp,n,`f`),n=S),typeof n==`function`&&(__classPrivateFieldSet(this,Lp,n,`f`),n=!1),n||__classPrivateFieldSet(this,Vp,t,`f`),__classPrivateFieldGet(this,Lp,`f`)&&__classPrivateFieldSet(this,Tp,!1,`f`);let C=this[Am](t,!!n),N=this.parsed;return __classPrivateFieldGet(this,yp,`f`).setParsed(this.parsed),isPromise(C)?C.then(t=>(__classPrivateFieldGet(this,Lp,`f`)&&__classPrivateFieldGet(this,Lp,`f`).call(this,__classPrivateFieldGet(this,Sp,`f`),t,__classPrivateFieldGet(this,Np,`f`)),t)).catch(t=>{throw __classPrivateFieldGet(this,Lp,`f`)&&__classPrivateFieldGet(this,Lp,`f`)(t,this.parsed.argv,__classPrivateFieldGet(this,Np,`f`)),t}).finally(()=>{this[gm](),this.parsed=N}):(__classPrivateFieldGet(this,Lp,`f`)&&__classPrivateFieldGet(this,Lp,`f`).call(this,__classPrivateFieldGet(this,Sp,`f`),C,__classPrivateFieldGet(this,Np,`f`)),this[gm](),this.parsed=N,C)}parseAsync(t,n,S){let C=this.parse(t,n,S);return isPromise(C)?C:Promise.resolve(C)}parseSync(t,n,S){let C=this.parse(t,n,S);if(isPromise(C))throw new gl(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return C}parserConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Ip,t,`f`),this}pkgConf(t,n){argsert(`<string> [string]`,[t,n],arguments.length);let S=null,C=this[lm](n||__classPrivateFieldGet(this,gp,`f`));return C[t]&&typeof C[t]==`object`&&(S=applyExtends(C[t],n||__classPrivateFieldGet(this,gp,`f`),this[im]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Up,`f`)),__classPrivateFieldGet(this,Pp,`f`).configObjects=(__classPrivateFieldGet(this,Pp,`f`).configObjects||[]).concat(S)),this}positional(t,n){argsert(`<string> <object>`,[t,n],arguments.length);let S=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];n=objFilter(n,(t,n)=>t===`type`&&![`string`,`number`,`boolean`].includes(n)?!1:S.includes(t));let C=__classPrivateFieldGet(this,vp,`f`).fullCommands[__classPrivateFieldGet(this,vp,`f`).fullCommands.length-1],N=C?__classPrivateFieldGet(this,hp,`f`).cmdToParseOptions(C):{array:[],alias:{},default:{},demand:{}};return objectKeys(N).forEach(S=>{let C=N[S];Array.isArray(C)?C.indexOf(t)!==-1&&(n[S]=!0):C[t]&&!(S in n)&&(n[S]=C[t])}),this.group(t,__classPrivateFieldGet(this,qp,`f`).getPositionalGroupName()),this.option(t,n)}recommendCommands(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Hp,t,`f`),this}required(t,n,S){return this.demand(t,n,S)}require(t,n,S){return this.demand(t,n,S)}requiresArg(t){return argsert(`<array|string|object> [number]`,[t],arguments.length),typeof t==`string`&&__classPrivateFieldGet(this,Pp,`f`).narg[t]||this[dm](this.requiresArg.bind(this),`narg`,t,NaN),this}showCompletionScript(t,n){return argsert(`[string] [string]`,[t,n],arguments.length),t||=this.$0,__classPrivateFieldGet(this,Mp,`f`).log(__classPrivateFieldGet(this,yp,`f`).generateCompletionScript(t,n||__classPrivateFieldGet(this,bp,`f`)||`completion`)),this}showHelp(t){if(argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldSet(this,kp,!0,`f`),!__classPrivateFieldGet(this,qp,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[Am](__classPrivateFieldGet(this,Vp,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,qp,`f`).showHelp(t)}),this}let n=__classPrivateFieldGet(this,hp,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,qp,`f`).showHelp(t)}),this}return __classPrivateFieldGet(this,qp,`f`).showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,n){return argsert(`[boolean|string] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,qp,`f`).showHelpOnFail(t,n),this}showVersion(t){return argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldGet(this,qp,`f`).showVersion(t),this}skipValidation(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`skipValidation`,t),this}strict(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Wp,t!==!1,`f`),this}strictCommands(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Gp,t!==!1,`f`),this}strictOptions(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Kp,t!==!1,`f`),this}string(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`string`,t),this[Nm](t),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,Up,`f`).process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Cp,!1,`f`),__classPrivateFieldGet(this,Up,`f`).y18n.updateLocale(t),this}usage(t,n,S,C){if(argsert(`<string|null|undefined> [string|boolean] [function|object] [function]`,[t,n,S,C],arguments.length),n!==void 0){if(assertNotStrictEqual(t,null,__classPrivateFieldGet(this,Up,`f`)),(t||``).match(/^\$0( |$)/))return this.command(t,n,S,C);throw new gl(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,qp,`f`).usage(t),this}usageConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Jp,t,`f`),this}version(t,n,S){let C=`version`;if(argsert(`[boolean|string] [string] [string]`,[t,n,S],arguments.length),__classPrivateFieldGet(this,Yp,`f`)&&(this[$p](__classPrivateFieldGet(this,Yp,`f`)),__classPrivateFieldGet(this,qp,`f`).version(void 0),__classPrivateFieldSet(this,Yp,null,`f`)),arguments.length===0)S=this[sm](),t=C;else if(arguments.length===1){if(t===!1)return this;S=t,t=C}else arguments.length===2&&(S=n,n=void 0);return __classPrivateFieldSet(this,Yp,typeof t==`string`?t:C,`f`),n||=__classPrivateFieldGet(this,qp,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,qp,`f`).version(S||void 0),this.boolean(__classPrivateFieldGet(this,Yp,`f`)),this.describe(__classPrivateFieldGet(this,Yp,`f`),n),this}wrap(t){return argsert(`<number|null|undefined>`,[t],arguments.length),__classPrivateFieldGet(this,qp,`f`).wrap(t),this}[(hp=new WeakMap,gp=new WeakMap,vp=new WeakMap,yp=new WeakMap,bp=new WeakMap,xp=new WeakMap,Sp=new WeakMap,Cp=new WeakMap,wp=new WeakMap,Tp=new WeakMap,Ep=new WeakMap,Dp=new WeakMap,Op=new WeakMap,kp=new WeakMap,Ap=new WeakMap,jp=new WeakMap,Mp=new WeakMap,Np=new WeakMap,Pp=new WeakMap,Fp=new WeakMap,Ip=new WeakMap,Lp=new WeakMap,Rp=new WeakMap,zp=new WeakMap,Bp=new WeakMap,Vp=new WeakMap,Hp=new WeakMap,Up=new WeakMap,Wp=new WeakMap,Gp=new WeakMap,Kp=new WeakMap,qp=new WeakMap,Jp=new WeakMap,Yp=new WeakMap,Xp=new WeakMap,Zp)](t){if(!t._||!t[`--`])return t;t._.push.apply(t._,t[`--`]);try{delete t[`--`]}catch{}return t}[Qp](){return{log:(...t)=>{this[Tm]()||ge.log(...t),__classPrivateFieldSet(this,kp,!0,`f`),__classPrivateFieldGet(this,Np,`f`).length&&__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+`
147
147
  `,`f`),__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+t.join(` `),`f`)},error:(...t)=>{this[Tm]()||ge.error(...t),__classPrivateFieldSet(this,kp,!0,`f`),__classPrivateFieldGet(this,Np,`f`).length&&__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+`
148
- `,`f`),__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+t.join(` `),`f`)}}}[$p](t){objectKeys(__classPrivateFieldGet(this,Pp,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,Pp,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,qp,`f`).getDescriptions()[t]}[em](t,n,S){__classPrivateFieldGet(this,wp,`f`)[S]||(__classPrivateFieldGet(this,Up,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,wp,`f`)[S]=!0)}[tm](){__classPrivateFieldGet(this,Ep,`f`).push({options:__classPrivateFieldGet(this,Pp,`f`),configObjects:__classPrivateFieldGet(this,Pp,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Tp,`f`),groups:__classPrivateFieldGet(this,Op,`f`),strict:__classPrivateFieldGet(this,Wp,`f`),strictCommands:__classPrivateFieldGet(this,Gp,`f`),strictOptions:__classPrivateFieldGet(this,Kp,`f`),completionCommand:__classPrivateFieldGet(this,bp,`f`),output:__classPrivateFieldGet(this,Np,`f`),exitError:__classPrivateFieldGet(this,Sp,`f`),hasOutput:__classPrivateFieldGet(this,kp,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Lp,`f`),parseContext:__classPrivateFieldGet(this,Rp,`f`)}),__classPrivateFieldGet(this,qp,`f`).freeze(),__classPrivateFieldGet(this,Xp,`f`).freeze(),__classPrivateFieldGet(this,hp,`f`).freeze(),__classPrivateFieldGet(this,Dp,`f`).freeze()}[nm](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Up,`f`).process.argv()[0])?__classPrivateFieldGet(this,Up,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Up,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[Om](__classPrivateFieldGet(this,gp,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,Up,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Up,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Up,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,Up,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Up,`f`).path.dirname(__classPrivateFieldGet(this,Up,`f`).process.execPath())}/`,``)),t}[im](){return __classPrivateFieldGet(this,Ip,`f`)}[am](){return __classPrivateFieldGet(this,Jp,`f`)}[om](){if(!__classPrivateFieldGet(this,Cp,`f`))return;let t=__classPrivateFieldGet(this,Up,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[sm](){return this[lm]().version||`unknown`}[cm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,Up,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[lm](t){let n=t||`*`;if(__classPrivateFieldGet(this,zp,`f`)[n])return __classPrivateFieldGet(this,zp,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,Up,`f`).mainFilename;__classPrivateFieldGet(this,Up,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,Up,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,Up,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,Up,`f`)),S=JSON.parse(__classPrivateFieldGet(this,Up,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,zp,`f`)[n]=S||{},__classPrivateFieldGet(this,zp,`f`)[n]}[um](t,n){n=[].concat(n),n.forEach(n=>{n=this[mm](n),__classPrivateFieldGet(this,Pp,`f`)[t].push(n)})}[dm](t,n,S,C){this[pm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Pp,`f`)[t][n]=S})}[fm](t,n,S,C){this[pm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Pp,`f`)[t][n]=(__classPrivateFieldGet(this,Pp,`f`)[t][n]||[]).concat(S)})}[pm](t,n,S,C,N){if(Array.isArray(S))S.forEach(n=>{t(n,C)});else if((t=>typeof t==`object`)(S))for(let n of objectKeys(S))t(n,S[n]);else N(n,this[mm](S),C)}[mm](t){return t===`__proto__`?`___proto___`:t}[hm](t,n){return this[dm](this[hm].bind(this),`key`,t,n),this}[gm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Ep,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,Up,`f`));let te;t=this,n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,{options:{set value(n){__classPrivateFieldSet(t,Pp,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Tp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,Op,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,Np,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Sp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,kp,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,Wp,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,Gp,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,Kp,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,bp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,Lp,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,Rp,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,Pp,`f`).configObjects=te,__classPrivateFieldGet(this,qp,`f`).unfreeze(),__classPrivateFieldGet(this,Xp,`f`).unfreeze(),__classPrivateFieldGet(this,hp,`f`).unfreeze(),__classPrivateFieldGet(this,Dp,`f`).unfreeze()}[_m](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[vm].bind(this),getContext:this[ym].bind(this),getHasOutput:this[bm].bind(this),getLoggerInstance:this[xm].bind(this),getParseContext:this[Sm].bind(this),getParserConfiguration:this[im].bind(this),getUsageConfiguration:this[am].bind(this),getUsageInstance:this[Cm].bind(this),getValidationInstance:this[wm].bind(this),hasParseCallback:this[Tm].bind(this),isGlobalContext:this[Em].bind(this),postProcess:this[Dm].bind(this),reset:this[km].bind(this),runValidation:this[jm].bind(this),runYargsParserAndExecuteCommands:this[Am].bind(this),setHasOutput:this[Mm].bind(this)}}[vm](){return __classPrivateFieldGet(this,hp,`f`)}[ym](){return __classPrivateFieldGet(this,vp,`f`)}[bm](){return __classPrivateFieldGet(this,kp,`f`)}[xm](){return __classPrivateFieldGet(this,Mp,`f`)}[Sm](){return __classPrivateFieldGet(this,Rp,`f`)||{}}[Cm](){return __classPrivateFieldGet(this,qp,`f`)}[wm](){return __classPrivateFieldGet(this,Xp,`f`)}[Tm](){return!!__classPrivateFieldGet(this,Lp,`f`)}[Em](){return __classPrivateFieldGet(this,jp,`f`)}[Dm](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[Zp](t)),(this[im]()[`parse-positional-numbers`]||this[im]()[`parse-positional-numbers`]===void 0)&&(t=this[cm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!1)),t)}[km](t={}){__classPrivateFieldSet(this,Pp,__classPrivateFieldGet(this,Pp,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,Pp,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,Pp,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,Bp,`f`),Object.keys(__classPrivateFieldGet(this,Op,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,Op,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,Op,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,Pp,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,Pp,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,Pp,`f`).envPrefix,__classPrivateFieldSet(this,Pp,n,`f`),__classPrivateFieldSet(this,qp,__classPrivateFieldGet(this,qp,`f`)?__classPrivateFieldGet(this,qp,`f`).reset(S):usage(this,__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`)?__classPrivateFieldGet(this,Xp,`f`).reset(S):validation(this,__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldSet(this,hp,__classPrivateFieldGet(this,hp,`f`)?__classPrivateFieldGet(this,hp,`f`).reset():command(__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,Dp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldGet(this,yp,`f`)||__classPrivateFieldSet(this,yp,completion(this,__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,hp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldGet(this,Dp,`f`).reset(),__classPrivateFieldSet(this,bp,null,`f`),__classPrivateFieldSet(this,Np,``,`f`),__classPrivateFieldSet(this,Sp,null,`f`),__classPrivateFieldSet(this,kp,!1,`f`),this.parsed=!1,this}[Om](t,n){return __classPrivateFieldGet(this,Up,`f`).path.relative(t,n)}[Am](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,Vp,`f`),__classPrivateFieldGet(this,Pp,`f`).__=__classPrivateFieldGet(this,Up,`f`).y18n.__,__classPrivateFieldGet(this,Pp,`f`).configuration=this[im]();let I=!!__classPrivateFieldGet(this,Pp,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,Pp,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,Up,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,Pp,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,Rp,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,Ap,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Yp,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,qp,`f`).clearCachedHelpMessage();try{if(this[om](),n)return this[Dm](q,I,!!S,!1);__classPrivateFieldGet(this,Ap,`f`)&&[__classPrivateFieldGet(this,Ap,`f`)].concat(X[__classPrivateFieldGet(this,Ap,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,jp,!1,`f`);let H=__classPrivateFieldGet(this,hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,yp,`f`)?.completionKey?[__classPrivateFieldGet(this,yp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,yp,`f`)?.completionKey]??[]].some(t=>Object.prototype.hasOwnProperty.call(q,t)):!1,re=Z||ne||N;if(q._.length){if(H.length){let t;for(let n=C||0,F;q._[n]!==void 0;n++)if(F=String(q._[n]),H.includes(F)&&F!==__classPrivateFieldGet(this,bp,`f`)){let t=__classPrivateFieldGet(this,hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[Dm](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,bp,`f`)){t=F;break}!__classPrivateFieldGet(this,hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Hp,`f`)&&t&&!re&&__classPrivateFieldGet(this,Xp,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,bp,`f`)&&q._.includes(__classPrivateFieldGet(this,bp,`f`))&&!ne&&(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,hp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,hp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[Dm](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,yp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,yp,`f`).getCompletion(n,(t,n)=>{if(t)throw new gl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,Mp,`f`).log(t)}),this.exit(0)}),this[Dm](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,kp,`f`)||(Z?(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,Mp,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,qp,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,Pp,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,Pp,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new gl(W.error.message);if(!ne){let t=this[jm](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!0)),Y=this[_m](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof gl)__classPrivateFieldGet(this,qp,`f`).fail(t.message,t);else throw t}return this[Dm](Y??q,I,!!S,!0)}[jm](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new gl(S.message);__classPrivateFieldGet(this,Xp,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Xp,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,Gp,`f`)&&(I=__classPrivateFieldGet(this,Xp,`f`).unknownCommands(F)),__classPrivateFieldGet(this,Wp,`f`)&&!I?__classPrivateFieldGet(this,Xp,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,Kp,`f`)&&__classPrivateFieldGet(this,Xp,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Xp,`f`).limitedChoices(F),__classPrivateFieldGet(this,Xp,`f`).implications(F),__classPrivateFieldGet(this,Xp,`f`).conflicting(F)}}[Mm](){__classPrivateFieldSet(this,kp,!0,`f`)}[Nm](t){if(typeof t==`string`)__classPrivateFieldGet(this,Pp,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,Pp,`f`).key[n]=!0}}}),Im,Lm=__esmMin(()=>{Jf(),Fm(),Im=YargsFactory(qf)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var Rm=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.59.0`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var zm=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,Bm=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(t,n){super(`Package not found in registry: ${t} (${n})`),this.name=t,this.url=n,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(t,n){super(`Tarball integrity mismatch for ${t} (expected ${n})`),this.url=t,this.integrity=n,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(t,n,S){let C=Math.round(n/100)/10,N=Math.round(n*S/100)/10;super(`@gjsify/npm-registry: GET ${t} timed out after ${C}s × ${S} attempt(s) (total ~${N}s). This usually means the registry CDN is slow or unreachable.`),this.url=t,this.timeoutMs=n,this.attempts=S,this.name=`RegistryTimeoutError`}},RegistryUnreachableError=class extends Error{url;attempts;elapsedMs;constructor(t,n,S,C){let N=Math.round(S/100)/10,F=C instanceof Error?C.message:String(C);super(`@gjsify/npm-registry: GET ${t} failed after ${n} attempt(s) over ~${N}s: ${F}. This usually means the registry or the network dropped out.`),this.url=t,this.attempts=n,this.elapsedMs=S,this.name=`RegistryUnreachableError`,this.cause=C}}});function registryFor(t,n){if(n&&t.startsWith(`@`)){let S=t.slice(0,t.indexOf(`/`)),C=n.scopes[S];if(C)return ensureTrailingSlash$1(C)}return n?.registry?ensureTrailingSlash$1(n.registry):Vm}function parseNpmrc(t){let n={registry:Vm,scopes:{},authTokens:{},basicAuth:{}},S=t.split(/\r?\n/),C={};for(let t of S){let S=t.replace(/^\s+|\s+$/g,``);if(!S||S.startsWith(`#`)||S.startsWith(`;`))continue;let N=S.indexOf(`=`);if(N<0)continue;let F=S.slice(0,N).trim(),I=expandEnv(stripQuotes(S.slice(N+1).trim()));if(F===`registry`){n.registry=ensureTrailingSlash$1(I);continue}let H=F.match(/^(@[^:]+):registry$/);if(H){n.scopes[H[1]]=ensureTrailingSlash$1(I);continue}let W=F.match(/^\/\/(.+):_authToken$/);if(W){n.authTokens[normalizeAuthHost(W[1])]=I;continue}let q=F.match(/^\/\/(.+):username$/);if(q){(C[normalizeAuthHost(q[1])]??={}).user=I;continue}let Y=F.match(/^\/\/(.+):_password$/);if(Y){let t=base64Decode$1(I);(C[normalizeAuthHost(Y[1])]??={}).pass=t;continue}}for(let[t,S]of Object.entries(C))S.user&&S.pass!==void 0&&(n.basicAuth[t]={username:S.user,password:S.pass});return n}function normalizeAuthHost(t){return`//${t.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(t){return t.endsWith(`/`)?t:t+`/`}function stripQuotes(t){return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function expandEnv(t){return t.replace(/\$\{([A-Z0-9_]+)\}/gi,(t,n)=>globalThis.process?.env?.[n]??``)}function base64Decode$1(t){return atob(t)}var Vm,Hm=__esmMin(()=>{Vm=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(t,n,S){let C=S.fetch??globalThis.fetch;if(!C)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let N=Math.max(0,S.retries??5),F=Math.max(0,S.retryDelayMs??1e3),I=Math.max(0,S.timeoutMs??3e4),H=S.retryNotFound??!1,W=Date.now(),q=0,Y,X=0;for(;;){if(n.signal?.aborted)throw signalAbortError(n.signal);let Z=I>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${I}ms`)),I),ne=composeSignals(n.signal,Z?.signal);try{let F=await C(t,{...n,signal:ne}),I=isRetryableStatus(F.status)||H&&F.status===404;if(F.ok||!I||q>=N)return S.read?await S.read(F):F;try{await F.arrayBuffer()}catch{}Y=Error(`HTTP ${F.status} ${F.statusText}`)}catch(S){let C=Z!==null&&Z.signal.aborted,F=n.signal?.aborted===!0;if(C&&!F){if(X++,q>=N)throw new RegistryTimeoutError(t,I,X);Y=S}else if(F)throw signalAbortError(n.signal);else{if(!isRetryableError(S))throw S;if(q>=N)throw new RegistryUnreachableError(t,q+1,Date.now()-W,S);Y=S}}finally{te!==null&&clearTimeout(te)}let re=Math.min(F*2**q,8e3);S.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,n.signal),q++}}function composeSignals(t,n){return t?n?AbortSignal.any([t,n]):t:n}function isRetryableStatus(t){return t===408||t===425||t===429||t===500||t===502||t===503||t===504||t===521||t===522||t===524||t===525}function isRetryableError(t){if(t&&typeof t==`object`&&`name`in t&&t.name===`AbortError`)return!1;if(t instanceof TypeError)return!0;if(t&&typeof t==`object`&&`name`in t){let n=t.name;if(n===`FetchError`)return!0;if(n===`AbortError`)return!1}let n=t?.cause;if(n&&typeof n==`object`&&`code`in n){let t=n.code;if(typeof t==`string`)return t===`ECONNRESET`||t===`ECONNREFUSED`||t===`ENETUNREACH`||t===`ENOTFOUND`||t===`ETIMEDOUT`||t===`EAI_AGAIN`||t===`UND_ERR_SOCKET`||t===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t),onAbort=()=>{clearTimeout(N),C(signalAbortError(n))};if(n?.aborted){clearTimeout(N),C(signalAbortError(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}var Um=__esmMin(()=>{Bm(),__name$1(delay$1,`delay`)});async function verifyIntegrity(t,n){let S=n.trim().split(/\s+/);for(let n of S){let S=n.indexOf(`-`);if(S<0)continue;let C=n.slice(0,S).toLowerCase(),N=n.slice(S+1),F=globalThis.crypto?.subtle;if(!F)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let I=subriToWebCryptoAlgo(C);if(!I)continue;let H=await F.digest(I,dataAsArrayBuffer(t));if(bytesToBase64(new Uint8Array(H))===N)return!0}return!1}function subriToWebCryptoAlgo(t){switch(t){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(t){if(t.byteOffset===0&&t.byteLength===t.buffer.byteLength)return t.buffer;let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function bytesToBase64(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return btoa(n)}var Wm=__esmMin(()=>{});function assertPackument(t,n){if(!n||typeof n!=`object`)throw TypeError(`registry: ${t} packument is not an object`);let S=n;if(typeof S.name!=`string`)throw TypeError(`registry: ${t} packument missing string name`);if(!S.versions||typeof S.versions!=`object`)throw TypeError(`registry: ${t} packument missing versions map`)}function packumentUrl(t,n){let S=ensureTrailingSlash$1(n);if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw TypeError(`Invalid scoped package name: ${t}`);let C=t.slice(0,n),N=t.slice(n+1);return`${S}${encodeURIComponent(C)}/${encodeURIComponent(N)}`}return`${S}${encodeURIComponent(t)}`}async function fetchPackumentConditional(t,n={}){let S=packumentUrl(t,n.registry??registryFor(t,n.npmrc)),C=buildHeaders(S,{...n,acceptEncoding:`gzip`});C.accept??=n.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,n.ifNoneMatch&&(C[`if-none-match`]=n.ifNoneMatch);let N=await fetchWithRetry(S,{headers:C,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,read:async n=>{if(n.status===304){try{await n.arrayBuffer()}catch{}return{status:`not-modified`}}if(!n.ok)throw n.status===404||n.status===406?new PackageNotFoundError(t,S):Error(`registry GET ${S} -> ${n.status} ${n.statusText}`);return{status:`fresh`,body:await decodeJsonBody(n),etag:n.headers.get(`etag`)??void 0}}});if(N.status===`not-modified`)return{status:`not-modified`,etag:n.ifNoneMatch};let F=N.body;return assertPackument(t,F),{status:`fresh`,packument:F,etag:N.etag}}async function decodeJsonBody(t){return t.json()}async function fetchPackument(t,n={}){let S=await fetchPackumentConditional(t,n);if(!S.packument)throw Error(`registry: ${t} returned 304 Not Modified to an unconditional request`);return S.packument}var Gm=__esmMin(()=>{zm(),Bm(),Hm(),Um()});async function fetchTarball(t,n={}){let S=buildHeaders(t,{...n,acceptEncoding:`identity`});S.accept??=`application/octet-stream`;let C=await fetchWithRetry(t,{headers:S,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,retryNotFound:n.retryNotFound??!0,read:async n=>{if(!n.ok)throw Error(`tarball GET ${t} -> ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});if(n.integrity&&!await verifyIntegrity(C,n.integrity))throw new IntegrityError(t,n.integrity);return C}var Km=__esmMin(()=>{zm(),Bm(),Um(),Wm()});async function whoami(t,n){let S=`${ensureTrailingSlash$1(t)}-/whoami`,C=buildHeaders(S,{npmrc:n});C.accept=`application/json`;let N=globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=await N(S,{method:`GET`,headers:C});if(!F.ok)throw Error(`whoami GET ${S} -> ${F.status} ${F.statusText}`);let I=await F.json();if(I&&typeof I==`object`&&`username`in I){let t=I.username;if(typeof t==`string`&&t.length>0)return{username:t}}return{}}var qm=__esmMin(()=>{zm(),Hm()}),Jm=__esmMin(()=>{zm(),Hm(),Wm(),Gm(),Km(),qm()});function escapePackageName(t){return t.replace(`/`,`%2f`)}function buildPublishHeaders(t,n){let S=buildHeaders(t,{npmrc:n.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=n.otp?`legacy`:`web`,S[`user-agent`]=n.userAgent??defaultUserAgent(),n.otp&&(S[`npm-otp`]=n.otp),n.authorization&&(S.authorization=n.authorization),S}function cliVersion(){return Ym===void 0&&(Ym=`0.59.0`),Ym}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=wn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=wn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var Ym,Xm=__esmMin(()=>{Md(),jn(),Hn(),Jm()}),Zm,Qm=__esmMin(()=>{Zm=`gjsify`}),$m=__commonJSMin(((t,n)=>{let S=(jn(),__toCommonJS(gn)),C=(Al(),__toCommonJS(El)),N=(Md(),__toCommonJS(Ad)),resolveFrom=(t,n,F)=>{if(typeof t!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof t}\``);if(typeof n!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof n}\``);try{t=N.realpathSync(t)}catch(n){if(n.code===`ENOENT`)t=S.resolve(t);else if(F)return null;else throw n}let I=S.join(t,`noop.js`),resolveFileName=()=>C._resolveFilename(n,{id:I,filename:I,paths:C._nodeModulePaths(t)});if(F)try{return resolveFileName()}catch{return null}return resolveFileName()};n.exports=(t,n)=>resolveFrom(t,n),n.exports.silent=(t,n)=>resolveFrom(t,n,!0)})),eh=__commonJSMin(((t,n)=>{let callsites=()=>{let t=Error.prepareStackTrace;Error.prepareStackTrace=(t,n)=>n;let n=Error().stack.slice(1);return Error.prepareStackTrace=t,n};n.exports=callsites,n.exports.default=callsites})),th=__commonJSMin(((t,n)=>{let S=eh();n.exports=t=>{let n=S();if(!t)return n[2].getFileName();let C=!1;n.shift();for(let S of n){let n=S.getFileName();if(typeof n==`string`){if(n===t){C=!0;continue}if(n!==`module.js`&&C&&n!==t)return n}}}})),nh=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(Pl(),__toCommonJS(jl)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(jn(),__toCommonJS(gn)),H=$m(),W=th();n.exports=t=>{if(typeof t!=`string`)throw TypeError(`Expected a string`);let n=W(F),S=n?I.dirname(n):N,C=H(S,t),q=Y.cache[C];if(q&&q.parent){let t=q.parent.children.length;for(;t--;)q.parent.children[t].id===C&&q.parent.children.splice(t,1)}delete Y.cache[C];let X=Y.cache[n];return X===void 0||X.require===void 0?Y(C):X.require(C)}})),rh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),ih=__commonJSMin(((t,n)=>{var S=(yu(),__toCommonJS(hu)),C=rh(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
148
+ `,`f`),__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+t.join(` `),`f`)}}}[$p](t){objectKeys(__classPrivateFieldGet(this,Pp,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,Pp,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,qp,`f`).getDescriptions()[t]}[em](t,n,S){__classPrivateFieldGet(this,wp,`f`)[S]||(__classPrivateFieldGet(this,Up,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,wp,`f`)[S]=!0)}[tm](){__classPrivateFieldGet(this,Ep,`f`).push({options:__classPrivateFieldGet(this,Pp,`f`),configObjects:__classPrivateFieldGet(this,Pp,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Tp,`f`),groups:__classPrivateFieldGet(this,Op,`f`),strict:__classPrivateFieldGet(this,Wp,`f`),strictCommands:__classPrivateFieldGet(this,Gp,`f`),strictOptions:__classPrivateFieldGet(this,Kp,`f`),completionCommand:__classPrivateFieldGet(this,bp,`f`),output:__classPrivateFieldGet(this,Np,`f`),exitError:__classPrivateFieldGet(this,Sp,`f`),hasOutput:__classPrivateFieldGet(this,kp,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Lp,`f`),parseContext:__classPrivateFieldGet(this,Rp,`f`)}),__classPrivateFieldGet(this,qp,`f`).freeze(),__classPrivateFieldGet(this,Xp,`f`).freeze(),__classPrivateFieldGet(this,hp,`f`).freeze(),__classPrivateFieldGet(this,Dp,`f`).freeze()}[nm](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Up,`f`).process.argv()[0])?__classPrivateFieldGet(this,Up,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Up,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[Om](__classPrivateFieldGet(this,gp,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,Up,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Up,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Up,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,Up,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Up,`f`).path.dirname(__classPrivateFieldGet(this,Up,`f`).process.execPath())}/`,``)),t}[im](){return __classPrivateFieldGet(this,Ip,`f`)}[am](){return __classPrivateFieldGet(this,Jp,`f`)}[om](){if(!__classPrivateFieldGet(this,Cp,`f`))return;let t=__classPrivateFieldGet(this,Up,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[sm](){return this[lm]().version||`unknown`}[cm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,Up,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[lm](t){let n=t||`*`;if(__classPrivateFieldGet(this,zp,`f`)[n])return __classPrivateFieldGet(this,zp,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,Up,`f`).mainFilename;__classPrivateFieldGet(this,Up,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,Up,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,Up,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,Up,`f`)),S=JSON.parse(__classPrivateFieldGet(this,Up,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,zp,`f`)[n]=S||{},__classPrivateFieldGet(this,zp,`f`)[n]}[um](t,n){n=[].concat(n),n.forEach(n=>{n=this[mm](n),__classPrivateFieldGet(this,Pp,`f`)[t].push(n)})}[dm](t,n,S,C){this[pm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Pp,`f`)[t][n]=S})}[fm](t,n,S,C){this[pm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Pp,`f`)[t][n]=(__classPrivateFieldGet(this,Pp,`f`)[t][n]||[]).concat(S)})}[pm](t,n,S,C,N){if(Array.isArray(S))S.forEach(n=>{t(n,C)});else if((t=>typeof t==`object`)(S))for(let n of objectKeys(S))t(n,S[n]);else N(n,this[mm](S),C)}[mm](t){return t===`__proto__`?`___proto___`:t}[hm](t,n){return this[dm](this[hm].bind(this),`key`,t,n),this}[gm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Ep,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,Up,`f`));let te;t=this,n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,{options:{set value(n){__classPrivateFieldSet(t,Pp,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Tp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,Op,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,Np,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Sp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,kp,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,Wp,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,Gp,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,Kp,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,bp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,Lp,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,Rp,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,Pp,`f`).configObjects=te,__classPrivateFieldGet(this,qp,`f`).unfreeze(),__classPrivateFieldGet(this,Xp,`f`).unfreeze(),__classPrivateFieldGet(this,hp,`f`).unfreeze(),__classPrivateFieldGet(this,Dp,`f`).unfreeze()}[_m](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[vm].bind(this),getContext:this[ym].bind(this),getHasOutput:this[bm].bind(this),getLoggerInstance:this[xm].bind(this),getParseContext:this[Sm].bind(this),getParserConfiguration:this[im].bind(this),getUsageConfiguration:this[am].bind(this),getUsageInstance:this[Cm].bind(this),getValidationInstance:this[wm].bind(this),hasParseCallback:this[Tm].bind(this),isGlobalContext:this[Em].bind(this),postProcess:this[Dm].bind(this),reset:this[km].bind(this),runValidation:this[jm].bind(this),runYargsParserAndExecuteCommands:this[Am].bind(this),setHasOutput:this[Mm].bind(this)}}[vm](){return __classPrivateFieldGet(this,hp,`f`)}[ym](){return __classPrivateFieldGet(this,vp,`f`)}[bm](){return __classPrivateFieldGet(this,kp,`f`)}[xm](){return __classPrivateFieldGet(this,Mp,`f`)}[Sm](){return __classPrivateFieldGet(this,Rp,`f`)||{}}[Cm](){return __classPrivateFieldGet(this,qp,`f`)}[wm](){return __classPrivateFieldGet(this,Xp,`f`)}[Tm](){return!!__classPrivateFieldGet(this,Lp,`f`)}[Em](){return __classPrivateFieldGet(this,jp,`f`)}[Dm](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[Zp](t)),(this[im]()[`parse-positional-numbers`]||this[im]()[`parse-positional-numbers`]===void 0)&&(t=this[cm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!1)),t)}[km](t={}){__classPrivateFieldSet(this,Pp,__classPrivateFieldGet(this,Pp,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,Pp,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,Pp,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,Bp,`f`),Object.keys(__classPrivateFieldGet(this,Op,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,Op,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,Op,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,Pp,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,Pp,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,Pp,`f`).envPrefix,__classPrivateFieldSet(this,Pp,n,`f`),__classPrivateFieldSet(this,qp,__classPrivateFieldGet(this,qp,`f`)?__classPrivateFieldGet(this,qp,`f`).reset(S):usage(this,__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`)?__classPrivateFieldGet(this,Xp,`f`).reset(S):validation(this,__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldSet(this,hp,__classPrivateFieldGet(this,hp,`f`)?__classPrivateFieldGet(this,hp,`f`).reset():command(__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,Dp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldGet(this,yp,`f`)||__classPrivateFieldSet(this,yp,completion(this,__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,hp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldGet(this,Dp,`f`).reset(),__classPrivateFieldSet(this,bp,null,`f`),__classPrivateFieldSet(this,Np,``,`f`),__classPrivateFieldSet(this,Sp,null,`f`),__classPrivateFieldSet(this,kp,!1,`f`),this.parsed=!1,this}[Om](t,n){return __classPrivateFieldGet(this,Up,`f`).path.relative(t,n)}[Am](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,Vp,`f`),__classPrivateFieldGet(this,Pp,`f`).__=__classPrivateFieldGet(this,Up,`f`).y18n.__,__classPrivateFieldGet(this,Pp,`f`).configuration=this[im]();let I=!!__classPrivateFieldGet(this,Pp,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,Pp,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,Up,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,Pp,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,Rp,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,Ap,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Yp,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,qp,`f`).clearCachedHelpMessage();try{if(this[om](),n)return this[Dm](q,I,!!S,!1);__classPrivateFieldGet(this,Ap,`f`)&&[__classPrivateFieldGet(this,Ap,`f`)].concat(X[__classPrivateFieldGet(this,Ap,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,jp,!1,`f`);let H=__classPrivateFieldGet(this,hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,yp,`f`)?.completionKey?[__classPrivateFieldGet(this,yp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,yp,`f`)?.completionKey]??[]].some(t=>Object.prototype.hasOwnProperty.call(q,t)):!1,re=Z||ne||N;if(q._.length){if(H.length){let t;for(let n=C||0,F;q._[n]!==void 0;n++)if(F=String(q._[n]),H.includes(F)&&F!==__classPrivateFieldGet(this,bp,`f`)){let t=__classPrivateFieldGet(this,hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[Dm](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,bp,`f`)){t=F;break}!__classPrivateFieldGet(this,hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Hp,`f`)&&t&&!re&&__classPrivateFieldGet(this,Xp,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,bp,`f`)&&q._.includes(__classPrivateFieldGet(this,bp,`f`))&&!ne&&(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,hp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,hp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[Dm](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,yp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,yp,`f`).getCompletion(n,(t,n)=>{if(t)throw new gl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,Mp,`f`).log(t)}),this.exit(0)}),this[Dm](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,kp,`f`)||(Z?(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,Mp,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,qp,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,Pp,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,Pp,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new gl(W.error.message);if(!ne){let t=this[jm](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!0)),Y=this[_m](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof gl)__classPrivateFieldGet(this,qp,`f`).fail(t.message,t);else throw t}return this[Dm](Y??q,I,!!S,!0)}[jm](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new gl(S.message);__classPrivateFieldGet(this,Xp,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Xp,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,Gp,`f`)&&(I=__classPrivateFieldGet(this,Xp,`f`).unknownCommands(F)),__classPrivateFieldGet(this,Wp,`f`)&&!I?__classPrivateFieldGet(this,Xp,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,Kp,`f`)&&__classPrivateFieldGet(this,Xp,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Xp,`f`).limitedChoices(F),__classPrivateFieldGet(this,Xp,`f`).implications(F),__classPrivateFieldGet(this,Xp,`f`).conflicting(F)}}[Mm](){__classPrivateFieldSet(this,kp,!0,`f`)}[Nm](t){if(typeof t==`string`)__classPrivateFieldGet(this,Pp,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,Pp,`f`).key[n]=!0}}}),Im,Lm=__esmMin(()=>{Jf(),Fm(),Im=YargsFactory(qf)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var Rm=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.59.1`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var zm=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,Bm=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(t,n){super(`Package not found in registry: ${t} (${n})`),this.name=t,this.url=n,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(t,n){super(`Tarball integrity mismatch for ${t} (expected ${n})`),this.url=t,this.integrity=n,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(t,n,S){let C=Math.round(n/100)/10,N=Math.round(n*S/100)/10;super(`@gjsify/npm-registry: GET ${t} timed out after ${C}s × ${S} attempt(s) (total ~${N}s). This usually means the registry CDN is slow or unreachable.`),this.url=t,this.timeoutMs=n,this.attempts=S,this.name=`RegistryTimeoutError`}},RegistryUnreachableError=class extends Error{url;attempts;elapsedMs;constructor(t,n,S,C){let N=Math.round(S/100)/10,F=C instanceof Error?C.message:String(C);super(`@gjsify/npm-registry: GET ${t} failed after ${n} attempt(s) over ~${N}s: ${F}. This usually means the registry or the network dropped out.`),this.url=t,this.attempts=n,this.elapsedMs=S,this.name=`RegistryUnreachableError`,this.cause=C}}});function registryFor(t,n){if(n&&t.startsWith(`@`)){let S=t.slice(0,t.indexOf(`/`)),C=n.scopes[S];if(C)return ensureTrailingSlash$1(C)}return n?.registry?ensureTrailingSlash$1(n.registry):Vm}function parseNpmrc(t){let n={registry:Vm,scopes:{},authTokens:{},basicAuth:{}},S=t.split(/\r?\n/),C={};for(let t of S){let S=t.replace(/^\s+|\s+$/g,``);if(!S||S.startsWith(`#`)||S.startsWith(`;`))continue;let N=S.indexOf(`=`);if(N<0)continue;let F=S.slice(0,N).trim(),I=expandEnv(stripQuotes(S.slice(N+1).trim()));if(F===`registry`){n.registry=ensureTrailingSlash$1(I);continue}let H=F.match(/^(@[^:]+):registry$/);if(H){n.scopes[H[1]]=ensureTrailingSlash$1(I);continue}let W=F.match(/^\/\/(.+):_authToken$/);if(W){n.authTokens[normalizeAuthHost(W[1])]=I;continue}let q=F.match(/^\/\/(.+):username$/);if(q){(C[normalizeAuthHost(q[1])]??={}).user=I;continue}let Y=F.match(/^\/\/(.+):_password$/);if(Y){let t=base64Decode$1(I);(C[normalizeAuthHost(Y[1])]??={}).pass=t;continue}}for(let[t,S]of Object.entries(C))S.user&&S.pass!==void 0&&(n.basicAuth[t]={username:S.user,password:S.pass});return n}function normalizeAuthHost(t){return`//${t.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(t){return t.endsWith(`/`)?t:t+`/`}function stripQuotes(t){return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function expandEnv(t){return t.replace(/\$\{([A-Z0-9_]+)\}/gi,(t,n)=>globalThis.process?.env?.[n]??``)}function base64Decode$1(t){return atob(t)}var Vm,Hm=__esmMin(()=>{Vm=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(t,n,S){let C=S.fetch??globalThis.fetch;if(!C)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let N=Math.max(0,S.retries??5),F=Math.max(0,S.retryDelayMs??1e3),I=Math.max(0,S.timeoutMs??3e4),H=S.retryNotFound??!1,W=Date.now(),q=0,Y,X=0;for(;;){if(n.signal?.aborted)throw signalAbortError(n.signal);let Z=I>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${I}ms`)),I),ne=composeSignals(n.signal,Z?.signal);try{let F=await C(t,{...n,signal:ne}),I=isRetryableStatus(F.status)||H&&F.status===404;if(F.ok||!I||q>=N)return S.read?await S.read(F):F;try{await F.arrayBuffer()}catch{}Y=Error(`HTTP ${F.status} ${F.statusText}`)}catch(S){let C=Z!==null&&Z.signal.aborted,F=n.signal?.aborted===!0;if(C&&!F){if(X++,q>=N)throw new RegistryTimeoutError(t,I,X);Y=S}else if(F)throw signalAbortError(n.signal);else{if(!isRetryableError(S))throw S;if(q>=N)throw new RegistryUnreachableError(t,q+1,Date.now()-W,S);Y=S}}finally{te!==null&&clearTimeout(te)}let re=Math.min(F*2**q,8e3);S.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,n.signal),q++}}function composeSignals(t,n){return t?n?AbortSignal.any([t,n]):t:n}function isRetryableStatus(t){return t===408||t===425||t===429||t===500||t===502||t===503||t===504||t===521||t===522||t===524||t===525}function isRetryableError(t){if(t&&typeof t==`object`&&`name`in t&&t.name===`AbortError`)return!1;if(t instanceof TypeError)return!0;if(t&&typeof t==`object`&&`name`in t){let n=t.name;if(n===`FetchError`)return!0;if(n===`AbortError`)return!1}let n=t?.cause;if(n&&typeof n==`object`&&`code`in n){let t=n.code;if(typeof t==`string`)return t===`ECONNRESET`||t===`ECONNREFUSED`||t===`ENETUNREACH`||t===`ENOTFOUND`||t===`ETIMEDOUT`||t===`EAI_AGAIN`||t===`UND_ERR_SOCKET`||t===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t),onAbort=()=>{clearTimeout(N),C(signalAbortError(n))};if(n?.aborted){clearTimeout(N),C(signalAbortError(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}var Um=__esmMin(()=>{Bm(),__name$1(delay$1,`delay`)});async function verifyIntegrity(t,n){let S=n.trim().split(/\s+/);for(let n of S){let S=n.indexOf(`-`);if(S<0)continue;let C=n.slice(0,S).toLowerCase(),N=n.slice(S+1),F=globalThis.crypto?.subtle;if(!F)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let I=subriToWebCryptoAlgo(C);if(!I)continue;let H=await F.digest(I,dataAsArrayBuffer(t));if(bytesToBase64(new Uint8Array(H))===N)return!0}return!1}function subriToWebCryptoAlgo(t){switch(t){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(t){if(t.byteOffset===0&&t.byteLength===t.buffer.byteLength)return t.buffer;let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function bytesToBase64(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return btoa(n)}var Wm=__esmMin(()=>{});function assertPackument(t,n){if(!n||typeof n!=`object`)throw TypeError(`registry: ${t} packument is not an object`);let S=n;if(typeof S.name!=`string`)throw TypeError(`registry: ${t} packument missing string name`);if(!S.versions||typeof S.versions!=`object`)throw TypeError(`registry: ${t} packument missing versions map`)}function packumentUrl(t,n){let S=ensureTrailingSlash$1(n);if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw TypeError(`Invalid scoped package name: ${t}`);let C=t.slice(0,n),N=t.slice(n+1);return`${S}${encodeURIComponent(C)}/${encodeURIComponent(N)}`}return`${S}${encodeURIComponent(t)}`}async function fetchPackumentConditional(t,n={}){let S=packumentUrl(t,n.registry??registryFor(t,n.npmrc)),C=buildHeaders(S,{...n,acceptEncoding:`gzip`});C.accept??=n.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,n.ifNoneMatch&&(C[`if-none-match`]=n.ifNoneMatch);let N=await fetchWithRetry(S,{headers:C,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,read:async n=>{if(n.status===304){try{await n.arrayBuffer()}catch{}return{status:`not-modified`}}if(!n.ok)throw n.status===404||n.status===406?new PackageNotFoundError(t,S):Error(`registry GET ${S} -> ${n.status} ${n.statusText}`);return{status:`fresh`,body:await decodeJsonBody(n),etag:n.headers.get(`etag`)??void 0}}});if(N.status===`not-modified`)return{status:`not-modified`,etag:n.ifNoneMatch};let F=N.body;return assertPackument(t,F),{status:`fresh`,packument:F,etag:N.etag}}async function decodeJsonBody(t){return t.json()}async function fetchPackument(t,n={}){let S=await fetchPackumentConditional(t,n);if(!S.packument)throw Error(`registry: ${t} returned 304 Not Modified to an unconditional request`);return S.packument}var Gm=__esmMin(()=>{zm(),Bm(),Hm(),Um()});async function fetchTarball(t,n={}){let S=buildHeaders(t,{...n,acceptEncoding:`identity`});S.accept??=`application/octet-stream`;let C=await fetchWithRetry(t,{headers:S,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,retryNotFound:n.retryNotFound??!0,read:async n=>{if(!n.ok)throw Error(`tarball GET ${t} -> ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});if(n.integrity&&!await verifyIntegrity(C,n.integrity))throw new IntegrityError(t,n.integrity);return C}var Km=__esmMin(()=>{zm(),Bm(),Um(),Wm()});async function whoami(t,n){let S=`${ensureTrailingSlash$1(t)}-/whoami`,C=buildHeaders(S,{npmrc:n});C.accept=`application/json`;let N=globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=await N(S,{method:`GET`,headers:C});if(!F.ok)throw Error(`whoami GET ${S} -> ${F.status} ${F.statusText}`);let I=await F.json();if(I&&typeof I==`object`&&`username`in I){let t=I.username;if(typeof t==`string`&&t.length>0)return{username:t}}return{}}var qm=__esmMin(()=>{zm(),Hm()}),Jm=__esmMin(()=>{zm(),Hm(),Wm(),Gm(),Km(),qm()});function escapePackageName(t){return t.replace(`/`,`%2f`)}function buildPublishHeaders(t,n){let S=buildHeaders(t,{npmrc:n.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=n.otp?`legacy`:`web`,S[`user-agent`]=n.userAgent??defaultUserAgent(),n.otp&&(S[`npm-otp`]=n.otp),n.authorization&&(S.authorization=n.authorization),S}function cliVersion(){return Ym===void 0&&(Ym=`0.59.1`),Ym}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=wn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=wn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var Ym,Xm=__esmMin(()=>{Md(),jn(),Hn(),Jm()}),Zm,Qm=__esmMin(()=>{Zm=`gjsify`}),$m=__commonJSMin(((t,n)=>{let S=(jn(),__toCommonJS(gn)),C=(Al(),__toCommonJS(El)),N=(Md(),__toCommonJS(Ad)),resolveFrom=(t,n,F)=>{if(typeof t!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof t}\``);if(typeof n!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof n}\``);try{t=N.realpathSync(t)}catch(n){if(n.code===`ENOENT`)t=S.resolve(t);else if(F)return null;else throw n}let I=S.join(t,`noop.js`),resolveFileName=()=>C._resolveFilename(n,{id:I,filename:I,paths:C._nodeModulePaths(t)});if(F)try{return resolveFileName()}catch{return null}return resolveFileName()};n.exports=(t,n)=>resolveFrom(t,n),n.exports.silent=(t,n)=>resolveFrom(t,n,!0)})),eh=__commonJSMin(((t,n)=>{let callsites=()=>{let t=Error.prepareStackTrace;Error.prepareStackTrace=(t,n)=>n;let n=Error().stack.slice(1);return Error.prepareStackTrace=t,n};n.exports=callsites,n.exports.default=callsites})),th=__commonJSMin(((t,n)=>{let S=eh();n.exports=t=>{let n=S();if(!t)return n[2].getFileName();let C=!1;n.shift();for(let S of n){let n=S.getFileName();if(typeof n==`string`){if(n===t){C=!0;continue}if(n!==`module.js`&&C&&n!==t)return n}}}})),nh=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(Pl(),__toCommonJS(jl)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(jn(),__toCommonJS(gn)),H=$m(),W=th();n.exports=t=>{if(typeof t!=`string`)throw TypeError(`Expected a string`);let n=W(F),S=n?I.dirname(n):N,C=H(S,t),q=Y.cache[C];if(q&&q.parent){let t=q.parent.children.length;for(;t--;)q.parent.children[t].id===C&&q.parent.children.splice(t,1)}delete Y.cache[C];let X=Y.cache[n];return X===void 0||X.require===void 0?Y(C):X.require(C)}})),rh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),ih=__commonJSMin(((t,n)=>{var S=(yu(),__toCommonJS(hu)),C=rh(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
149
149
  `)},set:function(t){S=t}});var F=null,I=Object.getOwnPropertyDescriptor(this,`stack`),H=I.get,W=I.value;delete I.value,delete I.writable,I.set=function(t){F=t},I.get=function(){var t=(F||(H?H.call(this):W)).split(/\r?\n+/g);F||(t[0]=this.name+`: `+this.message);var S=1;for(var C in n)if(n.hasOwnProperty(C)){var N=n[C];if(`line`in N){var I=N.line(this[C]);I&&t.splice(S++,0,` `+I)}`stack`in N&&N.stack(this[C],t)}return t.join(`
150
150
  `)},Object.defineProperty(this,"stack",I)};return Object.setPrototypeOf?(Object.setPrototypeOf(N.prototype,Error.prototype),Object.setPrototypeOf(N,Error)):S.inherits(N,Error),N};N.append=function(t,n){return{message:function(S,C){return S||=n,S&&(C[0]+=` `+t.replace(`%s`,S.toString())),C}}},N.line=function(t,n){return{line:function(S){return S||=n,S?t.replace(`%s`,S.toString()):null}}},n.exports=N})),ah=__commonJSMin(((t,n)=>{let hexify=t=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return`0x`+(n.length%2?`0`:``)+n},parseError=(t,n,S)=>{if(!n)return{message:t.message+` while parsing empty string`,position:0};let C=t.message.match(/^Unexpected token (.) .*position\s+(\d+)/i),N=C?+C[2]:t.message.match(/^Unexpected end of JSON.*/i)?n.length-1:null,F=C?t.message.replace(/^Unexpected token ./,`Unexpected token ${JSON.stringify(C[1])} (${hexify(C[1])})`):t.message;if(N!=null){let t=N<=S?0:N-S,C=N+S>=n.length?n.length:N+S,I=(t===0?``:`...`)+n.slice(t,C)+(C===n.length?``:`...`);return{message:F+` while parsing ${n===I?``:`near `}${JSON.stringify(I)}`,position:N}}else return{message:F+` while parsing '${n.slice(0,S*2)}'`,position:0}};var JSONParseError=class extends SyntaxError{constructor(t,n,S,C){S||=20;let N=parseError(t,n,S);super(N.message),Object.assign(this,N),this.code=`EJSONPARSE`,this.systemError=t,Error.captureStackTrace(this,C||this.constructor)}get name(){return this.constructor.name}set name(t){}get[Symbol.toStringTag](){return this.constructor.name}};let S=Symbol.for(`indent`),C=Symbol.for(`newline`),N=/^\s*[{\[]((?:\r?\n)+)([\s\t]*)/,F=/^(?:\{\}|\[\])((?:\r?\n)+)?$/,parseJson=(t,n,I)=>{let H=stripBOM(t);I||=20;try{let[,t=`
151
151
  `,I=` `]=H.match(F)||H.match(N)||[,``,``],W=JSON.parse(H,n);return W&&typeof W==`object`&&(W[C]=t,W[S]=I),W}catch(n){if(typeof t!=`string`&&!Buffer.isBuffer(t)){let S=Array.isArray(t)&&t.length===0;throw Object.assign(TypeError(`Cannot parse ${S?`an empty array`:String(t)}`),{code:`EJSONPARSE`,systemError:n})}throw new JSONParseError(n,H,I,parseJson)}},stripBOM=t=>String(t).replace(/^\uFEFF/,``);n.exports=parseJson,parseJson.JSONParseError=JSONParseError,parseJson.noExceptions=(t,n)=>{try{return JSON.parse(stripBOM(t),n)}catch{}}})),oh=__commonJSMin((t=>{t.__esModule=!0,t.LinesAndColumns=void 0;var n=`
@@ -902,8 +902,8 @@ if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
902
902
  Add @gjsify/node-gi as a dependency to run the storybook on Node, e.g.:
903
903
  "devDependencies": { "@gjsify/node-gi": "^0.13.0" }`);let{env:N,envPrefix:F}=computeNativeEnvForBundle(t,C),I={...process.env,...N},H=nodeBinary(),W=[t,...n],q=[H,...W.map(t=>t.includes(` `)?`"${t}"`:t)].join(` `);ge.error(`$ ${F?`${F} `:``}${q}`);let Y;try{Y=await spawnToCompletion(H,W,{completion:S.completion,env:I})}catch(t){return ge.error(t.message),process.exit(1)}if(Y.code!==0)return ge.error(`node exited with ${describeExit(Y)}`),process.exit(Y.code??1);if(S.exitOnSuccess)return process.exit(0)}function bundleRequiresNodeGi(t){try{return readFileSync(t,`utf-8`).includes(`@gjsify/node-gi`)}catch{return!1}}async function runRuntimeBundle(t,n,S=[],C){let N=process.cwd(),F=vn(n);if(bundleRequiresNodeGi(F)&&!resolveNodeGiForBundle(F,N))throw Error(`Cannot run this bundle on ${t}: 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.:
904
904
  "dependencies": { "@gjsify/node-gi": "^0.13.0" }`);let{env:I,envPrefix:H}=computeNativeEnvForBundle(F,N),W={...process.env,...I},[,q]=N_[t].launch(F,S),Y=t===`node`?nodeBinary():N_[t].probe,X=[Y,...q.map(t=>t.includes(` `)?`"${t}"`:t)].join(` `);C.quiet||ge.error(`$ ${H?`${H} `:``}${X}`);let failed=t=>(process.exitCode=t,process.exit(t)),Z;try{Z=await spawnToCompletion(Y,q,{completion:C.completion,env:W})}catch(t){return ge.error(t.message),failed(1)}if(Z.code!==0)return C.quietExit||ge.error(`${t} exited with ${describeExit(Z)}`),failed(Z.code??1);if(C.exitOnSuccess)return process.exit(0)}var bI=__esmMin(()=>{_e(),Md(),jn(),t_(),vI(),P_(),j_()});function nearestNodeModules(t){let n=vn(t);for(;;){let t=xn(n,`node_modules`);if(existsSync(t))return t;let S=wn(n);if(S===n)return null;n=S}}async function rebuildForGjs(t,n,S){let C=t.nodeModules??nearestNodeModules(process.cwd())??xn(t.pkgDir,`node_modules`),N=findProjectLockfile(wn(C)),F=execCacheKey({pkgName:t.pkgName,pkgVersion:t.pkgVersion,entry:entryWithinPackage(t,n),cliVersion:cliVersion(),lockfileHash:N?hashFile(N):null}),I=execArtifactPath(execCacheRoot(C),t,n,t.installed?F:`local`),H=t.installed&&!S.rebuild;if(H&&existsSync(I))return S.verbose&&ge.error(`gjsify exec: reusing ${I}`),I;ge.error(`gjsify exec: rebuilding ${t.pkgName}@${t.pkgVersion} "${t.binName}" for GJS…`);let W=wn(I),q=`${W}.tmp-${process.pid.toString(16)}-${Date.now().toString(16)}`,Y=xn(q,Tn(I));try{let{BuildAction:C}=await Promise.resolve().then(()=>(GF(),HF));await C.bundleFileForGjs(n,Y,{verbose:S.verbose,preserveDefaultExport:!1,...t.installed?{}:{define:{"import.meta.url":JSON.stringify(pathToFileURL(n).href)}},toolchainAnchor:C.runningCliFile(),...S.verbose?{}:{logLevel:`silent`}})}catch(C){throw rmSync(q,{recursive:!0,force:!0}),new ExecRebuildError(t,n,C,S.verbose)}if(H&&existsSync(I))return rmSync(q,{recursive:!0,force:!0}),I;rmSync(W,{recursive:!0,force:!0});try{renameSync(q,W)}catch(t){if(rmSync(q,{recursive:!0,force:!0}),!existsSync(I))throw t}return pruneStaleArtifacts(wn(W),t,Tn(W)),I}function pruneStaleArtifacts(t,n,S){let C=`${n.pkgName}@${n.pkgVersion}`.replace(/[^a-zA-Z0-9._@-]/g,`_`),N;try{N=readdirSync(t)}catch{return}for(let n of N)n===S||!n.startsWith(`${C}-`)||n.includes(`.tmp-`)||rmSync(xn(t,n),{recursive:!0,force:!0})}var ExecRebuildError,xI,SI=__esmMin(()=>{_e(),Md(),jn(),Hn(),t_(),nI(),pI(),Xm(),vI(),bI(),ExecRebuildError=class extends Error{constructor(t,n,S,C){let N=S instanceof Error?S.message:String(S);super(`gjsify exec: rebuilding "${t.binName}" (${t.pkgName}@${t.pkgVersion}) for GJS failed.\n entry: ${n}\nNothing was run — gjsify exec never falls back to another runtime on its own. To run it on Node explicitly: \`gjsify exec --runtime node ${t.binName}\`.\n`+(C?``:`Re-run with \`gjsify exec --verbose ${t.binName}\` for the bundler's warnings.\n`)+`Bundler diagnostics:\n${N}`,{cause:S}),this.name=`ExecRebuildError`}},xI={command:`exec <entries..>`,description:"Run an installed npm bin on the runtime gjsify runs on: `gjsify exec [--runtime gjs|node|bun|deno] [--rebuild] [--verbose] <bin> [args…]`. On Node/Bun/Deno the bin runs unchanged; on GJS it is rebuilt `--app gjs` once, cached under node_modules/.cache/gjsify/exec/, and run with gjs. Options go BEFORE the bin; everything after it is the bin's own.",builder:t=>t.positional(`entries`,{description:`gjsify exec options, then the bin name and its arguments.`,type:`string`,array:!0}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n,S,C;try{n=splitExecArgv(t.entries??[],doubleDashArgs(t)),S=resolveExecBin(n.bin,process.cwd()),C=planExec(S,n.runtime??hostRuntime$1())}catch(t){if(t instanceof ExecBinNotFoundError)return ge.error(t.message),process.exit(127);if(t instanceof ExecPlanError)return ge.error(t.message),process.exit(1);throw t}let N={completion:`exit`,exitOnSuccess:!0,quiet:!n.verbose,quietExit:!0};if(C.kind===`direct`){await runRuntimeBundle(C.runtime,C.file,n.args,N);return}if(C.kind===`gjs-bundle`){await runGjsBundle(C.file,n.args,N);return}let F=await rebuildForGjs(S,C.entry,{rebuild:n.rebuild,verbose:n.verbose}),I=cliPackageDir();await runGjsBundle(F,n.args,{...N,nativeRoots:I?[I]:[]})}}});function bundleInputsPath(t){return`${t}.inputs.json`}function idToPath(t){if(t===``||t.startsWith(`\0`))return null;let n=t.search(/[?#]/);if(n===-1)return t;let S=t.slice(0,n);return isFile(S)?S:t}function isFile(t){try{return statSync(t).isFile()}catch{return!1}}function isToolchainScratch(t){return t.includes(`${On}node_modules${On}.cache${On}`)}function resolutionFilesFor(t){let n=[];for(let S=wn(t);;S=wn(S)){let t=xn(S,`package.json`);if(existsSync(t)){n.push(t);let C=xn(S,`tsconfig.json`);return existsSync(C)&&n.push(C),n}if(wn(S)===S)return n}}function createBundleInputsRecorder(t){let n=new Set,S=!0,record=t=>{let S=idToPath(t);S!==null&&n.add(S)},C={name:`gjsify:bundle-inputs`,transform(t,n){record(n)}},inputs=()=>{let t=[],S=new Set;for(let C of n){let n;try{n=statSync(C).isFile()}catch{continue}if(!n||isToolchainScratch(C))continue;t.push(C);let N=wn(C);if(!S.has(N)){S.add(N);for(let n of resolutionFilesFor(C))t.push(n)}}return[...new Set(t)].sort()};return{plugin:C,addWatchFiles(t){t.reportedByEngine||(S=!1);for(let n of t.files)record(n)},inputs,write(){let n=bundleInputsPath(t),C={version:2,inputs:inputs(),watchList:S},N=`${n}.tmp`;try{mkdirSync(wn(n),{recursive:!0}),writeFileSync(N,`${JSON.stringify(C,null,2)}\n`,`utf-8`),renameSync(N,n)}catch(t){try{rmSync(N,{force:!0})}catch{}ge.warn(`[gjsify test] could not record the build inputs beside ${n} (${t.message}) — the next run judges freshness by the package walk alone, which cannot see outside this package.`)}}}}function readBundleInputs(t){let n;try{n=JSON.parse(readFileSync(bundleInputsPath(t),`utf-8`))}catch{return null}return n?.version!==2||!Array.isArray(n.inputs)?null:{inputs:n.inputs.filter(t=>typeof t==`string`),watchList:n.watchList===!0}}function newestBundleInputMtimeMs(t){let n=0;for(let S of t)try{let{mtimeMs:t}=statSync(S);t>n&&(n=t)}catch{return 1/0}return n}var CI=__esmMin(()=>{_e(),Md(),jn()});async function buildTestBundle(t,n,S,C){let N=await new Config().forBuild({entryPoints:[t],outfile:n,app:S,verbose:C??!1,logLevel:`warning`,exclude:[]});N.library={...N.library};let F=createBundleInputsRecorder(n);N.bundler={...N.bundler,input:[t],output:{...N.bundler?.output,file:n},plugins:[...N.bundler?.plugins??[],F.plugin]},await new WF(N).start({app:S,library:!1,onWatchFiles:t=>F.addWatchFiles(t)}),F.write()}async function runTestBundle(t,n){if(n===`gjs`){await runGjsBundle(t,[],{completion:`exit`});return}let S=await spawnToCompletion(nodeBinary(),[t],{completion:`exit`});if(S.code!==0)throw Error(`node exited with ${describeExit(S)}`)}function isFresh(t,n,S,C){if(!existsSync(t))return!1;try{let N=statSync(t).mtimeMs,F=[],I=Sn(S,C).split(On).join(`/`);I!==``&&!I.startsWith(`../`)&&F.push(I);let H=readBundleInputs(t);return H!==null&&!H.watchList?!1:N>=Math.max(newestInputMtimeMs(packageBuildInputs(S,{extraOutputs:F})),H===null?0:newestBundleInputMtimeMs(H.inputs),statSync(n).mtimeMs,newestDepSignalMtimeMs(S))}catch{return!1}}var wI,TI=__esmMin(()=>{_e(),Md(),jn(),CI(),VF(),P_(),bI(),j_(),JF(),GF(),vI(),wI={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:t=>t.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 t=>{let n=process.cwd(),S=(await new Config().forBuild({}).catch(()=>({}))).test??{},C=vn(n,t.entry??S.entry??`src/test.mts`),N=vn(n,t.outdir??S.outdir??`dist`);if(!existsSync(C))return ge.error(`[gjsify test] no test entry at ${Sn(n,C)} — add an \`src/test.mts\` that aggregates your \`@gjsify/unit\` suites, or set \`gjsify.test.entry\` in package.json.`),process.exit(1);let F=t.runtime===`gjs`||t.runtime===`node`,I=t.runtime===`gjs`?[`gjs`]:t.runtime===`node`?[`node`]:S.runtimes&&S.runtimes.length>0?S.runtimes:[`gjs`,`node`],H=F?I:I.filter(t=>isRuntimeAvailable(t));for(let t of I.filter(t=>!H.includes(t)))ge.log(`[gjsify test] skipping ${t} — no \`${N_[t].probe}\` on PATH (not requested explicitly)`);if(H.length===0)return ge.error(`[gjsify test] none of the default runtimes (${I.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 W=[];for(let S of H){let F=xn(N,`test.${S}.mjs`);if(t.build!==!1)if(t.rebuild||!isFresh(F,C,n,N)){let N=Date.now();t.verbose&&ge.log(`[gjsify test] building → ${Sn(n,F)} (—app ${S})`);try{await buildTestBundle(C,F,S,t.verbose),t.verbose&&ge.log(`[gjsify test] built ${S} in ${Date.now()-N}ms`)}catch(t){ge.error(`[gjsify test] build failed for ${S}:`,t.message),W.push({runtime:S,ok:!1,durationMs:0,error:`build failed`});continue}}else t.verbose&&ge.log(`[gjsify test] ${S}: bundle is up-to-date — skipping build (use --rebuild to force)`);else if(!existsSync(F)){ge.error(`[gjsify test] --no-build but ${Sn(n,F)} doesn't exist. Build first or drop --no-build.`),W.push({runtime:S,ok:!1,durationMs:0,error:`no bundle`});continue}let I=Date.now();try{await runTestBundle(F,S),W.push({runtime:S,ok:!0,durationMs:Date.now()-I})}catch(t){W.push({runtime:S,ok:!1,durationMs:Date.now()-I,error:t.message})}}let q=W.map(t=>`${t.ok?`✅`:`❌`} ${t.runtime} (${t.durationMs}ms)${t.error?` — ${t.error}`:``}`).join(` `);if(ge.log(`[gjsify test] ${q}`),W.some(t=>!t.ok))return process.exit(1);process.exit(0)}}});function readPackageJson$1(t){if(!existsSync(t))return null;let n=readFileSync(t,`utf-8`);try{return JSON.parse(n)}catch(n){throw Error(`gjsify install: ${t} is not valid JSON: ${n.message}`)}}function writePackageJson(t,n){let S=sortKnownDepFields(n);writeFileSync(t,JSON.stringify(S,null,2)+`
905
- `,`utf-8`)}function parseSpec$2(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n===-1)return{name:t};let S=t.indexOf(`@`,n+1);return S===-1?{name:t}:{name:t.slice(0,S),range:t.slice(S+1)}}let n=t.indexOf(`@`);return n===-1?{name:t}:{name:t.slice(0,n),range:t.slice(n+1)}}function projectSpecsFromPackageJson(t){let n=[];for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=t[S];if(C)for(let[t,S]of Object.entries(C))typeof S==`string`&&(/^(workspace|link|file|portal|git\+|https?):/.test(S)||n.push(`${t}@${S}`))}return n}function addDependencyEntry(t,n,S,C){t[C]===void 0&&(t[C]={}),t[C][n]=S}function defaultRangeFromVersion(t){return`^${t}`}function sortKnownDepFields(t){let n={...t};for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let S=n[t];S&&(n[t]=Object.fromEntries(Object.entries(S).sort(([t],[n])=>t<n?-1:+(t>n))))}return n}var EI=__esmMin(()=>{Md(),__name$1(readPackageJson$1,`readPackageJson`),__name$1(parseSpec$2,`parseSpec`)});function scriptCacheEnabled(){let t=process.env.GJSIFY_NODE_SCRIPT_CACHE;return t===`1`||t===`true`||t===`yes`}async function runNodeScript(t,n=[],S){let C=vn(t);if(!existsSync(C)||!statSync(C).isFile())return ge.error(`gjsify run --node-script: no such file: ${C}`),process.exit(1);let N=hostRuntime$1();if(N!==`gjs`){await runRuntimeBundle(N,C,n,{completion:S.completion,exitOnSuccess:S.exitOnSuccess,quiet:!0});return}let{BuildAction:F}=await Promise.resolve().then(()=>(GF(),HF)),{globals:I,excludeGlobals:H}=await new Config().forNodeScript(C),W;try{W=await F.bundleFileForGjsCached(C,{cacheSubdir:`node-scripts`,label:Tn(C),cache:scriptCacheEnabled(),preserveDefaultExport:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(C).href)},globals:I,excludeGlobals:H,resolveFromToolchain:!0})}catch(t){throw Error(`gjsify run --node-script: failed to bundle ${C} for GJS. The script must import only what gjsify can provide under GJS (node: builtins, workspace packages, pure-JS npm deps). (${t.message})`)}await runGjsBundle(W,n,{completion:S.completion,exitOnSuccess:S.exitOnSuccess,quiet:!0})}var DI=__esmMin(()=>{_e(),Md(),jn(),Hn(),t_(),JF(),vI(),bI()});function makeProgressReporter(t={}){if(t.enabled===!1)return kI;let n=t.stream??process.stderr,S=!!n.isTTY;return t.enabled??!0?S?makeTtyReporter(n):makePlainReporter(n):kI}function makeTtyReporter(t){let n=0,S=``;function render(C,N=!1){let F=Date.now();!N&&F-n<33&&C===S||(n=F,S=C,t.write(`\r\x1B[2K`+C))}function clearLine(){t.write(`\r\x1B[2K`),S=``}return{beginPhase(n,S){render(formatBar(n,0,S,void 0,t.columns??80),!0)},update(n){render(formatBar(n.phase,n.current,n.total,n.name,t.columns??80))},endPhase(n){let S=OI[n];clearLine(),t.write(`gjsify install: ${S} done\n`)}}}function makePlainReporter(t){let n=0,S=0;return{beginPhase(C,N){n=Date.now(),S=0,t.write(`gjsify install: ${OI[C]} ${N} package(s)\n`)},update(C){let N=Date.now();if(N-n<AI||C.current<=S)return;n=N,S=C.current;let F=C.total>0?Math.round(C.current/C.total*100):0;t.write(`gjsify install: ${OI[C.phase]} ${C.current}/${C.total} (${F}%)\n`)},endPhase(n){t.write(`gjsify install: ${OI[n]} done\n`)}}}function formatBar(t,n,S,C,N){let F=OI[t],I=S>0?Math.min(1,n/S):0,H=`${n}/${S}`,W=`gjsify install: ${F} `,q=` ${H}`+(C?` ${C}`:``),Y=Math.max(8,Math.min(40,N-W.length-q.length-4)),X=Math.round(I*Y),Z=`█`.repeat(X)+`░`.repeat(Y-X),te=`${W}[${Z}]${q}`;if(te.length>N){let t=te.length-N+1,n=C&&C.length>t?C.slice(0,C.length-t-1)+`…`:``;te=`${W}[${Z}] ${H}${n?` `+n:``}`}return te}var OI,kI,AI,jI=__esmMin(()=>{OI={resolve:`resolving`,download:`downloading`,extract:`extracting`,link:`linking bins`},kI={update(){},beginPhase(){},endPhase(){}},AI=5e3});function parseTar(t){let n=[],S=null,C=null,N=null,F=0;for(;F+512<=t.length;){let I=t.subarray(F,F+512);if(allZeros(I)){let n=t.subarray(F+512,F+2*512);if(n.length===512&&allZeros(n))break;F+=512;continue}if(!validateChecksum(I))throw new TarParseError(`Bad header checksum at offset ${F} — file is not a valid tar archive`);let H=readString(I,0,100),W=parseOctal(I,100,8),q=parseOctal(I,124,12),Y=parseOctal(I,136,12),X=String.fromCharCode(I[156]||0),Z=readString(I,157,100),te=readString(I,257,6),ne=readString(I,345,155),re=readString(I,265,32),ie=readString(I,297,32);F+=512;let ae=t.subarray(F,F+q);if(F+=alignToBlock(q),X===`x`){S=parsePaxRecords(ae);continue}if(X===`g`)continue;if(X===`L`){C=bytesToString(ae).replace(/\0+$/,``);continue}if(X===`K`){N=bytesToString(ae).replace(/\0+$/,``);continue}let oe=H;te===`ustar`&&ne!==``&&(oe=`${ne}/${H}`),C!==null&&(oe=C,C=null);let Q=Z;if(N!==null&&(Q=N,N=null),S!==null){let C=S.get(`path`);C!==void 0&&(oe=C);let N=S.get(`linkpath`);N!==void 0&&(Q=N);let I=S.get(`size`);if(I!==void 0){let C=Number(I);if(Number.isFinite(C)){let N=F-alignToBlock(q),I=t.subarray(N,N+C);F=N+alignToBlock(C),S=null,n.push(buildEntry(oe,Q,X,W,Y,re,ie,I));continue}}S=null}n.push(buildEntry(oe,Q,X,W,Y,re,ie,ae))}return n}function buildEntry(t,n,S,C,N,F,I,H){return{name:t,linkname:n,type:typeflagToType(S,t),mode:C,mtime:N,body:H,uname:F,gname:I}}function typeflagToType(t,n){switch(t){case`0`:case`\0`:case``:return n.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(t){let n=new Map,S=0;for(;S<t.length;){let C=S;for(;C<t.length&&t[C]!==32;)C++;if(C>=t.length)break;let N=bytesToString(t.subarray(S,C)),F=Number(N);if(!Number.isFinite(F)||F<=0)break;let I=S+F;if(I>t.length)break;let H=bytesToString(t.subarray(C+1,I-1)),W=H.indexOf(`=`);if(W>0){let t=H.slice(0,W),S=H.slice(W+1);n.set(t,S)}S=I}return n}function readString(t,n,S){let C=n,N=n+S;for(;C<N&&t[C]!==0;)C++;return bytesToString(t.subarray(n,C))}function bytesToString(t){return new TextDecoder(`utf-8`,{fatal:!1}).decode(t)}function parseOctal(t,n,S){if(S>0&&t[n]&128){let C=t[n]&127;for(let N=1;N<S;N++)C=C*256+t[n+N];return C}let C=``;for(let N=0;N<S;N++){let S=t[n+N];S===0||S===32||(C+=String.fromCharCode(S))}return C===``?0:parseInt(C,8)}function alignToBlock(t){return Math.ceil(t/512)*512}function allZeros(t){for(let n=0;n<t.length;n++)if(t[n]!==0)return!1;return!0}function validateChecksum(t){let n=parseOctal(t,148,8),S=0,C=0;for(let n=0;n<512;n++){let N=n>=148&&n<156?32:t[n];S+=N,C+=N>127?N-256:N}return n===S||n===C}var TarParseError,MI=__esmMin(()=>{TarParseError=class extends Error{constructor(t){super(t),this.name=`TarParseError`}}});function createTarball(t){let n=[];for(let S of t){if(`directory`in S&&S.directory===!0){n.push(buildHeader$1(ensureTrailingSlash(S.name),0,`5`,S.mode??493,S.mtime??0));continue}let t=S,C=typeof t.body==`string`?new TextEncoder().encode(t.body):t.body,N=t.mode??defaultFileMode(C);n.push(buildHeader$1(t.name,C.byteLength,`0`,N,t.mtime??0)),n.push(C);let F=padTo512(C.byteLength);F>0&&n.push(new Uint8Array(F))}return n.push(new Uint8Array(512*2)),concatChunks(n)}function buildHeader$1(t,n,S,C,N){let{prefix:F,basename:I}=splitPathForUstar(t),H=new Uint8Array(512);writeAscii(H,I,0,100),writeOctal(H,C&4095,100,7),H[107]=0,writeOctal(H,0,108,7),H[115]=0,writeOctal(H,0,116,7),H[123]=0,writeOctal(H,n,124,11),H[135]=0,writeOctal(H,N,136,11),H[147]=0;for(let t=148;t<156;t++)H[t]=32;H[156]=S.charCodeAt(0),writeAscii(H,`ustar\0`,257,6),writeAscii(H,`00`,263,2),F&&writeAscii(H,F,345,155);let W=0;for(let t=0;t<512;t++)W+=H[t];return writeAscii(H,W.toString(8).padStart(6,`0`),148,6),H[154]=0,H[155]=32,H}function splitPathForUstar(t){if(t.length<=100)return{prefix:``,basename:t};if(t.length>255)throw Error(`createTarball: path too long (${t.length} > 255 chars): ${t}`);for(let n=Math.min(t.length-1,155);n>0;n--)if(t[n]===`/`&&t.length-n-1<=100)return{prefix:t.slice(0,n),basename:t.slice(n+1)};throw Error(`createTarball: cannot split path into ustar prefix+basename (basename slot is 100 chars): ${t}`)}function writeAscii(t,n,S,C){let N=new TextEncoder().encode(n);if(N.length>C)throw Error(`createTarball: field too long (${N.length} > ${C}): "${n}"`);t.set(N,S)}function writeOctal(t,n,S,C){writeAscii(t,n.toString(8).padStart(C,`0`),S,C)}function padTo512(t){let n=t%512;return n===0?0:512-n}function ensureTrailingSlash(t){return t.endsWith(`/`)?t:`${t}/`}function defaultFileMode(t){return t.length>=2&&t[0]===35&&t[1]===33?493:420}function concatChunks(t){let n=0;for(let S of t)n+=S.byteLength;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.byteLength;return S}var NI=__esmMin(()=>{__name$1(buildHeader$1,`buildHeader`)});async function extractTarball(t,n,S={}){let C=t instanceof Uint8Array?t:new Uint8Array(t),N=parseTar(S.gzip??(C.length>=2&&C[0]===31&&C[1]===139)?await gunzip(C):C);mkdirSync(n,{recursive:!0});let F=S.strip??1,I=S.preventEscape??!0,H={files:[],directories:[],symlinks:[],skipped:0};for(let t of N){let C=stripComponents(t.name,F);if(C===null||C===``){H.skipped++;continue}let N=vn(n,C);if(I&&!isInside$2(N,n))throw Error(`tar: refusing to extract ${t.name} outside ${n} (resolved=${N})`);if(S.filter&&!S.filter(t,N)){H.skipped++;continue}if(t.type===`directory`){mkdirSync(N,{recursive:!0}),H.directories.push(N);continue}if(t.type===`file`){mkdirSync(wn(N),{recursive:!0}),writeFileSync(N,t.body);let n=S.chmod?.(t,N)??t.mode&511;if(n>0)try{chmodSync(N,n)}catch{}H.files.push(N);continue}if(t.type===`symlink`){mkdirSync(wn(N),{recursive:!0});try{symlinkSync(t.linkname,N),H.symlinks.push(N)}catch{writeFileSync(N,t.linkname),H.files.push(N)}continue}H.skipped++}return H}async function gunzip(t){let n=globalThis.DecompressionStream;if(typeof n!=`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(t)]).stream().pipeThrough(new n(`gzip`)))}async function gzip(t,n){if(n?.level!==void 0){let{gzipSync:S}=await Promise.resolve().then(()=>(ia(),ea));return new Uint8Array(S(t,{level:n.level}))}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(t)]).stream().pipeThrough(new S(`gzip`)))}async function drainStream(t){let n=[],S=0,C=t.getReader();for(;;){let{value:t,done:N}=await C.read();if(N)break;let F=t instanceof Uint8Array?t:new Uint8Array(t);n.push(F),S+=F.length}let N=new Uint8Array(S),F=0;for(let t of n)N.set(t,F),F+=t.length;return N}function stripComponents(t,n){if(n<=0)return t;let S=t.split(`/`).filter(t=>t!==``);return S.length<=n?null:S.slice(n).join(`/`)}function isInside$2(t,n){let S=Sn(n,t);return S!==``&&!S.startsWith(`..`)&&!bn(S)}var PI=__esmMin(()=>{MI(),Md(),jn(),__name$1(isInside$2,`isInside`)}),FI=__exportAll$5({BLOCK_SIZE:()=>512,TarParseError:()=>TarParseError,createTarball:()=>createTarball,extractTarball:()=>extractTarball,gunzip:()=>gunzip,gzip:()=>gzip,parseTar:()=>parseTar}),II=__esmMin(()=>{MI(),NI(),PI()});function gjsifyCacheRoot(t,n){let S=process.env.XDG_CACHE_HOME;return xn(S&&S.length>0?S:xn(homedir(),`.cache`),`gjsify`,t,n)}function atomicWrite(t,n){try{atomicWriteStrict(t,n)}catch{}}function atomicWriteStrict(t,n){mkdirSync(xn(t,`..`),{recursive:!0});let S=`${t}.tmp.${process.pid}`;writeFileSync(S,n),renameSync(S,t)}function readCacheFile(t){if(!existsSync(t))return null;try{let n=readFileSync(t);return n.length===0?null:n}catch{return null}}var LI=__esmMin(()=>{Md(),Dg(),jn()});function isPidAlive(t){if(existsSync(`/proc/self`))return existsSync(`/proc/${t}`);try{return process.kill(t,0),!0}catch(t){return t.code!==`ESRCH`}}function parsePsPidPpid(t){let n=new Map;for(let S of t.split(`
906
- `)){let t=/^\s*(\d+)\s+(\d+)\s*$/.exec(S);if(!t)continue;let C=Number(t[1]),N=Number(t[2]);if(C<=0||N<=0||C===N)continue;let F=n.get(N);F?F.push(C):n.set(N,[C])}return n}function readProcChildren(t){let n;try{n=readdirSync(`/proc/${t}/task`)}catch{return null}let S=[],C=!1;for(let N of n)try{let n=readFileSync(`/proc/${t}/task/${N}/children`,`utf-8`);C=!0;for(let t of n.trim().split(/\s+/)){let n=Number(t);Number.isInteger(n)&&n>0&&S.push(n)}}catch{}return C?S:null}function procPpidMap(){let t=new Map,n=[];try{n=readdirSync(`/proc`)}catch{return t}for(let S of n){let n=Number(S);if(!(!Number.isInteger(n)||n<=0))try{let S=readFileSync(`/proc/${n}/stat`,`utf-8`),C=S.slice(S.lastIndexOf(`)`)+2).split(` `),N=Number(C[1]);if(!Number.isInteger(N)||N<=0)continue;let F=t.get(N);F?F.push(n):t.set(N,[n])}catch{}}return t}function osPpidMap(){let[t,n]=process.platform===`win32`?[`powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-Command`,`Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }`]]:[`ps`,[`-A`,`-o`,`pid=,ppid=`]];try{let S=spawnSync(t,n,{encoding:`utf-8`});return S.status!==0||typeof S.stdout!=`string`?new Map:parsePsPidPpid(S.stdout)}catch{return new Map}}function collectDescendants(t){let n=[],S=new Set([t]),C=[t],N=null;for(;C.length>0;){let t=C.shift(),F=N?null:readProcChildren(t);F===null&&(N||(N=procPpidMap(),N.size===0&&(N=osPpidMap())),F=N.get(t)??[]);for(let t of F)S.has(t)||(S.add(t),n.push(t),C.push(t))}return n}var RI=__esmMin(()=>{w_(),Md()});function staleMs(){let t=process.env.GJSIFY_INSTALL_LOCK_STALE_MS;if(t!==void 0){let n=Number(t);if(Number.isFinite(n)&&n>0)return n}return VI}function lockingDisabled(){let t=process.env.GJSIFY_INSTALL_LOCK;if(t===void 0)return!1;let n=t.trim();return n===`0`||n===`false`}function mtimeMs(t){try{return statSync(t).mtimeMs}catch{return null}}function assessLock(t){let n=xn(t,BI),S=null;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch{S=null}let C=Date.now();if(S&&typeof S.pid==`number`){if(!isPidAlive(S.pid))return{stale:!0,reason:`owner pid ${S.pid} is gone`,ownerPid:S.pid};let t=typeof S.startedAt==`number`?S.startedAt:mtimeMs(n);return t!==null&&C-t>staleMs()?{stale:!0,reason:`owner pid ${S.pid} exceeded the ${staleMs()}ms staleness budget`,ownerPid:S.pid}:{stale:!1,ownerPid:S.pid}}let N=mtimeMs(t);return N===null?{stale:!1}:C-N>HI?{stale:!0,reason:`no owner recorded within the acquire grace period`}:{stale:!1}}function stealStaleLock(t){let n=`${t}.stale-${process.pid}-${++qI}`;try{renameSync(t,n)}catch{return!1}try{rmSync(n,{recursive:!0,force:!0})}catch{}return!0}function abortErr(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}function delay(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let onAbort=()=>{clearTimeout(N),C(abortErr(n))},N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t);if(n?.aborted){clearTimeout(N),C(abortErr(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function makeHandle(t){let n=!1;return{release(){if(n)return;n=!0;let S=KI.get(t);if(S&&(S.count--,!(S.count>0))){KI.delete(t);try{let n=JSON.parse(readFileSync(xn(t,BI),`utf-8`));if(n.nonce!==void 0&&n.nonce!==S.nonce)return}catch{}try{rmSync(t,{recursive:!0,force:!0})}catch{}}}}}async function acquireInstallLock(t,n={}){if(lockingDisabled())return{release(){}};let S;try{S=realpathSync(t)}catch{S=vn(t)}let C=xn(S,`node_modules`,zI),N=KI.get(C);if(N)return N.count++,makeHandle(C);mkdirSync(wn(C),{recursive:!0});let F=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,I=WI,H=!1;for(;;){if(n.signal?.aborted)throw abortErr(n.signal);try{return mkdirSync(C),writeFileSync(xn(C,BI),JSON.stringify({pid:process.pid,nonce:F,startedAt:Date.now()})),KI.set(C,{count:1,nonce:F}),makeHandle(C)}catch(t){if(t.code!==`EEXIST`)throw t}let t=assessLock(C);if(t.stale){stealStaleLock(C)&&ge.warn(`gjsify install: removed stale install lock (${t.reason}) — ${C}`);continue}if(!H){H=!0;let n=t.ownerPid===void 0?``:` (pid ${t.ownerPid})`;ge.warn(`gjsify install: waiting for a concurrent install${n} to release ${C} …`)}await delay(I,n.signal),I=Math.min(Math.round(I*1.6),GI)}}var zI,BI,VI,HI,WI,GI,KI,qI,JI=__esmMin(()=>{_e(),Md(),jn(),RI(),zI=`.gjsify-install-lock`,BI=`owner.json`,VI=35*6e4,HI=15e3,WI=150,GI=1e3,KI=new Map,qI=0});function cacheRoot$1(){return gjsifyCacheRoot(`tarballs`,YI)}function parseSri$1(t){if(!t)return null;let n=t.indexOf(`-`);if(n<=0||n===t.length-1)return null;let S=t.slice(0,n),C=t.slice(n+1).replace(/=+$/,``),N=Xe.from(C,`base64`).toString(`hex`);return N.length<4?null:{algorithm:S,hex:N}}function pathFor$3(t){let n=parseSri$1(t);if(!n)return null;let S=n.hex.slice(0,2);return xn(cacheRoot$1(),n.algorithm,S,`${n.hex}.tgz`)}async function getCachedTarball(t){let n=pathFor$3(t);if(!n||!t)return null;let S=readCacheFile(n);if(!S)return null;if(await verifyIntegrity(S,t))return S;try{unlinkSync(n)}catch{}return null}function putCachedTarball(t,n){let S=pathFor$3(t);S&&(existsSync(S)||atomicWrite(S,n))}function npmCacacheContentDir(){let t=process.env.GJSIFY_NPM_CACHE;if(t!==void 0){let n=t.trim();return n===``||n===`0`||n===`false`?null:xn(n.endsWith(`_cacache`)?n:xn(n,`_cacache`),`content-v2`)}let n=process.env.npm_config_cache;return xn(n&&n.length>0?n:xn(homedir(),`.npm`),`_cacache`,`content-v2`)}function npmCachePathFor(t){let n=npmCacacheContentDir();if(!n)return null;let S=parseSri$1(t);return S?xn(n,S.algorithm,S.hex.slice(0,2),S.hex.slice(2,4),S.hex.slice(4)):null}async function getForeignCachedTarball(t){let n=npmCachePathFor(t);if(!n||!t)return null;let S=readCacheFile(n);return S&&await verifyIntegrity(S,t)?S:null}var YI,XI=__esmMin(()=>{ot(),Md(),Dg(),jn(),Jm(),LI(),YI=`v1`,__name$1(cacheRoot$1,`cacheRoot`),__name$1(parseSri$1,`parseSri`),__name$1(pathFor$3,`pathFor`)});function isEnabled(){let t=process.env.GJSIFY_PACKUMENT_CACHE;if(t===void 0)return!0;let n=t.trim();return!(n===`0`||n===`false`||n===``)}function cacheRoot(){return gjsifyCacheRoot(`metadata`,ZI)}function shardFor(t){let n=2166136261;for(let S=0;S<t.length;S++)n^=t.charCodeAt(S),n=Math.imul(n,16777619);return(n>>>0&255).toString(16).padStart(2,`0`)}function encodePart(t){return encodeURIComponent(t).replace(/\*/g,`%2A`)}function packumentCacheKey(t,n,S){return`${S},${encodePart(t)},${encodePart(n)}`}function pathFor$2(t,n,S){if(!isEnabled())return null;let C=packumentCacheKey(t,n,S);return xn(cacheRoot(),shardFor(C),`${C}.json`)}function getCachedPackument(t,n,S=`corgi`){let C=pathFor$2(t,n,S);if(!C)return null;let N=readCacheFile(C);if(!N)return null;try{let t=JSON.parse(N.toString(`utf-8`));return typeof t.etag!=`string`||!t.etag||!t.packument||typeof t.packument!=`object`?null:{etag:t.etag,packument:t.packument}}catch{return null}}function putCachedPackument(t,n,S,C,N=`corgi`){if(!S)return;let F=pathFor$2(t,n,N);F&&atomicWrite(F,JSON.stringify({etag:S,packument:C}))}var ZI,QI=__esmMin(()=>{jn(),LI(),ZI=`v3`,__name$1(pathFor$2,`pathFor`)});function parseNodeMajor(t){return Number.parseInt(String(t).split(`.`,1)[0]??``,10)}function nativeBackendNodeError(t,n){if(!n)return null;let S=parseNodeMajor(t);return!Number.isFinite(S)||S>=24?null:`gjsify install (native backend) requires Node ≥ 24, but this is Node ${t}. 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 t=nativeBackendNodeError(process.versions.node,onRealNode());if(t)throw Error(t)}var $I=__esmMin(()=>{t_()});function normalizePath(t){let n=On===`/`?t:t.split(On).join(`/`);return n.endsWith(`/`)?n.slice(0,-1):n}function findExtraneous(t){let n=new Set(t.expected.map(t=>normalizePath(t.installPath))),S=t.installed.filter(t=>t.bundles&&!t.linked).map(n=>`${normalizePath(Sn(t.prefix,n.dir))}/node_modules/`),C=[];for(let N of t.installed){if(N.linked)continue;let F=normalizePath(Sn(t.prefix,N.dir));F===``||F.startsWith(`..`)||n.has(F)||S.some(t=>F.startsWith(t))||C.push({installPath:F,name:N.name,version:N.version})}C.sort((t,n)=>t.installPath<n.installPath?-1:+(t.installPath>n.installPath));let N=[];for(let t of C){let n=N[N.length-1];n&&t.installPath.startsWith(`${n.installPath}/`)||N.push(t)}return N}function formatExtraneousError(t,n){let S=t.slice(0,20),C=S.map(t=>` ${t.installPath} (${t.name}@${t.version})`);return t.length>S.length&&C.push(` … and ${t.length-S.length} more`),[`install: --immutable, but ${n}/node_modules holds ${t.length} package(s) that gjsify-lock.json does not describe.`,`--immutable installs the lockfile and removes nothing, so each of these would survive the install and be resolved, bundled and type-checked as if it belonged (gjsify#1683: a nested copy of an already-hoisted package → TS2883, one type with two identities).`,...C,"Fix: delete those directories — or the whole node_modules — and re-run. A plain `gjsify install` does NOT clear them: it only ever adds, and its prune pass judges foreign-PLATFORM packages alone (prune-prefix.ts), so an undescribed package survives both. Deleting is currently the only thing that removes one. In CI this usually means a cache entry was restored from a DIFFERENT lockfile."].join(`
905
+ `,`utf-8`)}function parseSpec$2(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n===-1)return{name:t};let S=t.indexOf(`@`,n+1);return S===-1?{name:t}:{name:t.slice(0,S),range:t.slice(S+1)}}let n=t.indexOf(`@`);return n===-1?{name:t}:{name:t.slice(0,n),range:t.slice(n+1)}}function projectSpecsFromPackageJson(t){let n=[];for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=t[S];if(C)for(let[t,S]of Object.entries(C))typeof S==`string`&&(/^(workspace|link|file|portal|git\+|https?):/.test(S)||n.push(`${t}@${S}`))}return n}function addDependencyEntry(t,n,S,C){t[C]===void 0&&(t[C]={}),t[C][n]=S}function defaultRangeFromVersion(t){return`^${t}`}function sortKnownDepFields(t){let n={...t};for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let S=n[t];S&&(n[t]=Object.fromEntries(Object.entries(S).sort(([t],[n])=>t<n?-1:+(t>n))))}return n}var EI=__esmMin(()=>{Md(),__name$1(readPackageJson$1,`readPackageJson`),__name$1(parseSpec$2,`parseSpec`)});function scriptCacheEnabled(){let t=process.env.GJSIFY_NODE_SCRIPT_CACHE;return t===`1`||t===`true`||t===`yes`}async function runNodeScript(t,n=[],S){let C=vn(t);if(!existsSync(C)||!statSync(C).isFile())return ge.error(`gjsify run --node-script: no such file: ${C}`),process.exit(1);let N=hostRuntime$1();if(N!==`gjs`){await runRuntimeBundle(N,C,n,{completion:S.completion,exitOnSuccess:S.exitOnSuccess,quiet:!0});return}let{BuildAction:F}=await Promise.resolve().then(()=>(GF(),HF)),{globals:I,excludeGlobals:H}=await new Config().forNodeScript(C),W;try{W=await F.bundleFileForGjsCached(C,{cacheSubdir:`node-scripts`,label:Tn(C),cache:scriptCacheEnabled(),preserveDefaultExport:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(C).href)},globals:I,excludeGlobals:H,resolveFromToolchain:!0})}catch(t){throw Error(`gjsify run --node-script: failed to bundle ${C} for GJS. The script must import only what gjsify can provide under GJS (node: builtins, workspace packages, pure-JS npm deps). (${t.message})`)}await runGjsBundle(W,n,{completion:S.completion,exitOnSuccess:S.exitOnSuccess,quiet:!0})}var DI=__esmMin(()=>{_e(),Md(),jn(),Hn(),t_(),JF(),vI(),bI()});function gjsifyCacheRoot(t,n){let S=process.env.XDG_CACHE_HOME;return xn(S&&S.length>0?S:xn(homedir(),`.cache`),`gjsify`,t,n)}function atomicWrite(t,n){try{atomicWriteStrict(t,n)}catch{}}function atomicWriteStrict(t,n){mkdirSync(xn(t,`..`),{recursive:!0});let S=`${t}.tmp.${process.pid}`;writeFileSync(S,n),renameSync(S,t)}function readCacheFile(t){if(!existsSync(t))return null;try{let n=readFileSync(t);return n.length===0?null:n}catch{return null}}var OI=__esmMin(()=>{Md(),Dg(),jn()});function makeProgressReporter(t={}){if(t.enabled===!1)return AI;let n=t.stream??process.stderr,S=!!n.isTTY;return t.enabled??!0?S?makeTtyReporter(n):makePlainReporter(n):AI}function makeTtyReporter(t){let n=0,S=``;function render(C,N=!1){let F=Date.now();!N&&F-n<33&&C===S||(n=F,S=C,t.write(`\r\x1B[2K`+C))}function clearLine(){t.write(`\r\x1B[2K`),S=``}return{beginPhase(n,S){render(formatBar(n,0,S,void 0,t.columns??80),!0)},update(n){render(formatBar(n.phase,n.current,n.total,n.name,t.columns??80))},endPhase(n){let S=kI[n];clearLine(),t.write(`gjsify install: ${S} done\n`)}}}function makePlainReporter(t){let n=0,S=0;return{beginPhase(C,N){n=Date.now(),S=0,t.write(`gjsify install: ${kI[C]} ${N} package(s)\n`)},update(C){let N=Date.now();if(N-n<jI||C.current<=S)return;n=N,S=C.current;let F=C.total>0?Math.round(C.current/C.total*100):0;t.write(`gjsify install: ${kI[C.phase]} ${C.current}/${C.total} (${F}%)\n`)},endPhase(n){t.write(`gjsify install: ${kI[n]} done\n`)}}}function formatBar(t,n,S,C,N){let F=kI[t],I=S>0?Math.min(1,n/S):0,H=`${n}/${S}`,W=`gjsify install: ${F} `,q=` ${H}`+(C?` ${C}`:``),Y=Math.max(8,Math.min(40,N-W.length-q.length-4)),X=Math.round(I*Y),Z=`█`.repeat(X)+`░`.repeat(Y-X),te=`${W}[${Z}]${q}`;if(te.length>N){let t=te.length-N+1,n=C&&C.length>t?C.slice(0,C.length-t-1)+`…`:``;te=`${W}[${Z}] ${H}${n?` `+n:``}`}return te}var kI,AI,jI,MI=__esmMin(()=>{kI={resolve:`resolving`,download:`downloading`,extract:`extracting`,link:`linking bins`},AI={update(){},beginPhase(){},endPhase(){}},jI=5e3});function parseTar(t){let n=[],S=null,C=null,N=null,F=0;for(;F+512<=t.length;){let I=t.subarray(F,F+512);if(allZeros(I)){let n=t.subarray(F+512,F+2*512);if(n.length===512&&allZeros(n))break;F+=512;continue}if(!validateChecksum(I))throw new TarParseError(`Bad header checksum at offset ${F} — file is not a valid tar archive`);let H=readString(I,0,100),W=parseOctal(I,100,8),q=parseOctal(I,124,12),Y=parseOctal(I,136,12),X=String.fromCharCode(I[156]||0),Z=readString(I,157,100),te=readString(I,257,6),ne=readString(I,345,155),re=readString(I,265,32),ie=readString(I,297,32);F+=512;let ae=t.subarray(F,F+q);if(F+=alignToBlock(q),X===`x`){S=parsePaxRecords(ae);continue}if(X===`g`)continue;if(X===`L`){C=bytesToString(ae).replace(/\0+$/,``);continue}if(X===`K`){N=bytesToString(ae).replace(/\0+$/,``);continue}let oe=H;te===`ustar`&&ne!==``&&(oe=`${ne}/${H}`),C!==null&&(oe=C,C=null);let Q=Z;if(N!==null&&(Q=N,N=null),S!==null){let C=S.get(`path`);C!==void 0&&(oe=C);let N=S.get(`linkpath`);N!==void 0&&(Q=N);let I=S.get(`size`);if(I!==void 0){let C=Number(I);if(Number.isFinite(C)){let N=F-alignToBlock(q),I=t.subarray(N,N+C);F=N+alignToBlock(C),S=null,n.push(buildEntry(oe,Q,X,W,Y,re,ie,I));continue}}S=null}n.push(buildEntry(oe,Q,X,W,Y,re,ie,ae))}return n}function buildEntry(t,n,S,C,N,F,I,H){return{name:t,linkname:n,type:typeflagToType(S,t),mode:C,mtime:N,body:H,uname:F,gname:I}}function typeflagToType(t,n){switch(t){case`0`:case`\0`:case``:return n.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(t){let n=new Map,S=0;for(;S<t.length;){let C=S;for(;C<t.length&&t[C]!==32;)C++;if(C>=t.length)break;let N=bytesToString(t.subarray(S,C)),F=Number(N);if(!Number.isFinite(F)||F<=0)break;let I=S+F;if(I>t.length)break;let H=bytesToString(t.subarray(C+1,I-1)),W=H.indexOf(`=`);if(W>0){let t=H.slice(0,W),S=H.slice(W+1);n.set(t,S)}S=I}return n}function readString(t,n,S){let C=n,N=n+S;for(;C<N&&t[C]!==0;)C++;return bytesToString(t.subarray(n,C))}function bytesToString(t){return new TextDecoder(`utf-8`,{fatal:!1}).decode(t)}function parseOctal(t,n,S){if(S>0&&t[n]&128){let C=t[n]&127;for(let N=1;N<S;N++)C=C*256+t[n+N];return C}let C=``;for(let N=0;N<S;N++){let S=t[n+N];S===0||S===32||(C+=String.fromCharCode(S))}return C===``?0:parseInt(C,8)}function alignToBlock(t){return Math.ceil(t/512)*512}function allZeros(t){for(let n=0;n<t.length;n++)if(t[n]!==0)return!1;return!0}function validateChecksum(t){let n=parseOctal(t,148,8),S=0,C=0;for(let n=0;n<512;n++){let N=n>=148&&n<156?32:t[n];S+=N,C+=N>127?N-256:N}return n===S||n===C}var TarParseError,NI=__esmMin(()=>{TarParseError=class extends Error{constructor(t){super(t),this.name=`TarParseError`}}});function createTarball(t){let n=[];for(let S of t){if(`directory`in S&&S.directory===!0){n.push(buildHeader$1(ensureTrailingSlash(S.name),0,`5`,S.mode??493,S.mtime??0));continue}let t=S,C=typeof t.body==`string`?new TextEncoder().encode(t.body):t.body,N=t.mode??defaultFileMode(C);n.push(buildHeader$1(t.name,C.byteLength,`0`,N,t.mtime??0)),n.push(C);let F=padTo512(C.byteLength);F>0&&n.push(new Uint8Array(F))}return n.push(new Uint8Array(512*2)),concatChunks(n)}function buildHeader$1(t,n,S,C,N){let{prefix:F,basename:I}=splitPathForUstar(t),H=new Uint8Array(512);writeAscii(H,I,0,100),writeOctal(H,C&4095,100,7),H[107]=0,writeOctal(H,0,108,7),H[115]=0,writeOctal(H,0,116,7),H[123]=0,writeOctal(H,n,124,11),H[135]=0,writeOctal(H,N,136,11),H[147]=0;for(let t=148;t<156;t++)H[t]=32;H[156]=S.charCodeAt(0),writeAscii(H,`ustar\0`,257,6),writeAscii(H,`00`,263,2),F&&writeAscii(H,F,345,155);let W=0;for(let t=0;t<512;t++)W+=H[t];return writeAscii(H,W.toString(8).padStart(6,`0`),148,6),H[154]=0,H[155]=32,H}function splitPathForUstar(t){if(t.length<=100)return{prefix:``,basename:t};if(t.length>255)throw Error(`createTarball: path too long (${t.length} > 255 chars): ${t}`);for(let n=Math.min(t.length-1,155);n>0;n--)if(t[n]===`/`&&t.length-n-1<=100)return{prefix:t.slice(0,n),basename:t.slice(n+1)};throw Error(`createTarball: cannot split path into ustar prefix+basename (basename slot is 100 chars): ${t}`)}function writeAscii(t,n,S,C){let N=new TextEncoder().encode(n);if(N.length>C)throw Error(`createTarball: field too long (${N.length} > ${C}): "${n}"`);t.set(N,S)}function writeOctal(t,n,S,C){writeAscii(t,n.toString(8).padStart(C,`0`),S,C)}function padTo512(t){let n=t%512;return n===0?0:512-n}function ensureTrailingSlash(t){return t.endsWith(`/`)?t:`${t}/`}function defaultFileMode(t){return t.length>=2&&t[0]===35&&t[1]===33?493:420}function concatChunks(t){let n=0;for(let S of t)n+=S.byteLength;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.byteLength;return S}var PI=__esmMin(()=>{__name$1(buildHeader$1,`buildHeader`)});async function extractTarball(t,n,S={}){let C=t instanceof Uint8Array?t:new Uint8Array(t),N=parseTar(S.gzip??(C.length>=2&&C[0]===31&&C[1]===139)?await gunzip(C):C);mkdirSync(n,{recursive:!0});let F=S.strip??1,I=S.preventEscape??!0,H={files:[],directories:[],symlinks:[],skipped:0};for(let t of N){let C=stripComponents(t.name,F);if(C===null||C===``){H.skipped++;continue}let N=vn(n,C);if(I&&!isInside$2(N,n))throw Error(`tar: refusing to extract ${t.name} outside ${n} (resolved=${N})`);if(S.filter&&!S.filter(t,N)){H.skipped++;continue}if(t.type===`directory`){mkdirSync(N,{recursive:!0}),H.directories.push(N);continue}if(t.type===`file`){mkdirSync(wn(N),{recursive:!0}),writeFileSync(N,t.body);let n=S.chmod?.(t,N)??t.mode&511;if(n>0)try{chmodSync(N,n)}catch{}H.files.push(N);continue}if(t.type===`symlink`){mkdirSync(wn(N),{recursive:!0});try{symlinkSync(t.linkname,N),H.symlinks.push(N)}catch{writeFileSync(N,t.linkname),H.files.push(N)}continue}H.skipped++}return H}async function gunzip(t){let n=globalThis.DecompressionStream;if(typeof n!=`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(t)]).stream().pipeThrough(new n(`gzip`)))}async function gzip(t,n){if(n?.level!==void 0){let{gzipSync:S}=await Promise.resolve().then(()=>(ia(),ea));return new Uint8Array(S(t,{level:n.level}))}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(t)]).stream().pipeThrough(new S(`gzip`)))}async function drainStream(t){let n=[],S=0,C=t.getReader();for(;;){let{value:t,done:N}=await C.read();if(N)break;let F=t instanceof Uint8Array?t:new Uint8Array(t);n.push(F),S+=F.length}let N=new Uint8Array(S),F=0;for(let t of n)N.set(t,F),F+=t.length;return N}function stripComponents(t,n){if(n<=0)return t;let S=t.split(`/`).filter(t=>t!==``);return S.length<=n?null:S.slice(n).join(`/`)}function isInside$2(t,n){let S=Sn(n,t);return S!==``&&!S.startsWith(`..`)&&!bn(S)}var FI=__esmMin(()=>{NI(),Md(),jn(),__name$1(isInside$2,`isInside`)}),II=__exportAll$5({BLOCK_SIZE:()=>512,TarParseError:()=>TarParseError,createTarball:()=>createTarball,extractTarball:()=>extractTarball,gunzip:()=>gunzip,gzip:()=>gzip,parseTar:()=>parseTar}),LI=__esmMin(()=>{NI(),PI(),FI()});function isPidAlive(t){if(existsSync(`/proc/self`))return existsSync(`/proc/${t}`);try{return process.kill(t,0),!0}catch(t){return t.code!==`ESRCH`}}function parsePsPidPpid(t){let n=new Map;for(let S of t.split(`
906
+ `)){let t=/^\s*(\d+)\s+(\d+)\s*$/.exec(S);if(!t)continue;let C=Number(t[1]),N=Number(t[2]);if(C<=0||N<=0||C===N)continue;let F=n.get(N);F?F.push(C):n.set(N,[C])}return n}function readProcChildren(t){let n;try{n=readdirSync(`/proc/${t}/task`)}catch{return null}let S=[],C=!1;for(let N of n)try{let n=readFileSync(`/proc/${t}/task/${N}/children`,`utf-8`);C=!0;for(let t of n.trim().split(/\s+/)){let n=Number(t);Number.isInteger(n)&&n>0&&S.push(n)}}catch{}return C?S:null}function procPpidMap(){let t=new Map,n=[];try{n=readdirSync(`/proc`)}catch{return t}for(let S of n){let n=Number(S);if(!(!Number.isInteger(n)||n<=0))try{let S=readFileSync(`/proc/${n}/stat`,`utf-8`),C=S.slice(S.lastIndexOf(`)`)+2).split(` `),N=Number(C[1]);if(!Number.isInteger(N)||N<=0)continue;let F=t.get(N);F?F.push(n):t.set(N,[n])}catch{}}return t}function osPpidMap(){let[t,n]=process.platform===`win32`?[`powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-Command`,`Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }`]]:[`ps`,[`-A`,`-o`,`pid=,ppid=`]];try{let S=spawnSync(t,n,{encoding:`utf-8`});return S.status!==0||typeof S.stdout!=`string`?new Map:parsePsPidPpid(S.stdout)}catch{return new Map}}function collectDescendants(t){let n=[],S=new Set([t]),C=[t],N=null;for(;C.length>0;){let t=C.shift(),F=N?null:readProcChildren(t);F===null&&(N||(N=procPpidMap(),N.size===0&&(N=osPpidMap())),F=N.get(t)??[]);for(let t of F)S.has(t)||(S.add(t),n.push(t),C.push(t))}return n}var RI=__esmMin(()=>{w_(),Md()});function staleMs(){let t=process.env.GJSIFY_INSTALL_LOCK_STALE_MS;if(t!==void 0){let n=Number(t);if(Number.isFinite(n)&&n>0)return n}return VI}function lockingDisabled(){let t=process.env.GJSIFY_INSTALL_LOCK;if(t===void 0)return!1;let n=t.trim();return n===`0`||n===`false`}function mtimeMs(t){try{return statSync(t).mtimeMs}catch{return null}}function assessLock(t){let n=xn(t,BI),S=null;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch{S=null}let C=Date.now();if(S&&typeof S.pid==`number`){if(!isPidAlive(S.pid))return{stale:!0,reason:`owner pid ${S.pid} is gone`,ownerPid:S.pid};let t=typeof S.startedAt==`number`?S.startedAt:mtimeMs(n);return t!==null&&C-t>staleMs()?{stale:!0,reason:`owner pid ${S.pid} exceeded the ${staleMs()}ms staleness budget`,ownerPid:S.pid}:{stale:!1,ownerPid:S.pid}}let N=mtimeMs(t);return N===null?{stale:!1}:C-N>HI?{stale:!0,reason:`no owner recorded within the acquire grace period`}:{stale:!1}}function stealStaleLock(t){let n=`${t}.stale-${process.pid}-${++qI}`;try{renameSync(t,n)}catch{return!1}try{rmSync(n,{recursive:!0,force:!0})}catch{}return!0}function abortErr(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}function delay(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let onAbort=()=>{clearTimeout(N),C(abortErr(n))},N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t);if(n?.aborted){clearTimeout(N),C(abortErr(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function makeHandle(t){let n=!1;return{release(){if(n)return;n=!0;let S=KI.get(t);if(S&&(S.count--,!(S.count>0))){KI.delete(t);try{let n=JSON.parse(readFileSync(xn(t,BI),`utf-8`));if(n.nonce!==void 0&&n.nonce!==S.nonce)return}catch{}try{rmSync(t,{recursive:!0,force:!0})}catch{}}}}}async function acquireInstallLock(t,n={}){if(lockingDisabled())return{release(){}};let S;try{S=realpathSync(t)}catch{S=vn(t)}let C=xn(S,`node_modules`,zI),N=KI.get(C);if(N)return N.count++,makeHandle(C);mkdirSync(wn(C),{recursive:!0});let F=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,I=WI,H=!1;for(;;){if(n.signal?.aborted)throw abortErr(n.signal);try{return mkdirSync(C),writeFileSync(xn(C,BI),JSON.stringify({pid:process.pid,nonce:F,startedAt:Date.now()})),KI.set(C,{count:1,nonce:F}),makeHandle(C)}catch(t){if(t.code!==`EEXIST`)throw t}let t=assessLock(C);if(t.stale){stealStaleLock(C)&&ge.warn(`gjsify install: removed stale install lock (${t.reason}) — ${C}`);continue}if(!H){H=!0;let n=t.ownerPid===void 0?``:` (pid ${t.ownerPid})`;ge.warn(`gjsify install: waiting for a concurrent install${n} to release ${C} …`)}await delay(I,n.signal),I=Math.min(Math.round(I*1.6),GI)}}var zI,BI,VI,HI,WI,GI,KI,qI,JI=__esmMin(()=>{_e(),Md(),jn(),RI(),zI=`.gjsify-install-lock`,BI=`owner.json`,VI=35*6e4,HI=15e3,WI=150,GI=1e3,KI=new Map,qI=0});function cacheRoot$1(){return gjsifyCacheRoot(`tarballs`,YI)}function parseSri$1(t){if(!t)return null;let n=t.indexOf(`-`);if(n<=0||n===t.length-1)return null;let S=t.slice(0,n),C=t.slice(n+1).replace(/=+$/,``),N=Xe.from(C,`base64`).toString(`hex`);return N.length<4?null:{algorithm:S,hex:N}}function pathFor$3(t){let n=parseSri$1(t);if(!n)return null;let S=n.hex.slice(0,2);return xn(cacheRoot$1(),n.algorithm,S,`${n.hex}.tgz`)}async function getCachedTarball(t){let n=pathFor$3(t);if(!n||!t)return null;let S=readCacheFile(n);if(!S)return null;if(await verifyIntegrity(S,t))return S;try{unlinkSync(n)}catch{}return null}function putCachedTarball(t,n){let S=pathFor$3(t);S&&(existsSync(S)||atomicWrite(S,n))}function npmCacacheContentDir(){let t=process.env.GJSIFY_NPM_CACHE;if(t!==void 0){let n=t.trim();return n===``||n===`0`||n===`false`?null:xn(n.endsWith(`_cacache`)?n:xn(n,`_cacache`),`content-v2`)}let n=process.env.npm_config_cache;return xn(n&&n.length>0?n:xn(homedir(),`.npm`),`_cacache`,`content-v2`)}function npmCachePathFor(t){let n=npmCacacheContentDir();if(!n)return null;let S=parseSri$1(t);return S?xn(n,S.algorithm,S.hex.slice(0,2),S.hex.slice(2,4),S.hex.slice(4)):null}async function getForeignCachedTarball(t){let n=npmCachePathFor(t);if(!n||!t)return null;let S=readCacheFile(n);return S&&await verifyIntegrity(S,t)?S:null}var YI,XI=__esmMin(()=>{ot(),Md(),Dg(),jn(),Jm(),OI(),YI=`v1`,__name$1(cacheRoot$1,`cacheRoot`),__name$1(parseSri$1,`parseSri`),__name$1(pathFor$3,`pathFor`)});function isEnabled(){let t=process.env.GJSIFY_PACKUMENT_CACHE;if(t===void 0)return!0;let n=t.trim();return!(n===`0`||n===`false`||n===``)}function cacheRoot(){return gjsifyCacheRoot(`metadata`,ZI)}function shardFor(t){let n=2166136261;for(let S=0;S<t.length;S++)n^=t.charCodeAt(S),n=Math.imul(n,16777619);return(n>>>0&255).toString(16).padStart(2,`0`)}function encodePart(t){return encodeURIComponent(t).replace(/\*/g,`%2A`)}function packumentCacheKey(t,n,S){return`${S},${encodePart(t)},${encodePart(n)}`}function pathFor$2(t,n,S){if(!isEnabled())return null;let C=packumentCacheKey(t,n,S);return xn(cacheRoot(),shardFor(C),`${C}.json`)}function getCachedPackument(t,n,S=`corgi`){let C=pathFor$2(t,n,S);if(!C)return null;let N=readCacheFile(C);if(!N)return null;try{let t=JSON.parse(N.toString(`utf-8`));return typeof t.etag!=`string`||!t.etag||!t.packument||typeof t.packument!=`object`?null:{etag:t.etag,packument:t.packument}}catch{return null}}function putCachedPackument(t,n,S,C,N=`corgi`){if(!S)return;let F=pathFor$2(t,n,N);F&&atomicWrite(F,JSON.stringify({etag:S,packument:C}))}var ZI,QI=__esmMin(()=>{jn(),OI(),ZI=`v3`,__name$1(pathFor$2,`pathFor`)});function parseNodeMajor(t){return Number.parseInt(String(t).split(`.`,1)[0]??``,10)}function nativeBackendNodeError(t,n){if(!n)return null;let S=parseNodeMajor(t);return!Number.isFinite(S)||S>=24?null:`gjsify install (native backend) requires Node ≥ 24, but this is Node ${t}. 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 t=nativeBackendNodeError(process.versions.node,onRealNode());if(t)throw Error(t)}var $I=__esmMin(()=>{t_()});function normalizePath(t){let n=On===`/`?t:t.split(On).join(`/`);return n.endsWith(`/`)?n.slice(0,-1):n}function findExtraneous(t){let n=new Set(t.expected.map(t=>normalizePath(t.installPath))),S=t.installed.filter(t=>t.bundles&&!t.linked).map(n=>`${normalizePath(Sn(t.prefix,n.dir))}/node_modules/`),C=[];for(let N of t.installed){if(N.linked)continue;let F=normalizePath(Sn(t.prefix,N.dir));F===``||F.startsWith(`..`)||n.has(F)||S.some(t=>F.startsWith(t))||C.push({installPath:F,name:N.name,version:N.version})}C.sort((t,n)=>t.installPath<n.installPath?-1:+(t.installPath>n.installPath));let N=[];for(let t of C){let n=N[N.length-1];n&&t.installPath.startsWith(`${n.installPath}/`)||N.push(t)}return N}function formatExtraneousError(t,n){let S=t.slice(0,20),C=S.map(t=>` ${t.installPath} (${t.name}@${t.version})`);return t.length>S.length&&C.push(` … and ${t.length-S.length} more`),[`install: --immutable, but ${n}/node_modules holds ${t.length} package(s) that gjsify-lock.json does not describe.`,`--immutable installs the lockfile and removes nothing, so each of these would survive the install and be resolved, bundled and type-checked as if it belonged (gjsify#1683: a nested copy of an already-hoisted package → TS2883, one type with two identities).`,...C,"Fix: delete those directories — or the whole node_modules — and re-run. A plain `gjsify install` does NOT clear them: it only ever adds, and its prune pass judges foreign-PLATFORM packages alone (prune-prefix.ts), so an undescribed package survives both. Deleting is currently the only thing that removes one. In CI this usually means a cache entry was restored from a DIFFERENT lockfile."].join(`
907
907
  `)}var eL=__esmMin(()=>{jn()});function dirLinkTarget(t,n,S=tL){return S===`junction`?vn(n):Sn(wn(t),n)}function linkDirSync(t,n){assertAbsolute(n),symlinkSync(dirLinkTarget(t,n),t,nL)}function replicateLinkSync(t,n){let S=readlinkSync(t);if(!dirLinksAreJunctions()){symlinkSync(S,n);return}let C=vn(wn(t),S),N;try{N=statSync(C).isDirectory()}catch{symlinkSync(S,n);return}N?symlinkSync(C,n,`junction`):symlinkSync(S,n,`file`)}function assertAbsolute(t){if(vn(t)!==t)throw TypeError(`linkDir: target must be an absolute path, got ${JSON.stringify(t)}. 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 tL,nL,dirLinksAreJunctions,rL=__esmMin(()=>{Md(),hd(),jn(),tL=process.platform===`win32`?`junction`:`symlink`,nL=tL===`junction`?`junction`:void 0,dirLinksAreJunctions=()=>tL===`junction`});function checkList(t,n){let S=typeof n==`string`?[n]:n;if(S.length===1&&S[0]===`any`)return!0;let C=0,N=!1;for(let n of S){let S=n.charAt(0)===`!`,F=S?n.slice(1):n;if(S){if(C++,t===F)return!1}else N||=t===F}return N||C===S.length}function checkPlatform(t,n){let S=t.os?checkList(n.os,t.os):!0,C=t.cpu?checkList(n.cpu,t.cpu):!0,N=t.libc?checkList(n.libc,t.libc):!0;return t.libc&&!n.libc&&(N=!1),{ok:S&&C&&N,current:{os:n.os,cpu:n.cpu,libc:n.libc},required:{os:t.os,cpu:t.cpu,libc:t.libc}}}function declaresPlatform(t){return!!(t.os||t.cpu||t.libc)}function badPlatformError(t,n){let S=Error(`Unsupported platform for ${t}: wanted ${JSON.stringify(n.required)} (current: ${JSON.stringify(n.current)})`);return S.code=`EBADPLATFORM`,S.pkgid=t,S.current=n.current,S.required=n.required,S}function isMuslSharedObject(t){return t.includes(`libc.musl-`)||t.includes(`ld-musl-`)}function libcFromLddFile(t){let n=t.readTextFile(iL);if(n!==null)return n.includes(`musl`)?`musl`:n.includes(`GNU C Library`)?`glibc`:null}function libcFromReportData(t){return t.glibcVersionRuntime?`glibc`:Array.isArray(t.sharedObjects)&&t.sharedObjects.some(t=>isMuslSharedObject(String(t)))?`musl`:null}function libcFromLoaderScan(t,n=aL){let S=!1;for(let C of n){let n=t.listDir(C);if(n)for(let t of n){if(t.startsWith(`ld-linux`))return`glibc`;t.startsWith(`ld-musl-`)&&(S=!0)}}return S?`musl`:null}function detectLibc(t,n){if(t!==`linux`)return;let S=libcFromLddFile(n);if(S!==void 0)return S??void 0;let C=n.diagnosticReport();return C===null?libcFromLoaderScan(n)??void 0:libcFromReportData(C)??void 0}function defaultLibcProbeHost(){return{readTextFile(t){try{return readFileSync(t,`utf-8`)}catch{return null}},listDir(t){try{return readdirSync(t)}catch{return null}},diagnosticReport(){let t=process.report;if(!t||typeof t.getReport!=`function`)return null;let n=t.excludeNetwork;t.excludeNetwork=!0;try{let n=t.getReport();return{glibcVersionRuntime:n.header?.glibcVersionRuntime,sharedObjects:n.sharedObjects}}finally{t.excludeNetwork=n}}}}function hostLibc(t,n=defaultLibcProbeHost()){return sL||=(oL=detectLibc(t,n),!0),oL}function readPlatformOverrides(t){let pick=n=>{let S=t[n];if(typeof S!=`string`)return;let C=S.trim();return C===``?void 0:C},n={},S=pick(`npm_config_os`),C=pick(`npm_config_cpu`),N=pick(`npm_config_libc`);return S!==void 0&&(n.os=S),C!==void 0&&(n.cpu=C),N!==void 0&&(n.libc=N),n}function readPlatformForce(t){let n=t.npm_config_force;if(typeof n!=`string`)return!1;let S=n.trim().toLowerCase();return S===`true`||S===`1`}function resolveHostPlatform(t={}){let n=readPlatformOverrides(t.env??process.env),S=n.os??t.platform??process.platform;return{os:S,cpu:n.cpu??t.arch??process.arch,libc:n.libc??(S===`linux`?hostLibc(S,t.probe??defaultLibcProbeHost()):void 0)}}function describePlatformTarget(t){return`${t.os}-${t.cpu}${t.libc?`-${t.libc}`:``}`}var iL,aL,oL,sL,cL=__esmMin(()=>{Md(),iL=`/usr/bin/ldd`,aL=[`/lib`,`/lib64`,`/usr/lib`],sL=!1});function isReservedEntry(t){return t.startsWith(`.`)}function readManifest(t){try{let n=JSON.parse(readFileSync(xn(t,`package.json`),`utf8`)),S={os:n.os,cpu:n.cpu,libc:n.libc};return{name:typeof n.name==`string`?n.name:void 0,version:typeof n.version==`string`?n.version:void 0,platform:declaresPlatform(S)?S:void 0,bundles:[n.bundleDependencies,n.bundledDependencies].some(t=>t===!0||Array.isArray(t)&&t.length>0)}}catch{return null}}function collect(t,n){let S;try{S=readdirSync(t,{withFileTypes:!0})}catch{return}for(let C of S){if(isReservedEntry(C.name))continue;let S=xn(t,C.name);if(C.name.startsWith(`@`)){let t;try{t=readdirSync(S,{withFileTypes:!0})}catch{continue}for(let C of t)isReservedEntry(C.name)||addPackage(xn(S,C.name),n);continue}addPackage(S,n)}}function addPackage(t,n){let S=!1;try{S=lstatSync(t).isSymbolicLink()}catch{return}let C=readManifest(t);n.push({name:C?.name??t,version:C?.version??`0.0.0`,dir:t,linked:S,platform:C?.platform,bundles:C?.bundles}),S||collect(xn(t,`node_modules`),n)}function scanPrefix(t){let n=[];return collect(xn(t,`node_modules`),n),n}function planPlatformPrune(t,n){let S=[];for(let C of t){if(C.linked||!C.platform)continue;let t=checkPlatform(C.platform,n);t.ok||S.push({pkg:C,bytes:0,verdict:t})}return S}function dirBytes(t){let n=0,S=[t];for(;S.length>0;){let t=S.pop(),C;try{C=readdirSync(t,{withFileTypes:!0})}catch{continue}for(let N of C){let C=xn(t,N.name);if(N.isDirectory())S.push(C);else if(N.isFile())try{n+=statSync(C).size}catch{}}}return n}function planPrune(t){let n=scanPrefix(t.prefix),S=planPlatformPrune(n,t.target);for(let t of S)t.bytes=dirBytes(t.pkg.dir);return{prefix:t.prefix,target:t.target,scanned:n.length,entries:S,bytes:S.reduce((t,n)=>t+n.bytes,0)}}function executePrune(t,n={}){let S=[],C=[],N=[],F=n.remove??(t=>rmSync(t,{recursive:!0,force:!0,maxRetries:10}));if(!n.dryRun){for(let n of t.entries)try{F(n.pkg.dir),S.push(n)}catch(t){C.push({entry:n,error:t.message})}N.push(...pruneDeadBinLinks(t.prefix))}return{plan:t,removed:S,failed:C,bytes:S.reduce((t,n)=>t+n.bytes,0),binLinks:N}}function pruneDeadBinLinks(t){let n=xn(t,`node_modules`,`.bin`),S=[],C;try{C=readdirSync(n,{withFileTypes:!0})}catch{return S}for(let t of C){let C=xn(n,t.name);try{if(!lstatSync(C).isSymbolicLink()||existsSync(C))continue;unlinkSync(C),S.push(t.name)}catch{}}return S}function humanBytes(t){if(t<1024)return`${t} B`;let n=[`KB`,`MB`,`GB`],S=t/1024,C=0;for(;S>=1024&&C<n.length-1;)S/=1024,C+=1;return`${S.toFixed(1)} ${n[C]}`}function formatPruneReport(t,n){let{plan:S}=t,C=[`${S.prefix} · target ${describePlatformTarget(S.target)} · scanned ${S.scanned} package(s)`];if(S.entries.length===0)return C.push(`nothing to prune — no installed package declares a platform this target cannot use.`),C.join(`
908
908
  `);let N=n.verbose?S.entries:S.entries.slice(0,lL);for(let t of N){let n=JSON.stringify(t.verdict.required);C.push(` ${t.pkg.name}@${t.pkg.version} ${humanBytes(t.bytes)} requires ${n}`)}N.length<S.entries.length&&C.push(` … and ${S.entries.length-N.length} more (--verbose to list them)`),C.push(n.dryRun?`would free ${humanBytes(S.bytes)} across ${S.entries.length} package(s) (apparent size)`:`freed ${humanBytes(t.bytes)} across ${t.removed.length} package(s) (apparent size)`),t.binLinks.length>0&&C.push(`removed ${t.binLinks.length} dangling .bin link(s): ${t.binLinks.join(`, `)}`);for(let n of t.failed)C.push(`FAILED ${n.entry.pkg.name}: ${n.error}`);return C.join(`
909
909
  `)}function automaticPruneRefusal(t,n){return Object.keys(readPlatformOverrides(t)).length>0?`the platform target was overridden on the command line`:n?`--immutable`:null}function pruneAfterInstall(t,n,S={}){try{if(automaticPruneRefusal(S.env??process.env,S.immutable??!1))return;let C=planPrune({prefix:t,target:n});if(C.entries.length===0)return;let N=executePrune(C);if(N.removed.length===0)return;let F=S.hint?` (${S.hint} to review)`:``;ge.log(`gjsify: pruned ${N.removed.length} package(s) this host cannot use, freeing ${humanBytes(N.bytes)}${F}`)}catch(t){process.env.GJSIFY_DEBUG&&ge.error(`gjsify: prune skipped — ${t.message}`)}}var lL,uL=__esmMin(()=>{_e(),Md(),jn(),cL(),lL=10});function devLinkPath(t){return xn(t,dL)}function readDevLinkOverride(t){let n=devLinkPath(t);if(!existsSync(n))return null;let S;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch(t){throw Error(`gjsify link: ${n} is not valid JSON (${t instanceof Error?t.message:String(t)}). Fix it or run \`gjsify unlink\`.`)}if(!S||typeof S!=`object`)throw Error(`gjsify link: ${n} must contain a JSON object.`);let C=S;if(C.version!==1)throw Error(`gjsify link: ${n} declares version ${JSON.stringify(C.version)}; this CLI understands version 1 only.`);if(typeof C.checkout!=`string`||C.checkout.trim()===``)throw Error(`gjsify link: ${n} has no "checkout" path.`);return{version:1,checkout:bn(C.checkout)?C.checkout:vn(t,C.checkout),packages:Array.isArray(C.packages)?C.packages.filter(t=>typeof t==`string`):[]}}function writeDevLinkOverride(t,n){let S=devLinkPath(t);return writeFileSync(S,JSON.stringify(n,null,2)+`
@@ -916,13 +916,13 @@ Add @gjsify/node-gi as a dependency to run the storybook on Node, e.g.:
916
916
  `)}function nonEmpty(t){return t&&Object.keys(t).length>0?t:void 0}function buildPreferredVersions(t){let n=new Map;for(let[S,C]of Object.entries(t.packages)){let t=nameFromInstallPath(S),N=n.get(t);N||(N=new Set,n.set(t,N)),N.add(C.version)}return n}function preferredVersionFor(t,n){if(!t||t.size===0)return;let S;for(let C of t)satisfiesRange(C,n)&&(S===void 0||new SemVer(C).compare(new SemVer(S))>0)&&(S=C);return S}function lockfileToNodes(t){return Object.entries(t.packages).map(([t,n])=>{let S={os:n.os,cpu:n.cpu,libc:n.libc};return{name:nameFromInstallPath(t),version:n.version,tarballUrl:n.resolved,integrity:n.integrity,installPath:t,dependencies:n.dependencies??{},optionalDependencies:n.optionalDependencies??{},peerDependencies:n.peerDependencies,peerDependenciesMeta:n.peerDependenciesMeta,bin:n.bin,platform:declaresPlatform(S)?S:void 0,optional:n.optional===!0}})}function nameFromInstallPath(t){let n=t.lastIndexOf(`/node_modules/`);return n<0?t.replace(/^node_modules\//,``):t.slice(n+14)}function lockfileMatchesRequest(t,n){if(t.requested.length!==n.length)return!1;let S=[...t.requested].sort(),C=[...n].sort();return S.every((t,n)=>t===C[n])}function describeLockfileDrift(t,n){let S=new Set(t.requested),C=new Set(n),N=[],F=[];for(let t of C)S.has(t)||N.push(t);for(let t of S)C.has(t)||F.push(t);if(N.length===0&&F.length===0)return null;let I=[];return N.length>0&&I.push(` + ${N.sort().join(`
917
917
  + `)}`),F.length>0&&I.push(` - ${F.sort().join(`
918
918
  - `)}`),I.join(`
919
- `)}function parseSpec$1(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw Error(`Invalid spec (scoped name without slash): ${t}`);let S=t.indexOf(`@`,n);return S<0?{name:t,range:`latest`}:{name:t.slice(0,S),range:t.slice(S+1)||`latest`}}let n=t.indexOf(`@`);return n<0?{name:t,range:`latest`}:{name:t.slice(0,n),range:t.slice(n+1)||`latest`}}function pickVersion(t,n,S){if(S&&t.versions[S]&&satisfiesRange(S,n))return S;if(t[`dist-tags`][n])return t[`dist-tags`][n];let C;try{C=new wP(n)}catch{throw Error(`Invalid version range for ${t.name}: ${n}`)}return maxSatisfying(Object.keys(t.versions).filter(t=>{try{return new SemVer(t),!0}catch{return!1}}),C)}async function downloadAndExtractAll(t,n,S,C,N,F){let I=[...t].sort((t,n)=>depth$1(t.installPath)-depth$1(n.installPath)||(t.installPath<n.installPath?-1:1)),H=[],W=Math.max(1,Math.min(hL,I.length));F?.beginPhase(`download`,I.length);let q=0,Y=0,tickProgress=(t,n)=>{q++,n&&Y++,F?.update({phase:`download`,current:q,total:I.length,name:`${t.name}@${t.version}`})},X=0,Z=I.findIndex(t=>depth$1(t.installPath)>1),te=Z<0?I.length:Z;for(;X<te;){if(N?.aborted)throw abortError(N);let t=I[X++];if(!t)break;tickProgress(t,await extractOne(t,n,S,C,N))}for(let t=0;t<W;t++)H.push((async()=>{for(;;){if(N?.aborted)throw abortError(N);let t=X++;if(t>=I.length)return;let F=I[t];if(!F)return;let H=await extractOne(F,n,S,C,N);tickProgress(F,H)}})());await Promise.all(H),F?.endPhase(`download`),Y>0&&C(`install: %d/%d package(s) already up to date — extracted %d`,Y,I.length,I.length-Y)}function isAlreadyExtracted(t,n){let S=xn(t,`package.json`),C;try{C=readFileSync(S,`utf-8`)}catch{return!1}try{let t=JSON.parse(C);return!(t.version!==n.version||typeof t.name==`string`&&t.name!==n.name)}catch{return!1}}async function extractOne(t,n,S,C,N){let F=xn(n,t.installPath);if(assertNodeModulesDest(F,t,n),process.env.GJSIFY_INSTALL_FORCE_EXTRACT!==`1`&&isAlreadyExtracted(F,t))return C(`up-to-date: %s@%s (already extracted at %s)`,t.name,t.version,t.installPath),!0;let I=await getCachedTarball(t.integrity);return I?C(`cache-hit: %s@%s ← %s`,t.name,t.version,t.integrity):(I=await getForeignCachedTarball(t.integrity))?(C(`npm-cache-hit: %s@%s ← %s`,t.name,t.version,t.integrity),putCachedTarball(t.integrity,I)):(C(`fetch: %s@%s ← %s (→ %s)`,t.name,t.version,t.tarballUrl,t.installPath),I=await fetchTarball(t.tarballUrl,{npmrc:S,signal:N,integrity:t.integrity,onRetry:({attempt:n,error:S,delayMs:N})=>{C(`tarball %s@%s: retry %d after %dms (%s)`,t.name,t.version,n,N,errMsg(S))}}),putCachedTarball(t.integrity,I)),rmWithRetry(F),mkdirSync(F,{recursive:!0}),await extractWithStallGuard(I,F,t,N),!1}async function extractWithStallGuard(t,n,S,C){if(yL===0&&!C){await extractTarball(t,n);return}let N,onAbort;try{await new Promise((F,I)=>{if(process.env.GJSIFY_TEST_HANG_EXTRACT!==`1`&&extractTarball(t,n).then(()=>F(),I),yL>0&&(N=setTimeout(()=>{I(Error(`gjsify install: extract of ${S.name}@${S.version} stalled for ${Math.round(yL/1e3)}s (${S.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).`))},yL),N.unref?.()),C){if(C.aborted){I(abortError(C));return}onAbort=()=>I(abortError(C)),C.addEventListener(`abort`,onAbort,{once:!0})}})}finally{N&&clearTimeout(N),C&&onAbort&&C.removeEventListener(`abort`,onAbort)}}function abortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}function assertNodeModulesDest(t,n,S){if(!t.split(On).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${n.name}@${n.version} into ${t} — 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(t)}catch{return}if(!C.split(On).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${n.name}@${n.version} — ${t} 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.${devLinkRemedy(S,t)}`)}function devLinkRemedy(t,n){let S=devLinkRoot(t),C=devLinkPath(S);return`\n If a \`gjsify link\` development link put it there${existsSync(C)?` — ${C} is present`:``}: run \`gjsify unlink\` in ${S} to remove the links and restore the registry copies, or \`gjsify link <checkout> --packages …\` to re-select. If no override is left, delete ${n} by hand and re-run.`}function depth$1(t){return t.split(`/node_modules/`).length}function readShebang$1(t){let n;try{n=readFileSync(t,`utf-8`)}catch{return null}return parseShebang(n.trimStart().split(/\r*\n/,1)[0]??``)}function writeBinEntry(t){let{binDir:n,binName:S,targetAbs:C,gjs:N,nodeFallbackAbs:F}=t,I=t.platform??process.platform,H=xn(n,S);if(N){let t=isGjsBundlePath(C);for(let t of[H,`${H}.cmd`,`${H}.ps1`])rmWithRetry(t);writeFileSync(H,buildShLauncher(C,{envPreamble:N.envPreamble,isGjsBundle:t,nodeFallbackAbs:F}));try{chmodSync(H,493)}catch{}if(I===`win32`&&t){let t=N.prebuildDirs.join(`;`),n=buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:C,prependEnv:N.prebuildDirs.length>0?{GI_TYPELIB_PATH:t,PATH:t}:{},fallback:F===void 0?void 0:{interpreter:`node`,target:F}});writeFileSync(`${H}.cmd`,n.cmd),writeFileSync(`${H}.ps1`,n.ps1)}return}if(I===`win32`){let{sh:t,cmd:S,ps1:N}=buildCmdShim(Sn(n,C).split(`\\`).join(`/`),readShebang$1(C));for(let[n,C]of[[H,t],[`${H}.cmd`,S],[`${H}.ps1`,N]]){rmWithRetry(n),writeFileSync(n,C);try{chmodSync(n,493)}catch{}}return}rmWithRetry(H);let W=Sn(n,C);try{symlinkSync(W,H)}catch{copyFileSync(C,H),chmodSync(H,493)}}async function linkBins(t,n,S){let C=xn(n,`node_modules`,`.bin`),N=0,F,gjsEnvForPrefix=()=>{if(F===void 0){let t=detectNativePackages(n).map(t=>t.prebuildsDir);F={envPreamble:buildNativeEnvPreamble(n,t),prebuildDirs:t}}return F};for(let S of t){if(depth$1(S.installPath)!==1)continue;let t=xn(n,S.installPath),F=readInstalledManifest(t)??(S.bin===void 0?null:{bin:S.bin});if(F===null)continue;let I=pickBinMap(S.name,F);if(!(I===null||I.map.size===0)){mkdirSync(C,{recursive:!0});for(let[n,S]of I.map){let F=xn(t,S);if(!existsSync(F))continue;try{chmodSync(F,493)}catch{}let H=I.nodeFallback?.get(n),W=H===void 0?void 0:xn(t,H);writeBinEntry({binDir:C,binName:n,targetAbs:F,gjs:I.isGjsBin?gjsEnvForPrefix():void 0,nodeFallbackAbs:W!==void 0&&existsSync(W)?W:void 0}),N++}}}N>0&&S(`bin: linked %d entry(ies) under .bin/`,N)}function readInstalledManifest(t){try{let n=readFileSync(xn(t,`package.json`),`utf-8`);return JSON.parse(n)}catch{return null}}function rmWithRetry(t){rmSync(t,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}async function loadNpmrc$1(t){let n=homedir(),S={registry:t.registry??Vm,scopes:{},authTokens:{},basicAuth:{}};for(let C of[xn(n,`.npmrc`),xn(t.prefix,`.npmrc`)])if(existsSync(C))try{let t=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...t,scopes:{...S.scopes,...t.scopes}}}catch(t){ge.warn(`gjsify install: ignoring malformed ${C}: ${t.message}`)}let C=process.env.npm_config_registry;return C&&(S.registry=C),t.registry&&(S.registry=t.registry),S}function makeLogger(t){return t?(t,...n)=>{let S=t.replace(/%s|%d/g,()=>String(n.shift()));process.stderr.write(`gjsify install: ${S}\n`)}:()=>{}}var hL,gL,_L,vL,yL,bL=__esmMin(()=>{_e(),Md(),jn(),Dg(),TP(),Jm(),II(),LI(),JI(),XI(),QI(),$I(),uI(),QP(),eL(),pL(),uL(),cL(),hL=Number(process.env.GJSIFY_INSTALL_CONCURRENCY??`16`)||16,gL=`gjsify-lock.json`,_L=4,vL=new Set([2,3,_L]),__name$1(parseSpec$1,`parseSpec`),yL=(()=>{let t=process.env.GJSIFY_EXTRACT_STALL_MS;if(t===void 0)return 12e4;let n=Number(t);return Number.isFinite(n)&&n>=0?n:12e4})(),__name$1(depth$1,`depth`),__name$1(readShebang$1,`readShebang`),__name$1(loadNpmrc$1,`loadNpmrc`)}),xL=__exportAll$5({installPackages:()=>installPackages,makeProgressReporter:()=>makeProgressReporter});async function installPackages(t){if(SL===`npm`)return await installViaNpm(t),{installed:[]};let{installPackagesNative:n}=await Promise.resolve().then(()=>(bL(),mL));return{installed:await n(t)}}async function installViaNpm({prefix:t,specs:n,verbose:S,registry:C}){if(n.length===0)throw Error(`installPackages: empty specs list`);writeFileSync(xn(t,`package.json`),JSON.stringify({name:`gjsify-dlx-cache`,version:`0.0.0`,private:!0},null,2)),C&&writeFileSync(xn(t,`.npmrc`),`registry=${C}\n`);let{code:N}=await spawnToCompletion(`npm`,[`install`,`--no-package-lock`,`--no-audit`,`--no-fund`,`--prefix`,t,...S?[`--loglevel`,`verbose`]:[`--loglevel`,`warn`],...n],{completion:`return`,notFound:t=>Error(`npm not found on PATH — install Node.js, or unset GJSIFY_INSTALL_BACKEND to use the default native backend (${t.message})`)});if(N!==0)throw Error(`npm install exited with code ${N}`)}var SL,CL=__esmMin(()=>{Md(),jn(),j_(),jI(),SL=process.env.GJSIFY_INSTALL_BACKEND??`native`});function defaultGlobalLayout(){let t=process.env.GJSIFY_GLOBAL_PREFIX,n=process.env.GJSIFY_GLOBAL_BIN_DIR,S=homedir(),C=process.env.XDG_DATA_HOME??xn(S,`.local`,`share`);return{prefix:t??xn(C,`gjsify`,`global`),binDir:n??xn(S,`.local`,`bin`)}}function hasBundlerEngineInstalled(t){let n=new Set(detectNativePackages(t).map(t=>t.name));if(n.has(`@gjsify/rolldown-native`))return!0;let S=detectHostLibc(process.platform);return hostPlatformTokens(process.platform,process.arch,S).some(t=>n.has(platformPackageName(TL,t)))}async function installGjsEnginePackages(t,n,S={}){let C=S.verbose??!1,N=S.installFn??(async n=>{let{installPackages:S}=await Promise.resolve().then(()=>(CL(),xL));await S({prefix:t,specs:[n],verbose:C})});for(let t of wL){let S=n?`${t}@${n}`:t;try{await N(S)}catch(S){let N=S instanceof Error?S.message:String(S);t===`@gjsify/rolldown-native`?ge.warn(`\nWarning: could not install the GJS bundler engine ${t}@${n} — ${N}\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}).`):C&&ge.warn(`gjsify install: optional GJS engine ${t}@${n} not installed — ${N}`)}}}function linkGlobalBins(t,n){mkdirSync(n.binDir,{recursive:!0});let S=[],C=detectNativePackages(n.prefix).map(t=>t.prebuildsDir),N=buildNativeEnvPreamble(n.prefix,C);for(let F of t){let t=xn(n.prefix,`node_modules`,F),I=xn(t,`package.json`);if(!existsSync(I))continue;let H=pickBinMap(F,readJson(I));if(!(H===null||H.map.size===0))for(let[F,I]of H.map){let W=xn(t,I);if(!existsSync(W))continue;try{chmodSync(W,493)}catch{}let q=xn(n.binDir,F);for(let t of[q,`${q}.cmd`,`${q}.ps1`])rmSync(t,{force:!0,maxRetries:10,retryDelay:100});let Y=isGjsBundlePath(W),X=H.nodeFallback?.get(F),Z=X===void 0?void 0:xn(t,X),te=Z!==void 0&&existsSync(Z)?Z:void 0;if(writeFileSync(q,buildShLauncher(W,{envPreamble:N,isGjsBundle:Y,nodeFallbackAbs:te})),chmodSync(q,493),process.platform===`win32`){let t=C.join(`;`),n=Y&&C.length>0?{GI_TYPELIB_PATH:t,PATH:t}:{},S=Y?null:readShebangOf(W),N=buildLauncherShims(Y?{interpreter:`gjs`,interpreterArgs:[`-m`],target:W,prependEnv:n,fallback:te===void 0?void 0:{interpreter:`node`,target:te}}:{interpreter:S?.prog||`node`,interpreterArgs:S?.args.trim()?S.args.trim().split(/\s+/):[],target:W});writeFileSync(`${q}.cmd`,N.cmd),writeFileSync(`${q}.ps1`,N.ps1)}S.push({name:F,target:W,link:q})}}return S}function readShebangOf(t){try{return parseShebang(readFileSync(t,`utf-8`).trimStart().split(/\r*\n/,1)[0]??``)}catch{return null}}function readJson(t){return JSON.parse(readFileSync(t,`utf-8`))}function globalLayoutIsDefault(t=process.env){return!t.GJSIFY_GLOBAL_PREFIX&&!t.GJSIFY_GLOBAL_BIN_DIR}function pathFor$1(t){return t===`win32`?fn:un}function searchPathEntries(t,n){let S=pathFor$1(n),C=n===`win32`?`;`:`:`;return t.split(C).filter(Boolean).map(t=>S.resolve(t))}function binDirOnPath(t){let n=pathFor$1(process.platform).resolve(t);return searchPathEntries(process.env.PATH??``,process.platform).includes(n)}function resolveBinOnPath(t,n={}){let S=n.platform??process.platform,C=n.pathValue??process.env.PATH??``,N=n.exists??existsSync,F=S===`win32`?[...(n.pathExt??process.env.PATHEXT??EL).split(`;`).filter(Boolean).map(t=>t.startsWith(`.`)?t:`.${t}`),``]:[``],I=pathFor$1(S);for(let n of searchPathEntries(C,S))for(let S of F){let C=I.join(n,`${t}${S}`);if(N(C))return C}return null}function specToPackageName(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)return t;let S=t.indexOf(`@`,n);return S<0?t:t.slice(0,S)}let n=t.indexOf(`@`);return n<0?t:t.slice(0,n)}var wL,TL,EL,DL=__esmMin(()=>{_e(),Md(),Dg(),jn(),QP(),uI(),wL=[`@gjsify/rolldown-native`,`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`],TL=`@gjsify/rolldown-native`,__name$1(pathFor$1,`pathFor`),EL=`.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC`});function usingSelfShim(){return kL}function pathWithoutSelfShim(t=process.env.PATH??``,n=process.env.GJSIFY_SHIM_DIR,S=kn){return n?t.split(S).filter(t=>t!==n).join(S):t}function needsSelfShim(t){if(t.gjs)return!0;let n=Sn(t.workspaceRoot,t.selfEntry);return n===``||n.startsWith(`..`)||bn(n)}function ensureGjsifyShimOnPath(){if(OL)return;OL=!0;let t=process.env.GJSIFY_SHIM_DIR;if(t&&existsSync(xn(t,`gjsify`))){kL=!0,(process.env.PATH??``).split(kn).includes(t)||(process.env.PATH=t+kn+(process.env.PATH??``));return}let n=isGjs(),S=fileURLToPath(n?import.meta.url:new URL(`../index.js`,import.meta.url));if(!needsSelfShim({gjs:n,selfEntry:S,workspaceRoot:findWorkspaceRoot(process.cwd())??process.cwd()}))return;let C=mkdtempSync(xn(tmpdir(),`gjsify-shim-`)),N=xn(C,`gjsify`),F=n?process.env.GJS_CONSOLE||`gjs`:`node`,I=n?selfShimPreamble(S):``;if(writeFileSync(N,n?buildShLauncher(S,{isGjsBundle:!0,envPreamble:I,gjs:F}):`#!/bin/sh\nexec "${F}" "${S}" "$@"\n`,{mode:493}),chmodSync(N,493),!n&&process.platform===`win32`){let{cmd:t,ps1:n}=buildLauncherShims({interpreter:F,interpreterArgs:[],target:S});writeFileSync(`${N}.cmd`,t),writeFileSync(`${N}.ps1`,n)}kL=!0,process.env.GJSIFY_SHIM_DIR=C,process.env.PATH=C+kn+(process.env.PATH??``),writeNodeShim(C,n,S,I)}function selfShimScanRoot(t){let n=t.search(/[\\/]node_modules[\\/]/);return n>0?t.slice(0,n):findWorkspaceRoot(wn(t))??wn(t)}function selfShimPreamble(t){let n=[];try{n=detectNativePackages(wn(t)).map(t=>t.prebuildsDir)}catch{}return buildNativeEnvPreamble(selfShimScanRoot(t),n)}function dyldCarryPreamble(t,n){return t===`darwin`?Object.keys(n).filter(t=>/^DYLD_[A-Z_]+$/.test(t)&&n[t]).sort().map(t=>`${t}=${shQuoteArg(n[t])}\nexport ${t}\n`).join(``):``}function nodeShimDir(){let t=process.env.GJSIFY_SHIM_DIR;if(!t)return null;let n=xn(t,AL);return existsSync(xn(n,`node`))?n:null}function writeNodeShim(t,n,S,C){if(!n)return;let N=xn(t,AL);if(existsSync(xn(N,`node`))||resolveBinOnPath(`node`))return;let F=process.env.GJS_CONSOLE||`gjs`;mkdirSync(N,{recursive:!0});let I=xn(N,`node`);writeFileSync(I,`#!/bin/sh
919
+ `)}function parseSpec$1(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw Error(`Invalid spec (scoped name without slash): ${t}`);let S=t.indexOf(`@`,n);return S<0?{name:t,range:`latest`}:{name:t.slice(0,S),range:t.slice(S+1)||`latest`}}let n=t.indexOf(`@`);return n<0?{name:t,range:`latest`}:{name:t.slice(0,n),range:t.slice(n+1)||`latest`}}function pickVersion(t,n,S){if(S&&t.versions[S]&&satisfiesRange(S,n))return S;if(t[`dist-tags`][n])return t[`dist-tags`][n];let C;try{C=new wP(n)}catch{throw Error(`Invalid version range for ${t.name}: ${n}`)}return maxSatisfying(Object.keys(t.versions).filter(t=>{try{return new SemVer(t),!0}catch{return!1}}),C)}async function downloadAndExtractAll(t,n,S,C,N,F){let I=[...t].sort((t,n)=>depth$1(t.installPath)-depth$1(n.installPath)||(t.installPath<n.installPath?-1:1)),H=[],W=Math.max(1,Math.min(hL,I.length));F?.beginPhase(`download`,I.length);let q=0,Y=0,tickProgress=(t,n)=>{q++,n&&Y++,F?.update({phase:`download`,current:q,total:I.length,name:`${t.name}@${t.version}`})},X=0,Z=I.findIndex(t=>depth$1(t.installPath)>1),te=Z<0?I.length:Z;for(;X<te;){if(N?.aborted)throw abortError(N);let t=I[X++];if(!t)break;tickProgress(t,await extractOne(t,n,S,C,N))}for(let t=0;t<W;t++)H.push((async()=>{for(;;){if(N?.aborted)throw abortError(N);let t=X++;if(t>=I.length)return;let F=I[t];if(!F)return;let H=await extractOne(F,n,S,C,N);tickProgress(F,H)}})());await Promise.all(H),F?.endPhase(`download`),Y>0&&C(`install: %d/%d package(s) already up to date — extracted %d`,Y,I.length,I.length-Y)}function isAlreadyExtracted(t,n){let S=xn(t,`package.json`),C;try{C=readFileSync(S,`utf-8`)}catch{return!1}try{let t=JSON.parse(C);return!(t.version!==n.version||typeof t.name==`string`&&t.name!==n.name)}catch{return!1}}async function extractOne(t,n,S,C,N){let F=xn(n,t.installPath);if(assertNodeModulesDest(F,t,n),process.env.GJSIFY_INSTALL_FORCE_EXTRACT!==`1`&&isAlreadyExtracted(F,t))return C(`up-to-date: %s@%s (already extracted at %s)`,t.name,t.version,t.installPath),!0;let I=await getCachedTarball(t.integrity);return I?C(`cache-hit: %s@%s ← %s`,t.name,t.version,t.integrity):(I=await getForeignCachedTarball(t.integrity))?(C(`npm-cache-hit: %s@%s ← %s`,t.name,t.version,t.integrity),putCachedTarball(t.integrity,I)):(C(`fetch: %s@%s ← %s (→ %s)`,t.name,t.version,t.tarballUrl,t.installPath),I=await fetchTarball(t.tarballUrl,{npmrc:S,signal:N,integrity:t.integrity,onRetry:({attempt:n,error:S,delayMs:N})=>{C(`tarball %s@%s: retry %d after %dms (%s)`,t.name,t.version,n,N,errMsg(S))}}),putCachedTarball(t.integrity,I)),rmWithRetry(F),mkdirSync(F,{recursive:!0}),await extractWithStallGuard(I,F,t,N),!1}async function extractWithStallGuard(t,n,S,C){if(yL===0&&!C){await extractTarball(t,n);return}let N,onAbort;try{await new Promise((F,I)=>{if(process.env.GJSIFY_TEST_HANG_EXTRACT!==`1`&&extractTarball(t,n).then(()=>F(),I),yL>0&&(N=setTimeout(()=>{I(Error(`gjsify install: extract of ${S.name}@${S.version} stalled for ${Math.round(yL/1e3)}s (${S.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).`))},yL),N.unref?.()),C){if(C.aborted){I(abortError(C));return}onAbort=()=>I(abortError(C)),C.addEventListener(`abort`,onAbort,{once:!0})}})}finally{N&&clearTimeout(N),C&&onAbort&&C.removeEventListener(`abort`,onAbort)}}function abortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}function assertNodeModulesDest(t,n,S){if(!t.split(On).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${n.name}@${n.version} into ${t} — 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(t)}catch{return}if(!C.split(On).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${n.name}@${n.version} — ${t} 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.${devLinkRemedy(S,t)}`)}function devLinkRemedy(t,n){let S=devLinkRoot(t),C=devLinkPath(S);return`\n If a \`gjsify link\` development link put it there${existsSync(C)?` — ${C} is present`:``}: run \`gjsify unlink\` in ${S} to remove the links and restore the registry copies, or \`gjsify link <checkout> --packages …\` to re-select. If no override is left, delete ${n} by hand and re-run.`}function depth$1(t){return t.split(`/node_modules/`).length}function readShebang$1(t){let n;try{n=readFileSync(t,`utf-8`)}catch{return null}return parseShebang(n.trimStart().split(/\r*\n/,1)[0]??``)}function writeBinEntry(t){let{binDir:n,binName:S,targetAbs:C,gjs:N,nodeFallbackAbs:F}=t,I=t.platform??process.platform,H=xn(n,S);if(N){let t=isGjsBundlePath(C);for(let t of[H,`${H}.cmd`,`${H}.ps1`])rmWithRetry(t);writeFileSync(H,buildShLauncher(C,{envPreamble:N.envPreamble,isGjsBundle:t,nodeFallbackAbs:F}));try{chmodSync(H,493)}catch{}if(I===`win32`&&t){let t=N.prebuildDirs.join(`;`),n=buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:C,prependEnv:N.prebuildDirs.length>0?{GI_TYPELIB_PATH:t,PATH:t}:{},fallback:F===void 0?void 0:{interpreter:`node`,target:F}});writeFileSync(`${H}.cmd`,n.cmd),writeFileSync(`${H}.ps1`,n.ps1)}return}if(I===`win32`){let{sh:t,cmd:S,ps1:N}=buildCmdShim(Sn(n,C).split(`\\`).join(`/`),readShebang$1(C));for(let[n,C]of[[H,t],[`${H}.cmd`,S],[`${H}.ps1`,N]]){rmWithRetry(n),writeFileSync(n,C);try{chmodSync(n,493)}catch{}}return}rmWithRetry(H);let W=Sn(n,C);try{symlinkSync(W,H)}catch{copyFileSync(C,H),chmodSync(H,493)}}async function linkBins(t,n,S){let C=xn(n,`node_modules`,`.bin`),N=0,F,gjsEnvForPrefix=()=>{if(F===void 0){let t=detectNativePackages(n).map(t=>t.prebuildsDir);F={envPreamble:buildNativeEnvPreamble(n,t),prebuildDirs:t}}return F};for(let S of t){if(depth$1(S.installPath)!==1)continue;let t=xn(n,S.installPath),F=readInstalledManifest(t)??(S.bin===void 0?null:{bin:S.bin});if(F===null)continue;let I=pickBinMap(S.name,F);if(!(I===null||I.map.size===0)){mkdirSync(C,{recursive:!0});for(let[n,S]of I.map){let F=xn(t,S);if(!existsSync(F))continue;try{chmodSync(F,493)}catch{}let H=I.nodeFallback?.get(n),W=H===void 0?void 0:xn(t,H);writeBinEntry({binDir:C,binName:n,targetAbs:F,gjs:I.isGjsBin?gjsEnvForPrefix():void 0,nodeFallbackAbs:W!==void 0&&existsSync(W)?W:void 0}),N++}}}N>0&&S(`bin: linked %d entry(ies) under .bin/`,N)}function readInstalledManifest(t){try{let n=readFileSync(xn(t,`package.json`),`utf-8`);return JSON.parse(n)}catch{return null}}function rmWithRetry(t){rmSync(t,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}async function loadNpmrc$1(t){let n=homedir(),S={registry:t.registry??Vm,scopes:{},authTokens:{},basicAuth:{}};for(let C of[xn(n,`.npmrc`),xn(t.prefix,`.npmrc`)])if(existsSync(C))try{let t=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...t,scopes:{...S.scopes,...t.scopes}}}catch(t){ge.warn(`gjsify install: ignoring malformed ${C}: ${t.message}`)}let C=process.env.npm_config_registry;return C&&(S.registry=C),t.registry&&(S.registry=t.registry),S}function makeLogger(t){return t?(t,...n)=>{let S=t.replace(/%s|%d/g,()=>String(n.shift()));process.stderr.write(`gjsify install: ${S}\n`)}:()=>{}}var hL,gL,_L,vL,yL,bL=__esmMin(()=>{_e(),Md(),jn(),Dg(),TP(),Jm(),LI(),OI(),JI(),XI(),QI(),$I(),uI(),QP(),eL(),pL(),uL(),cL(),hL=Number(process.env.GJSIFY_INSTALL_CONCURRENCY??`16`)||16,gL=`gjsify-lock.json`,_L=4,vL=new Set([2,3,_L]),__name$1(parseSpec$1,`parseSpec`),yL=(()=>{let t=process.env.GJSIFY_EXTRACT_STALL_MS;if(t===void 0)return 12e4;let n=Number(t);return Number.isFinite(n)&&n>=0?n:12e4})(),__name$1(depth$1,`depth`),__name$1(readShebang$1,`readShebang`),__name$1(loadNpmrc$1,`loadNpmrc`)}),xL=__exportAll$5({installPackages:()=>installPackages,makeProgressReporter:()=>makeProgressReporter});async function installPackages(t){if(SL===`npm`)return await installViaNpm(t),{installed:[]};let{installPackagesNative:n}=await Promise.resolve().then(()=>(bL(),mL));return{installed:await n(t)}}async function installViaNpm({prefix:t,specs:n,verbose:S,registry:C}){if(n.length===0)throw Error(`installPackages: empty specs list`);writeFileSync(xn(t,`package.json`),JSON.stringify({name:`gjsify-dlx-cache`,version:`0.0.0`,private:!0},null,2)),C&&writeFileSync(xn(t,`.npmrc`),`registry=${C}\n`);let{code:N}=await spawnToCompletion(`npm`,[`install`,`--no-package-lock`,`--no-audit`,`--no-fund`,`--prefix`,t,...S?[`--loglevel`,`verbose`]:[`--loglevel`,`warn`],...n],{completion:`return`,notFound:t=>Error(`npm not found on PATH — install Node.js, or unset GJSIFY_INSTALL_BACKEND to use the default native backend (${t.message})`)});if(N!==0)throw Error(`npm install exited with code ${N}`)}var SL,CL=__esmMin(()=>{Md(),jn(),j_(),MI(),SL=process.env.GJSIFY_INSTALL_BACKEND??`native`});function defaultGlobalLayout(){let t=process.env.GJSIFY_GLOBAL_PREFIX,n=process.env.GJSIFY_GLOBAL_BIN_DIR,S=homedir(),C=process.env.XDG_DATA_HOME??xn(S,`.local`,`share`);return{prefix:t??xn(C,`gjsify`,`global`),binDir:n??xn(S,`.local`,`bin`)}}function hasBundlerEngineInstalled(t){let n=new Set(detectNativePackages(t).map(t=>t.name));if(n.has(`@gjsify/rolldown-native`))return!0;let S=detectHostLibc(process.platform);return hostPlatformTokens(process.platform,process.arch,S).some(t=>n.has(platformPackageName(TL,t)))}async function installGjsEnginePackages(t,n,S={}){let C=S.verbose??!1,N=S.installFn??(async n=>{let{installPackages:S}=await Promise.resolve().then(()=>(CL(),xL));await S({prefix:t,specs:[n],verbose:C})});for(let t of wL){let S=n?`${t}@${n}`:t;try{await N(S)}catch(S){let N=S instanceof Error?S.message:String(S);t===`@gjsify/rolldown-native`?ge.warn(`\nWarning: could not install the GJS bundler engine ${t}@${n} — ${N}\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}).`):C&&ge.warn(`gjsify install: optional GJS engine ${t}@${n} not installed — ${N}`)}}}function linkGlobalBins(t,n){mkdirSync(n.binDir,{recursive:!0});let S=[],C=detectNativePackages(n.prefix).map(t=>t.prebuildsDir),N=buildNativeEnvPreamble(n.prefix,C);for(let F of t){let t=xn(n.prefix,`node_modules`,F),I=xn(t,`package.json`);if(!existsSync(I))continue;let H=pickBinMap(F,readJson(I));if(!(H===null||H.map.size===0))for(let[F,I]of H.map){let W=xn(t,I);if(!existsSync(W))continue;try{chmodSync(W,493)}catch{}let q=xn(n.binDir,F);for(let t of[q,`${q}.cmd`,`${q}.ps1`])rmSync(t,{force:!0,maxRetries:10,retryDelay:100});let Y=isGjsBundlePath(W),X=H.nodeFallback?.get(F),Z=X===void 0?void 0:xn(t,X),te=Z!==void 0&&existsSync(Z)?Z:void 0;if(writeFileSync(q,buildShLauncher(W,{envPreamble:N,isGjsBundle:Y,nodeFallbackAbs:te})),chmodSync(q,493),process.platform===`win32`){let t=C.join(`;`),n=Y&&C.length>0?{GI_TYPELIB_PATH:t,PATH:t}:{},S=Y?null:readShebangOf(W),N=buildLauncherShims(Y?{interpreter:`gjs`,interpreterArgs:[`-m`],target:W,prependEnv:n,fallback:te===void 0?void 0:{interpreter:`node`,target:te}}:{interpreter:S?.prog||`node`,interpreterArgs:S?.args.trim()?S.args.trim().split(/\s+/):[],target:W});writeFileSync(`${q}.cmd`,N.cmd),writeFileSync(`${q}.ps1`,N.ps1)}S.push({name:F,target:W,link:q})}}return S}function readShebangOf(t){try{return parseShebang(readFileSync(t,`utf-8`).trimStart().split(/\r*\n/,1)[0]??``)}catch{return null}}function readJson(t){return JSON.parse(readFileSync(t,`utf-8`))}function globalLayoutIsDefault(t=process.env){return!t.GJSIFY_GLOBAL_PREFIX&&!t.GJSIFY_GLOBAL_BIN_DIR}function pathFor$1(t){return t===`win32`?fn:un}function searchPathEntries(t,n){let S=pathFor$1(n),C=n===`win32`?`;`:`:`;return t.split(C).filter(Boolean).map(t=>S.resolve(t))}function binDirOnPath(t){let n=pathFor$1(process.platform).resolve(t);return searchPathEntries(process.env.PATH??``,process.platform).includes(n)}function resolveBinOnPath(t,n={}){let S=n.platform??process.platform,C=n.pathValue??process.env.PATH??``,N=n.exists??existsSync,F=S===`win32`?[...(n.pathExt??process.env.PATHEXT??EL).split(`;`).filter(Boolean).map(t=>t.startsWith(`.`)?t:`.${t}`),``]:[``],I=pathFor$1(S);for(let n of searchPathEntries(C,S))for(let S of F){let C=I.join(n,`${t}${S}`);if(N(C))return C}return null}function specToPackageName(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)return t;let S=t.indexOf(`@`,n);return S<0?t:t.slice(0,S)}let n=t.indexOf(`@`);return n<0?t:t.slice(0,n)}var wL,TL,EL,DL=__esmMin(()=>{_e(),Md(),Dg(),jn(),QP(),uI(),wL=[`@gjsify/rolldown-native`,`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`],TL=`@gjsify/rolldown-native`,__name$1(pathFor$1,`pathFor`),EL=`.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC`});function usingSelfShim(){return kL}function pathWithoutSelfShim(t=process.env.PATH??``,n=process.env.GJSIFY_SHIM_DIR,S=kn){return n?t.split(S).filter(t=>t!==n).join(S):t}function needsSelfShim(t){if(t.gjs)return!0;let n=Sn(t.workspaceRoot,t.selfEntry);return n===``||n.startsWith(`..`)||bn(n)}function ensureGjsifyShimOnPath(){if(OL)return;OL=!0;let t=process.env.GJSIFY_SHIM_DIR;if(t&&existsSync(xn(t,`gjsify`))){kL=!0,(process.env.PATH??``).split(kn).includes(t)||(process.env.PATH=t+kn+(process.env.PATH??``));return}let n=isGjs(),S=fileURLToPath(n?import.meta.url:new URL(`../index.js`,import.meta.url));if(!needsSelfShim({gjs:n,selfEntry:S,workspaceRoot:findWorkspaceRoot(process.cwd())??process.cwd()}))return;let C=n?process.env.GJS_CONSOLE||`gjs`:`node`,N=n?selfShimPreamble(S):``,F={gjsify:n?buildShLauncher(S,{isGjsBundle:!0,envPreamble:N,gjs:C}):`#!/bin/sh\nexec "${C}" "${S}" "$@"\n`};if(!n&&process.platform===`win32`){let{cmd:t,ps1:n}=buildLauncherShims({interpreter:C,interpreterArgs:[],target:S});F[`gjsify.cmd`]=t,F[`gjsify.ps1`]=n}let I=buildNodeShim(n,S,N);I&&(F[`${AL}/node`]=I);let H=materializeShimDir(F);kL=!0,process.env.GJSIFY_SHIM_DIR=H,process.env.PATH=H+kn+(process.env.PATH??``)}function materializeShimDir(t,n=gjsifyCacheRoot(`shim`,`v1`)){let S=Object.keys(t).sort(),C=createHash(`sha256`);for(let n of S)C.update(`${n}\0${t[n]}\0`);let N=C.digest(`hex`).slice(0,16);try{return writeShimDir(xn(n,N),t,S)}catch{return writeShimDir(mkdtempSync(xn(tmpdir(),`gjsify-shim-`)),t,S)}}function writeShimDir(t,n,S){for(let C of S){let S=xn(t,C);if(existsSync(S)&&readFileSync(S,`utf8`)===n[C])continue;mkdirSync(wn(S),{recursive:!0});let N=`${S}.tmp.${process.pid}`;try{writeFileSync(N,n[C],{mode:493}),chmodSync(N,493),renameSync(N,S)}catch(t){throw rmSync(N,{force:!0}),t}}return t}function selfShimScanRoot(t){let n=t.search(/[\\/]node_modules[\\/]/);return n>0?t.slice(0,n):findWorkspaceRoot(wn(t))??wn(t)}function selfShimPreamble(t){let n=[];try{n=detectNativePackages(wn(t)).map(t=>t.prebuildsDir)}catch{}return buildNativeEnvPreamble(selfShimScanRoot(t),n)}function dyldCarryPreamble(t,n){return t===`darwin`?Object.keys(n).filter(t=>/^DYLD_[A-Z_]+$/.test(t)&&n[t]).sort().map(t=>`${t}=${shQuoteArg(n[t])}\nexport ${t}\n`).join(``):``}function nodeShimDir(){let t=process.env.GJSIFY_SHIM_DIR;if(!t)return null;let n=xn(t,AL);return existsSync(xn(n,`node`))?n:null}function buildNodeShim(t,n,S){if(!t||resolveBinOnPath(`node`))return null;let C=process.env.GJS_CONSOLE||`gjs`;return`#!/bin/sh
920
920
  `+dyldCarryPreamble(process.platform,process.env)+`case "$1" in
921
921
  -*) echo "gjsify: this host has no node; the gjsify shim runs a SCRIPT FILE only" >&2
922
922
  echo "gjsify: got: node $*" >&2
923
923
  exit 127 ;;
924
924
  esac
925
- `+C+`exec "${F}" -m "${S}" run --node-script "$@"\n`,{mode:493}),chmodSync(I,493)}var OL,kL,AL,jL=__esmMin(()=>{Md(),Dg(),jn(),Hn(),t_(),uI(),QP(),DL(),kP(),OL=!1,kL=!1,AL=`node-shim`});function markDaemonCommand(){ML=!0}function isDaemonCommand(){return ML}var ML,NL=__esmMin(()=>{ML=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(xn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=vn(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Tn(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=xn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[xn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(xn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(KG(),GG));await t(Z)}catch(n){ge.error(n.message),t=!0}if(!t&&isDaemonCommand())return;let n=t?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(n)}let te=n.length>0?`${I} ${n.map(shellEscape).join(` `)}`:I,ne;try{ne=await spawnToCompletion(te,[],{completion:`exit`,cwd:S,env:X,shell:!0})}catch(t){return ge.error(t.message),process.exit(1)}return ne.code===0?process.exit(0):(ge.error(`script "${t}" exited with ${describeExit(ne)}`),process.exit(1))}function shellEscape(t){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(t,n){let S=gjsifyCommandArgv(t);return S?[...S,...n]:null}var PL,FL=__esmMin(()=>{_e(),Md(),jn(),nI(),j_(),vI(),bI(),EI(),DI(),jL(),kP(),RF(),NL(),DP(),t_(),P_(),PL={command:`run <target> [args..]`,description:"Run a script from package.json (yarn-run-style) or a GJS bundle file. If <target> resolves to a file on disk (or has a path-like prefix), it is launched via gjs with LD_LIBRARY_PATH + GI_TYPELIB_PATH set for native packages. Otherwise it is looked up in the current package.json `scripts`.",builder:t=>t.positional(`target`,{description:"Either a script name (looked up in package.json `scripts`) or a path to a GJS bundle (e.g. dist/gjs.js).",type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments passed through to the script / gjs.`,type:`string`,array:!0,default:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:M_,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=t.target,S=[...t.args??[],...doubleDashArgs(t)];if(t.nodeScript===!0){let isSet=t=>typeof t==`string`&&t.length>0,C=isSet(t.runtime)?`--runtime`:isSet(t.workspace)?`--workspace`:null;if(C)return ge.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(n,S,{completion:`exit`,exitOnSuccess:!0});return}let C=t.runtime;if(typeof C==`string`&&C.length>0){if(typeof t.workspace==`string`&&t.workspace.length>0)return ge.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(C))return ge.error(`gjsify run: unknown --runtime "${C}" (expected: ${M_.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(xn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=vn(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),IL,LL=__esmMin(()=>{_e(),jn(),QP(),IL={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?vn(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),RL,zL=__esmMin(()=>{_e(),qP(),RL={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
925
+ `+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var OL,kL,AL,jL=__esmMin(()=>{Kc(),Md(),Dg(),jn(),Hn(),t_(),uI(),QP(),OI(),DL(),kP(),OL=!1,kL=!1,AL=`node-shim`});function markDaemonCommand(){ML=!0}function isDaemonCommand(){return ML}var ML,NL=__esmMin(()=>{ML=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(xn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=vn(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Tn(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=xn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[xn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(xn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(KG(),GG));await t(Z)}catch(n){ge.error(n.message),t=!0}if(!t&&isDaemonCommand())return;let n=t?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(n)}let te=n.length>0?`${I} ${n.map(shellEscape).join(` `)}`:I,ne;try{ne=await spawnToCompletion(te,[],{completion:`exit`,cwd:S,env:X,shell:!0})}catch(t){return ge.error(t.message),process.exit(1)}return ne.code===0?process.exit(0):(ge.error(`script "${t}" exited with ${describeExit(ne)}`),process.exit(1))}function shellEscape(t){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(t,n){let S=gjsifyCommandArgv(t);return S?[...S,...n]:null}var PL,FL=__esmMin(()=>{_e(),Md(),jn(),nI(),j_(),vI(),bI(),EI(),DI(),jL(),kP(),RF(),NL(),DP(),t_(),P_(),PL={command:`run <target> [args..]`,description:"Run a script from package.json (yarn-run-style) or a GJS bundle file. If <target> resolves to a file on disk (or has a path-like prefix), it is launched via gjs with LD_LIBRARY_PATH + GI_TYPELIB_PATH set for native packages. Otherwise it is looked up in the current package.json `scripts`.",builder:t=>t.positional(`target`,{description:"Either a script name (looked up in package.json `scripts`) or a path to a GJS bundle (e.g. dist/gjs.js).",type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments passed through to the script / gjs.`,type:`string`,array:!0,default:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:M_,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=t.target,S=[...t.args??[],...doubleDashArgs(t)];if(t.nodeScript===!0){let isSet=t=>typeof t==`string`&&t.length>0,C=isSet(t.runtime)?`--runtime`:isSet(t.workspace)?`--workspace`:null;if(C)return ge.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(n,S,{completion:`exit`,exitOnSuccess:!0});return}let C=t.runtime;if(typeof C==`string`&&C.length>0){if(typeof t.workspace==`string`&&t.workspace.length>0)return ge.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(C))return ge.error(`gjsify run: unknown --runtime "${C}" (expected: ${M_.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(xn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=vn(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),IL,LL=__esmMin(()=>{_e(),jn(),QP(),IL={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?vn(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),RL,zL=__esmMin(()=>{_e(),qP(),RL={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
926
926
  `);let H=n.filter(t=>t.severity===`required`),W=n.filter(t=>t.severity===`optional`);if(H.length>0){ge.log(`Required:`);for(let t of H){let n=t.found?`✓`:`✗`,S=t.version?` (${t.version})`:``;ge.log(` ${n} ${t.name}${S}`)}}if(W.length>0){ge.log(`
927
927
  Optional:`);for(let t of W){let n=t.found?`✓`:`⚠`,S=t.version?` (${t.version})`:``,C=t.requiredBy&&t.requiredBy.length>0?` — needed by ${t.requiredBy.join(`, `)}`:``;ge.log(` ${n} ${t.name}${S}${C}`)}}if(C.length>0){ge.log(`
928
928
  Type/runtime version skew:`);for(let t of C){let n=t.relation===`ahead`?`⚠`:`ℹ`;ge.log(` ${n} ${t.typePackage} describes ${t.declared}, installed ${t.pkgConfig} is ${t.installed}`)}C.some(t=>t.relation===`ahead`)&&ge.log(`
@@ -1089,7 +1089,7 @@ jobs:
1089
1089
  `;if(n.length!==Dz)throw Error(`gjsify ship: internal error — ar header is ${n.length} bytes, expected ${Dz}.`);return encodeUtf8(n)}function pad(t,n){if(t.length>n)throw Error(`gjsify ship: ar header field "${t}" does not fit in ${n} bytes.`);return t.padEnd(n,` `)}var Ez,Dz,Oz=__esmMin(()=>{Tz(),Ez=`!<arch>
1090
1090
  `,Dz=60});function warnAboutGjsFloor(t,n){return!Mz[t]||compareVersions(n,`1.82.3`)<=0||compareVersions(n,`1.88.1`)===0?[]:[`gjsify ship: \`Depends: gjs (>= ${n})\` is not satisfiable on Debian stable — ${jz}. 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(t,n){return!Pz[t]||compareVersions(n,`22`)<=0?[]:[`gjsify ship: \`Depends: nodejs (>= ${n})\` is not satisfiable on any current DEB stable/LTS — ${Nz}. 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(t,n){let S=t.split(`.`).map(Number),C=n.split(`.`).map(Number);for(let t=0;t<Math.max(S.length,C.length);t++){let n=(S[t]??0)-(C[t]??0);if(n!==0)return n}return 0}function hostProvidedNamespaces(t,n=[]){let S=new Set;for(let t of n){let n=/([A-Za-z0-9]+)-([\d.]+)\.typelib$/.exec(t);n&&(S.add(`${n[1]}-${n[2]}`),S.add(n[1]))}return[...new Set(t)].sort().filter(t=>!Iz.test(t)&&!S.has(t))}function deriveDepends(t,n){let S=n.interpreter===`node`?[`${kz[t]} >= ${n.minNodeVersion??`24`}`]:[`gjs >= ${n.minGjsVersion??`1.86`}`],C=[],N=new Set(n.optionalNamespaces??[]),F=[],I=[];for(let H of hostProvidedNamespaces(n.namespaces,n.bundledTypelibs)){let W=lookupTypelib(H,n.typelibPackages);if(W===void 0){(N.has(H)?I:F).push(H);continue}N.has(H)&&!S.includes(W[t])?C.push(W[t]):S.push(W[t])}if(F.length>0)throw Error(`gjsify ship: the bundle imports ${F.map(t=>`gi://${t.split(`-`)[0]}`).join(`, `)}, and no ${t} package is known to ship ${F.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:
1091
1091
  "gjsify": { "ship": { "typelibPackages": { ${JSON.stringify(F[0])}: { "deb": "gir1.2-…", "rpm": "…" } } } }
1092
- 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 n.hasIcons&&S.push(`hicolor-icon-theme`),n.hasSchemas&&S.push(Az[t]),S.push(...n.extra),{requires:[...new Set(S)],recommends:[...new Set(C)].filter(t=>!S.includes(t)),unmappedOptional:I}}function lookupTypelib(t,n={}){let S={...Fz,...n},C=S[t];if(C!==void 0)return C;if(t.includes(`-`))return;let N=Object.keys(S).filter(n=>n.startsWith(`${t}-`));if(N.length===1)return S[N[0]]}function parseDepend(t){let n=/^(\S+)\s*(>=|<=|=|>|<)\s*(\S+)$/.exec(t);return n?{name:n[1],relation:n[2],version:n[3]}:{name:t.trim()}}function formatDebDepend(t){let n=parseDepend(t);if(n.relation===void 0)return n.name;let S=n.relation===`>`?`>>`:n.relation===`<`?`<<`:n.relation;return`${n.name} (${S} ${n.version})`}var kz,Az,jz,Mz,Nz,Pz,Fz,Iz,Lz=__esmMin(()=>{kz={deb:`nodejs`,rpm:`nodejs(engine)`},Az={deb:`libglib2.0-bin`,rpm:`glib2`},jz=`trixie ships 1.82.3 and forky 1.88.1; 1.84 and 1.86 were skipped`,Mz={deb:!0,rpm:!1},Nz=`trixie ships 20, forky 24; Ubuntu 24.04 LTS ships 18 and 26.04 LTS 22`,Pz={deb:!0,rpm:!1},Fz={"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`}},Iz=/^Gjsify[A-Z]/});async function gzipDeterministic(t,n){let S=await gzip(t,n===void 0?void 0:{level: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 Rz=__esmMin(()=>{II()});function isUnder(t,n){return t.startsWith(`${n}/`)}var zz,Bz=__esmMin(()=>{zz={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(t,n){let S=[];return t.hasDesktopEntry&&S.push({probe:`update-desktop-database`,run:`update-desktop-database -q ${n}/${zz.applications}`}),t.hasIcons&&S.push({probe:`gtk-update-icon-cache`,run:`gtk-update-icon-cache -q -t -f ${n}/${zz.icons}`}),t.hasMimeTypes&&S.push({probe:`update-mime-database`,run:`update-mime-database ${n}/share/mime`}),t.hasSchemas&&S.push({probe:`glib-compile-schemas`,run:`glib-compile-schemas ${n}/${zz.schemas}`}),S.map(({probe:t,run:n})=>`if command -v ${t} >/dev/null 2>&1; then ${n} || true; fi`)}function renderDebScripts(t,n){let S=cacheRefreshCommands(t,n);if(S.length===0)return{};let C=S.map(t=>` ${t}`).join(`
1092
+ 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 n.hasIcons&&S.push(`hicolor-icon-theme`),n.hasSchemas&&S.push(Az[t]),S.push(...n.extra),{requires:[...new Set(S)],recommends:[...new Set(C)].filter(t=>!S.includes(t)),unmappedOptional:I}}function lookupTypelib(t,n={}){let S={...Fz,...n},C=S[t];if(C!==void 0)return C;if(t.includes(`-`))return;let N=Object.keys(S).filter(n=>n.startsWith(`${t}-`));if(N.length===1)return S[N[0]]}function parseDepend(t){let n=/^(\S+)\s*(>=|<=|=|>|<)\s*(\S+)$/.exec(t);return n?{name:n[1],relation:n[2],version:n[3]}:{name:t.trim()}}function formatDebDepend(t){let n=parseDepend(t);if(n.relation===void 0)return n.name;let S=n.relation===`>`?`>>`:n.relation===`<`?`<<`:n.relation;return`${n.name} (${S} ${n.version})`}var kz,Az,jz,Mz,Nz,Pz,Fz,Iz,Lz=__esmMin(()=>{kz={deb:`nodejs`,rpm:`nodejs(engine)`},Az={deb:`libglib2.0-bin`,rpm:`glib2`},jz=`trixie ships 1.82.3 and forky 1.88.1; 1.84 and 1.86 were skipped`,Mz={deb:!0,rpm:!1},Nz=`trixie ships 20, forky 24; Ubuntu 24.04 LTS ships 18 and 26.04 LTS 22`,Pz={deb:!0,rpm:!1},Fz={"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`}},Iz=/^Gjsify[A-Z]/});async function gzipDeterministic(t,n){let S=await gzip(t,n===void 0?void 0:{level: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 Rz=__esmMin(()=>{LI()});function isUnder(t,n){return t.startsWith(`${n}/`)}var zz,Bz=__esmMin(()=>{zz={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(t,n){let S=[];return t.hasDesktopEntry&&S.push({probe:`update-desktop-database`,run:`update-desktop-database -q ${n}/${zz.applications}`}),t.hasIcons&&S.push({probe:`gtk-update-icon-cache`,run:`gtk-update-icon-cache -q -t -f ${n}/${zz.icons}`}),t.hasMimeTypes&&S.push({probe:`update-mime-database`,run:`update-mime-database ${n}/share/mime`}),t.hasSchemas&&S.push({probe:`glib-compile-schemas`,run:`glib-compile-schemas ${n}/${zz.schemas}`}),S.map(({probe:t,run:n})=>`if command -v ${t} >/dev/null 2>&1; then ${n} || true; fi`)}function renderDebScripts(t,n){let S=cacheRefreshCommands(t,n);if(S.length===0)return{};let C=S.map(t=>` ${t}`).join(`
1093
1093
  `);return{postinst:[`#!/bin/sh`,`set -e`,`if [ "$1" = "configure" ]; then`,C,`fi`,``].join(`
1094
1094
  `),postrm:[`#!/bin/sh`,`set -e`,`if [ "$1" = "remove" ]; then`,C,`fi`,``].join(`
1095
1095
  `)}}function renderRpmScriptlets(t,n){let S=cacheRefreshCommands(t,n);if(S.length===0)return{};let C=`${S.join(`
@@ -1130,7 +1130,7 @@ $`,64,`ascii`),le.writeUInt32LE($z,60),le.write(`PE\0\0`,$z,`ascii`),le.writeUIn
1130
1130
  `)[0]??``).trim().split(/\s+/)[0]??``;return n.startsWith(`/`)?n:null}function isArchIndependent(t){return!t.some(t=>isNativeBinary(t.data))}function readBinaryArch(t){if(t.byteLength<20)return null;let n=(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;if(n===2135247942){let n=t[5]===1?t[18]|t[19]<<8:t[18]<<8|t[19];return RB[n]??null}if(n===4277009102||n===4277009103)return zB[(t[4]<<24|t[5]<<16|t[6]<<8|t[7])>>>0]??null;if(n===3472551422||n===3489328638)return zB[(t[7]<<24|t[6]<<16|t[5]<<8|t[4])>>>0]??null;if(t[0]===77&&t[1]===90&&t.byteLength>=64){let n=(t[60]|t[61]<<8|t[62]<<16|t[63]<<24)>>>0;return n+6>t.byteLength||(t[n]|t[n+1]<<8|t[n+2]<<16)>>>0!=17744||t[n+3]!==0?null:BB[t[n+4]|t[n+5]<<8]??null}return null}function assertPayloadMatchesArch(t,n){for(let S of t){let t=readBinaryArch(S.data);if(!(t===null||t===n))throw Error(`gjsify ship: the payload is ${t}, but the package would be labelled ${n} — ${S.path} is built for ${t}.\n \`--arch\` names the architecture the PAYLOAD was built for; it does not cross-compile anything.
1131
1131
  A package labelled ${n} installs on ${n} and then fails to load. Build the payload for ${n}\n (its own prebuild), or assemble the stage without \`--arch\` and label the payload you actually have.`)}}function classifyBinary(t){if(t.byteLength<4)return null;switch((t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0){case 2135247942:return`elf`;case 4277009102:case 4277009103:case 3472551422:case 3489328638:case 3405691582:return`macho`;default:return t[0]===77&&t[1]===90?`pe`:null}}function isNativeBinary(t){return classifyBinary(t)!==null}var MB,NB,PB,FB,IB,LB,RB,zB,BB,VB=__esmMin(()=>{Md(),EB(),jB(),Bz(),MB=new Set([`rem`,`set`,`setlocal`,`endlocal`,`echo`,`goto`,`exit`,`title`,`pause`,`shift`,`cd`,`chdir`,`pushd`,`popd`,`color`,`cls`,`verify`,`prompt`]),NB=new Set([`exist`,`defined`,`errorlevel`]),PB=new Set([`equ`,`neq`,`lss`,`leq`,`gtr`,`geq`]),FB=32,IB=[[zz.schemas,({hasCompiledSchemas:t})=>t?[`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`"]],[zz.mime,()=>[`inert`,"needs `update-mime-database`; detection runs off the compiled cache"]],[zz.icons,()=>[`inert`,"needs `gtk-update-icon-cache`; neither OS reads the hicolor theme"]],[zz.applications,()=>[`inert`,`a freedesktop desktop entry; neither OS reads one`]],[zz.metainfo,()=>[`inert`,`an AppStream component; neither OS reads one`]]],LB=[zz.locale,zz.fonts,AB],RB={3:`ia32`,21:`ppc64`,22:`s390x`,40:`arm`,62:`x64`,183:`arm64`,243:`riscv64`},zB={7:`ia32`,12:`arm`,16777223:`x64`,16777228:`arm64`},BB={332:`ia32`,34404:`x64`,43620:`arm64`}});async function buildDeb(t){let{payload:n,mtime:S}=t,C=t.prefix.replace(/^\/+/,``),N=n.map(t=>({...t,tarPath:`./${un.join(C,t.path)}`})),F=ancestorDirectories(N.map(t=>t.tarPath)),I=await gzipDeterministic(createTarball([...F.map(t=>({name:t,mode:493,mtime:S,directory:!0})),...N.map(t=>({name:t.tarPath,body:t.data,mode:t.mode,mtime:S}))])),H=renderControl(t,N.reduce((t,n)=>t+Math.ceil(n.data.byteLength/1024),0)+F.length),W=N.map(t=>`${createHash(`md5`).update(t.data).digest(`hex`)} ${t.tarPath.slice(2)}\n`).join(``),q=[{name:`./`,mode:493,mtime:S,directory:!0},{name:`./control`,body:H,mode:420,mtime:S},{name:`./md5sums`,body:W,mode:420,mtime:S}],Y=renderDebScripts(readPayloadFacts(n),t.prefix);for(let[t,n]of Object.entries(Y))q.push({name:`./${t}`,body:n,mode:493,mtime:S});let X=await gzipDeterministic(createTarball(q));return createArArchive([{name:`debian-binary`,data:new TextEncoder().encode(`2.0
1132
1132
  `),mtime:S},{name:`control.tar.gz`,data:X,mtime:S},{name:`data.tar.gz`,data:I,mtime:S}])}function singleLine(t){return t.replace(/[\r\n]+/g,` `).trim()}function ancestorDirectories(t){let n=new Set([`./`]);for(let S of t){let t=S.replace(/^\.\//,``).split(`/`);t.pop();let C=`.`;for(let S of t)C=`${C}/${S}`,n.add(`${C}/`)}return[...n].sort()}function renderControl(t,n){let{settings:S}=t,C=[[`Package`,S.binaryName],[`Version`,`${S.version}-${S.release}`],[`Architecture`,t.archLabel],[`Maintainer`,S.maintainer],[`Installed-Size`,String(n)]];t.depends.length>0&&C.push([`Depends`,t.depends.map(formatDebDepend).join(`, `)]),t.recommends!==void 0&&t.recommends.length>0&&C.push([`Recommends`,t.recommends.map(formatDebDepend).join(`, `)]),C.push([`Section`,S.section],[`Priority`,`optional`]),S.homepage&&C.push([`Homepage`,S.homepage]);let N=C.map(([t,n])=>`${t}: ${singleLine(n)}`);return N.push(`Description: ${singleLine(S.summary)}`),S.description.filter(t=>t!==S.summary).forEach((t,n)=>{n>0&&N.push(` .`),N.push(` ${t}`)}),`${N.join(`
1133
- `)}\n`}var HB=__esmMin(()=>{Kc(),jn(),II(),Oz(),Lz(),Rz(),Vz(),VB()});function xmlEscape(t){return t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&apos;`)}var UB=__esmMin(()=>{});function validateMimeTypes(t){let n=new Set;for(let S of t){if(!WB.test(S.type))throw Error(`gjsify ship: \`gjsify.ship.mimeTypes\` has an invalid type "${S.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(n.has(S.type))throw Error(`gjsify ship: \`gjsify.ship.mimeTypes\` defines ${S.type} twice. Which comment and glob set win would depend on document order.`);if(n.add(S.type),S.comment.trim()===``)throw Error(`gjsify ship: ${S.type} has an empty \`comment\`. A file manager then shows the user the raw type string instead of a name.`);for(let t of S.globs??[])if(!t.includes(`*`)&&!t.includes(`?`)&&!t.includes(`[`))throw Error(`gjsify ship: ${S.type} has the glob "${t}", which matches only a file named exactly that. A suffix pattern is written \`*.${t.replace(/^\.+/,``)}\`.`);if((S.globs??[]).length===0&&S.subClassOf===void 0)throw Error(`gjsify ship: ${S.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(t){return`<?xml version="1.0" encoding="UTF-8"?>
1133
+ `)}\n`}var HB=__esmMin(()=>{Kc(),jn(),LI(),Oz(),Lz(),Rz(),Vz(),VB()});function xmlEscape(t){return t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&apos;`)}var UB=__esmMin(()=>{});function validateMimeTypes(t){let n=new Set;for(let S of t){if(!WB.test(S.type))throw Error(`gjsify ship: \`gjsify.ship.mimeTypes\` has an invalid type "${S.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(n.has(S.type))throw Error(`gjsify ship: \`gjsify.ship.mimeTypes\` defines ${S.type} twice. Which comment and glob set win would depend on document order.`);if(n.add(S.type),S.comment.trim()===``)throw Error(`gjsify ship: ${S.type} has an empty \`comment\`. A file manager then shows the user the raw type string instead of a name.`);for(let t of S.globs??[])if(!t.includes(`*`)&&!t.includes(`?`)&&!t.includes(`[`))throw Error(`gjsify ship: ${S.type} has the glob "${t}", which matches only a file named exactly that. A suffix pattern is written \`*.${t.replace(/^\.+/,``)}\`.`);if((S.globs??[]).length===0&&S.subClassOf===void 0)throw Error(`gjsify ship: ${S.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(t){return`<?xml version="1.0" encoding="UTF-8"?>
1134
1134
  <mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
1135
1135
  ${t.map(t=>{let n=[` <mime-type type="${xmlEscape(t.type)}">`,` <comment>${xmlEscape(t.comment)}</comment>`];t.subClassOf!==void 0&&n.push(` <sub-class-of type="${xmlEscape(t.subClassOf)}"/>`);for(let S of t.globs??[])n.push(` <glob pattern="${xmlEscape(S)}"/>`);return t.genericIcon!==void 0&&n.push(` <generic-icon name="${xmlEscape(t.genericIcon)}"/>`),n.push(` </mime-type>`),n.join(`
1136
1136
  `)}).join(`
@@ -1162,7 +1162,7 @@ A misplaced catalogue installs and then shows nothing, which reads exactly like
1162
1162
  `)]},{tag:EH.BUILDTIME,type:4,value:[t.mtime]},{tag:EH.BUILDHOST,type:6,value:`localhost`},{tag:EH.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:EH.LICENSE,type:6,value:N.license},{tag:EH.GROUP,type:9,value:[N.group]},{tag:EH.OS,type:6,value:`linux`},{tag:EH.ARCH,type:6,value:t.archLabel},{tag:EH.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:EH.RPMVERSION,type:6,value:`4.20.0`},{tag:EH.ENCODING,type:6,value:`utf-8`},{tag:EH.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:EH.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:EH.FILERDEVS,type:3,value:n.map(()=>0)},{tag:EH.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:EH.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:EH.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:EH.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:EH.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:EH.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:EH.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:EH.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:EH.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:EH.FILELANGS,type:8,value:n.map(()=>``)},{tag:EH.FILEDIGESTALGO,type:4,value:[kH]},{tag:EH.DIRINDEXES,type:4,value:H},{tag:EH.BASENAMES,type:8,value:W},{tag:EH.DIRNAMES,type:8,value:I},{tag:EH.PROVIDENAME,type:8,value:[N.binaryName]},{tag:EH.PROVIDEFLAGS,type:4,value:[OH.EQUAL]},{tag:EH.PROVIDEVERSION,type:8,value:[F]},{tag:EH.REQUIRENAME,type:8,value:Y.names},{tag:EH.REQUIREFLAGS,type:4,value:Y.flags},{tag:EH.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:EH.RECOMMENDNAME,type:8,value:X.names},{tag:EH.RECOMMENDFLAGS,type:4,value:X.flags},{tag:EH.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:EH.PAYLOADFORMAT,type:6,value:`cpio`},{tag:EH.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:EH.PAYLOADFLAGS,type:6,value:`9`},{tag:EH.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:EH.PAYLOADDIGESTALGO,type:4,value:[kH]},{tag:EH.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:EH.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:EH.POSTIN,type:6,value:q.post}),Z.push({tag:EH.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:EH.POSTUN,type:6,value:q.postun}),Z.push({tag:EH.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([EH.FILESIZES,EH.FILEMODES,EH.FILERDEVS,EH.FILEMTIMES,EH.FILEDIGESTS,EH.FILELINKTOS,EH.FILEFLAGS,EH.FILEUSERNAME,EH.FILEGROUPNAME,EH.FILEVERIFYFLAGS,EH.FILEDEVICES,EH.FILEINODES,EH.FILELANGS,EH.DIRINDEXES,EH.BASENAMES]);for(let C of t){if(!S.has(C.tag))continue;let t=Array.isArray(C.value)?C.value.length:1;if(t!==n)throw Error(`gjsify ship: internal error — rpm tag ${C.tag} has ${t} values for ${n} files.`)}}function buildRequires(t,n,S){let C=[],N=[],F=[];for(let n of t){let t=parseDepend(n);C.push(t.name),N.push(senseFor(t.relation)),F.push(t.version??``)}n.post!==void 0&&(C.push(`/bin/sh`),N.push(OH.INTERP|OH.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(OH.INTERP|OH.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(OH.FIND_REQUIRES),F.push(``);for(let[t,n]of AH)C.push(t),N.push(OH.RPMLIB|OH.LESS|OH.EQUAL),F.push(n);return{names:C,flags:N,versions:F}}function buildRecommends(t){let n=[],S=[],C=[];for(let N of t){let t=parseDepend(N);n.push(t.name),S.push(senseFor(t.relation)),C.push(t.version??``)}return{names:n,flags:S,versions:C}}function senseFor(t){switch(t){case`>=`:return OH.GREATER|OH.EQUAL;case`>`:return OH.GREATER;case`<=`:return OH.LESS|OH.EQUAL;case`<`:return OH.LESS;case`=`:return OH.EQUAL;default:return 0}}function hashHex(t,n){return createHash(t).update(n).digest(`hex`)}function hashBytes(t,n){return new Uint8Array(createHash(t).update(n).digest())}var EH,DH,OH,kH,AH,jH,MH=__esmMin(()=>{Kc(),Tz(),bH(),Lz(),VB(),TH(),Rz(),Vz(),Bz(),EH={HEADERI18NTABLE:100,NAME:1e3,VERSION:1001,RELEASE:1002,SUMMARY:1004,DESCRIPTION:1005,BUILDTIME:1006,BUILDHOST:1007,SIZE:1009,LICENSE:1014,GROUP:1016,URL:1020,OS:1021,ARCH:1022,POSTIN:1024,POSTUN:1026,FILESIZES:1028,FILEMODES:1030,FILERDEVS:1033,FILEMTIMES:1034,FILEDIGESTS:1035,FILELINKTOS:1036,FILEFLAGS:1037,FILEUSERNAME:1039,FILEGROUPNAME:1040,SOURCERPM:1044,FILEVERIFYFLAGS:1045,PROVIDENAME:1047,REQUIREFLAGS:1048,REQUIRENAME:1049,REQUIREVERSION:1050,RECOMMENDNAME:5046,RECOMMENDVERSION:5047,RECOMMENDFLAGS:5048,RPMVERSION:1064,POSTINPROG:1086,POSTUNPROG:1088,FILEDEVICES:1095,FILEINODES:1096,FILELANGS:1097,PROVIDEFLAGS:1112,PROVIDEVERSION:1113,DIRINDEXES:1116,BASENAMES:1117,DIRNAMES:1118,PAYLOADFORMAT:1124,PAYLOADCOMPRESSOR:1125,PAYLOADFLAGS:1126,FILEDIGESTALGO:5011,ENCODING:5062,PAYLOADDIGEST:5092,PAYLOADDIGESTALGO:5093,PAYLOADDIGESTALT:5097},DH={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},OH={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},kH=8,AH=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],jH=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${zz.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${zz.metainfo}`,`/usr/share/glib-2.0`,`/usr/${zz.schemas}`,`/usr/${zz.fonts}`,`/etc`,`/opt`,`/var`])});async function assemble(t){let n=process.cwd(),S=t.os===void 0?hostLayout():resolveLayout(t.os),C=await new Config().forCommand(n),N=C.ship??{},F=C.flatpak??{},I=resolveShipApp({project:C.app,perTarget:N.app,layoutOs:S.os}),H=I.app;I.overridden&&ge.log(`${NH} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(xn(n,`package.json`))??{},q,Y=[];if(t.target!==void 0)q=resolveFormats(t.target,S);else if(N.targets!==void 0){let t=configuredFormats(N.targets,S);q=t.formats,t.dropped.length>0&&ge.log(`${NH} \`gjsify.ship.targets\` names ${t.dropped.join(`, `)}, which wrap another layout — not built for ${S.name}. Pass --target to ask for one explicitly.`)}else{let t=defaultFormatIds(S.os).map(t=>BV[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${NH} ${Y.map(t=>t.id).join(`, `)} wrap the ${S.name} layout but cannot run \`${H}\`, which \`${I.key}\` resolves to — ${Y[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${S.os}\` to "${Y[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}q.some(t=>t.id===`flatpak`)&&assertNoDroppedFlatpakModules(F),t.stage||assertPackable(q,S,t.os===void 0?`host`:`positional`,Y);let X=resolveSignPlan({flag:t.sign,config:N.sign,layoutOs:S.os}),Z=resolveNotaryPlan({flag:t.notarize,layoutOs:S.os,sign:X});if(t.stage&&assertNothingToSignYet(t),t.stage||(announceSigning(X,Z),X.kind===`sign`&&assertHostCanSign(X.signer)),t.stage||assertKindCanPack(q,resolveShipKind(N,F)),!t.stage)for(let t of q)assertCanPack(t);t[`skip-build`]||await runProjectBuild(n);let te=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});te.overridden&&ge.log(`${NH} entry for ${S.name}: ${te.declared} — \`${te.key}\` overrides \`gjsify.main\`.`);let ne=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:te.declared,foreignBundles:te.foreign}),{settings:re,metadata:ie,warnings:ae}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ne,app:H});for(let t of ae)ge.warn(`${NH} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,re.app);let oe=readFileSync(re.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:re.app,source:oe,entry:Sn(n,re.bundlePath)||re.bundlePath,appKey:I.key,bundleKey:te.key,layoutOs:S.os});let Q=buildTimestamp(re.bundlePath),se={appId:re.appId,name:re.name,command:re.binaryName,kind:re.kind,metadata:ie,configKey:`gjsify.ship`,copyrightYear:new Date(Q*1e3).getUTCFullYear()};for(let t of validateAppMetadata(se))ge.warn(`${NH} ${t.field} is not set — ${t.hint}`);re.licenseFile!==void 0&&wn(re.licenseFile)!==n&&ge.log(`${NH} licence text from ${Sn(n,re.licenseFile)} (this package carries none of its own)`);let ce=localizeMetadata({metainfo:re.kind===`app`?renderMetainfoApp$1(se):renderMetainfoCli$1(se),desktopEntry:re.kind===`app`?renderDesktopEntry(se):void 0},re.localeFiles),le=resolveCarriedRuntime(S,re,n),ue={bundleFiles:ne.bundleFiles,launcher:renderLauncher(re,Tn(re.bundlePath),S,le.launcher),metainfo:ce.metainfo,desktopEntry:ce.desktopEntry,licenseText:re.licenseFile===void 0?void 0:readFileSync(re.licenseFile,`utf-8`),changelogText:re.changelogFile===void 0?void 0:readFileSync(re.changelogFile,`utf-8`),mtime:Q},de=vn(n,re.outDir),fe=xn(de,`stage`),pe=[...planStage(re,ue),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:re.schemaFiles,workDir:xn(de,`schemas`)})],me=re.kind===`app`&&S.icon!==void 0?await resolveAppIcon({iconFiles:re.iconFiles,appId:re.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;me!==void 0&&ge.log(`${NH} icon: ${iconSizes(me).join(`/`)} px, ${me.source}`);let he=placeStage(S,{...re,icon:me},pe,le.files);if(writeStage(fe,he),ge.log(`${NH} staged ${he.length} file(s) for ${S.name} in ${Sn(n,fe)}/`),t.verbose)for(let t of he)ge.log(`${NH} ${t.path}`);if(assertPayloadMatchesArch(readStage([fe],he),re.arch),S.os!==`linux`){let t=linuxInstallDependent(pe);if(t.length>0){ge.warn(`${NH} the ${S.name} layout carries ${t.length} file(s) whose Linux correctness comes from a package install step it has no equivalent for:`);let n={aborts:`ABORTS: `,unknown:`UNCLASSIFIED: `,inert:``};for(let{path:S,verdict:C,why:N}of t)ge.warn(`${NH} ${n[C]??``}${S} — ${N}`)}for(let t of le.found)ge.log(`${NH} carries its own ${t}`);for(let t of le.missing)ge.warn(`${NH} ${t}`);le.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${NH} ${S.runtimeGap}`),S.fontGap!==void 0&&pe.some(t=>isUnder(t.path,zz.fonts))&&ge.warn(`${NH} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(re.arch)&&ge.warn(`${NH} this stage is labelled ${re.arch} and the ${S.name} layout has no runtime for it — ${S.arches.why}. Nothing can pack this stage; \`--arch ${S.arches.only.join(`|`)}\` is what produces an artifact.`)}let _e=scanGiRequirements(oe),ve=_e.namespaces,ye=_e.optional;if(t.verbose){let t=ve.filter(t=>!ye.includes(t));ge.log(`${NH} gi namespaces: ${ve.join(`, `)||`(none)`}`),ye.length>0&&(ge.log(`${NH} gi optional namespaces: ${ye.join(`, `)}`),ge.log(`${NH} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let be=new Map;for(let t of q)be.set(t.id,(await planOverlay(re,t,ue)).map(t=>({...t,path:place(S,re,t.path)})));let xe=readPayloadFacts(pe);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:ve,optionalNamespaces:ye,hasIcons:xe.hasIcons,hasSchemas:xe.hasSchemas,interpreter:re.app,extra:re.extraDepends[t.depends],typelibPackages:re.typelibPackages,bundledTypelibs:xe.bundledTypelibs,minGjsVersion:re.minGjsVersion,minNodeVersion:re.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${NH} gi://${S} is imported optionally, but no ${t.depends} package is known to ship its typelib, so no Recommends entry names it. The package builds and runs without it. Add the row if the namespace should be recommended: \`gjsify.ship.typelibPackages.${S} = { "${t.depends}": "…" }\`.`);let S=re.app===`node`?warnAboutNodeFloor(t.depends,re.minNodeVersion):warnAboutGjsFloor(t.depends,re.minGjsVersion);for(let t of S)ge.warn(`${NH} ${t}`)}let Se=writeStageManifest({stageDir:fe,settings:re,formats:q,mtime:Q,namespaces:ve,optionalNamespaces:ye,staged:he,overlay:be});if(t.stage){let t=Y.length>0?`(none — ${Y.map(t=>t.id).join(` and `)} need \`gjsify.ship.app.${S.os}: "node"\`)`:formatIdsFor(S.os).length===0?`(none — no format wraps the ${S.name} layout)`:`(none asked for)`,n=Se.formats.join(`, `)||t;ge.log(`${NH} stage manifest: ${formatTarget(Se.target)}, formats ${n}`);return}let Ce=[];for(let n of q)Ce.push(await packOne({format:n,settings:re,arch:re.arch,staged:he,overlay:be.get(n.id)??[],stageDir:fe,outRoot:de,namespaces:ve,optionalNamespaces:ye,mtime:Q,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,Ce)}function assertNothingToSignYet(t){let n=t.sign===void 0?t.notarize===void 0?void 0:`--notarize`:`--sign`;if(n!==void 0)throw Error(`gjsify ship: ${n} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(t,n){t.kind===`skip`&&ge.warn(`${NH} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${NH} ${n.message}`)}function resolveCarriedRuntime(t,n,S){let C={files:[],launcher:{},found:[],missing:[]};if(t.os===`linux`||n.app!==`node`)return C;let N=`${t.os}-${n.arch}`;return isGtkRuntimeTarget(N)?stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null}):C}async function finishFromStage(t,n){if(t.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(t[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(t.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(t.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${t.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let S=process.cwd(),C=vn(S,n),N=readStageManifest(C);assertExpectedTarget(N,t[`expect-target`]);let F=layoutForOs(N.target.os);t.target===void 0&&assertPackable(N.formats.map(t=>BV[t]),F,`stage`,defaultFormatIds(F.os).map(t=>BV[t]).filter(t=>!t.interpreters.includes(N.settings.app)));let I=resolveFormats(t.target??N.formats,F);assertFormatsStaged(N,I);for(let t of I)assertCanPack(t);let H=resolveSignPlan({flag:t.sign,layoutOs:F.os}),W=resolveNotaryPlan({flag:t.notarize,layoutOs:F.os,sign:H});announceSigning(H,W),H.kind===`sign`&&assertHostCanSign(H.signer);for(let t of warnOnToolSkew(N))ge.warn(`${NH} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${NH} ${t}`);if(ge.log(`${NH} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Sn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${NH} ${t.path}`);ge.log(`${NH} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${NH} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?wn(C):vn(S,t.out),Z=[];for(let n of I){if(assertFormatCanRunInterpreter(n,N.settings.app),n.depends!==null){let t=N.settings.app===`node`?warnAboutNodeFloor(n.depends,N.settings.minNodeVersion):warnAboutGjsFloor(n.depends,N.settings.minGjsVersion);for(let n of t)ge.warn(`${NH} ${n}`)}Z.push(await packOne({format:n,settings:N.settings,arch:N.target.arch,staged:N.staged,overlay:overlayFiles(N,n.id),stageDir:C,outRoot:X,namespaces:N.namespaces,optionalNamespaces:N.optionalNamespaces??[],mtime:q,sign:H,notarize:W,verbose:t.verbose}))}printArtifacts(S,Z)}async function packOne(t){let{format:n,settings:S,stageDir:C,outRoot:N,mtime:F}=t;assertOverlayIsLicensed(n.id,S.binaryName,t.overlay);let I=xn(N,`overlay`,n.id);writeStage(I,t.overlay);let H=readStage([C,I],[...t.staged,...t.overlay]),W=readPayloadFacts(H),q=n.depends===null?{requires:[],recommends:[],unmappedOptional:[]}:deriveDepends(n.depends,{namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,hasIcons:W.hasIcons,hasSchemas:W.hasSchemas,interpreter:S.app,extra:S.extraDepends[n.depends],typelibPackages:S.typelibPackages,bundledTypelibs:W.bundledTypelibs,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion}),Y=q.requires,X=q.recommends;assertPayloadMatchesArch(H,t.arch);let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:xn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:xn(N,`signed`,`${n.id}.entitlements.plist`),verbose:t.verbose,log:t=>ge.log(`${NH} ${t}`)}):H,ne=n.archName(t.arch,isArchIndependent(te)),re={settings:S,payload:te,prefix:n.prefix,depends:Y,recommends:X,archLabel:ne,mtime:F},ie=xn(N,`out`);mkdirSync(ie,{recursive:!0});let ae=xn(ie,n.fileName(S,ne));switch(n.id){case`deb`:writeFileSync(ae,await buildDeb(re));break;case`rpm`:writeFileSync(ae,await buildRpm(re));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:lH,workDir:xn(N,`flatpak`),target:ae,archLabel:ne,verbose:t.verbose});break;case`appimage`:{let n=appImageHostRequirements({app:S.app,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion,namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,bundledTypelibs:W.bundledTypelibs}),C=appDirFor(N),I=appDirPayload(S,te,n,await compileSchemasForPayload({payload:te,workDir:xn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${NH} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(ne);ge.log(`${NH} ${appImageRuntimeNotice(ne,H)}`),await buildAppImage({appDir:C,target:ae,archLabel:ne,runtimeFile:H,workDir:wn(C),verbose:t.verbose});break}case`macos-app`:case`windows-dir`:writePayload(ae,te,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);writePayload(n,te,``),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:ae,workDir:wn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(ae,buildZip(zipEntriesFromPayload(te),F));break;case`windows-dir-zip`:writeFileSync(ae,buildZip(zipEntriesFromPayload(te,windowsProgramDirName(S)),F));break;case`msi`:{let n=xn(N,`msi`);writePayload(xn(n,KV),te,Z.root(S)),await buildMsi({settings:S,files:te.map(t=>({path:t.path,source:`${KV}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:ne,workDir:n,target:ae,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let oe=n.artifactKind===`directory`?directorySize(ae):statSync(ae).size;return t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${NH} ${n.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:t.notarize,artifact:ae,verbose:t.verbose,log:t=>ge.log(`${NH} ${t}`)}),canCarryTicket(n.id)?await stapleArtifact({notary:t.notarize.notary,artifact:ae,verbose:t.verbose,log:t=>ge.log(`${NH} ${t}`)}):ge.warn(`${NH} ${n.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),{format:n.id,path:ae,size:oe}}function printArtifacts(t,n){for(let S of n)ge.log(`${NH} ${S.format}: ${Sn(t,S.path)} (${S.size} bytes)`)}function assertCanPack(t){assertHostCanFinish(t),assertToolsInstalled(t)}function assertPackable(t,n,S,C=[]){if(t.length>0)return;if(C.length>0)throw Error(`gjsify ship: ${C.map(t=>t.id).join(` and `)} wrap the ${n.name} layout, and neither can run this project — ${C[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${n.os}\` to "${C[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
1163
1163
  \`gjsify ship ${n.name} --stage\` assembles the tree either way.`);let N=formatIdsFor(n.os).sort();if(N.length>0){let t=S===`stage`?`${n.name} --stage --target`:`${n.name} --target`;throw Error(`gjsify ship: this run records no formats for the ${n.name} layout, so there is nothing to pack — and it is not that none exist: ${N.join(`, `)} wrap it.\n An empty list means none were SELECTED. \`gjsify.ship.targets\` is filtered to the layout being assembled,
1164
1164
  so a configured list naming only another OS's formats leaves this one empty and says so at stage time.
1165
- Name one where the payload is assembled: \`gjsify ship ${t} ${N[0]}\`.`)}let F=defaultFormatIds(`linux`).join(`,`),I={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${n.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${F} from right here.`,positional:`\`gjsify ship ${n.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${n.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[S];throw Error(`gjsify ship: no format wraps the ${n.name} layout, so there is nothing to pack. ${I} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(t,n){if(!t.interpreters.includes(n))throw Error(`gjsify ship: this ${t.layoutOs} target runs \`${n}\`, and the ${t.id} runtime cannot run it — it provides ${t.interpreters.join(`, `)}.\n ${t.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${t.layoutOs}: "${t.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(t){if(typeof readPackageJson$2(xn(t,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ge.log(`${NH} running the project's build script`);let n=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,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(n.code!==0)throw Error(`gjsify ship: the project's build script failed with ${describeExit(n)}.`)}var NH,PH,FH=__esmMin(()=>{_e(),Md(),jn(),JF(),KR(),OP(),j_(),HB(),Lz(),mV(),rV(),CV(),EV(),WR(),DV(),Kz(),OV(),UV(),EB(),aV(),Bz(),jB(),qV(),tH(),iH(),sH(),VB(),uV(),mH(),hH(),MH(),$B(),uH(),dH(),NH=`[gjsify ship]`,PH={command:`ship [os]`,description:`Build installable artifacts (${VV.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${wB.join(`|`)}, ADR 0024 § A2). Default: this host. Assembly is not host-bound, so any of them can be staged anywhere.`}).option(`target`,{type:`string`,array:!0,description:`Formats to build, comma-separated or repeated. Default: every format wrapping the target OS's layout that needs no extra tooling — on linux, ${defaultFormatIds(`linux`).join(`,`)}. Also available for linux, and opt-in because it needs tooling this CLI does not carry: ${formatIdsFor(`linux`).filter(t=>!defaultFormatIds(`linux`).includes(t)).join(`, `)}.`}).option(`out`,{type:`string`,normalize:!0,description:"Output root, relative to the project. Default: `gjsify.ship.outDir`, else `ship`."}).option(`stage`,{type:`boolean`,default:!1,description:`Produce the staged payload and stop, without packing anything.`}).option(`from-stage`,{type:`string`,normalize:!0,description:"Pack a staged payload written by an earlier `--stage` run. Needs no project: the stage carries its own closure."}).option(`expect-target`,{type:`string`,description:"With --from-stage: refuse unless the stage was assembled for this `<os>-<arch>`, e.g. `linux-arm64`."}).option(`skip-build`,{type:`boolean`,default:!1,description:"Package what is already built instead of running the project's `build` script."}).option(`arch`,{type:`string`,description:"Target architecture in `process.arch` spelling. Default: this host."}).option(`sign`,{type:`string`,requiresArg:!0,description:"Sign the payload with this identity, e.g. a Developer ID name or SHA-1 fingerprint. `-` signs ad-hoc and needs no developer identity. Default: `gjsify.ship.sign.<darwin|win32>.identity`; absent means unsigned, which is a legitimate output."}).option(`notarize`,{type:`string`,requiresArg:!0,description:"Submit the signed artifact to Apple with this `notarytool` keychain profile. Needs --sign; darwin only."}).option(`verbose`,{type:`boolean`,default:!1,description:`Print each staged file, the GI namespaces the bundle imports, and every tool a host-bound packer invokes.`}),handler:async t=>{if(t[`from-stage`]!==void 0)return await finishFromStage(t,t[`from-stage`]);await assemble(t)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var IH=__esmMin(()=>{t_()});function workspaceLinkTarget(t,n){return LH===`junction`?vn(n):Sn(wn(t),n)}function applyPlatformConfigFromFlags(t){for(let[n,S]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let C=t[n];if(typeof C!=`string`)continue;let N=C.trim();N!==``&&(process.env[S]=N)}t.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(t){if(!t||typeof t!=`object`)return!1;let n=t.name;if(n===`AbortError`)return!0;let S=t.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||n===`RegistryTimeoutError`)}function readCliVersionFrom(t){try{if(!existsSync(t))return null;let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===BH&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=wn(vn(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==wn(t);n++){let n=readCliVersionFrom(xn(t,`package.json`));if(n)return n;t=wn(t)}}catch{}return null}function readWorkspaceCliVersion(t){return readCliVersionFrom(xn(t,`node_modules`,BH,`package.json`))??readCliVersionFrom(xn(t,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(t){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let n=readRunningCliVersion(),S=readWorkspaceCliVersion(t);!n||!S||n===S||ge.warn(`gjsify install: version skew — you are running @gjsify/cli v${n}, but this workspace pins v${S}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(t){let n=readPackageJson$1(xn(t,`package.json`));return n?n.workspaces!==void 0:!1}function optionalDependencyNames(t){let n=new Set,S=new Set;for(let C of t){let t=new Set(Object.keys(C.optionalDependencies??{}));for(let S of t)n.add(S);for(let n of[`dependencies`,`devDependencies`])for(let N of Object.keys(C[n]??{}))t.has(N)||S.add(N)}for(let t of S)n.delete(t);return n}function depKindFromArgs(t){return t[`save-dev`]?`devDependencies`:t[`save-peer`]?`peerDependencies`:t[`save-optional`]?`optionalDependencies`:`dependencies`}function activateDevLinks(t,n){let S=prepareDevLinks(devLinkRoot(t));if(!S)return null;let C=applyDevLinks(S.links);if(!n)return S;ge.log(`gjsify install: development link ACTIVE (${S.overridePath}) — ${S.links.length} package(s) come from ${S.checkout}, linked rather than fetched (${C.length} (re)written, ${S.links.length-C.length} already current):`);let N=S.links.map(t=>t.name),F=N.slice(0,12);return ge.log(` ${F.join(`, `)}${N.length>F.length?`, +${N.length-F.length} more`:``}`),ge.log(" `gjsify unlink` restores the registry copies; `gjsify install --immutable` refuses while it exists."),S}function reportRewiredDevLinks(t){if(!t)return;let n=applyDevLinks(t.links);n.length!==0&&ge.log(`gjsify install: re-applied ${n.length} development link(s) the install had replaced: ${n.map(t=>t.name).join(`, `)}`)}async function projectInstallNative(t,n){let S=process.cwd(),C=xn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(xn(S,t)));if(N.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${N.join(`, `)} in ${S}).\n\n• If this project uses \`gjsify install\` to manage dependencies, these PnP files are stale residue from an earlier \`yarn install\` — remove them and re-run:\n rm -f .pnp.cjs .pnp.loader.mjs && rm -rf .yarn/cache .yarn/unplugged\n gjsify install\n\n• If instead you want Yarn to manage dependencies, set \`nodeLinker: node-modules\` in .yarnrc.yml and run \`yarn install\` (not \`gjsify install\`).`);if(!t.packages||t.packages.length===0){let C=isWorkspaceRoot(S)?S:findWorkspaceRoot(S);if(C){C!==S&&ge.log(`gjsify install: resolved workspace root ${C} (from ${S}); installing the workspace.`),await workspaceInstall(C,t,n);return}}let F,I=readPackageJson$1(C),H=I?projectSpecsFromPackageJson(I):[];if(t.packages&&t.packages.length>0){let n=new Set(t.packages.map(t=>parseSpec$2(t).name));F=[...H.filter(t=>!n.has(parseSpec$2(t).name)),...t.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ge.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!t.verbose&&!t.quiet&&t.progress!==!1}),q=await acquireInstallLock(S,{signal:n});try{let N=activateDevLinks(S,!0),H=await installPackages({prefix:S,specs:F,verbose:t.verbose,lockfile:!t.immutable,frozen:t.immutable,refreshLockfile:t[`refresh-lockfile`],signal:n,progress:W,optionalSpecs:new Set([...optionalDependencyNames(I?[I]:[]),...t[`save-optional`]?(t.packages??[]).map(t=>parseSpec$2(t).name):[]]),linkedNames:N?.names});if(reportRewiredDevLinks(N),t.packages&&t.packages.length>0&&I){let n=depKindFromArgs(t);for(let S of t.packages){let{name:t,range:C}=parseSpec$2(S),N=H.installed.find(n=>n.name===t);addDependencyEntry(I,t,C??(N?defaultRangeFromVersion(N.version):`latest`),n)}writePackageJson(C,I),t.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}finally{q.release()}}function syncLockfileRequested(t,n){let S=xn(t,`gjsify-lock.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`)),C=[...n].sort(),N=[...t.requested??[]].sort();if(C.length===N.length&&C.every((t,n)=>t===N[n]))return;t.requested=n,atomicWriteStrict(S,JSON.stringify(t,null,2)+`
1165
+ Name one where the payload is assembled: \`gjsify ship ${t} ${N[0]}\`.`)}let F=defaultFormatIds(`linux`).join(`,`),I={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${n.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${F} from right here.`,positional:`\`gjsify ship ${n.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${n.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[S];throw Error(`gjsify ship: no format wraps the ${n.name} layout, so there is nothing to pack. ${I} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(t,n){if(!t.interpreters.includes(n))throw Error(`gjsify ship: this ${t.layoutOs} target runs \`${n}\`, and the ${t.id} runtime cannot run it — it provides ${t.interpreters.join(`, `)}.\n ${t.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${t.layoutOs}: "${t.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(t){if(typeof readPackageJson$2(xn(t,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ge.log(`${NH} running the project's build script`);let n=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,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(n.code!==0)throw Error(`gjsify ship: the project's build script failed with ${describeExit(n)}.`)}var NH,PH,FH=__esmMin(()=>{_e(),Md(),jn(),JF(),KR(),OP(),j_(),HB(),Lz(),mV(),rV(),CV(),EV(),WR(),DV(),Kz(),OV(),UV(),EB(),aV(),Bz(),jB(),qV(),tH(),iH(),sH(),VB(),uV(),mH(),hH(),MH(),$B(),uH(),dH(),NH=`[gjsify ship]`,PH={command:`ship [os]`,description:`Build installable artifacts (${VV.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${wB.join(`|`)}, ADR 0024 § A2). Default: this host. Assembly is not host-bound, so any of them can be staged anywhere.`}).option(`target`,{type:`string`,array:!0,description:`Formats to build, comma-separated or repeated. Default: every format wrapping the target OS's layout that needs no extra tooling — on linux, ${defaultFormatIds(`linux`).join(`,`)}. Also available for linux, and opt-in because it needs tooling this CLI does not carry: ${formatIdsFor(`linux`).filter(t=>!defaultFormatIds(`linux`).includes(t)).join(`, `)}.`}).option(`out`,{type:`string`,normalize:!0,description:"Output root, relative to the project. Default: `gjsify.ship.outDir`, else `ship`."}).option(`stage`,{type:`boolean`,default:!1,description:`Produce the staged payload and stop, without packing anything.`}).option(`from-stage`,{type:`string`,normalize:!0,description:"Pack a staged payload written by an earlier `--stage` run. Needs no project: the stage carries its own closure."}).option(`expect-target`,{type:`string`,description:"With --from-stage: refuse unless the stage was assembled for this `<os>-<arch>`, e.g. `linux-arm64`."}).option(`skip-build`,{type:`boolean`,default:!1,description:"Package what is already built instead of running the project's `build` script."}).option(`arch`,{type:`string`,description:"Target architecture in `process.arch` spelling. Default: this host."}).option(`sign`,{type:`string`,requiresArg:!0,description:"Sign the payload with this identity, e.g. a Developer ID name or SHA-1 fingerprint. `-` signs ad-hoc and needs no developer identity. Default: `gjsify.ship.sign.<darwin|win32>.identity`; absent means unsigned, which is a legitimate output."}).option(`notarize`,{type:`string`,requiresArg:!0,description:"Submit the signed artifact to Apple with this `notarytool` keychain profile. Needs --sign; darwin only."}).option(`verbose`,{type:`boolean`,default:!1,description:`Print each staged file, the GI namespaces the bundle imports, and every tool a host-bound packer invokes.`}),handler:async t=>{if(t[`from-stage`]!==void 0)return await finishFromStage(t,t[`from-stage`]);await assemble(t)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var IH=__esmMin(()=>{t_()});function workspaceLinkTarget(t,n){return LH===`junction`?vn(n):Sn(wn(t),n)}function applyPlatformConfigFromFlags(t){for(let[n,S]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let C=t[n];if(typeof C!=`string`)continue;let N=C.trim();N!==``&&(process.env[S]=N)}t.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(t){if(!t||typeof t!=`object`)return!1;let n=t.name;if(n===`AbortError`)return!0;let S=t.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||n===`RegistryTimeoutError`)}function readCliVersionFrom(t){try{if(!existsSync(t))return null;let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===BH&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=wn(vn(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==wn(t);n++){let n=readCliVersionFrom(xn(t,`package.json`));if(n)return n;t=wn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(xn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[BH];typeof C==`string`&&(S=!0);let N=typeof C==`string`?/^[\^~=v]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(C.trim()):null;if(N)return N[1]}if(!S){let n=readCliVersionFrom(xn(t,`node_modules`,BH,`package.json`));if(n)return n}return readCliVersionFrom(xn(t,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(t){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let n=readRunningCliVersion(),S=readWorkspaceCliVersion(t);!n||!S||n===S||ge.warn(`gjsify install: version skew — you are running @gjsify/cli v${n}, but this workspace pins v${S}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(t){let n=readPackageJson$1(xn(t,`package.json`));return n?n.workspaces!==void 0:!1}function optionalDependencyNames(t){let n=new Set,S=new Set;for(let C of t){let t=new Set(Object.keys(C.optionalDependencies??{}));for(let S of t)n.add(S);for(let n of[`dependencies`,`devDependencies`])for(let N of Object.keys(C[n]??{}))t.has(N)||S.add(N)}for(let t of S)n.delete(t);return n}function depKindFromArgs(t){return t[`save-dev`]?`devDependencies`:t[`save-peer`]?`peerDependencies`:t[`save-optional`]?`optionalDependencies`:`dependencies`}function activateDevLinks(t,n){let S=prepareDevLinks(devLinkRoot(t));if(!S)return null;let C=applyDevLinks(S.links);if(!n)return S;ge.log(`gjsify install: development link ACTIVE (${S.overridePath}) — ${S.links.length} package(s) come from ${S.checkout}, linked rather than fetched (${C.length} (re)written, ${S.links.length-C.length} already current):`);let N=S.links.map(t=>t.name),F=N.slice(0,12);return ge.log(` ${F.join(`, `)}${N.length>F.length?`, +${N.length-F.length} more`:``}`),ge.log(" `gjsify unlink` restores the registry copies; `gjsify install --immutable` refuses while it exists."),S}function reportRewiredDevLinks(t){if(!t)return;let n=applyDevLinks(t.links);n.length!==0&&ge.log(`gjsify install: re-applied ${n.length} development link(s) the install had replaced: ${n.map(t=>t.name).join(`, `)}`)}async function projectInstallNative(t,n){let S=process.cwd(),C=xn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(xn(S,t)));if(N.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${N.join(`, `)} in ${S}).\n\n• If this project uses \`gjsify install\` to manage dependencies, these PnP files are stale residue from an earlier \`yarn install\` — remove them and re-run:\n rm -f .pnp.cjs .pnp.loader.mjs && rm -rf .yarn/cache .yarn/unplugged\n gjsify install\n\n• If instead you want Yarn to manage dependencies, set \`nodeLinker: node-modules\` in .yarnrc.yml and run \`yarn install\` (not \`gjsify install\`).`);if(!t.packages||t.packages.length===0){let C=isWorkspaceRoot(S)?S:findWorkspaceRoot(S);if(C){C!==S&&ge.log(`gjsify install: resolved workspace root ${C} (from ${S}); installing the workspace.`),await workspaceInstall(C,t,n);return}}let F,I=readPackageJson$1(C),H=I?projectSpecsFromPackageJson(I):[];if(t.packages&&t.packages.length>0){let n=new Set(t.packages.map(t=>parseSpec$2(t).name));F=[...H.filter(t=>!n.has(parseSpec$2(t).name)),...t.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ge.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!t.verbose&&!t.quiet&&t.progress!==!1}),q=await acquireInstallLock(S,{signal:n});try{let N=activateDevLinks(S,!0),H=await installPackages({prefix:S,specs:F,verbose:t.verbose,lockfile:!t.immutable,frozen:t.immutable,refreshLockfile:t[`refresh-lockfile`],signal:n,progress:W,optionalSpecs:new Set([...optionalDependencyNames(I?[I]:[]),...t[`save-optional`]?(t.packages??[]).map(t=>parseSpec$2(t).name):[]]),linkedNames:N?.names});if(reportRewiredDevLinks(N),t.packages&&t.packages.length>0&&I){let n=depKindFromArgs(t);for(let S of t.packages){let{name:t,range:C}=parseSpec$2(S),N=H.installed.find(n=>n.name===t);addDependencyEntry(I,t,C??(N?defaultRangeFromVersion(N.version):`latest`),n)}writePackageJson(C,I),t.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}finally{q.release()}}function syncLockfileRequested(t,n){let S=xn(t,`gjsify-lock.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`)),C=[...n].sort(),N=[...t.requested??[]].sort();if(C.length===N.length&&C.every((t,n)=>t===N[n]))return;t.requested=n,atomicWriteStrict(S,JSON.stringify(t,null,2)+`
1166
1166
  `)}catch{}}async function workspaceInstall(t,n,S){let C=await acquireInstallLock(t,{signal:S});try{await workspaceInstallLocked(t,n,S)}finally{C.release()}}async function workspaceInstallLocked(t,n,S){let C=discoverWorkspaces(t,{includeRoot:!0});if(C.length===0)throw Error(`gjsify install: ${t} has a "workspaces" field but no workspaces were discovered`);let N=new Map(C.map(t=>[t.name,t])),F=n.focus&&n.focus.length>0?planFocus(C,n.focus,`gjsify install`):void 0,I=F?new Set(F.workspaces):void 0,H=new Set,W=new Map,q=[];for(let t of C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){if(typeof S!=`string`)continue;let C=N.get(n);if(C&&!/^(link|file|portal|git\+|https?):/.test(S)){if(I&&!I.has(t))continue;q.push({fromWorkspaceName:t.name,depName:n,targetLocation:C.location});continue}if(S.startsWith(`workspace:`))throw Error(`gjsify install: ${t.name} declares "${n}: ${S}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(S))continue;let F=`${n}@${S}`;H.add(F);let Y=W.get(F);Y||(Y=new Set,W.set(F,Y)),Y.add(t.name)}}}ge.log(`gjsify install: ${C.length} workspace(s), ${H.size} external dep spec(s), ${q.length} workspace symlink(s)`);let Y=activateDevLinks(t,!0);writeWorkspaceBinShims(t,F?.workspaces??C);let wireWorkspaceSymlinks=async()=>{if(q.length>0){let t=await Promise.resolve().then(()=>(hd(),fd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=xn(C.location,`node_modules`,t.depName);n.add(wn(F));let I=workspaceLinkTarget(F,t.targetLocation);S.push({linkPath:F,relTarget:I})}await Promise.all([...n].map(n=>t.mkdir(n,{recursive:!0})));let C=0,F=[],wireOne=async(n,S)=>{try{await t.rm(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await t.symlink(S,n,LH)};for(let t=0;t<Math.min(32,S.length);t++)F.push((async()=>{for(;;){let t=C++;if(t>=S.length)return;let n=S[t];if(!n)return;await wireOne(n.linkPath,n.relTarget)}})());await Promise.all(F),ge.log(`gjsify install: wired ${q.length} workspace symlink(s)`)}let n=xn(t,`node_modules`),S=0;for(let N of F?.workspaces??C){if(N.location===t||!N.name)continue;let C=xn(n,N.name),F=!1;try{lstatSync(C),F=!0}catch{}F||(mkdirSync(wn(C),{recursive:!0}),symlinkSync(workspaceLinkTarget(C,N.location),C,LH),S++)}S>0&&ge.log(`gjsify install: hoisted ${S} workspace(s) to root node_modules/`)};await wireWorkspaceSymlinks();let X=C.find(n=>n.location===t)?.manifest,Z=extractOverrides(X),te=Z?.global,ne=new Map,re=new Set;if(Z&&Z.scoped.size>0){for(let t of F?.workspaces??C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){let C=scopedOverrideFor(t,n,Z);if(!C)continue;let N=C,F=t.location,I=ne.get(F);I||(I=new Set,ne.set(F,I)),I.add(`${n}@${N}`),re.add(`${n}@${S}`)}}}let t=new Set;for(let n of C)for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n.manifest[S];if(C)for(let[S,N]of Object.entries(C))scopedOverrideFor(n,S,Z)||t.add(`${S}@${N}`)}for(let n of re)t.has(n)||H.delete(n);ne.size>0&&ge.log(`gjsify install: ${ne.size} workspace(s) have scoped overrides — they will install their overridden deps locally after the root install`)}if(H.size>0){let I=makeProgressReporter({enabled:!n.verbose&&!n.quiet&&n.progress!==!1});await installPackages({prefix:t,specs:[...H],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,refreshLockfile:n[`refresh-lockfile`],overrides:te,signal:S,progress:I,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,specOrigins:new Map([...W].map(([t,n])=>[t,[...n]])),optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest)),focusSpecs:F?.specs})}else n.verbose&&ge.log(`gjsify install: no external deps to fetch`);for(let[t,F]of ne){if(F.size===0)continue;let I=C.find(n=>n.location===t)?.name??t;n.verbose&&ge.log(`gjsify install: ${I} — installing ${F.size} scoped-override spec(s) into ${t}/node_modules/`),await installPackages({prefix:t,specs:[...F],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,signal:S,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest))})}await wireWorkspaceSymlinks(),reportRewiredDevLinks(Y);let ie=writeWorkspaceBinShims(t,F?.workspaces??C);ie>0&&ge.log(`gjsify install: linked ${ie} workspace bin(s) into node_modules/.bin/`)}function writeWorkspaceBinShims(t,n){let S=xn(t,`node_modules`,`.bin`),C=detectNativePackages(t).map(t=>t.prebuildsDir),N=0;for(let F of n){let n=F.manifest,I=n.gjsify?.bin,H=n.bin,W=mergeWorkspaceBins(F.name,I,H);if(W.size!==0){mkdirSync(S,{recursive:!0});for(let[n,{nodeTarget:I,gjsTarget:H}]of W){let W=xn(S,n);for(let t of[W,`${W}.cmd`,`${W}.ps1`])try{rmSync(t,{force:!0,maxRetries:10,retryDelay:100})}catch{}if(writeFileSync(W,buildBinShim(F.location,I,H,C,process.platform,t),{mode:493}),chmodSync(W,493),process.platform===`win32`)for(let[t,n]of Object.entries(buildWorkspaceBinShimsForWindows(F.location,I,H,C)))writeFileSync(`${W}.${t}`,n,{mode:493});N++}}}return N}function extractOverrides(t){if(!t)return;let n={},S=new Map,merge=(t,C)=>{if(t){for(let[N,F]of Object.entries(t))if(!N.startsWith(`_`)){if(typeof F==`string`){let t=N,S=N.startsWith(`@`)?N.indexOf(`@`,1):N.indexOf(`@`);S>0&&(t=N.slice(0,S)),n[t]=F;continue}if(F&&typeof F==`object`&&!Array.isArray(F)){let t={};for(let[n,S]of Object.entries(F)){if(n.startsWith(`_`))continue;if(typeof S!=`string`){ge.warn(`gjsify install: ${C}["${N}"]["${n}"] is not a string — only one level of nesting is supported, skipping`);continue}let F=n,I=n.startsWith(`@`)?n.indexOf(`@`,1):n.indexOf(`@`);I>0&&(F=n.slice(0,I)),t[F]=S}if(Object.keys(t).length>0){let n=S.get(N)??{};S.set(N,{...n,...t})}continue}ge.warn(`gjsify install: ${C}["${N}"] is not a string or object — skipping`)}}};if(merge(t.overrides,`overrides`),merge(t.resolutions,`resolutions`),!(Object.keys(n).length===0&&S.size===0))return{global:n,scoped:S}}function scopedOverrideFor(t,n,S){if(!S||S.scoped.size===0)return;let C=[t.name,t.relativeLocation];for(let t of C){let C=S.scoped.get(t);if(C?.[n])return C[n]}}function buildBinShim(t,n,S,C=[],N=process.platform,F=t){let I=n?xn(t,n):null,H=S?xn(t,S):null,W=buildNativeEnvPreamble(F,C,{platform:N});if(I&&H){let t=N===`darwin`||N===`win32`,n=`if command -v gjs >/dev/null 2>&1 && [ -f "${H}" ]; then\n${W}exec gjs -m "${H}" "$@"\nfi\nexec node "${I}" "$@"\n`,S=`if command -v node >/dev/null 2>&1 && [ -f "${I}" ]; then\nexec node "${I}" "$@"\nfi\n${W}exec gjs -m "${H}" "$@"\n`;return`#!/bin/sh
1167
1167
  `+(t?S:n)}if(I)return`#!/bin/sh\nexec node "${I}" "$@"\n`;if(H)return`#!/bin/sh\n${W}exec gjs -m "${H}" "$@"\n`;throw Error(`buildBinShim: either nodeTarget or gjsTarget must be provided`)}function buildWorkspaceBinShimsForWindows(t,n,S,C=[]){let N=n?xn(t,n):null,F=S?xn(t,S):null;if(N)return buildLauncherShims({interpreter:`node`,target:N});if(F){let t=C.join(`;`);return buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:F,prependEnv:C.length===0?{}:{GI_TYPELIB_PATH:t,PATH:t}})}throw Error(`buildWorkspaceBinShimsForWindows: either nodeTarget or gjsTarget must be provided`)}function mergeWorkspaceBins(t,n,S){let C=new Map,N=t.startsWith(`@`)?t.slice(t.indexOf(`/`)+1):t,get=t=>{let n=C.get(t);return n||(n={},C.set(t,n)),n};if(typeof S==`string`)get(N).nodeTarget=S;else if(S&&typeof S==`object`)for(let[t,n]of Object.entries(S))typeof n==`string`&&n.length>0&&(get(t).nodeTarget=n);if(typeof n==`string`)get(N).gjsTarget=n;else if(n&&typeof n==`object`)for(let[t,S]of Object.entries(n))typeof S==`string`&&S.length>0&&(get(t).gjsTarget=S);return C}async function projectInstallViaNpm(t){let n=[`install`];t[`save-dev`]&&n.push(`--save-dev`),t[`save-peer`]&&n.push(`--save-peer`),t[`save-optional`]&&n.push(`--save-optional`),t.verbose&&n.push(`--loglevel`,`verbose`),t.packages&&t.packages.length>0&&n.push(...t.packages),await spawnNpm(n)}async function spawnNpm(t){return spawnToCompletion(`npm`,t,{completion:`return`,notFound:()=>Error(`npm not found on PATH — install Node.js first.`)}).then(({code:t})=>{if(t!==0)throw Error(`npm install exited with code ${t}`)}).catch(t=>{let n=t.code;ge.error(n===void 0?t.message:`npm install failed: ${t.message}`),process.exit(1)})}async function installGlobalAndLink(t,n){let S=defaultGlobalLayout();mkdirSync(S.prefix,{recursive:!0}),ge.log(`gjsify install --global → ${S.prefix}`),ge.log(` bins → ${S.binDir}`);let C=await acquireInstallLock(S.prefix,{});try{let C=await installPackages({prefix:S.prefix,specs:t,verbose:n.verbose}),N=t.map(specToPackageName);if(N.includes(`@gjsify/cli`)){let t=C.installed.find(t=>t.name===`@gjsify/cli`)?.version??`latest`;await installGjsEnginePackages(S.prefix,t,{verbose:n.verbose})}n.prune!==!1&&pruneAfterInstall(S.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`}),reportLinkedBins(linkGlobalBins(N,S),S.binDir)}finally{C.release()}}function pruneProjectPrefix(t){t.prune!==!1&&pruneAfterInstall(process.cwd(),resolveHostPlatform({env:{}}),{immutable:t.immutable===!0,hint:`gjsify prune --dry-run`})}function reportLinkedBins(t,n){if(t.length===0)ge.warn("\nNo bins declared (neither `gjsify.bin` nor `bin` in package.json) — nothing was symlinked.");else{ge.log(`\nLinked ${t.length} bin(s):`);for(let n of t)ge.log(` • ${n.link} → ${n.target}`)}t.length>0&&!binDirOnPath(n)&&ge.warn(`\nNote: ${n} is not on your PATH.\nAdd it to your shell rc file:\n export PATH="${n}:$PATH"`)}async function ensureProjectGjsEngine(t,n,S={}){let C=S.cwd??process.cwd(),N=S.hasEngineFn??hasBundlerEngineInstalled;if(!existsSync(xn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))||!n||N(C))return;if(t.immutable){ge.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${TL} is not installed, and\n --immutable cannot add it (the lockfile does not name it). Declare it so the lockfile carries it:
1168
1168
  gjsify install ${TL}\n Under Node the npm \`rolldown\` engine is used instead and this does not apply.`);return}let F=readCliVersionFrom(xn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))??`latest`;ge.log(`\n${TL} is missing and this host can run gjs, so \`gjsify build\` would have no\n bundler engine (there is no npm \`rolldown\` fallback under GJS). Installing the GJS engine set at\n ${F}, in lockstep with the CLI.`),await(S.installFn??installGjsEnginePackages)(C,F,{verbose:t.verbose})}async function runPostInstallChecks(t){ge.log(`
@@ -1175,13 +1175,13 @@ A misplaced catalogue installs and then shows nothing, which reads exactly like
1175
1175
  A bridge lost that way is silently absent from the next build rather than
1176
1176
  reported, so the first symptom can be an unrelated-looking bundler error
1177
1177
  (\`Could not load <file>\` from rolldown, for the CSS bridge). Nothing to
1178
- install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=xn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(xn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var LH,RH,zH,BH,VH=__esmMin(()=>{_e(),Md(),jn(),Hn(),w_(),IH(),DP(),qP(),QP(),uI(),CL(),LI(),JI(),bI(),j_(),kP(),oz(),DL(),cL(),uL(),EI(),pL(),LH=process.platform===`win32`?`junction`:void 0,RH=18e5,zH={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:t=>t.positional(`packages`,{description:`Optional package specs. With none, runs a full project install.`,type:`string`,array:!0}).option(`global`,{description:`Install into the user-global XDG location and symlink bins into ~/.local/bin.`,type:`boolean`,alias:`g`,default:!1}).option(`save-dev`,{type:`boolean`,alias:`D`}).option(`save-peer`,{type:`boolean`}).option(`save-optional`,{type:`boolean`,alias:`O`}).option(`immutable`,{description:`CI mode: install strictly from gjsify-lock.json, fail if the lockfile is missing or stale. Equivalent to yarn --immutable / npm ci --frozen-lockfile.`,type:`boolean`,default:!1}).option(`refresh-lockfile`,{description:`Re-resolve every dependency to the newest version satisfying its range and rewrite the lockfile (bumps in-range transitive deps). Without it, a resolve preserves versions already pinned in the lockfile and only resolves new/changed deps — the npm/yarn/pnpm default. Mirrors yarn install --mode=update-lockfile.`,type:`boolean`,default:!1}).option(`focus`,{description:`Install only the named workspaces (package names), the workspaces they depend on, and their external dependencies, as if they were the only members of the monorepo (yarn workspaces focus). Reads gjsify-lock.json and never rewrites it; fails if it is missing or stale. Workspace projects only.`,type:`string`,array:!0}).option(`verbose`,{description:`Verbose install logging.`,type:`boolean`,default:!1}).option(`quiet`,{description:`Silence the progress bar.`,type:`boolean`,default:!1}).option(`progress`,{description:`Show a TTY-aware progress bar for resolve / download / extract phases. Auto-enabled when stderr is a TTY (override with --no-progress). Implicitly off under --verbose (per-package log lines replace the bar) or --quiet.`,type:`boolean`,default:!0}).option(`backend`,{description:"Install backend. `native` (default) routes through `@gjsify/{semver,npm-registry,tar}` — no Node/npm at runtime. `npm` shells out to `npm install` as an escape hatch for cases the native backend does not yet model (Yarn PnP repos, lifecycle scripts). Overrides `GJSIFY_INSTALL_BACKEND` if both are set.",type:`string`,choices:[`native`,`npm`]}).option(`timeout`,{description:`Overall install wall-clock timeout in ms (default 1800000 = 30 min). On timeout, all in-flight registry fetches are aborted and the install exits non-zero with a clear "install timed out — likely a registry slowdown" message. Per-request timeouts in @gjsify/npm-registry (default 30s) still apply within this budget. Set to 0 to disable the overall budget.`,type:`number`,default:RH}).option(`os`,{description:"Resolve/install for this OS instead of the running one (npm config key `os`, e.g. darwin, win32, linux). Affects which packages pass the os/cpu/libc compatibility check; the lockfile stays platform-independent either way.",type:`string`}).option(`cpu`,{description:"Resolve/install for this CPU architecture instead of the running one (npm config key `cpu`, e.g. x64, arm64).",type:`string`}).option(`libc`,{description:"Resolve/install for this libc family instead of probing the host (npm config key `libc`: glibc or musl). Only meaningful with --os=linux. A package declaring a libc is incompatible when the target libc is unknown.",type:`string`}).option(`force`,{description:"Install a REQUIRED dependency even when its os/cpu/libc excludes the target, instead of failing with EBADPLATFORM (npm config key `force`). Incompatible OPTIONAL dependencies stay skipped — npm ignores --force for those too, and a binary that cannot load is not worth downloading.",type:`boolean`,default:!1}).option(`prune`,{description:`After installing, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable. Skipped automatically under --immutable, and whenever --os/--cpu/--libc is given: an install must never delete against a target the user typed.`,type:`boolean`,default:!0}),handler:async t=>{if(applyPlatformConfigFromFlags(t),t.immutable){if(t.packages&&t.packages.length>0)return ge.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(t.global)return ge.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(t[`refresh-lockfile`])return ge.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1);assertNoDevLinkUnderImmutable(process.cwd())}if(t.global){if(!t.packages||t.packages.length===0)return ge.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let n of[`save-dev`,`save-peer`,`save-optional`])t[n]&&ge.warn(`gjsify install --global ignores --${n}: global installs do not modify a project package.json.`);await installGlobalAndLink(t.packages,{verbose:t.verbose,prune:t.prune});return}if(warnOnCliVersionSkew(process.cwd()),(t.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(t),pruneProjectPrefix(t),await runPostInstallChecks(t);return}let n=t.timeout>0?t.timeout:0,S=n>0?new AbortController:null,C=S===null?null:setTimeout(()=>S.abort(Error(`install-overall-timeout`)),n),N=n>0?setTimeout(()=>{let t=Math.round(n/100)/10;ge.error(`gjsify install: the ${t}s budget elapsed and the abort did not unwind within 10s — forcing exit. That means one of two things, and this timer cannot distinguish them: the install was still WORKING (a cold tree here extracts several GB, and extraction blocks the loop in multi-second synchronous stretches), or a step genuinely wedged. Re-running tells you which, and is safe: extraction is idempotent, every package already on disk is skipped, so a second run finishes the remainder in a fraction of the time. A re-run that makes NO further progress is a real wedge — file an issue.`),forceExit(1)},n+1e4):null;N?.unref?.();try{await projectInstallNative(t,S?.signal),pruneProjectPrefix(t),await runPostInstallChecks(t)}catch(t){if(S!==null&&S.signal.aborted&&isAbortedFromOverallTimeout(t)){let t=Math.round(n/100)/10;return ge.error(`gjsify install: timed out after ${t}s — likely a registry slowdown or a wedged extract.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw t}finally{C!==null&&clearTimeout(C),N!==null&&clearTimeout(N)}}},BH=`@gjsify/cli`});function sweepCheckouts(t,n){let S=null;try{S=readDevLinkOverride(t)?.checkout??null}catch{S=null}return S&&S!==n?[S,n]:[n]}var HH,UH,WH=__esmMin(()=>{_e(),Md(),jn(),pL(),HH={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually depends on are ever linked.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=vn(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} depends on${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Sn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H);writeDevLinkOverride(n,{version:1,checkout:C,packages:I});let re=ensureLocallyIgnored(n);ge.log(`\n ${ne.length} link(s) written, ${H.length-ne.length} already current.`),Z.length>0&&ge.log(` ${te.length} of ${Z.length} retired link(s) removed.`),ge.log(` override: ${N}`),re===`added`&&ge.log(` git: ${dL} added to .git/info/exclude (local, never committed)`),re===`no-git`&&ge.log(` git: ${n} is not a git repository — nothing to ignore`),re===`unreadable-git`&&ge.warn(` ! git: ${n} has a .git POINTER that does not parse, so ${dL} is NOT ignored. Add it to .gitignore by hand, or the next \`git add -A\` commits your local override.`),ge.log("\nEvery `gjsify install` here now re-applies these links and says so.\n`gjsify install --immutable` refuses while the override exists. Undo: `gjsify unlink`.")}},UH={command:`unlink`,description:"Undo `gjsify link`: remove the development links and the .gjsify-link.json override, then reinstall the registry copies.",builder:t=>t.option(`dry-run`,{description:`Print what would be removed and change nothing.`,type:`boolean`,default:!1}).option(`install`,{description:"Reinstall after unlinking, to put the registry copies back where the links were. On by default; --no-install leaves the holes for a later `gjsify install`.",type:`boolean`,default:!0}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=devLinkPath(n);if(!existsSync(C)){ge.log(`gjsify unlink: no development link in ${n} (no ${dL}).`);return}let N=[];try{let t=readDevLinkOverride(n)?.checkout;t&&N.push(t)}catch{}let F=[];try{F=prepareDevLinks(n)?.links??[]}catch(t){ge.warn(`gjsify unlink: ${t instanceof Error?t.message:String(t)}\n Removing the override anyway; any dangling links are cleaned by the reinstall.`)}let I=`gjsify unlink${S?` (dry-run)`:``}`;if(ge.log(`${I} in ${n}`),S){let t=new Set(F.map(t=>t.name));for(let S of scanDevLinks(n,N))t.add(S.name);for(let n of[...t].sort())ge.log(` would remove link ${n}`);ge.log(` would remove ${C}`),ge.log(` would remove ${dL} entry from .git/info/exclude (if this module wrote it)`),ge.log(`\n${I}: nothing changed. Drop --dry-run to apply.`);return}let H=removeDevLinks(F),W=new Set(H.map(t=>t.name));for(let t of retireDevLinks(n,N,new Set))W.has(t.name)||H.push(t);for(let t of H)ge.log(` unlinked ${t.name}`);let q=scanDevLinks(n,N);if(q.length>0)return ge.error(`gjsify unlink: ${q.length} link(s) still point into a checkout and could not be removed:\n`+q.map(t=>` ${t.name} ${t.linkPath} → ${t.target}`).join(`
1178
+ install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=xn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(xn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var LH,RH,zH,BH,VH=__esmMin(()=>{_e(),Md(),jn(),Hn(),w_(),IH(),DP(),qP(),QP(),uI(),CL(),OI(),JI(),bI(),j_(),kP(),oz(),DL(),cL(),uL(),EI(),pL(),LH=process.platform===`win32`?`junction`:void 0,RH=18e5,zH={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:t=>t.positional(`packages`,{description:`Optional package specs. With none, runs a full project install.`,type:`string`,array:!0}).option(`global`,{description:`Install into the user-global XDG location and symlink bins into ~/.local/bin.`,type:`boolean`,alias:`g`,default:!1}).option(`save-dev`,{type:`boolean`,alias:`D`}).option(`save-peer`,{type:`boolean`}).option(`save-optional`,{type:`boolean`,alias:`O`}).option(`immutable`,{description:`CI mode: install strictly from gjsify-lock.json, fail if the lockfile is missing or stale. Equivalent to yarn --immutable / npm ci --frozen-lockfile.`,type:`boolean`,default:!1}).option(`refresh-lockfile`,{description:`Re-resolve every dependency to the newest version satisfying its range and rewrite the lockfile (bumps in-range transitive deps). Without it, a resolve preserves versions already pinned in the lockfile and only resolves new/changed deps — the npm/yarn/pnpm default. Mirrors yarn install --mode=update-lockfile.`,type:`boolean`,default:!1}).option(`focus`,{description:`Install only the named workspaces (package names), the workspaces they depend on, and their external dependencies, as if they were the only members of the monorepo (yarn workspaces focus). Reads gjsify-lock.json and never rewrites it; fails if it is missing or stale. Workspace projects only.`,type:`string`,array:!0}).option(`verbose`,{description:`Verbose install logging.`,type:`boolean`,default:!1}).option(`quiet`,{description:`Silence the progress bar.`,type:`boolean`,default:!1}).option(`progress`,{description:`Show a TTY-aware progress bar for resolve / download / extract phases. Auto-enabled when stderr is a TTY (override with --no-progress). Implicitly off under --verbose (per-package log lines replace the bar) or --quiet.`,type:`boolean`,default:!0}).option(`backend`,{description:"Install backend. `native` (default) routes through `@gjsify/{semver,npm-registry,tar}` — no Node/npm at runtime. `npm` shells out to `npm install` as an escape hatch for cases the native backend does not yet model (Yarn PnP repos, lifecycle scripts). Overrides `GJSIFY_INSTALL_BACKEND` if both are set.",type:`string`,choices:[`native`,`npm`]}).option(`timeout`,{description:`Overall install wall-clock timeout in ms (default 1800000 = 30 min). On timeout, all in-flight registry fetches are aborted and the install exits non-zero with a clear "install timed out — likely a registry slowdown" message. Per-request timeouts in @gjsify/npm-registry (default 30s) still apply within this budget. Set to 0 to disable the overall budget.`,type:`number`,default:RH}).option(`os`,{description:"Resolve/install for this OS instead of the running one (npm config key `os`, e.g. darwin, win32, linux). Affects which packages pass the os/cpu/libc compatibility check; the lockfile stays platform-independent either way.",type:`string`}).option(`cpu`,{description:"Resolve/install for this CPU architecture instead of the running one (npm config key `cpu`, e.g. x64, arm64).",type:`string`}).option(`libc`,{description:"Resolve/install for this libc family instead of probing the host (npm config key `libc`: glibc or musl). Only meaningful with --os=linux. A package declaring a libc is incompatible when the target libc is unknown.",type:`string`}).option(`force`,{description:"Install a REQUIRED dependency even when its os/cpu/libc excludes the target, instead of failing with EBADPLATFORM (npm config key `force`). Incompatible OPTIONAL dependencies stay skipped — npm ignores --force for those too, and a binary that cannot load is not worth downloading.",type:`boolean`,default:!1}).option(`prune`,{description:`After installing, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable. Skipped automatically under --immutable, and whenever --os/--cpu/--libc is given: an install must never delete against a target the user typed.`,type:`boolean`,default:!0}),handler:async t=>{if(applyPlatformConfigFromFlags(t),t.immutable){if(t.packages&&t.packages.length>0)return ge.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(t.global)return ge.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(t[`refresh-lockfile`])return ge.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1);assertNoDevLinkUnderImmutable(process.cwd())}if(t.global){if(!t.packages||t.packages.length===0)return ge.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let n of[`save-dev`,`save-peer`,`save-optional`])t[n]&&ge.warn(`gjsify install --global ignores --${n}: global installs do not modify a project package.json.`);await installGlobalAndLink(t.packages,{verbose:t.verbose,prune:t.prune});return}if(warnOnCliVersionSkew(process.cwd()),(t.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(t),pruneProjectPrefix(t),await runPostInstallChecks(t);return}let n=t.timeout>0?t.timeout:0,S=n>0?new AbortController:null,C=S===null?null:setTimeout(()=>S.abort(Error(`install-overall-timeout`)),n),N=n>0?setTimeout(()=>{let t=Math.round(n/100)/10;ge.error(`gjsify install: the ${t}s budget elapsed and the abort did not unwind within 10s — forcing exit. That means one of two things, and this timer cannot distinguish them: the install was still WORKING (a cold tree here extracts several GB, and extraction blocks the loop in multi-second synchronous stretches), or a step genuinely wedged. Re-running tells you which, and is safe: extraction is idempotent, every package already on disk is skipped, so a second run finishes the remainder in a fraction of the time. A re-run that makes NO further progress is a real wedge — file an issue.`),forceExit(1)},n+1e4):null;N?.unref?.();try{await projectInstallNative(t,S?.signal),pruneProjectPrefix(t),await runPostInstallChecks(t)}catch(t){if(S!==null&&S.signal.aborted&&isAbortedFromOverallTimeout(t)){let t=Math.round(n/100)/10;return ge.error(`gjsify install: timed out after ${t}s — likely a registry slowdown or a wedged extract.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw t}finally{C!==null&&clearTimeout(C),N!==null&&clearTimeout(N)}}},BH=`@gjsify/cli`});function sweepCheckouts(t,n){let S=null;try{S=readDevLinkOverride(t)?.checkout??null}catch{S=null}return S&&S!==n?[S,n]:[n]}var HH,UH,WH=__esmMin(()=>{_e(),Md(),jn(),pL(),HH={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually depends on are ever linked.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=vn(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} depends on${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Sn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H);writeDevLinkOverride(n,{version:1,checkout:C,packages:I});let re=ensureLocallyIgnored(n);ge.log(`\n ${ne.length} link(s) written, ${H.length-ne.length} already current.`),Z.length>0&&ge.log(` ${te.length} of ${Z.length} retired link(s) removed.`),ge.log(` override: ${N}`),re===`added`&&ge.log(` git: ${dL} added to .git/info/exclude (local, never committed)`),re===`no-git`&&ge.log(` git: ${n} is not a git repository — nothing to ignore`),re===`unreadable-git`&&ge.warn(` ! git: ${n} has a .git POINTER that does not parse, so ${dL} is NOT ignored. Add it to .gitignore by hand, or the next \`git add -A\` commits your local override.`),ge.log("\nEvery `gjsify install` here now re-applies these links and says so.\n`gjsify install --immutable` refuses while the override exists. Undo: `gjsify unlink`.")}},UH={command:`unlink`,description:"Undo `gjsify link`: remove the development links and the .gjsify-link.json override, then reinstall the registry copies.",builder:t=>t.option(`dry-run`,{description:`Print what would be removed and change nothing.`,type:`boolean`,default:!1}).option(`install`,{description:"Reinstall after unlinking, to put the registry copies back where the links were. On by default; --no-install leaves the holes for a later `gjsify install`.",type:`boolean`,default:!0}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=devLinkPath(n);if(!existsSync(C)){ge.log(`gjsify unlink: no development link in ${n} (no ${dL}).`);return}let N=[];try{let t=readDevLinkOverride(n)?.checkout;t&&N.push(t)}catch{}let F=[];try{F=prepareDevLinks(n)?.links??[]}catch(t){ge.warn(`gjsify unlink: ${t instanceof Error?t.message:String(t)}\n Removing the override anyway; any dangling links are cleaned by the reinstall.`)}let I=`gjsify unlink${S?` (dry-run)`:``}`;if(ge.log(`${I} in ${n}`),S){let t=new Set(F.map(t=>t.name));for(let S of scanDevLinks(n,N))t.add(S.name);for(let n of[...t].sort())ge.log(` would remove link ${n}`);ge.log(` would remove ${C}`),ge.log(` would remove ${dL} entry from .git/info/exclude (if this module wrote it)`),ge.log(`\n${I}: nothing changed. Drop --dry-run to apply.`);return}let H=removeDevLinks(F),W=new Set(H.map(t=>t.name));for(let t of retireDevLinks(n,N,new Set))W.has(t.name)||H.push(t);for(let t of H)ge.log(` unlinked ${t.name}`);let q=scanDevLinks(n,N);if(q.length>0)return ge.error(`gjsify unlink: ${q.length} link(s) still point into a checkout and could not be removed:\n`+q.map(t=>` ${t.name} ${t.linkPath} → ${t.target}`).join(`
1179
1179
  `)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${dL} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${H.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${H.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:Y}=await Promise.resolve().then(()=>(KG(),GG));await Y([`install`])}}});function signalTree(t,n,S){for(let t=n.length-1;t>=0;t--)try{process.kill(n[t],S)}catch{}try{t.kill(S)}catch{}}function killActiveChildren(){let t=new Map;for(let n of GH){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of GH){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},KH).unref?.()}function assertEveryIncludeMatches(t,n){if(!n||n.length===0)return;let S=n.filter(n=>filterWorkspaces(t,{include:[n]}).length===0);if(S.length===0)return;let C=[`gjsify foreach: --include matched no workspace (${S.length} of ${n.length} pattern(s)):`];for(let n of S){C.push(` ${JSON.stringify(n)}`);let S=stripSurroundingQuotes(n);if(S!==n&&filterWorkspaces(t,{include:[S]}).length>0){C.push(` → matches as ${JSON.stringify(S)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let N=t.map(t=>t.name).filter(t=>t.toLowerCase().includes(S.replace(/\*/g,``).toLowerCase())).slice(0,3);N.length>0&&C.push(` → did you mean: ${N.join(`, `)}?`)}throw C.push(` ${t.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ge.error(C.join(`
1180
1180
  `)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(t){return t.length>=2&&(t[0]===`'`||t[0]===`"`)&&t[t.length-1]===t[0]?t.slice(1,-1):t}async function runSequential(t,n,S,C,N,F){for(let I of t)await runOne(I,n,S,!1,C,N,F)}async function runParallel(t,n,S,C,N,F,I){let H=0,W=[];for(let q=0;q<C;q++)W.push((async()=>{for(;H<t.length;)await runOne(t[H++],n,S,!0,N,F,I)})());await Promise.all(W)}async function runTopologicalParallel(t,n,S,C,N,F,I,H){let W=new Map([...buildDependencyGraph(t,{includeDev:F}).edges].map(([t,n])=>[t,new Set(n)])),q=new Map(t.map(t=>[t.name,t])),Y=t.length,X=new Set,Z=0,te=!process.stdout.isTTY||N,ne=new Map,re=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),ie=(Number.isFinite(re)&&re>0?re:20)*6e4;return new Promise((t,F)=>{let re=null,ae=Date.now(),describeInflight=()=>[...ne.entries()].map(([t,n])=>`${t} (${Math.round((Date.now()-n)/1e3)}s)`).join(`, `),failFast=t=>{re||(re=t,killActiveChildren(),setTimeout(()=>settle(),qH).unref?.())},oe=setInterval(()=>{let t=Date.now()-ae;t<3e5||ne.size===0||(ge.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(t/6e4)}min — in-flight: ${describeInflight()}`),t>=ie&&failFast(Error(`gjsify foreach: stalled — no workspace completed for ${Math.round(t/6e4)}min (override via GJSIFY_FOREACH_STALL_MINUTES); killed in-flight: ${describeInflight()}`)))},6e4);oe.unref?.();let settle=()=>{clearInterval(oe),re?F(re):t()},pump=()=>{if(!re){for(;Z<C;){let t=[...W.entries()].filter(([,t])=>[...t].every(t=>X.has(t))).map(([t])=>t);if(t.length===0)break;let C=t.sort()[0];W.delete(C),Z++,ne.set(C,Date.now()),te&&ge.error(`[gjsify foreach] start ${C} (${X.size}/${Y} done, ${Z} in flight)`),runOne(q.get(C),n,S,!0,N,I,H).then(()=>{X.add(C)}).catch(t=>{failFast(t instanceof Error?t:Error(String(t)))}).finally(()=>{Z--,ne.delete(C),ae=Date.now(),re?Z===0&&settle():W.size===0&&Z===0?settle():pump()})}W.size>0&&Z===0&&!re&&(clearInterval(oe),F(Error(`gjsify foreach --topological: stuck — workspaces ${[...W.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne(t,n,S,C,N,F,I){if(F){N&&ge.error(`[${t.name}] $ ${n} ${S.join(` `)}`),await spawnPrefixed(n,S,t.location,C?`[${t.name}] `:null);return}if(I&&I.tryRestore(t))return;let H=I?.snapshotOutputs(t),W=detectPackageManager(),q=W===`gjsify`?[`run`,n,...S]:[`run`,n,...S.length>0?[`--`,...S]:[]];N&&ge.error(`[${t.name}] $ ${W} ${q.join(` `)}`),await spawnPrefixed(W,q,t.location,C?`[${t.name}] `:null),I&&H&&I.storeAfterSuccess(t,H)}async function spawnPrefixed(t,n,S,C){let N=null,F=[];try{let I=await spawnToCompletion(t,n,{completion:`exit`,cwd:S,stdio:C?`pipe`:`inherit`,color:!0,onSpawn:t=>{N=t,GH.add(t);let n=!process.stdout.isTTY;C&&t.stdout&&t.stderr&&(F.push(prefixLines(t.stdout,process.stdout,C,n)),F.push(prefixLines(t.stderr,process.stderr,C,n)))}});for(let t of F)t();if(I.code!==0)throw Error(`${t} ${n.join(` `)} exited with code ${I.code}`)}finally{N&&GH.delete(N)}}var GH,KH,qH,JH,YH=__esmMin(()=>{_e(),j_(),RI(),Dg(),DP(),kP(),nH(),BL(),nI(),WL(),qL(),GH=new Set,KH=5e3,qH=15e3,JH={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[xn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(xn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var XH=__esmMin(()=>{jn(),j_(),kP()});async function packWorkspace(t,n={}){let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
1181
1181
  `,Z=collectPackedFiles(t,q);assertTypeDeclarationsShipped(t,q,Z);let te=[{name:`package/`,directory:!0,mode:493}],ne=[],re=0;for(let n of Z){let S;S=n===`package.json`?new TextEncoder().encode(X):new Uint8Array(readFileSync(xn(t,n)));let C=statSync(xn(t,n)).mode&511;te.push({name:`package/${n}`,body:S,mode:C,mtime:0}),ne.push({path:n,size:S.byteLength,mode:C}),re+=S.byteLength}let ie=await gzip(createTarball(te)),ae=`${F.startsWith(`@`)?F.slice(1).replace(`/`,`-`):F}-${I}.tgz`,oe=createHash(`sha1`).update(ie).digest(`hex`),Q=`sha512-${createHash(`sha512`).update(ie).digest(`base64`)}`,se=n.destination?vn(n.destination):t,ce=xn(se,ae);return n.dryRun||(mkdirSync(se,{recursive:!0}),writeFileSync(ce,ie)),{filename:ae,name:F,version:I,size:ie.byteLength,unpackedSize:re,shasum:oe,integrity:Q,entryCount:ne.length,files:ne,absolutePath:n.dryRun?null:ce}}function collectPackedFiles(t,n){let S=forceIncluded(n),C=Array.isArray(n.files)?n.files.filter(t=>typeof t==`string`):null,N=new Set;if(C)for(let n of expandFilesPatterns(t,C))N.add(n);else{let n=loadIgnore(t);for(let S of walkAll(t))n(S)||N.add(S)}for(let n of S)existsSync(xn(t,n))&&N.add(n);return[...N].sort()}function collectTypeDeclarationRefs(t){let n=new Set,add=t=>{if(typeof t!=`string`)return;let S=t.replace(/^\.\//,``);S.includes(`*`)||n.add(S)};for(let n of[`types`,`typings`])add(t[n]);let walk=t=>{if(!(!t||typeof t!=`object`)){if(Array.isArray(t)){for(let n of t)walk(n);return}for(let[n,S]of Object.entries(t))n===`types`||n===`typings`?add(S):walk(S)}};return walk(t.exports),[...n]}function assertTypeDeclarationsShipped(t,n,S){let C=new Set(S),N=collectTypeDeclarationRefs(n).filter(n=>{let S=xn(t,n);return existsSync(S)&&statSync(S).isFile()&&!C.has(n)});if(N.length===0)return;let F=typeof n.name==`string`?n.name:`(unnamed)`,I=Array.isArray(n.files)?JSON.stringify(n.files):`(none)`;throw Error(`gjsify pack: ${F} references TypeScript declaration file(s) via "exports"/"types" that exist on disk but are excluded from the tarball by the "files" allowlist (${I}):\n`+N.map(t=>` - ${t}`).join(`
1182
1182
  `)+`
1183
1183
  Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(t){let n=new Set;n.add(`package.json`);for(let t of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])n.add(t);let S=typeof t.main==`string`?t.main:null;S&&n.add(S.replace(/^\.\//,``));let C=t.bin;if(typeof C==`string`)n.add(C.replace(/^\.\//,``));else if(C&&typeof C==`object`)for(let t of Object.values(C))typeof t==`string`&&n.add(t.replace(/^\.\//,``));return[...n]}function walkAll(t,n=``){let S=[],C=n?xn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(QH.has(C.name)||C.name.startsWith(`.tsbuildinfo`))continue;let N=n?`${n}/${C.name}`:C.name;C.isDirectory()?S.push(...walkAll(t,N)):C.isFile()&&S.push(N)}return S}function expandFilesPatterns(t,n){let S=new Set,C=null;for(let N of n){let n=N.replace(/^\.\//,``).replace(/\/$/,``);if(!n)continue;if(!/[*?[\]]/.test(n)){let C=xn(t,n);if(!existsSync(C))continue;let N=statSync(C);if(N.isDirectory())for(let C of walkAll(t,n))S.add(C);else N.isFile()&&S.add(n);continue}C??=walkAll(t);let F=filesGlobToRegExp(n),I=filesGlobToRegExp(`${n}/**`);for(let t of C)(F.test(t)||I.test(t))&&S.add(t)}return[...S]}function filesGlobToRegExp(t){let n=`^`;for(let S=0;S<t.length;S++){let C=t[S];if(C===`*`)t[S+1]===`*`?(n+=`.*`,S++,t[S+1]===`/`&&S++):n+=`[^/]*`;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=S+1,N=`[`;for(t[C]===`!`&&(N+=`^`,C++);C<t.length&&t[C]!==`]`;C++)N+=t[C];C<t.length?(n+=`${N}]`,S=C):n+=`\\[`}else".+^${}()|\\]".includes(C)?n+=`\\${C}`:n+=C}return RegExp(`${n}$`)}function loadIgnore(t){let n=xn(t,`.npmignore`),S=xn(t,`.gitignore`),C=[],N=existsSync(n)?n:existsSync(S)?S:null;if(N){let t=readFileSync(N,`utf-8`).split(`
1184
- `);for(let n of t){let t=n.trim();!t||t.startsWith(`#`)||t.startsWith(`!`)||C.push(globToRegex(t))}}return t=>{for(let n of C)if(n.test(t))return!0;return!1}}function globToRegex(t){let n=t.replace(/^\//,``);return n=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`),n=n.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),n=n.replace(/\?/g,`[^/]`),RegExp(`^${n}($|/)`)}function collectWorkspaceProtocolDeps(t){let n=[];for(let S of $H){let C=t[S];if(C)for(let[t,N]of Object.entries(C))typeof N==`string`&&N.startsWith(`workspace:`)&&n.push(`${S}.${t}`)}return n}function findPackWorkspaceRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=t;for(let t=0;t<12;t++){let t=xn(S,`package.json`);if(existsSync(t)&&readPackageJson$2(t)?.workspaces!==void 0)return S;let n=vn(S,`..`);if(n===S)break;S=n}return null}function rewriteWorkspaceDeps(t,n){let S=findPackWorkspaceRoot(n);if(!S){let S=collectWorkspaceProtocolDeps(t);if(S.length>0)throw Error(`gjsify pack: ${String(t.name)} declares workspace: ranges (${S.join(`, `)}) but ${n} is not inside a monorepo (no ancestor package.json declares "workspaces"). A workspace: range cannot be published — replace it with a real npm range, or pack from within the monorepo.`);return t}let C=new Map;for(let t of discoverWorkspaces(S))t.name&&t.version&&C.set(t.name,t.version);let N=JSON.parse(JSON.stringify(t));for(let t of $H){let n=N[t];if(n)for(let[F,I]of Object.entries(n)){if(typeof I!=`string`||!I.startsWith(`workspace:`))continue;let H=C.get(F);if(!H)throw Error(`gjsify pack: ${N.name} declares ${I} on ${F} (${t}) but no sibling workspace with that name exists in the monorepo at ${S}`);let W=I.slice(10);W===`*`||W===``?n[F]=H:W===`^`||W===`~`?n[F]=`${W}${H}`:n[F]=W}}return N}function indentOf(t){let n=t.match(/\n([ \t]+)"/);return n?n[1]:` `}var ZH,QH,$H,eU=__esmMin(()=>{Md(),Kc(),jn(),II(),DP(),kP(),OP(),XH(),ZH={command:`pack [path]`,description:`Produce an npm-compatible .tgz tarball for the workspace at <path> (default: cwd). Rewrites workspace:^/~/* deps to resolved versions.`,builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`pack-destination`,{description:`Directory to write the tarball into. Default: workspace cwd.`,type:`string`}).option(`json`,{description:"Emit pack metadata as JSON on stdout (mirrors `npm pack --json`).",type:`boolean`,default:!1}).option(`dry-run`,{description:`Compute everything but do not write the .tgz.`,type:`boolean`,default:!1}).option(`ignore-scripts`,{description:"Skip the `prepack` lifecycle script before packing. Mirrors `npm pack --ignore-scripts`. Use when scripts are already run by the outer workflow.",type:`boolean`,default:!1}),handler:async t=>{let n=await packWorkspace(vn(t.path??process.cwd()),{destination:t[`pack-destination`],dryRun:t[`dry-run`]===!0,lifecycleScripts:t[`ignore-scripts`]?[]:[`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`});t.json?process.stdout.write(`${JSON.stringify([n],null,2)}\n`):process.stdout.write(`${n.filename}\n`)}},QH=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`]),$H=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});function decodeJwtPayload(t){let n=t.split(`.`);if(n.length!==3)return null;try{let t=n[1].replace(/-/g,`+`).replace(/_/g,`/`),S=typeof atob==`function`?atob(t):Buffer.from(t,`base64`).toString(`binary`);return JSON.parse(S)}catch{return null}}function hasGithubOidcEnv(){return!!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL&&process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)}async function fetchGithubOidcToken(t,n){let S=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,C=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!S||!C)throw new OidcUnavailableError("GitHub Actions OIDC env vars (ACTIONS_ID_TOKEN_REQUEST_{URL,TOKEN}) not set. The calling workflow needs `permissions: id-token: write`.",`no-env`);let N=`${S}${S.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(t)}`;n?.(`gjsify oidc: GET ${N.replace(C,`<bearer>`)}`);let F=await fetch(N,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${C}`}});if(!F.ok){let t=await F.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${F.status} ${F.statusText} — ${t.slice(0,200)}`,`fetch-id-token`)}let I=await F.json().catch(()=>({}));if(!I.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return I.value}async function exchangeOidcForNpmToken(t){let{packageName:n,registry:S,idToken:C,log:N}=t,F=`${S.endsWith(`/`)?S.slice(0,-1):S}/-/npm/v1/oidc/token/exchange/package/${n.startsWith(`@`)?(()=>{let t=n.indexOf(`/`),S=n.slice(1,t),C=n.slice(t+1);return`@${encodeURIComponent(S)}%2f${encodeURIComponent(C)}`})():encodeURIComponent(n)}`;N?.(`gjsify oidc: POST ${F}`);let I=t.maxRetries??3,H=t.retryBaseMs??1e3;for(let t=0;;t++){let S;try{S=await fetch(F,{method:`POST`,headers:{Authorization:`Bearer ${C}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`})}catch(S){if(t<I){let S=Math.min(H*2**t,8e3);N?.(`gjsify oidc: network error for ${n} (attempt ${t+1}/${I+1}), retrying in ${S}ms`),await sleep(S);continue}throw new OidcExchangeError(`npm OIDC token exchange network error for ${n} after ${t+1} attempt(s): ${S instanceof Error?S.message:String(S)}`,0,``,n,decodeJwtPayload(C)??void 0)}let W=await S.text().catch(()=>``);if(!S.ok){if(tU.has(S.status)&&t<I){let C=Math.min(H*2**t,8e3);N?.(`gjsify oidc: transient ${S.status} ${S.statusText} for ${n} (attempt ${t+1}/${I+1}), retrying in ${C}ms`),await sleep(C);continue}throw new OidcExchangeError(`npm OIDC token exchange failed for ${n}: ${S.status} ${S.statusText} — ${W.slice(0,300)}`,S.status,W,n,decodeJwtPayload(C)??void 0)}let q;try{q=JSON.parse(W)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${n}: ${W.slice(0,200)}`,S.status,W,n)}if(!q.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${n}`,S.status,W,n);return q.token}}async function getNpmTrustedToken(t){let n=`npm:${new URL(t.registry).hostname}`,S=await fetchGithubOidcToken(n,t.log);return{token:await exchangeOidcForNpmToken({...t,idToken:S}),audience:n}}var tU,sleep,OidcUnavailableError,OidcExchangeError,nU=__esmMin(()=>{tU=new Set([408,425,429,500,502,503,504]),sleep=t=>new Promise(n=>setTimeout(n,t)),OidcUnavailableError=class extends Error{reason;constructor(t,n){super(t),this.reason=n,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(t,n,S,C,N){super(t),this.status=n,this.body=S,this.packageName=C,this.claims=N,this.name=`OidcExchangeError`}}});async function diagnose404(t){let{packageName:n,version:S,registry:C,npmrc:N}=t,F={};try{F=await whoami(C,N)}catch{return{reason:`unknown`,message:formatUnknown(n,S)}}return F.username&&F.username.length>0?{reason:`live-token-404`,username:F.username,message:formatLiveToken404(n,S,F.username)}:{reason:`dead-token`,message:formatDeadToken(n,S)}}function formatDeadToken(t,n){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`The npm token in ~/.npmrc appears to be revoked or expired (the /-/whoami probe`,`returned {} instead of {"username": "..."}). The 404 is npm's response to a PUT`,`authenticated with an invalid bearer token.`,``,`To refresh:`,` npm login`,` # or, future: gjsify login (tracked as project_gjsify_login_goal)`,``,`Then verify before publishing:`,` curl -s -H "Authorization: Bearer $(grep registry.npmjs.org ~/.npmrc | sed 's|.*=||')" \\`,` https://registry.npmjs.org/-/whoami`,` # Healthy: {"username":"<you>"}`,` # Dead: {}`].join(`
1184
+ `);for(let n of t){let t=n.trim();!t||t.startsWith(`#`)||t.startsWith(`!`)||C.push(globToRegex(t))}}return t=>{for(let n of C)if(n.test(t))return!0;return!1}}function globToRegex(t){let n=t.replace(/^\//,``);return n=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`),n=n.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),n=n.replace(/\?/g,`[^/]`),RegExp(`^${n}($|/)`)}function collectWorkspaceProtocolDeps(t){let n=[];for(let S of $H){let C=t[S];if(C)for(let[t,N]of Object.entries(C))typeof N==`string`&&N.startsWith(`workspace:`)&&n.push(`${S}.${t}`)}return n}function findPackWorkspaceRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=t;for(let t=0;t<12;t++){let t=xn(S,`package.json`);if(existsSync(t)&&readPackageJson$2(t)?.workspaces!==void 0)return S;let n=vn(S,`..`);if(n===S)break;S=n}return null}function rewriteWorkspaceDeps(t,n){let S=findPackWorkspaceRoot(n);if(!S){let S=collectWorkspaceProtocolDeps(t);if(S.length>0)throw Error(`gjsify pack: ${String(t.name)} declares workspace: ranges (${S.join(`, `)}) but ${n} is not inside a monorepo (no ancestor package.json declares "workspaces"). A workspace: range cannot be published — replace it with a real npm range, or pack from within the monorepo.`);return t}let C=new Map;for(let t of discoverWorkspaces(S))t.name&&t.version&&C.set(t.name,t.version);let N=JSON.parse(JSON.stringify(t));for(let t of $H){let n=N[t];if(n)for(let[F,I]of Object.entries(n)){if(typeof I!=`string`||!I.startsWith(`workspace:`))continue;let H=C.get(F);if(!H)throw Error(`gjsify pack: ${N.name} declares ${I} on ${F} (${t}) but no sibling workspace with that name exists in the monorepo at ${S}`);let W=I.slice(10);W===`*`||W===``?n[F]=H:W===`^`||W===`~`?n[F]=`${W}${H}`:n[F]=W}}return N}function indentOf(t){let n=t.match(/\n([ \t]+)"/);return n?n[1]:` `}var ZH,QH,$H,eU=__esmMin(()=>{Md(),Kc(),jn(),LI(),DP(),kP(),OP(),XH(),ZH={command:`pack [path]`,description:`Produce an npm-compatible .tgz tarball for the workspace at <path> (default: cwd). Rewrites workspace:^/~/* deps to resolved versions.`,builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`pack-destination`,{description:`Directory to write the tarball into. Default: workspace cwd.`,type:`string`}).option(`json`,{description:"Emit pack metadata as JSON on stdout (mirrors `npm pack --json`).",type:`boolean`,default:!1}).option(`dry-run`,{description:`Compute everything but do not write the .tgz.`,type:`boolean`,default:!1}).option(`ignore-scripts`,{description:"Skip the `prepack` lifecycle script before packing. Mirrors `npm pack --ignore-scripts`. Use when scripts are already run by the outer workflow.",type:`boolean`,default:!1}),handler:async t=>{let n=await packWorkspace(vn(t.path??process.cwd()),{destination:t[`pack-destination`],dryRun:t[`dry-run`]===!0,lifecycleScripts:t[`ignore-scripts`]?[]:[`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`});t.json?process.stdout.write(`${JSON.stringify([n],null,2)}\n`):process.stdout.write(`${n.filename}\n`)}},QH=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`]),$H=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});function decodeJwtPayload(t){let n=t.split(`.`);if(n.length!==3)return null;try{let t=n[1].replace(/-/g,`+`).replace(/_/g,`/`),S=typeof atob==`function`?atob(t):Buffer.from(t,`base64`).toString(`binary`);return JSON.parse(S)}catch{return null}}function hasGithubOidcEnv(){return!!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL&&process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)}async function fetchGithubOidcToken(t,n){let S=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,C=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!S||!C)throw new OidcUnavailableError("GitHub Actions OIDC env vars (ACTIONS_ID_TOKEN_REQUEST_{URL,TOKEN}) not set. The calling workflow needs `permissions: id-token: write`.",`no-env`);let N=`${S}${S.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(t)}`;n?.(`gjsify oidc: GET ${N.replace(C,`<bearer>`)}`);let F=await fetch(N,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${C}`}});if(!F.ok){let t=await F.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${F.status} ${F.statusText} — ${t.slice(0,200)}`,`fetch-id-token`)}let I=await F.json().catch(()=>({}));if(!I.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return I.value}async function exchangeOidcForNpmToken(t){let{packageName:n,registry:S,idToken:C,log:N}=t,F=`${S.endsWith(`/`)?S.slice(0,-1):S}/-/npm/v1/oidc/token/exchange/package/${n.startsWith(`@`)?(()=>{let t=n.indexOf(`/`),S=n.slice(1,t),C=n.slice(t+1);return`@${encodeURIComponent(S)}%2f${encodeURIComponent(C)}`})():encodeURIComponent(n)}`;N?.(`gjsify oidc: POST ${F}`);let I=t.maxRetries??3,H=t.retryBaseMs??1e3;for(let t=0;;t++){let S;try{S=await fetch(F,{method:`POST`,headers:{Authorization:`Bearer ${C}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`})}catch(S){if(t<I){let S=Math.min(H*2**t,8e3);N?.(`gjsify oidc: network error for ${n} (attempt ${t+1}/${I+1}), retrying in ${S}ms`),await sleep(S);continue}throw new OidcExchangeError(`npm OIDC token exchange network error for ${n} after ${t+1} attempt(s): ${S instanceof Error?S.message:String(S)}`,0,``,n,decodeJwtPayload(C)??void 0)}let W=await S.text().catch(()=>``);if(!S.ok){if(tU.has(S.status)&&t<I){let C=Math.min(H*2**t,8e3);N?.(`gjsify oidc: transient ${S.status} ${S.statusText} for ${n} (attempt ${t+1}/${I+1}), retrying in ${C}ms`),await sleep(C);continue}throw new OidcExchangeError(`npm OIDC token exchange failed for ${n}: ${S.status} ${S.statusText} — ${W.slice(0,300)}`,S.status,W,n,decodeJwtPayload(C)??void 0)}let q;try{q=JSON.parse(W)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${n}: ${W.slice(0,200)}`,S.status,W,n)}if(!q.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${n}`,S.status,W,n);return q.token}}async function getNpmTrustedToken(t){let n=`npm:${new URL(t.registry).hostname}`,S=await fetchGithubOidcToken(n,t.log);return{token:await exchangeOidcForNpmToken({...t,idToken:S}),audience:n}}var tU,sleep,OidcUnavailableError,OidcExchangeError,nU=__esmMin(()=>{tU=new Set([408,425,429,500,502,503,504]),sleep=t=>new Promise(n=>setTimeout(n,t)),OidcUnavailableError=class extends Error{reason;constructor(t,n){super(t),this.reason=n,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(t,n,S,C,N){super(t),this.status=n,this.body=S,this.packageName=C,this.claims=N,this.name=`OidcExchangeError`}}});async function diagnose404(t){let{packageName:n,version:S,registry:C,npmrc:N}=t,F={};try{F=await whoami(C,N)}catch{return{reason:`unknown`,message:formatUnknown(n,S)}}return F.username&&F.username.length>0?{reason:`live-token-404`,username:F.username,message:formatLiveToken404(n,S,F.username)}:{reason:`dead-token`,message:formatDeadToken(n,S)}}function formatDeadToken(t,n){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`The npm token in ~/.npmrc appears to be revoked or expired (the /-/whoami probe`,`returned {} instead of {"username": "..."}). The 404 is npm's response to a PUT`,`authenticated with an invalid bearer token.`,``,`To refresh:`,` npm login`,` # or, future: gjsify login (tracked as project_gjsify_login_goal)`,``,`Then verify before publishing:`,` curl -s -H "Authorization: Bearer $(grep registry.npmjs.org ~/.npmrc | sed 's|.*=||')" \\`,` https://registry.npmjs.org/-/whoami`,` # Healthy: {"username":"<you>"}`,` # Dead: {}`].join(`
1185
1185
  `)}function formatLiveToken404(t,n,S){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`Authenticated as: ${S}`,``,`Your token authenticates, so this is NOT a dead-token problem. The package`,`${t} is not (yet) on npmjs.com. Two cases:`,``,` 1. First publish of a brand-new scoped package — do the one-time bootstrap`,` (see AGENTS.md > "New @gjsify/* package: first-publish + Trusted`,` Publisher bootstrap"). The npm registry can also 404 *transiently*`,` while provisioning a brand-new package: simply re-run, or do the very`," first publish with `npm publish` (then configure the Trusted Publisher)."," 2. You lack publish access to the scope — verify with `npm access ls-packages`."].join(`
1186
1186
  `)}function formatUnknown(t,n){return`gjsify publish: ${t}@${n} — 404 Not Found`}function is404DiagnosticCandidate(t){let n=t.trim();return!!(n.length===0||/^not found$/i.test(n)||/"error"\s*:\s*"Not Found"/i.test(n))}var rU=__esmMin(()=>{Jm()});function backoffFor(t){return iU[Math.min(Math.max(t,0),iU.length-1)]??3e4}function probeTimeoutFor(t,n){return Math.min(t,Math.max(n,aU))}function cacheBustedUrl(t,n){return`${t}${t.includes(`?`)?`&`:`?`}__gjsify_readback=${encodeURIComponent(n)}`}async function verifyPublishedVersion(t){let{registry:n,name:S,version:C,budgetMs:N}=t,F=t.fetchImpl??((...t)=>globalThis.fetch(...t)),I=t.sleep??(t=>new Promise(n=>setTimeout(n,t))),H=t.now??(()=>Date.now()),W=t.probeTimeoutMs??3e4,q=`${n.endsWith(`/`)?n.slice(0,-1):n}/${escapePackageName(S)}`,Y=H(),X=0,Z={state:`error`,detail:`no probe was sent`};for(let n=0;X++,Z=await probeOnce({url:q,version:C,doFetch:F,probeTimeoutMs:probeTimeoutFor(W,N-(H()-Y)),authorization:t.authorization,nonce:`${Y}-${X}`}),t.log?.(`gjsify publish: read-back probe ${X} of ${S}@${C} → ${Z.state}`+(Z.state===`present`?``:` (${Z.detail})`)),Z.state!==`present`;n++){let t=N-(H()-Y);if(t<=0)break;await I(Math.min(backoffFor(n),t))}let te={attempts:X,elapsedMs:H()-Y,url:q,last:Z};if(Z.state===`present`)return{...te,confirmed:!0,verdict:`confirmed`,verdictDetail:`${q} serves ${C} with a tarball`};if(Z.state===`error`)return{...te,confirmed:!1,verdict:`unknown`,verdictDetail:`the read-back could not reach a verdict — ${Z.detail}`};let ne=await probeRegistryRecord({url:q,version:C,doFetch:F,probeTimeoutMs:W,authorization:t.authorization,nonce:`${Y}-record`});return t.log?.(`gjsify publish: read-back record probe of ${S}@${C} → ${ne.state} (${ne.detail})`),ne.state===`recorded`?{...te,confirmed:!1,verdict:`recorded-not-served`,verdictDetail:ne.detail,recordedAt:ne.recordedAt}:ne.state===`no-record`?{...te,confirmed:!1,verdict:`not-published`,verdictDetail:ne.detail}:{...te,confirmed:!1,verdict:`unknown`,verdictDetail:ne.detail}}async function probeRegistryRecord(t){let{url:n,version:S,doFetch:C,probeTimeoutMs:N}=t,F=new AbortController,I=setTimeout(()=>F.abort(),N),H;try{H=await C(cacheBustedUrl(n,t.nonce),{headers:{"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},signal:F.signal})}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record was unreadable (${t instanceof Error?t.message:String(t)})`}}finally{clearTimeout(I)}if(H.status===404)return{state:`no-record`,detail:`the registry has no packument for this name at all (404)`};if(!H.ok)return{state:`unknown`,detail:`the registry serves no ${S} and its own record answered ${H.status} ${H.statusText}`};let W;try{W=await H.json()}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record is not JSON (${t instanceof Error?t.message:String(t)})`}}let q=W?.time,Y=q&&typeof q==`object`?q[S]:void 0;return typeof Y==`string`&&Y.length>0?{state:`recorded`,recordedAt:Y,detail:`the registry RECORDS ${S} at ${Y} and its install document does not serve it`}:{state:`no-record`,detail:`the registry has no record of ${S} — neither in its install document nor in its own \`time\` map`}}async function sendPackumentRequest(t){let{url:n,doFetch:S,probeTimeoutMs:C}=t,N={accept:`application/vnd.npm.install-v1+json`,"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},send=async t=>{let n=new AbortController,F=setTimeout(()=>n.abort(),C);try{return await S(t,{headers:N,signal:n.signal})}finally{clearTimeout(F)}},F;try{F=await send(cacheBustedUrl(n,t.nonce)),!F.ok&&F.status!==404&&F.status>=400&&F.status<500&&(F=await send(n))}catch(t){return{error:`request failed (${t instanceof Error?t.message:String(t)})`}}return F}async function probeOnce(t){let{version:n}=t,S=await sendPackumentRequest(t);if(`error`in S)return{state:`error`,detail:S.error};let C=S;if(C.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!C.ok)return{state:`error`,status:C.status,detail:`${C.status} ${C.statusText}`};let N;try{N=await C.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`error`,status:C.status,detail:`packument is not JSON (${n})`}}let F=N?.versions,I=F&&typeof F==`object`?Object.keys(F):[],H=F&&typeof F==`object`&&Object.hasOwn(F,n)?F[n]:void 0;if(!H){let t=I.length>0?I[I.length-1]:`(none)`;return{state:`absent`,status:C.status,detail:`packument carries ${I.length} version(s), newest ${t} — ${n} is not among them`}}let W=H.dist?.tarball;return typeof W!=`string`||W.length===0?{state:`absent`,status:C.status,detail:`packument has ${n} but its \`dist.tarball\` is missing`}:{state:`present`,status:C.status,tarball:W}}function formatUnconfirmedPublish(t){let{name:n,version:S,putUrl:C,putStatus:N,putStatusText:F,payloadBytes:I,readback:H}=t,W=t.claim??`accepted`,q=(H.elapsedMs/1e3).toFixed(1),Y=H.last.state===`present`?`served`:H.last.detail,X=W===`already-published`?`npm says ${S} is ALREADY PUBLISHED`:`npm ACCEPTED the upload`,Z=H.verdict===`unknown`?H.last.state===`absent`?`${X}; its install document does not serve ${S} and the registry's own record could NOT be read.`:`${X} and the read-back could NOT establish whether the registry serves it.`:H.verdict===`recorded-not-served`?`${X}; the registry RECORDS ${S} and its install document does not serve it.`:`${X} and the registry has no record of ${S}.`,te=H.verdict===`unknown`?[` This is NOT a report that the publish failed, and it is not one that it worked. The read-back`,` reached no answer it could act on, so the version may or may not be installable — confirm it`," before releasing anything that depends on it (`npm view <name>@<version> dist.tarball`)."]:H.verdict===`recorded-not-served`?[` Do NOT re-publish: the registry holds the write, so a re-run is answered 409 and changes`,` nothing. The document npm installs from is behind the registry's own record — measured on`,` the ts-for-gir v5.1.0 release, @ts-for-gir/reporter was recorded at 21:43:00.983Z and a`,` cache-busted read of its install document still did not carry 5.1.0 ~40 min later. Wait and`,` re-read; if it persists, check https://status.npmjs.org/.`]:W===`already-published`?[` A 409 is npm refusing to overwrite a version it holds, which is not the same as serving it:`,` in the v0.46.0 recovery @gjsify/node-runtime-darwin-arm64 was answered 409 at 09:48:49 and`,` the registry recorded 0.46.0 at 09:49:07, 18s later. Re-running answers the same 409, so it`," cannot fix this — wait and re-read (`npm view <name>@<version>`), or check",` https://status.npmjs.org/.`]:[` A 2xx from npm is an ACCEPTED write, not a durable one. In the v0.46.0 release 19 of 199`,` packages were recorded by the registry 56-252s after their 2xx, and ONE was never recorded`,` at all while its job stayed green — that is the failure this check exists to name.`," Re-run this publish (`--tolerate-republish` no-ops if it landed meanwhile). If it keeps",` failing, the write was rejected downstream of the 2xx: check https://status.npmjs.org/.`];return[`gjsify publish: ${n}@${S} — ${Z}`,` PUT ${C} (${I} bytes) → ${N} ${F}`,` read-back GET ${H.url} (accept: application/vnd.npm.install-v1+json, per-probe cache buster)`,` answered ${H.last.state}: ${Y}`,` after ${H.attempts} probe(s) over ${q}s`,` verdict ${H.verdict} — ${H.verdictDetail}`,...te].join(`
1187
1187
  `)}async function probePackageName(t){let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=await sendPackumentRequest({url:`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/${escapePackageName(t.name)}`,doFetch:n,probeTimeoutMs:t.probeTimeoutMs??3e4,authorization:t.authorization,nonce:`name-${Date.now()}-${++sU}`});if(`error`in S)return{state:`unknown`,detail:S.error};if(S.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!S.ok)return{state:`unknown`,status:S.status,detail:`${S.status} ${S.statusText}`};let C;try{C=await S.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`unknown`,status:S.status,detail:`packument is not JSON (${n})`}}let N=C?.versions,F=N&&typeof N==`object`?Object.keys(N).length:0;return F===0?{state:`unknown`,status:S.status,detail:`a 200 carrying no versions establishes nothing`}:{state:`present`,status:S.status,versions:F}}var iU,aU,oU,sU,cU=__esmMin(()=>{Xm(),iU=[2e3,4e3,8e3,15e3,3e4],aU=2e3,oU=6e5,sU=0});function collectWorkspacePins(t,n){let S=[];for(let C of lU){let N=depsOf(t,C),F=depsOf(n,C);for(let[t,n]of Object.entries(N))typeof n!=`string`||!n.startsWith(`workspace:`)||S.push({name:t,spec:F[t]??n,block:C})}return S}var lU,depsOf,uU=__esmMin(()=>{lU=[`dependencies`,`optionalDependencies`,`peerDependencies`],depsOf=(t,n)=>{let S=t[n];return S&&typeof S==`object`?S:{}}});function beginPrompt(){dU++}function endPrompt(t=defaultWrite){if(dU=Math.max(0,dU-1),dU>0||fU.length===0)return;let n=fU.splice(0,fU.length);for(let S of n)t(S)}function writeAroundPrompt(t,n=defaultWrite){if(dU>0){fU.push(t);return}n(t)}function defaultWrite(t){process.stdout.write(t)}var dU,fU,pU=__esmMin(()=>{dU=0,fU=[]});function isTtyStdin(){let t=process.stdin;return!!t.isTTY&&typeof t.setRawMode==`function`}function applyKey(t,n,S){return n===`\r`||n===`
@@ -1190,7 +1190,7 @@ Add the missing path(s) to package.json "files" so type resolution isn't silentl
1190
1190
  `,done:!1,interrupt:!0}:n===hU||n===gU?t.length>0?{buf:t.slice(0,-1),echo:`\b \b`,done:!1,interrupt:!1}:{buf:t,echo:``,done:!1,interrupt:!1}:n>=` `?{buf:t+n,echo:S?`*`:n,done:!1,interrupt:!1}:{buf:t,echo:``,done:!1,interrupt:!1}}async function runRawSession(t){let n=process.stdin,S=process.stdout,C=null,cleanup=()=>{n.removeListener(`data`,onData);try{n.setRawMode(!1)}catch{}typeof n.pause==`function`&&n.pause()},onData=t=>{let n=typeof t==`string`?t:t.toString(`utf-8`);for(let t of n){if(!C)continue;let n=applyKey(C.buf,t,C.mask);if(C.buf=n.buf,n.echo&&S.write(n.echo),n.interrupt)return cleanup(),process.exit(130);if(n.done){let{resolve:t}=C;C=null,t(n.buf)}}};n.setRawMode(!0),typeof n.resume==`function`&&n.resume(),n.setEncoding(`utf-8`),n.on(`data`,onData);let read=(t,n)=>new Promise(N=>{beginPrompt(),S.write(t),C={mask:n,buf:``,resolve:t=>{endPrompt(),N(t)}}});try{return await t(read)}finally{cleanup()}}function readLine(){return new Promise(t=>{let n=``,onData=S=>{n+=typeof S==`string`?S:S.toString(`utf-8`);let C=n.search(/[\r\n]/);C>=0&&(cleanup(),t(n.slice(0,C)))},onEnd=()=>{cleanup(),t(n.replace(/\r$/,``).trim())},cleanup=()=>{process.stdin.removeListener(`data`,onData),process.stdin.removeListener(`end`,onEnd)};process.stdin.setEncoding(`utf-8`),typeof process.stdin.isPaused==`function`&&process.stdin.isPaused()&&process.stdin.resume(),process.stdin.on(`data`,onData),process.stdin.once(`end`,onEnd)})}async function promptLine(t){if(!isTtyStdin()){beginPrompt(),process.stdout.write(t);try{return await readLine()}finally{endPrompt()}}return runRawSession(n=>n(t,!1))}async function promptCredentials(t){if(!isTtyStdin()){let n=t;n||=(process.stdout.write(`Username: `),await readLine()),process.stdout.write(`Password: `);let S=await readLine();return{username:n,password:S}}return runRawSession(async n=>({username:t??await n(`Username: `,!1),password:await n(`Password: `,!0)}))}var mU,hU,gU,_U=__esmMin(()=>{pU(),mU=``,hU=``,gU=`\b`});function isOtpCacheEnabled(){let t=process.env[vU];return!(t===`1`||t===`true`||t===`yes`)}function normalizeRegistry(t){return t.endsWith(`/`)?t.slice(0,-1):t}function cacheBaseDir(t){if(t?.dir)return t.dir;let n=process.env.XDG_RUNTIME_DIR;return xn(n&&n.length>0?n:tmpdir(),yU)}function cacheFileFor(t,n){let S=normalizeRegistry(t).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120);return xn(cacheBaseDir(n),`otp-${S||`default`}.json`)}function readCachedOtp(t,n){if(!isOtpCacheEnabled())return;let S=n?.now??Date.now(),C=cacheFileFor(t,n);try{if(!existsSync(C))return;let n=JSON.parse(readFileSync(C,`utf8`));if(!n||typeof n.otp!=`string`||typeof n.expiresAt!=`number`){deleteCacheFile(C);return}if(n.registry!==normalizeRegistry(t))return;if(S>=n.expiresAt){deleteCacheFile(C);return}return n.otp.length>0?n.otp:void 0}catch{deleteCacheFile(C);return}}function writeCachedOtp(t,n,S){if(!isOtpCacheEnabled()||!n||n.length===0)return;let C=S?.now??Date.now(),N=S?.ttlMs??3e4;try{mkdirSync(cacheBaseDir(S),{recursive:!0,mode:448});let F=cacheFileFor(t,S),I={otp:n,expiresAt:C+N,registry:normalizeRegistry(t)};writeFileSync(F,JSON.stringify(I),{mode:384}),chmodSync(F,384)}catch{}}function clearCachedOtp(t,n){deleteCacheFile(cacheFileFor(t,n))}function deleteCacheFile(t){try{existsSync(t)&&rmSync(t,{force:!0})}catch{}}var vU,yU,bU=__esmMin(()=>{Md(),Dg(),jn(),vU=`GJSIFY_NO_OTP_CACHE`,yU=`gjsify-otp`});async function isOtpChallenge(t){if(t.status!==401)return!1;if((t.headers.get(`www-authenticate`)??``).toLowerCase().includes(`otp`))return!0;let n=await t.clone().text().catch(()=>``);return/one-time pass/i.test(n)||/\bEOTP\b/.test(n)}async function withOtpRetry(t,n,S={}){let C=S.maxPrompts??2,N=S.question,F=n.current(),I=S.seedFirstAttempt===!0&&F!==void 0,H=n.epoch(),W=await t(I?F:void 0);if(!await isOtpChallenge(W))return W;if(I&&n.invalidate(H),!I&&n.current()!==void 0){if(H=n.epoch(),W=await t(n.current()),!await isOtpChallenge(W))return W;n.invalidate(H)}for(let S=0;S<C;S++){let S=await n.refresh(N,H);if(!S||(H=n.epoch(),W=await t(S),!await isOtpChallenge(W)))return W;n.invalidate(H)}return W}var xU,SU,OtpProvider,CU=__esmMin(()=>{_U(),bU(),xU=`This operation requires a one-time password.
1191
1191
  Enter OTP: `,SU=`The previous one-time password is no longer valid (npm codes last about 30 seconds).
1192
1192
  Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(t,n=promptLine,S={}){this.promptFn=n,this.registry=S.registry;let C=t&&t.length>0?t:void 0;C?(this.cached=C,this.registry&&writeCachedOtp(this.registry,C)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(t,n){if(n!==void 0&&this.generation>n&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(t??(this.generation>0?SU:xU));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(t){let n=(await this.promptFn(t)).trim();return n&&(this.cached=n,this.generation++,this.registry&&writeCachedOtp(this.registry,n)),n}invalidate(t){t!==void 0&&this.generation!==t||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});async function publishWorkspace(t){let{wsDir:n,tag:S,access:C,provenance:N,tolerate:F,tolerateUntrustedNew:I,trustedFlag:H,verbose:W,json:q,otpProvider:Y}=t,X=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:q?`inherit-stderr`:`inherit`}),Z=await packWorkspaceToBytes(n),te=readFileSync(xn(n,`package.json`),`utf-8`),ne=JSON.parse(te),re=await loadRewrittenManifest(n,ne),ie=await loadNpmrc(n),ae=t.registry??process.env.npm_config_registry??registryFor(X.name,ie)??Vm,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,Q=`${oe}/${escapePackageName(X.name)}`,se=`${X.name.includes(`/`)?X.name.slice(X.name.indexOf(`/`)+1):X.name}-${X.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:S,access:C,tarballBytes:Z,tarballUrl:`${oe}/${X.name}/-/${se}`,packed:{...X,wireFilename:se},provenance:N}),le=buildPublishHeaders(Q,{npmrc:ie}),ue=new Set(t.assumePresent??[]),de=collectWorkspacePins(ne,re).filter(t=>!ue.has(t.name));if(de.length>0){let t=await Promise.all(de.map(async t=>({pin:t,presence:await probePackageName({registry:ae,name:t.name,authorization:le.authorization})}))),n=[];for(let{pin:S,presence:C}of t){if(C.state===`present`)continue;let t=`${S.block}.${S.name}@${S.spec}`;if(C.state===`unknown`){ge.error(`gjsify publish: could not establish whether ${S.name} exists (${C.detail}) — not blocking on ${t}`);continue}if(S.block!==`dependencies`){ge.error(`gjsify publish: ${t} names a package ${ae} does not have — npm installs around it, Yarn (\`YN0035\`) does not`);continue}n.push(S)}if(n.length>0)return{ok:I,action:`blocked-missing-dependency`,name:X.name,version:X.version,registry:ae,tolerated:I,missing:n}}let fe=H===!0||H===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,pe=`token`;if(fe)try{let{token:t,audience:n}=await getNpmTrustedToken({packageName:X.name,registry:ae,log:W?t=>ge.error(t):void 0});le.authorization=`Bearer ${t}`,pe=`oidc`,W&&ge.error(`gjsify publish: OIDC token obtained (audience=${n})`)}catch(t){if(t instanceof OidcExchangeError&&t.status===404&&/package not found/i.test(t.body)&&I)return{ok:!0,action:`skipped-untrusted-new`,name:X.name,version:X.version};if(H===!0)return{ok:!1,action:`oidc-failed`,name:X.name,version:X.version,error:t};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:X.name,version:X.version,error:t};if(W){let n=t instanceof Error?t.message:String(t);ge.error(`gjsify publish: OIDC auto-detect failed (${n}) — falling back to token auth`)}}W&&(ge.error(`gjsify publish: PUT ${Q} (${X.name}@${X.version})`),ge.error(` auth-mode: ${pe}`),ge.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ge.error(` payload size: ${JSON.stringify(ce).length} bytes`));let me=JSON.stringify(ce),doPut=t=>{let n={...le};return t&&(n[`npm-otp`]=t,n[`npm-auth-type`]=`legacy`),fetch(Q,{method:`PUT`,headers:n,body:me})},he=await withOtpRetry(doPut,Y,{seedFirstAttempt:t.seedOtpFirst});if(W){ge.error(` response: ${he.status} ${he.statusText}`);let t=await he.clone().text().catch(()=>``);t&&ge.error(` body: ${t.slice(0,300)}`)}let readBack=async()=>{let n=t.verifyBudgetMs??6e5;if(!(n<=0))return verifyPublishedVersion({registry:oe,name:X.name,version:X.version,budgetMs:n,authorization:le.authorization,log:W?t=>ge.error(t):void 0})};if(await isOtpChallenge(he))return{ok:!1,action:`otp-required`,name:X.name,version:X.version,status:he.status};if(he.ok){let t=await readBack();return t?.confirmed&&W&&ge.error(` read-back: confirmed after ${t.attempts} probe(s) in ${t.elapsedMs} ms`),t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`accepted`,name:X.name,version:X.version,registry:oe,putStatus:he.status,putStatusText:he.statusText,putUrl:Q,payloadBytes:me.length,readback:t}:{ok:!0,action:`published`,name:X.name,version:X.version,filename:X.filename,size:X.size,integrity:X.integrity,tag:S,registry:oe,readback:t}}let _e=await he.text().catch(()=>`<no body>`);if((he.status===409||he.status===403&&/previously published/i.test(_e))&&F){let t=await readBack();return t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`already-published`,name:X.name,version:X.version,registry:oe,putStatus:he.status,putStatusText:he.statusText,putUrl:Q,payloadBytes:me.length,readback:t}:{ok:!0,action:`republish-tolerated`,name:X.name,version:X.version,status:he.status,registry:oe,readback:t}}if(he.status===404&&pe===`token`&&is404DiagnosticCandidate(_e)){let t=await diagnose404({packageName:X.name,version:X.version,registry:oe,npmrc:ie});if(t.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:X.name,version:X.version,status:404,diag:t}}return{ok:!1,action:`error`,name:X.name,version:X.version,status:he.status,statusText:he.statusText,text:_e}}function describeVerification(t,n){if(!t?.confirmed)return{verified:!1,clause:`(UNVERIFIED — read-back disabled by --verify-timeout 0)`,json:null};let S=(t.elapsedMs/1e3).toFixed(1);return{verified:!0,clause:`(verified on ${n} — ${t.attempts} probe(s), ${S}s)`,json:{registry:n,verdict:t.verdict,probes:t.attempts,elapsedMs:t.elapsedMs,tarball:t.last.state===`present`?t.last.tarball:null}}}function warnUnverified(t,n,S){process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Publish unverified::${t}@${n} was published with the read-back disabled (--verify-timeout 0) — nothing confirmed that ${S} serves it\n`)}function reportPublishOutcome(t,n,S=!1){switch(t.action){case`published`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,name:t.name,version:t.version,filename:t.filename,size:t.size,integrity:t.integrity,tag:t.tag,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${t.name}@${t.version} ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`publish-unconfirmed`:{let C=formatUnconfirmedPublish(t);if(n?process.stdout.write(`${JSON.stringify({ok:!1,action:`publish-unconfirmed`,name:t.name,version:t.version,registry:t.registry,claim:t.claim,putStatus:t.putStatus,probes:t.readback.attempts,elapsedMs:t.readback.elapsedMs,readbackUrl:t.readback.url,readbackState:t.readback.last.state,verdict:t.readback.verdict,verdictDetail:t.readback.verdictDetail,recordedAt:t.readback.recordedAt??null,deferred:S},null,2)}\n`):process.stderr.write(`${C}\n`),S){if(process.env.GITHUB_ACTIONS){let n=t.claim===`already-published`?`was reported already published`:`was accepted`;process.stderr.write(`::warning title=Publish unconfirmed::${t.name}@${t.version} ${n} (HTTP ${t.putStatus}) but did not resolve on ${t.registry} within ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}] — the release-closure job must confirm it
1193
- `)}return}return process.exit(1)}case`republish-tolerated`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,action:`republish-tolerated`,name:t.name,version:t.version,status:t.status,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${t.name}@${t.version} (already published, tolerated) ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`skipped-untrusted-new`:n?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:t.name,version:t.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`blocked-missing-dependency`:{let S=t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `);return n?process.stdout.write(`${JSON.stringify({ok:t.ok,action:`blocked-missing-dependency`,name:t.name,version:t.version,registry:t.registry,tolerated:t.tolerated,missing:t.missing},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (NOT published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${S})\n`),ge.error(`gjsify publish: every consumer install of ${t.name} would fail with \`npm error 404\`, on every package manager — a required edge is not skippable. Bootstrap the target first (docs/publishing.md § New \`@gjsify/*\` package), then re-run. See #1713.`),t.tolerated?void 0:process.exit(1)}case`otp-required`:return ge.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(t.error,t.name,n),process.exit(1);case`oidc-no-token`:{let S=t.error instanceof Error?t.error.message:String(t.error);return ge.error(`gjsify publish: OIDC token exchange failed for ${t.name} (${S}) and no fallback npm token is configured — refusing to publish without credentials.`),n&&process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return n?process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,status:404,diagnostic:t.diag.reason,username:t.diag.username},null,2)}\n`):process.stderr.write(`${t.diag.message}\n`),process.exit(1);case`error`:return ge.error(`gjsify publish: ${t.name}@${t.version} — ${t.status} ${t.statusText}`),ge.error(t.text),process.exit(1)}}async function packWorkspaceToBytes(t){let n=xn(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),S=await packWorkspace(t,{destination:n,dryRun:!1,lifecycleScripts:[]});if(!S.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let C=new Uint8Array(readFileSync(S.absolutePath));try{(await Promise.resolve().then(()=>(Md(),Ad))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(Md(),Ad))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=xn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(Md(),Ad));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(II(),FI)),H=new Uint8Array(readFileSync(C.absolutePath));N(S,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let W=await F(H);for(let t of I(W))if(t.name===`package/package.json`&&t.body)return JSON.parse(new TextDecoder().decode(t.body));return n}function buildPublishPayload(t){let{pkg:n,tag:S,access:C,tarballBytes:N,tarballUrl:F,packed:I,provenance:H}=t,W={...n,_id:`${I.name}@${I.version}`,dist:{integrity:I.integrity,shasum:I.shasum,tarball:F}};H&&(W._hasShrinkwrap=!1);let q={_id:I.name,name:I.name,description:typeof n.description==`string`?n.description:``,"dist-tags":{[S]:I.version},versions:{[I.version]:W},readme:``,_attachments:{[I.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(N),length:N.byteLength}}};return C&&(q.access=C),q}function handleOidcFailure(t,n,S){if(t instanceof OidcUnavailableError){let C=`gjsify publish: OIDC not available — ${t.message}`;S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-unavailable`,reason:t.reason,message:t.message})}\n`):process.stderr.write(`${C}\n`);return}if(t instanceof OidcExchangeError){let C=t.status===401||t.status===403?`npm rejected the OIDC exchange (${t.status}) — check that ${n} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(n)}/access pointing at this workflow.`:t.message;if(S)process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-exchange`,status:t.status,body:t.body,claims:t.claims,message:t.message})}\n`);else if(process.stderr.write(`✗ ${n}: ${C}\n`),t.body&&process.stderr.write(` ↳ npm said: ${t.body.slice(0,300)}\n`),t.claims){let n=t.claims,S=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(t=>n[t]!==void 0).map(t=>`${t}=${JSON.stringify(n[t])}`).join(`, `);S&&process.stderr.write(` ↳ JWT claims npm received: ${S}\n`)}return}let C=t instanceof Error?t.message:String(t);S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`unknown`,message:C})}\n`):process.stderr.write(`✗ ${n}: ${C}\n`)}var wU,TU=__esmMin(()=>{_e(),Md(),Dg(),jn(),cH(),Jm(),Xm(),eU(),nU(),rU(),cU(),uU(),aR(),CU(),_U(),wU={command:`publish [path]`,description:"Pack + upload the workspace at <path> (default: cwd) to its npm registry. Drop-in for `npm publish` with workspace:^ rewrite handled automatically.",builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`tag`,{description:`Dist-tag to publish under. Default: latest.`,type:`string`,default:`latest`}).option(`access`,{description:"Package access — `public` or `restricted` (required for first publish of scoped packages on the public registry).",type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as the `npm-otp` header. Required for manual publishes from a 2FA-enabled account.",type:`string`}).option(`tolerate-republish`,{description:'Treat "version already published" as success — covers both classic 409 Conflict and the npm OIDC-path 403 Forbidden + `"previously published"` body shape. Matches yarn `--tolerate-republish`.',type:`boolean`,default:!1}).option(`tolerate-untrusted-new`,{description:'Skip (exit 0) when OIDC token exchange returns `package not found` AND no fallback token is configured — i.e. a never-before-published `@scope/<name>` whose Trusted Publisher entry hasn\'t been set up on npmjs.com yet. Without this flag, one un-bootstrapped new package breaks the entire serialized `gjsify foreach publish` loop. Pair with `--tolerate-republish` in CI release workflows so a fresh-merged package gracefully skips its first CI publish, leaving the manual-bootstrap step to a maintainer (see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap").',type:`boolean`,default:!1}).option(`verify-timeout`,{description:"Seconds to keep asking the registry for the just-published version before giving up. npm answers 2xx to a write it has only ACCEPTED: in the v0.46.0 release 19 of 199 packages were recorded 56-252s after their 2xx and one was never recorded at all, so a shorter window turns normal queueing into a false red. `0` disables the read-back — for a registry with no packument read path; the success line then reads `UNVERIFIED` and says so, because a publish nothing checked must never look like one that was checked.",type:`number`,default:oU/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 t=>{let n=vn(t.path??process.cwd()),S=t.tag??`latest`,C=t.access,N=t.otp,F=t[`tolerate-republish`]===!0,I=t[`tolerate-untrusted-new`]===!0,H=t[`verify-timeout`]??6e5/1e3;if(!Number.isFinite(H)||H<0)return ge.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`verify-timeout`])}`),process.exit(2);let W=Math.round(H*1e3),q=t[`verify-defer`]===!0,Y=t.provenance===!0,X=t[`dry-run`]===!0,Z=t[`check-trusted`]===!0,te=t.trusted,ne=!!process.env.GJSIFY_PUBLISH_DEBUG;if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=xn(n,`package.json`),C=JSON.parse(readFileSync(S,`utf-8`));if(typeof C.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${S} has no \`name\` field\n`),process.exit(2);if(C.private===!0){let n={ok:!0,action:`check-trusted`,name:C.name,skipped:`private`};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`- ${C.name}: skipped (private package)\n`);return}let N=await loadNpmrc(n),F=process.env.npm_config_registry??registryFor(C.name,N)??Vm;try{await getNpmTrustedToken({packageName:C.name,registry:F,log:ne?t=>ge.error(t):void 0});let n={ok:!0,action:`check-trusted`,name:C.name,registry:F};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`✓ ${C.name}: trusted publisher OK\n`);return}catch(n){handleOidcFailure(n,C.name,t.json===!0);return}}if(X){let S=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`}),C={ok:!0,action:`dry-run`,name:S.name,version:S.version,filename:S.filename,size:S.size,shasum:S.shasum,integrity:S.integrity};t.json?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${S.name}@${S.version} (dry-run, ${S.size} bytes, ${S.entryCount} files)\n`);return}let re=!!(process.stdin.isTTY&&process.stdout.isTTY),ie=await loadNpmrc(n),ae;try{ae=JSON.parse(readFileSync(xn(n,`package.json`),`utf-8`)).name}catch{}let oe=process.env.npm_config_registry??(ae?registryFor(ae,ie):void 0)??ie.registry??Vm,Q=new OtpProvider(N,re?promptLine:async()=>``,{registry:oe});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:Q,seedOtpFirst:N!==void 0,verifyBudgetMs:W}),t.json===!0,q)}}}),EU,DU=__esmMin(()=>{Jm(),aR(),EU={command:`whoami`,description:`Print the npm-registry username for the current ~/.npmrc token. Clear failure message when the token is dead, missing, or the registry is unreachable.`,builder:t=>t.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${Vm}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??n.registry??Vm,C=S.endsWith(`/`)?S.slice(0,-1):S,N=t.json===!0;if(!hasAnyCredential(n))return N?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:C})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${C}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
1193
+ `)}return}return process.exit(1)}case`republish-tolerated`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,action:`republish-tolerated`,name:t.name,version:t.version,status:t.status,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${t.name}@${t.version} (already published, tolerated) ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`skipped-untrusted-new`:n?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:t.name,version:t.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`blocked-missing-dependency`:{let S=t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `);return n?process.stdout.write(`${JSON.stringify({ok:t.ok,action:`blocked-missing-dependency`,name:t.name,version:t.version,registry:t.registry,tolerated:t.tolerated,missing:t.missing},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (NOT published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${S})\n`),ge.error(`gjsify publish: every consumer install of ${t.name} would fail with \`npm error 404\`, on every package manager — a required edge is not skippable. Bootstrap the target first (docs/publishing.md § New \`@gjsify/*\` package), then re-run. See #1713.`),t.tolerated?void 0:process.exit(1)}case`otp-required`:return ge.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(t.error,t.name,n),process.exit(1);case`oidc-no-token`:{let S=t.error instanceof Error?t.error.message:String(t.error);return ge.error(`gjsify publish: OIDC token exchange failed for ${t.name} (${S}) and no fallback npm token is configured — refusing to publish without credentials.`),n&&process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return n?process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,status:404,diagnostic:t.diag.reason,username:t.diag.username},null,2)}\n`):process.stderr.write(`${t.diag.message}\n`),process.exit(1);case`error`:return ge.error(`gjsify publish: ${t.name}@${t.version} — ${t.status} ${t.statusText}`),ge.error(t.text),process.exit(1)}}async function packWorkspaceToBytes(t){let n=xn(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),S=await packWorkspace(t,{destination:n,dryRun:!1,lifecycleScripts:[]});if(!S.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let C=new Uint8Array(readFileSync(S.absolutePath));try{(await Promise.resolve().then(()=>(Md(),Ad))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(Md(),Ad))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=xn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(Md(),Ad));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(LI(),II)),H=new Uint8Array(readFileSync(C.absolutePath));N(S,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let W=await F(H);for(let t of I(W))if(t.name===`package/package.json`&&t.body)return JSON.parse(new TextDecoder().decode(t.body));return n}function buildPublishPayload(t){let{pkg:n,tag:S,access:C,tarballBytes:N,tarballUrl:F,packed:I,provenance:H}=t,W={...n,_id:`${I.name}@${I.version}`,dist:{integrity:I.integrity,shasum:I.shasum,tarball:F}};H&&(W._hasShrinkwrap=!1);let q={_id:I.name,name:I.name,description:typeof n.description==`string`?n.description:``,"dist-tags":{[S]:I.version},versions:{[I.version]:W},readme:``,_attachments:{[I.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(N),length:N.byteLength}}};return C&&(q.access=C),q}function handleOidcFailure(t,n,S){if(t instanceof OidcUnavailableError){let C=`gjsify publish: OIDC not available — ${t.message}`;S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-unavailable`,reason:t.reason,message:t.message})}\n`):process.stderr.write(`${C}\n`);return}if(t instanceof OidcExchangeError){let C=t.status===401||t.status===403?`npm rejected the OIDC exchange (${t.status}) — check that ${n} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(n)}/access pointing at this workflow.`:t.message;if(S)process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-exchange`,status:t.status,body:t.body,claims:t.claims,message:t.message})}\n`);else if(process.stderr.write(`✗ ${n}: ${C}\n`),t.body&&process.stderr.write(` ↳ npm said: ${t.body.slice(0,300)}\n`),t.claims){let n=t.claims,S=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(t=>n[t]!==void 0).map(t=>`${t}=${JSON.stringify(n[t])}`).join(`, `);S&&process.stderr.write(` ↳ JWT claims npm received: ${S}\n`)}return}let C=t instanceof Error?t.message:String(t);S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`unknown`,message:C})}\n`):process.stderr.write(`✗ ${n}: ${C}\n`)}var wU,TU=__esmMin(()=>{_e(),Md(),Dg(),jn(),cH(),Jm(),Xm(),eU(),nU(),rU(),cU(),uU(),aR(),CU(),_U(),wU={command:`publish [path]`,description:"Pack + upload the workspace at <path> (default: cwd) to its npm registry. Drop-in for `npm publish` with workspace:^ rewrite handled automatically.",builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`tag`,{description:`Dist-tag to publish under. Default: latest.`,type:`string`,default:`latest`}).option(`access`,{description:"Package access — `public` or `restricted` (required for first publish of scoped packages on the public registry).",type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as the `npm-otp` header. Required for manual publishes from a 2FA-enabled account.",type:`string`}).option(`tolerate-republish`,{description:'Treat "version already published" as success — covers both classic 409 Conflict and the npm OIDC-path 403 Forbidden + `"previously published"` body shape. Matches yarn `--tolerate-republish`.',type:`boolean`,default:!1}).option(`tolerate-untrusted-new`,{description:'Skip (exit 0) when OIDC token exchange returns `package not found` AND no fallback token is configured — i.e. a never-before-published `@scope/<name>` whose Trusted Publisher entry hasn\'t been set up on npmjs.com yet. Without this flag, one un-bootstrapped new package breaks the entire serialized `gjsify foreach publish` loop. Pair with `--tolerate-republish` in CI release workflows so a fresh-merged package gracefully skips its first CI publish, leaving the manual-bootstrap step to a maintainer (see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap").',type:`boolean`,default:!1}).option(`verify-timeout`,{description:"Seconds to keep asking the registry for the just-published version before giving up. npm answers 2xx to a write it has only ACCEPTED: in the v0.46.0 release 19 of 199 packages were recorded 56-252s after their 2xx and one was never recorded at all, so a shorter window turns normal queueing into a false red. `0` disables the read-back — for a registry with no packument read path; the success line then reads `UNVERIFIED` and says so, because a publish nothing checked must never look like one that was checked.",type:`number`,default:oU/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 t=>{let n=vn(t.path??process.cwd()),S=t.tag??`latest`,C=t.access,N=t.otp,F=t[`tolerate-republish`]===!0,I=t[`tolerate-untrusted-new`]===!0,H=t[`verify-timeout`]??6e5/1e3;if(!Number.isFinite(H)||H<0)return ge.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`verify-timeout`])}`),process.exit(2);let W=Math.round(H*1e3),q=t[`verify-defer`]===!0,Y=t.provenance===!0,X=t[`dry-run`]===!0,Z=t[`check-trusted`]===!0,te=t.trusted,ne=!!process.env.GJSIFY_PUBLISH_DEBUG;if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=xn(n,`package.json`),C=JSON.parse(readFileSync(S,`utf-8`));if(typeof C.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${S} has no \`name\` field\n`),process.exit(2);if(C.private===!0){let n={ok:!0,action:`check-trusted`,name:C.name,skipped:`private`};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`- ${C.name}: skipped (private package)\n`);return}let N=await loadNpmrc(n),F=process.env.npm_config_registry??registryFor(C.name,N)??Vm;try{await getNpmTrustedToken({packageName:C.name,registry:F,log:ne?t=>ge.error(t):void 0});let n={ok:!0,action:`check-trusted`,name:C.name,registry:F};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`✓ ${C.name}: trusted publisher OK\n`);return}catch(n){handleOidcFailure(n,C.name,t.json===!0);return}}if(X){let S=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`}),C={ok:!0,action:`dry-run`,name:S.name,version:S.version,filename:S.filename,size:S.size,shasum:S.shasum,integrity:S.integrity};t.json?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${S.name}@${S.version} (dry-run, ${S.size} bytes, ${S.entryCount} files)\n`);return}let re=!!(process.stdin.isTTY&&process.stdout.isTTY),ie=await loadNpmrc(n),ae;try{ae=JSON.parse(readFileSync(xn(n,`package.json`),`utf-8`)).name}catch{}let oe=process.env.npm_config_registry??(ae?registryFor(ae,ie):void 0)??ie.registry??Vm,Q=new OtpProvider(N,re?promptLine:async()=>``,{registry:oe});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:Q,seedOtpFirst:N!==void 0,verifyBudgetMs:W}),t.json===!0,q)}}}),EU,DU=__esmMin(()=>{Jm(),aR(),EU={command:`whoami`,description:`Print the npm-registry username for the current ~/.npmrc token. Clear failure message when the token is dead, missing, or the registry is unreachable.`,builder:t=>t.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${Vm}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??n.registry??Vm,C=S.endsWith(`/`)?S.slice(0,-1):S,N=t.json===!0;if(!hasAnyCredential(n))return N?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:C})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${C}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
1194
1194
  `)+`
1195
1195
  `),process.exit(1);let F;try{F=await whoami(S,n)}catch(t){let n=t instanceof Error?t.message:String(t);return N?process.stdout.write(`${JSON.stringify({error:n,registry:C})}\n`):(process.stderr.write(`gjsify whoami: ${n}\n`),process.stderr.write(`Registry: ${C}\n`)),process.exit(1)}if(F.username&&F.username.length>0){N?process.stdout.write(`${JSON.stringify({username:F.username,registry:C})}\n`):(process.stdout.write(`Logged in as: ${F.username}\n`),process.stdout.write(`Registry: ${C}\n`));return}N?process.stdout.write(`${JSON.stringify({error:`dead-token`,registry:C})}\n`):process.stderr.write([`gjsify whoami: token appears dead or revoked (registry returned an empty whoami response).`,``,`Refresh via: npm login`,`Then verify: gjsify whoami`,``,`For the @gjsify scope, see AGENTS.md > "New @gjsify/* package: first-publish + Trusted Publisher bootstrap".`].join(`
1196
1196
  `)+`