@kaisers-io/refs 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/refs.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{access as e,chmod as t,constants as n,copyFile as r,lstat as i,mkdir as a,open as o,readFile as s,readdir as c,realpath as l,rename as u,rm as d,rmdir as f,stat as p,utimes as ee,writeFile as te}from"node:fs/promises";import ne,{basename as re,dirname as ie,isAbsolute as ae,join as m,posix as oe,relative as se,resolve as ce,sep as le}from"node:path";import{createHash as ue,randomUUID as de}from"node:crypto";import fe,{existsSync as pe,realpathSync as me}from"node:fs";import{homedir as he}from"node:os";import{setTimeout as ge}from"node:timers/promises";import{EventEmitter as _e,once as ve}from"node:events";import ye,{spawn as be}from"node:child_process";import h from"node:process";import{stripVTControlCharacters as xe}from"node:util";const g={CONFLICT:5,NOT_FOUND:4,OK:0,UNEXPECTED:1,USAGE:2,VALIDATION:3};var _=class extends Error{code;exitCode;reason;constructor(e,t,n,r){super(n,r),this.code=t,this.exitCode=e,this.name=`RefsError`,r?.reason!==void 0&&(this.reason=r.reason)}};const Se=e=>new _(g.CONFLICT,`conflict`,e),v=(e,t)=>new _(g.NOT_FOUND,`not_found`,e,t===void 0?void 0:{reason:t}),y=e=>new _(g.USAGE,`usage`,e),b=e=>new _(g.VALIDATION,`validation`,e),Ce=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,we=(e,t)=>e instanceof _?{code:e.code,exitCode:e.exitCode,message:Ce(e.message,e.stack,t.verbose),...e.reason===void 0?{}:{reason:e.reason}}:e instanceof Error?{code:`unexpected`,exitCode:g.UNEXPECTED,message:Ce(e.message,e.stack,t.verbose)}:{code:`unexpected`,exitCode:g.UNEXPECTED,message:String(e)};function Te(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Ee(e,t=`|`){return e.map(e=>Xe(e)).join(t)}function De(e,t){return typeof t==`bigint`?t.toString():t}var Oe=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function ke(e){return new Oe(e)}function Ae(e){return e==null}function je(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Me(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function Ne(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Pe(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Fe(e){return Pe(e._zod.def)??e._zod.def.shape}function Ie(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Ne(this,t,e),e},enumerable:!0,configurable:!0})}function Le(e,t,n){t in e?Ne(e,t,n):e[t]=n}function Re(e,t,n,r){let i=Fe(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Ie(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Le(e,a,r?r(n.value,a):n.value))}}function ze(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Ie(e,n,()=>t[n]):Le(e,n,r.value))}}function x(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Be(e){return JSON.stringify(e)}function Ve(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const He=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ue(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const We=ke(()=>{if(T.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Ge(e){if(Ue(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Ue(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Ke(e){return Ge(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const qe=new Set([`string`,`number`,`symbol`]);function Je(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ye(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function S(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Xe(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Ze(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const Qe={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},$e={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function et(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return Re(i,e,tt(e,t)),Ye(e,x(n,{shape:i,checks:[]}))}function tt(e,t){let n=Fe(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function nt(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(tt(e,t)),a={};return Re(a,e,Reflect.ownKeys(Fe(e)).filter(e=>!i.has(e))),Ye(e,x(n,{shape:a,checks:[]}))}function rt(e,t){if(!Ge(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Fe(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ye(e,x(e._zod.def,{shape:it(e,t)}))}function it(e,t){let n={};return Re(n,e,Reflect.ownKeys(Fe(e))),ze(n,t),n}function at(e,t){if(!Ge(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ye(e,x(e._zod.def,{shape:it(e,t)}))}function ot(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return Re(n,e,Reflect.ownKeys(Fe(e))),Re(n,t,Reflect.ownKeys(Fe(t))),Ye(e,x(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function st(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(tt(t,n)):void 0,o={};return Re(o,t,Reflect.ownKeys(Fe(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Ye(t,x(t._zod.def,{shape:o,checks:[]}))}function ct(e,t,n){let r=n?new Set(tt(t,n)):void 0,i={};return Re(i,t,Reflect.ownKeys(Fe(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Ye(t,x(t._zod.def,{shape:i}))}function lt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ut(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function dt(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ft(e){return typeof e==`string`?e:e?.message}function pt(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function mt(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:ft(e.inst?._zod.def?.error?.(e))??ft(a?.(e))??ft(t?.error?.(e))??ft(n.customError?.(e))??ft(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}const ht=/[\uD800-\uDBFF]/;function gt(e){let t=e.length;if(!ht.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function _t(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function vt(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function yt(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function bt(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):wt(e,n,r.value)}for(let n of Object.getOwnPropertySymbols(t))wt(e,n,t[n])}function xt(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function St(e,t,n){return xt(e,t,n,!1)}function Ct(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return xt(this,n,r(this))},set(e){xt(this,n,e)}})}return t}function wt(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:xt(this,t,n.bind(this))},set(e){xt(this,t,e)}})}function Tt(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Et,Dt=!1;const Ot={configurable:!0,get(){Dt=!0}};function C(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Et!==e._zod){Et=void 0;return}Et=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Ot);let e=Dt;Dt=!1;try{let r=n(this);return Dt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Dt||=e,r}catch(n){throw delete this[t],Dt||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function kt(e,t,n,r){let i=Tt(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function At(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var jt;const Mt={value:void 0,enumerable:!1};let Nt=`captureStackTrace`in Error?Error:null;function Pt(e){let t=Nt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Nt=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function w(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Mt.value=new a(r);try{Object.defineProperty(n,"_zod",Mt)}finally{Mt.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),bt(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Pt(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Ft=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},It=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(jt=globalThis).__zod_globalConfig??(jt.__zod_globalConfig={});const T=globalThis.__zod_globalConfig;function Lt(e){return e&&Object.assign(T,e),T}function Rt(){let e=this._zod;return e.message??=JSON.stringify(e.def,De,2),e.message}function zt(e){this._zod.message=e}const Bt={get:Rt,set:zt,enumerable:!0,configurable:!0},Vt={value:void 0,enumerable:!1},Ht=new WeakSet([Object.prototype,Error.prototype]),Ut=(e,t)=>{e.name=`$ZodError`,Vt.value=t,Object.defineProperty(e,"issues",Vt),Vt.value=void 0,Object.defineProperty(e,"message",Bt);let n=Object.getPrototypeOf(e);Ht.has(n)||(Ht.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Wt=w(`$ZodError`,Ut);w(`$ZodError`,Ut,void 0,{Parent:Error});function Gt(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Kt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Gt(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function qt(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function Jt(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function E(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${Jt(e.path)}`);return t.join(`
3
- `)}function Yt(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Xt=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ft;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>mt(e,o,Lt())));throw He(n,a?.callee??t),n}return s.value};return t},Zt=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>mt(e,o,Lt())));throw He(n,a?.callee??t),n}return s.value};return t},Qt=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ft;return a.issues.length?$t(e,a.issues,i):{success:!0,data:a.value}};function $t(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>mt(e,n,Lt()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const en=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?$t(e,a.issues,i):{success:!0,data:a.value}},tn=Symbol.for(`zod.compile.invalid`),nn=Symbol.for(`zod.compile.fallback`),rn=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==tn)return!0;if(r.definite===!0&&n===void 0)return!1}return an(e,t,n)});function an(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[nn]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new Ft;return a.issues.length===0}const on=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},sn=e=>{let t=Xt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Yt(n,a))};return n},cn=e=>{let t=Xt(e),n=(e,r,i,a)=>t(e,r,i,Yt(n,a));return n},ln=e=>{let t=Zt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Yt(n,a))};return n},un=e=>{let t=Zt(e),n=async(e,r,i,a)=>await t(e,r,i,Yt(n,a));return n},dn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Qt(e)(t,n,i)},fn=e=>(t,n,r)=>Qt(e)(t,n,r),pn=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return en(e)(t,n,i)},mn=e=>async(t,n,r)=>en(e)(t,n,r),hn=/^[cC][0-9a-z]{6,}$/,gn=/^[0-9a-z]+$/,_n=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,vn=/^[0-9a-vA-V]{20}$/,yn=/^[A-Za-z0-9]{27}$/,bn=/^[a-zA-Z0-9_-]{21}$/;function xn(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Sn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cn=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,wn=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Tn=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function En(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const Dn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,On=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,kn=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,An=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mn=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Nn=/^https?$/,Pn=/^\+[1-9]\d{6,14}$/,Fn=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function In(e){return RegExp(`^${e}$`)}const Ln=In(Fn);function Rn(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function zn(e){return RegExp(`^${Rn(e)}$`)}function Bn(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Rn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Rn({precision:e.precision})}`:n;return RegExp(`^${Fn}T(?:${r})$`)}const Vn=/^[\s\S]{0,}$/,Hn=/^-?\d+$/,Un=/^-?\d+(?:\.\d+)?$/,Wn=/^(?:true|false)$/i,Gn=/^[^A-Z]*$/,Kn=/^[^a-z]*$/,D=w(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),qn=e=>{let t=e.value;return!Ae(t)&&t.length!==void 0},Jn={number:`number`,bigint:`bigint`,object:`date`},Yn=w(`$ZodCheckLessThan`,(e,t)=>{D.init(e,t);let n=Jn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Jn[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xn=w(`$ZodCheckGreaterThan`,(e,t)=>{D.init(e,t);let n=Jn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Jn[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Zn=w(`$ZodCheckMultipleOf`,(e,t)=>{D.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Me(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Qn=w(`$ZodCheckNumberFormat`,(e,t)=>{D.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Qe[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),$n=w(`$ZodCheckMaxLength`,(e,t)=>{var n;D.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?gt(r):i)<=t.maximum)return;let a=_t(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),er=w(`$ZodCheckMinLength`,(e,t)=>{var n;D.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?gt(r):i)>=t.minimum)return;let a=_t(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),tr=w(`$ZodCheckLengthEquals`,(e,t)=>{var n;D.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?gt(r):i;if(a===t.length)return;let o=_t(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),nr=w(`$ZodCheckStringFormat`,(e,t)=>{var n,r;D.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),rr=w(`$ZodCheckRegex`,(e,t)=>{nr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ir=w(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Gn,nr.init(e,t)}),ar=w(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Kn,nr.init(e,t)}),or=w(`$ZodCheckIncludes`,(e,t)=>{D.init(e,t);let n=Je(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),sr=w(`$ZodCheckStartsWith`,(e,t)=>{D.init(e,t);let n=RegExp(`^${Je(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),cr=w(`$ZodCheckEndsWith`,(e,t)=>{D.init(e,t);let n=RegExp(`.*${Je(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),lr=w(`$ZodCheckOverwrite`,(e,t)=>{D.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var ur=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
2
+ import{access as e,chmod as t,constants as n,copyFile as r,lstat as i,mkdir as a,open as o,readFile as s,readdir as c,realpath as l,rename as u,rm as d,rmdir as f,stat as p,utimes as ee,writeFile as te}from"node:fs/promises";import ne,{basename as re,dirname as ie,isAbsolute as ae,join as m,posix as oe,relative as se,resolve as ce,sep as le}from"node:path";import{createHash as ue,randomUUID as de}from"node:crypto";import fe,{existsSync as pe,realpathSync as me}from"node:fs";import{homedir as he}from"node:os";import{setTimeout as ge}from"node:timers/promises";import{EventEmitter as _e,once as ve}from"node:events";import ye,{spawn as be}from"node:child_process";import h from"node:process";import{stripVTControlCharacters as xe}from"node:util";const Se={CONFLICT:5,NOT_FOUND:4,OK:0,UNEXPECTED:1,USAGE:2,VALIDATION:3};var g=class extends Error{code;exitCode;reason;constructor(e,t,n,r){super(n,r),this.code=t,this.exitCode=e,this.name=`RefsError`,r?.reason!==void 0&&(this.reason=r.reason)}};const Ce=e=>new g(Se.CONFLICT,`conflict`,e),_=(e,t)=>new g(Se.NOT_FOUND,`not_found`,e,t===void 0?void 0:{reason:t}),v=e=>new g(Se.USAGE,`usage`,e),y=e=>new g(Se.VALIDATION,`validation`,e),we=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,Te=(e,t)=>e instanceof g?{code:e.code,exitCode:e.exitCode,message:we(e.message,e.stack,t.verbose),...e.reason===void 0?{}:{reason:e.reason}}:e instanceof Error?{code:`unexpected`,exitCode:Se.UNEXPECTED,message:we(e.message,e.stack,t.verbose)}:{code:`unexpected`,exitCode:Se.UNEXPECTED,message:String(e)};function Ee(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function De(e,t=`|`){return e.map(e=>Ze(e)).join(t)}function Oe(e,t){return typeof t==`bigint`?t.toString():t}var ke=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function Ae(e){return new ke(e)}function je(e){return e==null}function Me(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ne(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function Pe(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Fe(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Ie(e){return Fe(e._zod.def)??e._zod.def.shape}function Le(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Pe(this,t,e),e},enumerable:!0,configurable:!0})}function Re(e,t,n){t in e?Pe(e,t,n):e[t]=n}function ze(e,t,n,r){let i=Ie(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Le(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Re(e,a,r?r(n.value,a):n.value))}}function Be(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Le(e,n,()=>t[n]):Re(e,n,r.value))}}function b(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Ve(e){return JSON.stringify(e)}function He(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Ue=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function We(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ge=Ae(()=>{if(w.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Ke(e){if(We(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return We(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function qe(e){return Ke(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Je=new Set([`string`,`number`,`symbol`]);function Ye(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Xe(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function x(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ze(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Qe(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const $e={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},et={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function tt(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return ze(i,e,nt(e,t)),Xe(e,b(n,{shape:i,checks:[]}))}function nt(e,t){let n=Ie(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function rt(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(nt(e,t)),a={};return ze(a,e,Reflect.ownKeys(Ie(e)).filter(e=>!i.has(e))),Xe(e,b(n,{shape:a,checks:[]}))}function it(e,t){if(!Ke(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Ie(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Xe(e,b(e._zod.def,{shape:at(e,t)}))}function at(e,t){let n={};return ze(n,e,Reflect.ownKeys(Ie(e))),Be(n,t),n}function ot(e,t){if(!Ke(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Xe(e,b(e._zod.def,{shape:at(e,t)}))}function st(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return ze(n,e,Reflect.ownKeys(Ie(e))),ze(n,t,Reflect.ownKeys(Ie(t))),Xe(e,b(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function ct(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(nt(t,n)):void 0,o={};return ze(o,t,Reflect.ownKeys(Ie(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Xe(t,b(t._zod.def,{shape:o,checks:[]}))}function lt(e,t,n){let r=n?new Set(nt(t,n)):void 0,i={};return ze(i,t,Reflect.ownKeys(Ie(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Xe(t,b(t._zod.def,{shape:i}))}function ut(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function dt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ft(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function pt(e){return typeof e==`string`?e:e?.message}function mt(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function ht(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:pt(e.inst?._zod.def?.error?.(e))??pt(a?.(e))??pt(t?.error?.(e))??pt(n.customError?.(e))??pt(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}const gt=/[\uD800-\uDBFF]/;function _t(e){let t=e.length;if(!gt.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function vt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function yt(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function bt(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function xt(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):Tt(e,n,r.value)}for(let n of Object.getOwnPropertySymbols(t))Tt(e,n,t[n])}function St(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Ct(e,t,n){return St(e,t,n,!1)}function wt(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return St(this,n,r(this))},set(e){St(this,n,e)}})}return t}function Tt(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:St(this,t,n.bind(this))},set(e){St(this,t,e)}})}function Et(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Dt,Ot=!1;const kt={configurable:!0,get(){Ot=!0}};function S(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Dt!==e._zod){Dt=void 0;return}Dt=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,kt);let e=Ot;Ot=!1;try{let r=n(this);return Ot?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Ot||=e,r}catch(n){throw delete this[t],Ot||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function At(e,t,n,r){let i=Et(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function jt(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var Mt;const Nt={value:void 0,enumerable:!1};let Pt=`captureStackTrace`in Error?Error:null;function Ft(e){let t=Pt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Pt=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function C(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Nt.value=new a(r);try{Object.defineProperty(n,"_zod",Nt)}finally{Nt.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),xt(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Ft(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var It=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Lt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Mt=globalThis).__zod_globalConfig??(Mt.__zod_globalConfig={});const w=globalThis.__zod_globalConfig;function Rt(e){return e&&Object.assign(w,e),w}function zt(){let e=this._zod;return e.message??=JSON.stringify(e.def,Oe,2),e.message}function Bt(e){this._zod.message=e}const Vt={get:zt,set:Bt,enumerable:!0,configurable:!0},Ht={value:void 0,enumerable:!1},Ut=new WeakSet([Object.prototype,Error.prototype]),Wt=(e,t)=>{e.name=`$ZodError`,Ht.value=t,Object.defineProperty(e,"issues",Ht),Ht.value=void 0,Object.defineProperty(e,"message",Vt);let n=Object.getPrototypeOf(e);Ut.has(n)||(Ut.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Gt=C(`$ZodError`,Wt);C(`$ZodError`,Wt,void 0,{Parent:Error});function Kt(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function qt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Kt(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Jt(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function Yt(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function T(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${Yt(e.path)}`);return t.join(`
3
+ `)}function Xt(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Zt=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new It;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>ht(e,o,Rt())));throw Ue(n,a?.callee??t),n}return s.value};return t},Qt=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>ht(e,o,Rt())));throw Ue(n,a?.callee??t),n}return s.value};return t},$t=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new It;return a.issues.length?en(e,a.issues,i):{success:!0,data:a.value}};function en(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>ht(e,n,Rt()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const tn=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?en(e,a.issues,i):{success:!0,data:a.value}},nn=Symbol.for(`zod.compile.invalid`),rn=Symbol.for(`zod.compile.fallback`),an=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==nn)return!0;if(r.definite===!0&&n===void 0)return!1}return on(e,t,n)});function on(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[rn]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new It;return a.issues.length===0}const sn=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},cn=e=>{let t=Zt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Xt(n,a))};return n},ln=e=>{let t=Zt(e),n=(e,r,i,a)=>t(e,r,i,Xt(n,a));return n},un=e=>{let t=Qt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Xt(n,a))};return n},dn=e=>{let t=Qt(e),n=async(e,r,i,a)=>await t(e,r,i,Xt(n,a));return n},fn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return $t(e)(t,n,i)},pn=e=>(t,n,r)=>$t(e)(t,n,r),mn=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return tn(e)(t,n,i)},hn=e=>async(t,n,r)=>tn(e)(t,n,r),gn=/^[cC][0-9a-z]{6,}$/,_n=/^[0-9a-z]+$/,vn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,yn=/^[0-9a-vA-V]{20}$/,bn=/^[A-Za-z0-9]{27}$/,xn=/^[a-zA-Z0-9_-]{21}$/;function Sn(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Cn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,wn=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Tn=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,En=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Dn(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const On=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,An=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,jn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Mn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Nn=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Pn=/^https?$/,Fn=/^\+[1-9]\d{6,14}$/,In=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function Ln(e){return RegExp(`^${e}$`)}const Rn=Ln(In);function zn(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Bn(e){return RegExp(`^${zn(e)}$`)}function Vn(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${zn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${zn({precision:e.precision})}`:n;return RegExp(`^${In}T(?:${r})$`)}const Hn=/^[\s\S]{0,}$/,Un=/^-?\d+$/,Wn=/^-?\d+(?:\.\d+)?$/,Gn=/^(?:true|false)$/i,Kn=/^[^A-Z]*$/,qn=/^[^a-z]*$/,E=C(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Jn=e=>{let t=e.value;return!je(t)&&t.length!==void 0},Yn={number:`number`,bigint:`bigint`,object:`date`},Xn=C(`$ZodCheckLessThan`,(e,t)=>{E.init(e,t);let n=Yn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Yn[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Zn=C(`$ZodCheckGreaterThan`,(e,t)=>{E.init(e,t);let n=Yn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Yn[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Qn=C(`$ZodCheckMultipleOf`,(e,t)=>{E.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Ne(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),$n=C(`$ZodCheckNumberFormat`,(e,t)=>{E.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=$e[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),er=C(`$ZodCheckMaxLength`,(e,t)=>{var n;E.init(e,t),(n=e._zod.def).when??(n.when=Jn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?_t(r):i)<=t.maximum)return;let a=vt(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),tr=C(`$ZodCheckMinLength`,(e,t)=>{var n;E.init(e,t),(n=e._zod.def).when??(n.when=Jn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?_t(r):i)>=t.minimum)return;let a=vt(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),nr=C(`$ZodCheckLengthEquals`,(e,t)=>{var n;E.init(e,t),(n=e._zod.def).when??(n.when=Jn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?_t(r):i;if(a===t.length)return;let o=vt(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),rr=C(`$ZodCheckStringFormat`,(e,t)=>{var n,r;E.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),ir=C(`$ZodCheckRegex`,(e,t)=>{rr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ar=C(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Kn,rr.init(e,t)}),or=C(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=qn,rr.init(e,t)}),sr=C(`$ZodCheckIncludes`,(e,t)=>{E.init(e,t);let n=Ye(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),cr=C(`$ZodCheckStartsWith`,(e,t)=>{E.init(e,t);let n=RegExp(`^${Ye(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),lr=C(`$ZodCheckEndsWith`,(e,t)=>{E.init(e,t);let n=RegExp(`.*${Ye(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),ur=C(`$ZodCheckOverwrite`,(e,t)=>{E.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var dr=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
4
4
  `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
5
- `)}\n};`)(...Object.values(this.closed))}};const dr={major:4,minor:6,patch:2},O=w(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=dr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=lt(t),a;for(let o of n){if(o._zod.def.when){if(ut(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Ft;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(pt(t.issues,n,e),i||=lt(t,n))});else{if(t.issues.length===n)continue;pt(t.issues,n,e),i||=lt(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(lt(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Ft;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Ft;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return St(this,`~standard`,mr(this))},set"~standard"(e){xt(this,`~standard`,e)}}),fr=(e,t)=>e.issues.length?{issues:e.issues.map(e=>mt(e,t,Lt()))}:{value:e.value};async function pr(e,t){let n={async:!0};return fr(await e._zod.run({value:t,issues:[]},n),n)}function mr(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return fr(r,n)}catch{}return pr(e,t)},vendor:`zod`,version:1}}const hr=w(`$ZodString`,(e,t)=>{O.init(e,t),e._zod.pattern=t.pattern??Vn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),k=w(`$ZodStringFormat`,(e,t)=>{nr.init(e,t),hr.init(e,t)}),gr=w(`$ZodGUID`,(e,t)=>{t.pattern??=Cn,k.init(e,t)}),_r=w(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=wn(e)}else t.pattern??=wn();k.init(e,t)}),vr=w(`$ZodEmail`,(e,t)=>{t.pattern??=Tn,k.init(e,t)});function yr(e,t){if(!t.normalize&&t.protocol?.source===Nn.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}const br=/[\t\n\r]/g;function xr(e){return e.replace(br,``)}function Sr(e,t){return t.lastIndex=0,t.test(e.hostname)}function Cr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const wr=w(`$ZodURL`,(e,t)=>{k.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=yr(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}t.hostname&&!Sr(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!Cr(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:xr(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Tr=w(`$ZodEmoji`,(e,t)=>{t.pattern??=En(),k.init(e,t)}),Er=w(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?bn:xn(t.length),k.init(e,t)}),Dr=w(`$ZodCUID`,(e,t)=>{t.pattern??=hn,k.init(e,t)}),Or=w(`$ZodCUID2`,(e,t)=>{t.pattern??=gn,k.init(e,t)}),kr=w(`$ZodULID`,(e,t)=>{t.pattern??=_n,k.init(e,t)}),Ar=w(`$ZodXID`,(e,t)=>{t.pattern??=vn,k.init(e,t)}),jr=w(`$ZodKSUID`,(e,t)=>{t.pattern??=yn,k.init(e,t)}),Mr=w(`$ZodISODateTime`,(e,t)=>{t.pattern??=Bn(t),k.init(e,t)}),Nr=w(`$ZodISODate`,(e,t)=>{t.pattern??=Ln,k.init(e,t)}),Pr=w(`$ZodISOTime`,(e,t)=>{t.pattern??=zn(t),k.init(e,t)}),Fr=w(`$ZodISODuration`,(e,t)=>{t.pattern??=Sn,k.init(e,t)}),Ir=w(`$ZodIPv4`,(e,t)=>{t.pattern??=Dn,k.init(e,t)}),Lr=/^[0-9a-fA-F:.]+$/;function Rr(e){if(!Lr.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}const zr=w(`$ZodIPv6`,(e,t)=>{t.pattern??=On,k.init(e,t),e._zod.check=n=>{Rr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Br=w(`$ZodCIDRv4`,(e,t)=>{t.pattern??=kn,k.init(e,t)});function Vr(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Rr(n)}const Hr=w(`$ZodCIDRv6`,(e,t)=>{t.pattern??=An,k.init(e,t),e._zod.check=n=>{Vr(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Ur(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Wr=/^[0-9a-zA-Z+/]*={0,2}$/,Gr=w(`$ZodBase64`,(e,t)=>{t.pattern??=Wr,k.init(e,t),e._zod.check=n=>{Ur(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Kr=/^[A-Za-z0-9_-]*$/;function qr(e){if(!Kr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Ur(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Jr=w(`$ZodBase64URL`,(e,t)=>{t.pattern??=Kr,k.init(e,t),e._zod.check=n=>{qr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Yr=w(`$ZodE164`,(e,t)=>{t.pattern??=Pn,k.init(e,t)});function Xr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Zr=w(`$ZodJWT`,(e,t)=>{k.init(e,t),e._zod.check=n=>{Xr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Qr=w(`$ZodNumber`,(e,t)=>{O.init(e,t),e._zod.pattern=Un,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),$r=w(`$ZodNumberFormat`,(e,t)=>{Qn.init(e,t),Qr.init(e,t)}),ei=w(`$ZodBoolean`,(e,t)=>{O.init(e,t),e._zod.pattern=Wn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),ti=w(`$ZodUnknown`,(e,t)=>{O.init(e,t),e._zod.parse=e=>e}),ni=w(`$ZodNever`,(e,t)=>{O.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function ri(e,t,n){e.issues.length&&t.issues.push(...dt(n,e.issues)),t.value[n]=e.value}const ii=w(`$ZodArray`,(e,t)=>{O.init(e,t);let n=T.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>ri(t,r,e)));else if(ri(c,r,e),s&&c.issues.length!==0&&lt(c))break}return o.length?Promise.all(o).then(()=>r):r}});function ai(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...dt(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}const oi=[];function si(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:oi,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Ze(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function ci(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(lt(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>ai(e,n,i,t,d,f))):ai(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const li=w(`$ZodObject`,(e,t)=>{O.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=ke(()=>si(t));C(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Ne(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=Ue,o=t.catchall,s,c=T.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(lt(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>ai(n,t,e,r,a,o))):ai(s,t,e,r,a,o)}return o?ci(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),ui=w(`$ZodObjectJIT`,(e,t)=>{li.init(e,t);let n=e._zod.parse,r=ke(()=>si(t)),i=T.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new ur([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
5
+ `)}\n};`)(...Object.values(this.closed))}};const fr={major:4,minor:6,patch:2},D=C(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=fr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=ut(t),a;for(let o of n){if(o._zod.def.when){if(dt(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new It;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(mt(t.issues,n,e),i||=ut(t,n))});else{if(t.issues.length===n)continue;mt(t.issues,n,e),i||=ut(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(ut(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new It;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new It;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return Ct(this,`~standard`,hr(this))},set"~standard"(e){St(this,`~standard`,e)}}),pr=(e,t)=>e.issues.length?{issues:e.issues.map(e=>ht(e,t,Rt()))}:{value:e.value};async function mr(e,t){let n={async:!0};return pr(await e._zod.run({value:t,issues:[]},n),n)}function hr(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return pr(r,n)}catch{}return mr(e,t)},vendor:`zod`,version:1}}const gr=C(`$ZodString`,(e,t)=>{D.init(e,t),e._zod.pattern=t.pattern??Hn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),O=C(`$ZodStringFormat`,(e,t)=>{rr.init(e,t),gr.init(e,t)}),_r=C(`$ZodGUID`,(e,t)=>{t.pattern??=wn,O.init(e,t)}),vr=C(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Tn(e)}else t.pattern??=Tn();O.init(e,t)}),yr=C(`$ZodEmail`,(e,t)=>{t.pattern??=En,O.init(e,t)});function br(e,t){if(!t.normalize&&t.protocol?.source===Pn.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}const xr=/[\t\n\r]/g;function Sr(e){return e.replace(xr,``)}function Cr(e,t){return t.lastIndex=0,t.test(e.hostname)}function wr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const Tr=C(`$ZodURL`,(e,t)=>{O.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=br(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}t.hostname&&!Cr(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!wr(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:Sr(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Er=C(`$ZodEmoji`,(e,t)=>{t.pattern??=Dn(),O.init(e,t)}),Dr=C(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?xn:Sn(t.length),O.init(e,t)}),Or=C(`$ZodCUID`,(e,t)=>{t.pattern??=gn,O.init(e,t)}),kr=C(`$ZodCUID2`,(e,t)=>{t.pattern??=_n,O.init(e,t)}),Ar=C(`$ZodULID`,(e,t)=>{t.pattern??=vn,O.init(e,t)}),jr=C(`$ZodXID`,(e,t)=>{t.pattern??=yn,O.init(e,t)}),Mr=C(`$ZodKSUID`,(e,t)=>{t.pattern??=bn,O.init(e,t)}),Nr=C(`$ZodISODateTime`,(e,t)=>{t.pattern??=Vn(t),O.init(e,t)}),Pr=C(`$ZodISODate`,(e,t)=>{t.pattern??=Rn,O.init(e,t)}),Fr=C(`$ZodISOTime`,(e,t)=>{t.pattern??=Bn(t),O.init(e,t)}),Ir=C(`$ZodISODuration`,(e,t)=>{t.pattern??=Cn,O.init(e,t)}),Lr=C(`$ZodIPv4`,(e,t)=>{t.pattern??=On,O.init(e,t)}),Rr=/^[0-9a-fA-F:.]+$/;function zr(e){if(!Rr.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}const Br=C(`$ZodIPv6`,(e,t)=>{t.pattern??=kn,O.init(e,t),e._zod.check=n=>{zr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Vr=C(`$ZodCIDRv4`,(e,t)=>{t.pattern??=An,O.init(e,t)});function Hr(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:zr(n)}const Ur=C(`$ZodCIDRv6`,(e,t)=>{t.pattern??=jn,O.init(e,t),e._zod.check=n=>{Hr(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Wr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Gr=/^[0-9a-zA-Z+/]*={0,2}$/,Kr=C(`$ZodBase64`,(e,t)=>{t.pattern??=Gr,O.init(e,t),e._zod.check=n=>{Wr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),qr=/^[A-Za-z0-9_-]*$/;function Jr(e){if(!qr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Wr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Yr=C(`$ZodBase64URL`,(e,t)=>{t.pattern??=qr,O.init(e,t),e._zod.check=n=>{Jr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Xr=C(`$ZodE164`,(e,t)=>{t.pattern??=Fn,O.init(e,t)});function Zr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Qr=C(`$ZodJWT`,(e,t)=>{O.init(e,t),e._zod.check=n=>{Zr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),$r=C(`$ZodNumber`,(e,t)=>{D.init(e,t),e._zod.pattern=Wn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),ei=C(`$ZodNumberFormat`,(e,t)=>{$n.init(e,t),$r.init(e,t)}),ti=C(`$ZodBoolean`,(e,t)=>{D.init(e,t),e._zod.pattern=Gn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),ni=C(`$ZodUnknown`,(e,t)=>{D.init(e,t),e._zod.parse=e=>e}),ri=C(`$ZodNever`,(e,t)=>{D.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function ii(e,t,n){e.issues.length&&t.issues.push(...ft(n,e.issues)),t.value[n]=e.value}const ai=C(`$ZodArray`,(e,t)=>{D.init(e,t);let n=w.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>ii(t,r,e)));else if(ii(c,r,e),s&&c.issues.length!==0&&ut(c))break}return o.length?Promise.all(o).then(()=>r):r}});function oi(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...ft(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}const si=[];function ci(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:si,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Qe(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function li(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(ut(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>oi(e,n,i,t,d,f))):oi(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const ui=C(`$ZodObject`,(e,t)=>{D.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=Ae(()=>ci(t));S(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Pe(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=We,o=t.catchall,s,c=w.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(ut(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>oi(n,t,e,r,a,o))):oi(s,t,e,r,a,o)}return o?li(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),di=C(`$ZodObjectJIT`,(e,t)=>{ui.init(e,t);let n=e._zod.parse,r=Ae(()=>ci(t)),i=w.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new dr([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
6
6
  let ${e}_ab = false;
7
7
  for (let i = 0; i < ${e}.issues.length; i++) {
8
8
  const iss = ${e}.issues[i];
@@ -13,7 +13,7 @@ import{access as e,chmod as t,constants as n,copyFile as r,lstat as i,mkdir as a
13
13
  if (${e}_ab && ctx && ctx.abortEarly) {
14
14
  payload.value = newResult;
15
15
  return payload;
16
- }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:Be(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
16
+ }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:Ve(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
17
17
  const ${n}_present = ${i};
18
18
  if (!${n}.issues.length || ${n}_present) {
19
19
  if (${n}.issues.length) {${c(n,r)}
@@ -52,9 +52,9 @@ import{access as e,chmod as t,constants as n,copyFile as r,lstat as i,mkdir as a
52
52
  newResult[${r}] = ${n}.value;
53
53
  }
54
54
 
55
- `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Ue,c=!T.jitless,l=c&&We.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?ci([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function di(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!lt(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>mt(e,r,Lt())))}),t)}const fi=w(`$ZodUnion`,(e,t)=>{O.init(e,t),C(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),C(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),C(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),C(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>je(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>di(t,r,e,i)):di(o,r,e,i)}}),pi=w(`$ZodIntersection`,(e,t)=>{O.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>hi(e,t,n)):hi(e,i,a)}});function mi(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ge(e)&&Ge(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=mi(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=mi(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function hi(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=mi(t.value,n.value);if(!c.valid){if(lt(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const gi=w(`$ZodRecord`,(e,t)=>{O.init(e,t);let n=T.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Ge(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>mt(e,i,Lt())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...dt(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...dt(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Un.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>mt(e,i,Lt())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...dt(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...dt(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),_i=w(`$ZodEnum`,(e,t)=>{O.init(e,t);let n=Te(t.entries),r=new Set(n);e._zod.values=r,C(e,`pattern`,e=>{let t=Te(e.def.entries).filter(e=>qe.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Je(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),vi=w(`$ZodTransform`,(e,t)=>{O.init(e,t),e._zod.optin=`optional`,T.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new It(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Ft;return n.value=i,n}});function yi(e,t){return e.value=t.issues.length?void 0:t.value,e}const bi=w(`$ZodOptional`,(e,t)=>{O.init(e,t),C(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,C(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),C(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${je(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>yi(e,t)):yi(e,r)}return t.innerType._zod.run(e,n)}}),xi=w(`$ZodExactOptional`,(e,t)=>{bi.init(e,t),C(e,`values`,e=>e.def.innerType._zod.values),C(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Si=w(`$ZodNullable`,(e,t)=>{O.init(e,t),C(e,`optin`,e=>e.def.innerType._zod.optin),C(e,`optout`,e=>e.def.innerType._zod.optout),C(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${je(t.source)}|null)$`):void 0}),C(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ci=w(`$ZodDefault`,(e,t)=>{O.init(e,t),e._zod.optin=`defaulted`,C(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>wi(e,t)):wi(r,t)}});function wi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Ti=w(`$ZodPrefault`,(e,t)=>{O.init(e,t),e._zod.optin=`defaulted`,C(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Ei=w(`$ZodNonOptional`,(e,t)=>{O.init(e,t),C(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Di(t,e)):Di(i,e)}});function Di(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Oi(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>mt(e,r,Lt()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const ki=w(`$ZodCatch`,(e,t)=>{O.init(e,t),C(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),C(e,`optout`,e=>e.def.innerType._zod.optout),C(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Oi(e,r,t,n)):Oi(e,r,t,n)}}),Ai=w(`$ZodPipe`,(e,t)=>{O.init(e,t),C(e,`values`,e=>e.def.in._zod.values),C(e,`optin`,e=>e.def.in._zod.optin),C(e,`optout`,e=>e.def.out._zod.optout),C(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>ji(e,t.in,n)):ji(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ji(e,t.out,n)):ji(r,t.out,n)}});function ji(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Mi=w(`$ZodPreprocess`,(e,t)=>{Ai.init(e,t)}),Ni=w(`$ZodReadonly`,(e,t)=>{O.init(e,t),C(e,`propValues`,e=>e.def.innerType._zod.propValues),C(e,`values`,e=>e.def.innerType._zod.values),C(e,`optin`,e=>e.def.innerType?._zod?.optin),C(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Pi):Pi(r)}});function Pi(e){return e.memo||(e.value=Object.freeze(e.value)),e}const Fi=w(`$ZodCustom`,(e,t)=>{D.init(e,t),O.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ii(t,n,r,e));Ii(i,n,r,e)}});function Ii(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(yt(e))}}var Li=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Ri=`~memo`,zi=[];function Bi(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function Vi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const Hi=new WeakMap;function Ui(e,t,n){let r=Hi.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,a=e=>{if(i!==2&&e?._zod){let r=Ui(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?Ui(o.value,t,n):0;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=Pe(c);s(e?o(e,!0):1),a(c.catchall);break}case`properties`:s(o(c.shape,!1));break;case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Ui(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Wi(e,i)}function Wi(e,t){return t!==1&&Hi.set(e,t===2),t}function Gi(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}let Ki;const qi=[],Ji={alloc(e,t,n){let r=Ki;if(!r)return n;Ki=void 0;let i={value:n,issues:null};return r.set(t.value,i),qi.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Xi(n,e.value))throw new Li;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Ui(e,new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!Bi(l))return t(s,c);let u=c[Ri];u||(u={buckets:new WeakMap,backEdges:void 0},c[Ri]=u);let d;i===c?d=a:(d=Gi(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Vi(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;Ki=d;let p=qi.length,ee=t(s,c);Ki=void 0;let te=qi.length>p?qi.pop():void 0;return ee instanceof Promise?ee.then(e=>(te&&(te.issues=e.issues.length?Vi(e.issues):zi),e)):(te&&(te.issues=ee.issues.length?Vi(ee.issues):zi),ee)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function Yi(){return Ji}function Xi(e,t){let n=e[Ri]?.backEdges;return n!==void 0&&Bi(t)&&n.has(t)}const Zi=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(vt(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Xe(e.values[0])}`:`Invalid option: expected one of ${Ee(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${Ee(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Qi(){return{localeError:Zi()}}var $i,ea=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function ta(){return new ea}($i=globalThis).__zod_globalRegistry??($i.__zod_globalRegistry=ta());const na=globalThis.__zod_globalRegistry;function ra(e,t){return new e({type:`string`,...S(t)})}function ia(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...S(t)})}function aa(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...S(t)})}function oa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...S(t)})}function sa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...S(t)})}function ca(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...S(t)})}function la(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...S(t)})}function ua(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...S(t)})}function da(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...S(t)})}function fa(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...S(t)})}function pa(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...S(t)})}function ma(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...S(t)})}function ha(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...S(t)})}function ga(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...S(t)})}function _a(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...S(t)})}function va(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...S(t)})}function ya(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...S(t)})}function ba(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...S(t)})}function xa(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...S(t)})}function Sa(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...S(t)})}function Ca(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...S(t)})}function wa(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...S(t)})}function Ta(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...S(t)})}function Ea(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...S(t)})}function Da(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...S(t)})}function Oa(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...S(t)})}function ka(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...S(t)})}function Aa(e,t){return new e({type:`number`,checks:[],...S(t)})}function ja(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...S(t)})}function Ma(e,t){return new e({type:`boolean`,...S(t)})}function Na(e){return new e({type:`unknown`})}function Pa(e,t){return new e({type:`never`,...S(t)})}function Fa(e,t){return new Yn({check:`less_than`,...S(t),value:e,inclusive:!1})}function Ia(e,t){return new Yn({check:`less_than`,...S(t),value:e,inclusive:!0})}function La(e,t){return new Xn({check:`greater_than`,...S(t),value:e,inclusive:!1})}function Ra(e,t){return new Xn({check:`greater_than`,...S(t),value:e,inclusive:!0})}function za(e,t){return new Zn({check:`multiple_of`,...S(t),value:e})}function Ba(e,t){return new $n({check:`max_length`,...S(t),maximum:e})}function Va(e,t){return new er({check:`min_length`,...S(t),minimum:e})}function Ha(e,t){return new tr({check:`length_equals`,...S(t),length:e})}function Ua(e,t){return new rr({check:`string_format`,format:`regex`,...S(t),pattern:e})}function Wa(e){return new ir({check:`string_format`,format:`lowercase`,...S(e)})}function Ga(e){return new ar({check:`string_format`,format:`uppercase`,...S(e)})}function Ka(e,t){return new or({check:`string_format`,format:`includes`,...S(t),includes:e})}function qa(e,t){return new sr({check:`string_format`,format:`starts_with`,...S(t),prefix:e})}function Ja(e,t){return new cr({check:`string_format`,format:`ends_with`,...S(t),suffix:e})}function Ya(e){return new lr({check:`overwrite`,tx:e})}function Xa(e){return Ya(t=>t.normalize(e))}function Za(){return Ya(e=>e.trim())}function Qa(){return Ya(e=>e.toLowerCase())}function $a(){return Ya(e=>e.toUpperCase())}function eo(){return Ya(e=>Ve(e))}function to(e,t,n){return new e({type:`array`,element:t,...S(n)})}function no(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...S(n)})}function ro(e,t){let n=io(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(yt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(yt(r))}},e(t.value,t)),t);return n}function io(e,t){let n=new D({check:`custom`,...S(t)});return n._zod.check=e,n}function ao(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ne(e,t,n[t]);return e}function oo(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??na,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function so(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function A(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,A(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&ao(o.schema,c),t.io===`input`&&j(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function co(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function lo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${co(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+co(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
55
+ `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=We,c=!w.jitless,l=c&&Ge.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?li([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function fi(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ut(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ht(e,r,Rt())))}),t)}const pi=C(`$ZodUnion`,(e,t)=>{D.init(e,t),S(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),S(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),S(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),S(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Me(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>fi(t,r,e,i)):fi(o,r,e,i)}}),mi=C(`$ZodIntersection`,(e,t)=>{D.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>gi(e,t,n)):gi(e,i,a)}});function hi(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ke(e)&&Ke(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=hi(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=hi(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function gi(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=hi(t.value,n.value);if(!c.valid){if(ut(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const _i=C(`$ZodRecord`,(e,t)=>{D.init(e,t);let n=w.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Ke(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>ht(e,i,Rt())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...ft(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...ft(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Wn.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>ht(e,i,Rt())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...ft(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...ft(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),vi=C(`$ZodEnum`,(e,t)=>{D.init(e,t);let n=Ee(t.entries),r=new Set(n);e._zod.values=r,S(e,`pattern`,e=>{let t=Ee(e.def.entries).filter(e=>Je.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Ye(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),yi=C(`$ZodTransform`,(e,t)=>{D.init(e,t),e._zod.optin=`optional`,w.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Lt(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new It;return n.value=i,n}});function bi(e,t){return e.value=t.issues.length?void 0:t.value,e}const xi=C(`$ZodOptional`,(e,t)=>{D.init(e,t),S(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,S(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),S(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Me(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>bi(e,t)):bi(e,r)}return t.innerType._zod.run(e,n)}}),Si=C(`$ZodExactOptional`,(e,t)=>{xi.init(e,t),S(e,`values`,e=>e.def.innerType._zod.values),S(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Ci=C(`$ZodNullable`,(e,t)=>{D.init(e,t),S(e,`optin`,e=>e.def.innerType._zod.optin),S(e,`optout`,e=>e.def.innerType._zod.optout),S(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Me(t.source)}|null)$`):void 0}),S(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),wi=C(`$ZodDefault`,(e,t)=>{D.init(e,t),e._zod.optin=`defaulted`,S(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Ti(e,t)):Ti(r,t)}});function Ti(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Ei=C(`$ZodPrefault`,(e,t)=>{D.init(e,t),e._zod.optin=`defaulted`,S(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Di=C(`$ZodNonOptional`,(e,t)=>{D.init(e,t),S(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Oi(t,e)):Oi(i,e)}});function Oi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function ki(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>ht(e,r,Rt()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const Ai=C(`$ZodCatch`,(e,t)=>{D.init(e,t),S(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),S(e,`optout`,e=>e.def.innerType._zod.optout),S(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>ki(e,r,t,n)):ki(e,r,t,n)}}),ji=C(`$ZodPipe`,(e,t)=>{D.init(e,t),S(e,`values`,e=>e.def.in._zod.values),S(e,`optin`,e=>e.def.in._zod.optin),S(e,`optout`,e=>e.def.out._zod.optout),S(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Mi(e,t.in,n)):Mi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Mi(e,t.out,n)):Mi(r,t.out,n)}});function Mi(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Ni=C(`$ZodPreprocess`,(e,t)=>{ji.init(e,t)}),Pi=C(`$ZodReadonly`,(e,t)=>{D.init(e,t),S(e,`propValues`,e=>e.def.innerType._zod.propValues),S(e,`values`,e=>e.def.innerType._zod.values),S(e,`optin`,e=>e.def.innerType?._zod?.optin),S(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Fi):Fi(r)}});function Fi(e){return e.memo||(e.value=Object.freeze(e.value)),e}const Ii=C(`$ZodCustom`,(e,t)=>{E.init(e,t),D.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Li(t,n,r,e));Li(i,n,r,e)}});function Li(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(bt(e))}}var Ri=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const zi=`~memo`,Bi=[];function Vi(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function Hi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const Ui=new WeakMap;function Wi(e,t,n){let r=Ui.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,a=e=>{if(i!==2&&e?._zod){let r=Wi(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?Wi(o.value,t,n):0;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=Fe(c);s(e?o(e,!0):1),a(c.catchall);break}case`properties`:s(o(c.shape,!1));break;case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Wi(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Gi(e,i)}function Gi(e,t){return t!==1&&Ui.set(e,t===2),t}function Ki(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}let qi;const Ji=[],Yi={alloc(e,t,n){let r=qi;if(!r)return n;qi=void 0;let i={value:n,issues:null};return r.set(t.value,i),Ji.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Zi(n,e.value))throw new Ri;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Wi(e,new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!Vi(l))return t(s,c);let u=c[zi];u||(u={buckets:new WeakMap,backEdges:void 0},c[zi]=u);let d;i===c?d=a:(d=Ki(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Hi(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;qi=d;let p=Ji.length,ee=t(s,c);qi=void 0;let te=Ji.length>p?Ji.pop():void 0;return ee instanceof Promise?ee.then(e=>(te&&(te.issues=e.issues.length?Hi(e.issues):Bi),e)):(te&&(te.issues=ee.issues.length?Hi(ee.issues):Bi),ee)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function Xi(){return Yi}function Zi(e,t){let n=e[zi]?.backEdges;return n!==void 0&&Vi(t)&&n.has(t)}const Qi=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(yt(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Ze(e.values[0])}`:`Invalid option: expected one of ${De(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${De(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function $i(){return{localeError:Qi()}}var ea,ta=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function na(){return new ta}(ea=globalThis).__zod_globalRegistry??(ea.__zod_globalRegistry=na());const ra=globalThis.__zod_globalRegistry;function ia(e,t){return new e({type:`string`,...x(t)})}function aa(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...x(t)})}function oa(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...x(t)})}function sa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...x(t)})}function ca(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...x(t)})}function la(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...x(t)})}function ua(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...x(t)})}function da(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...x(t)})}function fa(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...x(t)})}function pa(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...x(t)})}function ma(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...x(t)})}function ha(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...x(t)})}function ga(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...x(t)})}function _a(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...x(t)})}function va(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...x(t)})}function ya(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...x(t)})}function ba(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...x(t)})}function xa(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...x(t)})}function Sa(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...x(t)})}function Ca(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...x(t)})}function wa(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...x(t)})}function Ta(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...x(t)})}function Ea(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...x(t)})}function Da(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...x(t)})}function Oa(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...x(t)})}function ka(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...x(t)})}function Aa(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...x(t)})}function ja(e,t){return new e({type:`number`,checks:[],...x(t)})}function Ma(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...x(t)})}function Na(e,t){return new e({type:`boolean`,...x(t)})}function Pa(e){return new e({type:`unknown`})}function Fa(e,t){return new e({type:`never`,...x(t)})}function Ia(e,t){return new Xn({check:`less_than`,...x(t),value:e,inclusive:!1})}function La(e,t){return new Xn({check:`less_than`,...x(t),value:e,inclusive:!0})}function Ra(e,t){return new Zn({check:`greater_than`,...x(t),value:e,inclusive:!1})}function za(e,t){return new Zn({check:`greater_than`,...x(t),value:e,inclusive:!0})}function Ba(e,t){return new Qn({check:`multiple_of`,...x(t),value:e})}function Va(e,t){return new er({check:`max_length`,...x(t),maximum:e})}function Ha(e,t){return new tr({check:`min_length`,...x(t),minimum:e})}function Ua(e,t){return new nr({check:`length_equals`,...x(t),length:e})}function Wa(e,t){return new ir({check:`string_format`,format:`regex`,...x(t),pattern:e})}function Ga(e){return new ar({check:`string_format`,format:`lowercase`,...x(e)})}function Ka(e){return new or({check:`string_format`,format:`uppercase`,...x(e)})}function qa(e,t){return new sr({check:`string_format`,format:`includes`,...x(t),includes:e})}function Ja(e,t){return new cr({check:`string_format`,format:`starts_with`,...x(t),prefix:e})}function Ya(e,t){return new lr({check:`string_format`,format:`ends_with`,...x(t),suffix:e})}function Xa(e){return new ur({check:`overwrite`,tx:e})}function Za(e){return Xa(t=>t.normalize(e))}function Qa(){return Xa(e=>e.trim())}function $a(){return Xa(e=>e.toLowerCase())}function eo(){return Xa(e=>e.toUpperCase())}function to(){return Xa(e=>He(e))}function no(e,t,n){return new e({type:`array`,element:t,...x(n)})}function ro(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...x(n)})}function io(e,t){let n=ao(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(bt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(bt(r))}},e(t.value,t)),t);return n}function ao(e,t){let n=new E({check:`custom`,...x(t)});return n._zod.check=e,n}function oo(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Pe(e,t,n[t]);return e}function so(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??ra,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function co(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function k(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,k(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&oo(o.schema,c),t.io===`input`&&A(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function lo(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${lo(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+lo(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
56
56
 
57
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function uo(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;uo(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const fo=new Set([`type`,`properties`,`required`,`additionalProperties`]),po=[`oneOf`,`anyOf`];function mo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function ho(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!fo.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??mo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ne(n,r,e.length===1?e[0]:ho(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=mo(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function go(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of fo)if(t in e)return;let n=t.filter(e=>po.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=ho(t);else{let e=n[0],i=po.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>ho([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,ao(e,r))}function _o(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):ao(i,s),ao(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())uo(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])go(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}ao(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ne(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:yo(t,`input`,e.processors),output:yo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function j(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return j(r.element,n);if(r.type===`set`)return j(r.valueType,n);if(r.type===`lazy`)return j(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return j(r.innerType,n);if(r.type===`intersection`)return j(r.left,n)||j(r.right,n);if(r.type===`record`||r.type===`map`)return j(r.keyType,n)||j(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:j(r.in,n)||j(r.out,n);if(r.type===`object`){for(let e in r.shape)if(j(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(j(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(j(e,n))return!0;return!!(r.rest&&j(r.rest,n))}return!1}const vo=(e,t={})=>n=>{let r=oo({...n,processors:t});return A(e,r),lo(r,e),_o(r,e)},yo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=oo({...i??{},target:a,io:t,processors:n});return A(e,o),lo(o,e),_o(o,e)},bo=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},xo=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},So=(e,t)=>{bo(e,`minimum`,t),xo(e,`maximum`,t)},Co=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},wo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},To=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Eo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Do=(e,t)=>bo(e,`minimum`,t.minimum),Oo=(e,t)=>xo(e,`maximum`,t.maximum),ko=e=>(t,n)=>{Eo(t,n.format);let[r,i]=e[n.format];bo(t,`minimum`,r),xo(t,`maximum`,i)},Ao={greater_than:(e,t)=>bo(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>xo(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Co(e,t.value),number_format:ko(Qe),bigint_format:ko($e),min_length:Do,max_length:Oo,length_equals:(e,t)=>So(e,t.length),min_size:Do,max_size:Oo,size_equals:(e,t)=>So(e,t.size),string_format:(e,t)=>{Eo(e,t.format),t.pattern&&wo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>To(e,t.mime)};function M(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Ao[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&bo(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&bo(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&xo(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&xo(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Co(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&To(t,i.mime);for(let e of i.patterns??[])wo(t,e);return t}const jo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Mo=new Map([[Wr,jn],[Kr,Mn]]),No=e=>Mo.get(e)??e,Po=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=M(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=jo[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(No);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Fo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=M(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):so(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Io=(e,t,n,r)=>{n.type=`boolean`},Lo=(e,t,n,r)=>{n.not={}},Ro=(e,t,n,r)=>{let i=e._zod.def,a=Te(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},zo=(e,t,n,r)=>{so(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Bo=(e,t,n,r)=>{so(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Vo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=M(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=A(a.element,t,{...r,path:[...r.path,`items`]})};function Ho(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Ho(t.out):t.type===`catch`?Ho(t.innerType):e._zod.optin}const Uo=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&so(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ne(i.properties,e,A(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e];return t.io===`input`?Ho(n)===void 0:n._zod.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=A(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Wo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>A(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Go=(e,t,n,r)=>{let i=e._zod.def,a=A(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=A(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)};function Ko(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ko(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ko(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Un:Hn).source),p):p}const qo=new WeakMap;function Jo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of qo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ko(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const Yo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=M(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=A(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ne(i.patternProperties,No(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=A(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=qo.get(t);n||(n=[],qo.set(t,n),t.deferred.push(()=>Jo(t))),n.push(e)}i.additionalProperties=A(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Ho(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Xo=(e,t,n,r)=>{let i=e._zod.def,a=A(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Zo=(e,t,n,r)=>{let i=e._zod.def;A(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Qo=Symbol();function $o(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(so(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Qo):JSON.parse(o)}const es=(e,t,n,r)=>{let i=e._zod.def;A(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n.default=o)},ts=(e,t,n,r)=>{let i=e._zod.def;A(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n._prefault=o)},ns=(e,t,n,r)=>{let i=e._zod.def;A(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{so(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},rs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;A(o,t,r);let s=t.seen.get(e);s.ref=o},is=(e,t,n,r)=>{let i=e._zod.def;A(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},as=(e,t,n,r)=>{let i=e._zod.def;A(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},os=new WeakSet([Object.prototype,Error.prototype]);function ss(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const N=w(`ZodError`,(e,t)=>{Wt.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);os.has(n)||(os.add(n),ss(n,`format`,e=>t=>qt(e,t)),ss(n,`flatten`,e=>t=>Kt(e,t)),ss(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,De,2)}),ss(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,De,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),cs=Xt(N),ls=Zt(N),us=Qt(N),ds=en(N),fs=sn(N),ps=cn(N),ms=ln(N),hs=un(N),gs=dn(N),_s=fn(N),vs=pn(N),ys=mn(N);function bs(){T.localeError||Lt(Qi())}function xs(){T.memoizer||Lt({memoizer:Yi()})}const P=w(`ZodType`,(e,t)=>(bs(),O.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(x(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ye(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Lc(e,t))},superRefine(e,t){return this.check(Rc(e,t))},overwrite(e){return this.check(Ya(e))},optional(){return vc(this)},exactOptional(){return bc(this)},nullable(){return Sc(this)},nullish(){return vc(Sc(this))},nonoptional(e){return Oc(this,e)},array(){return ic(this)},or(e){return cc([this,e])},and(e){return uc(this,e)},transform(e){return Mc(this,gc(e))},default(e){return wc(this,e)},prefault(e){return Ec(this,e)},catch(e){return Ac(this,e)},pipe(e){return Mc(this,e)},readonly(){return Fc(this)},describe(e){let t=this.clone();return na.add(t,{description:e}),t},meta(...e){if(e.length===0)return na.get(this);let t=this.clone();return na.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return St(this,`~standard`,{...mr(this),jsonSchema:{input:yo(this,`input`),output:yo(this,`output`)}})},set"~standard"(e){xt(this,`~standard`,e)},parse:function e(t,n){return cs(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ls(this,t,n,{callee:e})},safeParse(e,t){return us(this,e,t)},async safeParseAsync(e,t){return ds(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){xt(this,`spa`,e)},validate(e,t){return rn(this,e,t)},validateAsync(e,t){return on(this,e,t)},encode:function e(t,n){return fs(this,t,n,{callee:e})},decode:function e(t,n){return ps(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await ms(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await hs(this,t,n,{callee:e})},safeEncode(e,t){return gs(this,e,t)},safeDecode(e,t){return _s(this,e,t)},async safeEncodeAsync(e,t){return vs(this,e,t)},async safeDecodeAsync(e,t){return ys(this,e,t)},toJSONSchema(e){return vo(this,{})(e)},get description(){return na.get(this)?.description},get _def(){return this._zod.def}}),Ss=w(`_ZodString`,(e,t)=>{hr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r)},Ct({format:e=>M(e).format??null,minLength:e=>M(e).minimum??null,maxLength:e=>M(e).maximum??null},{regex(...e){return this.check(Ua(...e))},includes(...e){return this.check(Ka(...e))},startsWith(...e){return this.check(qa(...e))},endsWith(...e){return this.check(Ja(...e))},min(...e){return this.check(Va(...e))},max(...e){return this.check(Ba(...e))},length(...e){return this.check(Ha(...e))},nonempty(...e){return this.check(Va(1,...e))},lowercase(e){return this.check(Wa(e))},uppercase(e){return this.check(Ga(e))},trim(){return this.check(Za())},normalize(...e){return this.check(Xa(...e))},toLowerCase(){return this.check(Qa())},toUpperCase(){return this.check($a())},slugify(){return this.check(eo())}})),Cs=w(`ZodString`,(e,t)=>{hr.init(e,t),Ss.init(e,t)},{email(e){return this.check(ia(Os,e))},url(e){return this.check(ua(js,e))},jwt(e){return this.check(Ta(Ks,e))},emoji(e){return this.check(da(Ms,e))},guid(e){return this.check(aa(ks,e))},uuid(e){return this.check(oa(As,e))},uuidv4(e){return this.check(sa(As,e))},uuidv6(e){return this.check(ca(As,e))},uuidv7(e){return this.check(la(As,e))},nanoid(e){return this.check(fa(Ns,e))},cuid(e){return this.check(pa(Ps,e))},cuid2(e){return this.check(ma(Fs,e))},ulid(e){return this.check(ha(Is,e))},base64(e){return this.check(Sa(Us,e))},base64url(e){return this.check(Ca(Ws,e))},xid(e){return this.check(ga(Ls,e))},ksuid(e){return this.check(_a(Rs,e))},ipv4(e){return this.check(va(zs,e))},ipv6(e){return this.check(ya(Bs,e))},cidrv4(e){return this.check(ba(Vs,e))},cidrv6(e){return this.check(xa(Hs,e))},e164(e){return this.check(wa(Gs,e))},datetime(e){return this.check(Ea(ws,e))},date(e){return this.check(Da(Ts,e))},time(e){return this.check(Oa(Es,e))},duration(e){return this.check(ka(Ds,e))}});function F(e){return ra(Cs,e)}const I=w(`ZodStringFormat`,(e,t)=>{k.init(e,t),Ss.init(e,t)}),ws=w(`ZodISODateTime`,(e,t)=>{Mr.init(e,t),I.init(e,t)}),Ts=w(`ZodISODate`,(e,t)=>{Nr.init(e,t),I.init(e,t)}),Es=w(`ZodISOTime`,(e,t)=>{Pr.init(e,t),I.init(e,t)}),Ds=w(`ZodISODuration`,(e,t)=>{Fr.init(e,t),I.init(e,t)}),Os=w(`ZodEmail`,(e,t)=>{vr.init(e,t),I.init(e,t)}),ks=w(`ZodGUID`,(e,t)=>{gr.init(e,t),I.init(e,t)}),As=w(`ZodUUID`,(e,t)=>{_r.init(e,t),I.init(e,t)}),js=w(`ZodURL`,(e,t)=>{wr.init(e,t),I.init(e,t)}),Ms=w(`ZodEmoji`,(e,t)=>{Tr.init(e,t),I.init(e,t)}),Ns=w(`ZodNanoID`,(e,t)=>{Er.init(e,t),I.init(e,t)}),Ps=w(`ZodCUID`,(e,t)=>{Dr.init(e,t),I.init(e,t)}),Fs=w(`ZodCUID2`,(e,t)=>{Or.init(e,t),I.init(e,t)}),Is=w(`ZodULID`,(e,t)=>{kr.init(e,t),I.init(e,t)}),Ls=w(`ZodXID`,(e,t)=>{Ar.init(e,t),I.init(e,t)}),Rs=w(`ZodKSUID`,(e,t)=>{jr.init(e,t),I.init(e,t)}),zs=w(`ZodIPv4`,(e,t)=>{Ir.init(e,t),I.init(e,t)}),Bs=w(`ZodIPv6`,(e,t)=>{zr.init(e,t),I.init(e,t)}),Vs=w(`ZodCIDRv4`,(e,t)=>{Br.init(e,t),I.init(e,t)}),Hs=w(`ZodCIDRv6`,(e,t)=>{Hr.init(e,t),I.init(e,t)}),Us=w(`ZodBase64`,(e,t)=>{Gr.init(e,t),I.init(e,t)}),Ws=w(`ZodBase64URL`,(e,t)=>{Jr.init(e,t),I.init(e,t)}),Gs=w(`ZodE164`,(e,t)=>{Yr.init(e,t),I.init(e,t)}),Ks=w(`ZodJWT`,(e,t)=>{Zr.init(e,t),I.init(e,t)}),qs=w(`ZodNumber`,(e,t)=>{Qr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.isFinite=!0},Ct({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=M(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=M(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=M(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>M(e).format??null},{gt(e,t){return this.check(La(e,t))},gte(e,t){return this.check(Ra(e,t))},min(e,t){return this.check(Ra(e,t))},lt(e,t){return this.check(Fa(e,t))},lte(e,t){return this.check(Ia(e,t))},max(e,t){return this.check(Ia(e,t))},int(e){return this.check(Xs(e))},safe(e){return this.check(Xs(e))},positive(e){return this.check(La(0,e))},nonnegative(e){return this.check(Ra(0,e))},negative(e){return this.check(Fa(0,e))},nonpositive(e){return this.check(Ia(0,e))},multipleOf(e,t){return this.check(za(e,t))},step(e,t){return this.check(za(e,t))},finite(){return this}}));function Js(e){return Aa(qs,e)}const Ys=w(`ZodNumberFormat`,(e,t)=>{$r.init(e,t),qs.init(e,t)});function Xs(e){return ja(Ys,e)}const Zs=w(`ZodBoolean`,(e,t)=>{ei.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r)});function Qs(e){return Ma(Zs,e)}const $s=w(`ZodUnknown`,(e,t)=>{ti.init(e,t),P.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function ec(){return Na($s)}const tc=w(`ZodNever`,(e,t)=>{ni.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function nc(e){return Pa(tc,e)}const rc=w(`ZodArray`,(e,t)=>{xs(),ii.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Va(e,t))},nonempty(e){return this.check(Va(1,e))},max(e,t){return this.check(Ba(e,t))},length(e,t){return this.check(Ha(e,t))},unwrap(){return this.element}});function ic(e,t){return to(rc,e,t)}const ac=w(`ZodObject`,(e,t)=>{xs(),ui.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),kt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return mc(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(x(this._zod.def,{catchall:e}))},passthrough(){return this.clone(x(this._zod.def,{catchall:ec()}))},loose(){return this.clone(x(this._zod.def,{catchall:ec()}))},strict(){return this.clone(x(this._zod.def,{catchall:nc()}))},strip(){return this.clone(x(this._zod.def,{catchall:void 0}))},extend(e){return rt(this,e)},safeExtend(e){return at(this,e)},merge(e){return ot(this,e)},pick(e){return et(this,e)},omit(e){return nt(this,e)},partial(...e){return st(_c,this,e[0])},exactPartial(...e){return st(yc,this,e[0],`exactPartial`)},required(...e){return ct(Dc,this,e[0])}});function L(e,t){return new ac({type:`object`,shape:e,catchall:nc(),...S(t)})}function oc(e,t){return new ac({type:`object`,shape:e,catchall:ec(),...S(t)})}const sc=w(`ZodUnion`,(e,t)=>{fi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r),e.options=t.options});function cc(e,t){return new sc({type:`union`,options:e,...S(t)})}const lc=w(`ZodIntersection`,(e,t)=>{pi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r)});function uc(e,t){return new lc({type:`intersection`,left:e,right:t})}const dc=w(`ZodRecord`,(e,t)=>{xs(),gi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function fc(e,t,n){return!t||!t._zod?new dc({type:`record`,keyType:F(),valueType:e,...S(t)}):new dc({type:`record`,keyType:e,valueType:t,...S(n)})}const pc=w(`ZodEnum`,(e,t)=>{_i.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new pc({...t,checks:[],...S(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new pc({...t,checks:[],...S(r),entries:i})}});function mc(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new pc({type:`enum`,entries:n,...S(t)})}const hc=w(`ZodTransform`,(e,t)=>{xs(),vi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new It(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(yt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(yt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function gc(e){return new hc({type:`transform`,transform:e})}const _c=w(`ZodOptional`,(e,t)=>{bi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vc(e){return new _c({type:`optional`,innerType:e})}const yc=w(`ZodExactOptional`,(e,t)=>{xi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bc(e){return new yc({type:`optional`,innerType:e})}const xc=w(`ZodNullable`,(e,t)=>{Si.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sc(e){return new xc({type:`nullable`,innerType:e})}const Cc=w(`ZodDefault`,(e,t)=>{Ci.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function wc(e,t){return new Cc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ke(t)}})}const Tc=w(`ZodPrefault`,(e,t)=>{Ti.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ec(e,t){return new Tc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ke(t)}})}const Dc=w(`ZodNonOptional`,(e,t)=>{Ei.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oc(e,t){return new Dc({type:`nonoptional`,innerType:e,...S(t)})}const kc=w(`ZodCatch`,(e,t)=>{ki.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ac(e,t){return new kc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:At(t)})}const jc=w(`ZodPipe`,(e,t)=>{Ai.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.in=t.in,e.out=t.out});function Mc(e,t){return new jc({type:`pipe`,in:e,out:t})}const Nc=w(`ZodPreprocess`,(e,t)=>{jc.init(e,t),Mi.init(e,t)}),Pc=w(`ZodReadonly`,(e,t)=>{Ni.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Fc(e){return new Pc({type:`readonly`,innerType:e})}const Ic=w(`ZodCustom`,(e,t)=>{Fi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r)});function Lc(e,t={}){return no(Ic,e,t)}function Rc(e,t){return ro(e,t)}function zc(e,t){return new Nc({type:`pipe`,in:gc(e),out:t})}function Bc(e){return Ea(ws,e)}const Vc=new Set([`__proto__`,`constructor`,`prototype`]),Hc=(e,t,n)=>zc((n,r)=>{if(typeof n==`object`&&n)for(let i of Reflect.ownKeys(n))(typeof i!=`string`||!e(i))&&r.addIssue({code:`custom`,message:t(String(i)),path:[String(i)]});return n},n),Uc=e=>e.length>0&&!Vc.has(e),Wc=e=>Hc(Uc,()=>`package key must be non-empty and not "__proto__", "constructor", or "prototype"`,fc(F().min(1),e)),Gc=e=>Uc(e),Kc=[`blobless`,`full`],qc=[`ssh`,`https`],Jc=/^(?!\.{1,2}$)[^/\\%:]+$/u,Yc=/^[a-z0-9][a-z0-9.-]*(?:_[1-9]\d{0,4})?$/u,Xc=/^(?<amount>[1-9]\d{0,3})(?<unit>[mhd])$/u,Zc={d:864e5,h:36e5,m:6e4},Qc=e=>e!==``&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e),$c=e=>{if(e===void 0)return!0;let t=Number(e);return t>=1&&t<=65535},el=e=>{let[t=``,n]=e.split(`_`);return $c(n)?t.split(`.`).every(e=>Qc(e)):!1},tl=e=>e.isWellFormed(),nl=e=>{let[t,...n]=e.split(`/`);return t===void 0||n.length<2||!Yc.test(t)||!el(t)?!1:n.every(e=>Jc.test(e))},rl=F().refine(e=>tl(e)&&nl(e),`ref key must be host/path…/repo with safe, non-empty segments`).brand(),il=F().regex(Xc,`duration must be <n>m, <n>h, or <n>d`).brand(),al=e=>{let t=Xc.exec(e);if(t===null)throw Error(`invalid duration: ${e}`);let{amount:n,unit:r}=t.groups??{};if(!n||!r)throw Error(`invalid duration: ${e}`);return Number(n)*Zc[r]},ol=mc(Kc),sl=mc(qc),cl=F().refine(e=>e.includes(`{version}`),`tag format must contain {version}`),ll=F().refine(e=>{if(e===`.`)return!0;let t=e.split(`/`);return t.length>0&&t.every(e=>Jc.test(e)&&e!==`.`)},`package path must be "." or a normalized relative path without traversal`),ul={clone_mode:`blobless`,git_transport:`https`,sync_ttl:`1h`},dl=L({clone_mode:ol.default(ul.clone_mode),git_transport:sl.default(ul.git_transport),sync_ttl:il.default(il.parse(ul.sync_ttl))}),fl=L((e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.removeDefault().optional()])))(dl.shape)),pl=L({description:F().min(1),path:ll,tag_format:cl.optional()}),ml=L({default_branch:F().min(1),description:F().min(1),packages:Wc(pl).optional(),tag_format:cl.optional(),url:F().min(1),...fl.shape}),hl=oc({cli_version:F().min(1),schema_version:Js().int().positive()}),gl=Hc(e=>rl.safeParse(e).success,()=>`ref key must be host/path…/repo with safe, non-empty segments`,fc(F(),ml)),_l=L({check:Qs().default(!0),notify:Qs().default(!0)}),vl=L({meta:hl,refs:gl.default({}),settings:dl,updates:_l.optional()});
57
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function fo(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;fo(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const po=new Set([`type`,`properties`,`required`,`additionalProperties`]),mo=[`oneOf`,`anyOf`];function ho(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function go(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!po.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??ho(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Pe(n,r,e.length===1?e[0]:go(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=ho(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function _o(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of po)if(t in e)return;let n=t.filter(e=>mo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=go(t);else{let e=n[0],i=mo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>go([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,oo(e,r))}function vo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):oo(i,s),oo(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())fo(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])_o(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}oo(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Pe(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:bo(t,`input`,e.processors),output:bo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function A(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return A(r.element,n);if(r.type===`set`)return A(r.valueType,n);if(r.type===`lazy`)return A(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return A(r.innerType,n);if(r.type===`intersection`)return A(r.left,n)||A(r.right,n);if(r.type===`record`||r.type===`map`)return A(r.keyType,n)||A(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:A(r.in,n)||A(r.out,n);if(r.type===`object`){for(let e in r.shape)if(A(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(A(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(A(e,n))return!0;return!!(r.rest&&A(r.rest,n))}return!1}const yo=(e,t={})=>n=>{let r=so({...n,processors:t});return k(e,r),uo(r,e),vo(r,e)},bo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=so({...i??{},target:a,io:t,processors:n});return k(e,o),uo(o,e),vo(o,e)},xo=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},So=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Co=(e,t)=>{xo(e,`minimum`,t),So(e,`maximum`,t)},wo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},To=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},Eo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Do=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Oo=(e,t)=>xo(e,`minimum`,t.minimum),ko=(e,t)=>So(e,`maximum`,t.maximum),Ao=e=>(t,n)=>{Do(t,n.format);let[r,i]=e[n.format];xo(t,`minimum`,r),So(t,`maximum`,i)},jo={greater_than:(e,t)=>xo(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>So(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>wo(e,t.value),number_format:Ao($e),bigint_format:Ao(et),min_length:Oo,max_length:ko,length_equals:(e,t)=>Co(e,t.length),min_size:Oo,max_size:ko,size_equals:(e,t)=>Co(e,t.size),string_format:(e,t)=>{Do(e,t.format),t.pattern&&To(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Eo(e,t.mime)};function j(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)jo[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&xo(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&xo(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&So(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&So(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&wo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Eo(t,i.mime);for(let e of i.patterns??[])To(t,e);return t}const Mo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},No=new Map([[Gr,Mn],[qr,Nn]]),Po=e=>No.get(e)??e,Fo=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=j(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Mo[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Po);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Io=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=j(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):co(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Lo=(e,t,n,r)=>{n.type=`boolean`},Ro=(e,t,n,r)=>{n.not={}},zo=(e,t,n,r)=>{let i=e._zod.def,a=Ee(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Bo=(e,t,n,r)=>{co(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Vo=(e,t,n,r)=>{co(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Ho=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=j(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=k(a.element,t,{...r,path:[...r.path,`items`]})};function Uo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Uo(t.out):t.type===`catch`?Uo(t.innerType):e._zod.optin}const Wo=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&co(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Pe(i.properties,e,k(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e];return t.io===`input`?Uo(n)===void 0:n._zod.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=k(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Go=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>k(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ko=(e,t,n,r)=>{let i=e._zod.def,a=k(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=k(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)};function qo(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=qo(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>qo(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Wn:Un).source),p):p}const Jo=new WeakMap;function Yo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of Jo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=qo(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const Xo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=j(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=k(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Pe(i.patternProperties,Po(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=k(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Jo.get(t);n||(n=[],Jo.set(t,n),t.deferred.push(()=>Yo(t))),n.push(e)}i.additionalProperties=k(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Uo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Zo=(e,t,n,r)=>{let i=e._zod.def,a=k(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Qo=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},$o=Symbol();function es(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(co(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),$o):JSON.parse(o)}const ts=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=es(i.defaultValue,e,t,n,r);o!==$o&&(n.default=o)},ns=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=es(i.defaultValue,e,t,n,r);o!==$o&&(n._prefault=o)},rs=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{co(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},is=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;k(o,t,r);let s=t.seen.get(e);s.ref=o},as=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},os=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ss=new WeakSet([Object.prototype,Error.prototype]);function cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const M=C(`ZodError`,(e,t)=>{Gt.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);ss.has(n)||(ss.add(n),cs(n,`format`,e=>t=>Jt(e,t)),cs(n,`flatten`,e=>t=>qt(e,t)),cs(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Oe,2)}),cs(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Oe,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),ls=Zt(M),us=Qt(M),ds=$t(M),fs=tn(M),ps=cn(M),ms=ln(M),hs=un(M),gs=dn(M),_s=fn(M),vs=pn(M),ys=mn(M),bs=hn(M);function xs(){w.localeError||Rt($i())}function Ss(){w.memoizer||Rt({memoizer:Xi()})}const N=C(`ZodType`,(e,t)=>(xs(),D.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(b(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Xe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Rc(e,t))},superRefine(e,t){return this.check(zc(e,t))},overwrite(e){return this.check(Xa(e))},optional(){return yc(this)},exactOptional(){return xc(this)},nullable(){return Cc(this)},nullish(){return yc(Cc(this))},nonoptional(e){return kc(this,e)},array(){return ac(this)},or(e){return lc([this,e])},and(e){return dc(this,e)},transform(e){return Nc(this,_c(e))},default(e){return Tc(this,e)},prefault(e){return Dc(this,e)},catch(e){return jc(this,e)},pipe(e){return Nc(this,e)},readonly(){return Ic(this)},describe(e){let t=this.clone();return ra.add(t,{description:e}),t},meta(...e){if(e.length===0)return ra.get(this);let t=this.clone();return ra.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Ct(this,`~standard`,{...hr(this),jsonSchema:{input:bo(this,`input`),output:bo(this,`output`)}})},set"~standard"(e){St(this,`~standard`,e)},parse:function e(t,n){return ls(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await us(this,t,n,{callee:e})},safeParse(e,t){return ds(this,e,t)},async safeParseAsync(e,t){return fs(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){St(this,`spa`,e)},validate(e,t){return an(this,e,t)},validateAsync(e,t){return sn(this,e,t)},encode:function e(t,n){return ps(this,t,n,{callee:e})},decode:function e(t,n){return ms(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await hs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await gs(this,t,n,{callee:e})},safeEncode(e,t){return _s(this,e,t)},safeDecode(e,t){return vs(this,e,t)},async safeEncodeAsync(e,t){return ys(this,e,t)},async safeDecodeAsync(e,t){return bs(this,e,t)},toJSONSchema(e){return yo(this,{})(e)},get description(){return ra.get(this)?.description},get _def(){return this._zod.def}}),Cs=C(`_ZodString`,(e,t)=>{gr.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r)},wt({format:e=>j(e).format??null,minLength:e=>j(e).minimum??null,maxLength:e=>j(e).maximum??null},{regex(...e){return this.check(Wa(...e))},includes(...e){return this.check(qa(...e))},startsWith(...e){return this.check(Ja(...e))},endsWith(...e){return this.check(Ya(...e))},min(...e){return this.check(Ha(...e))},max(...e){return this.check(Va(...e))},length(...e){return this.check(Ua(...e))},nonempty(...e){return this.check(Ha(1,...e))},lowercase(e){return this.check(Ga(e))},uppercase(e){return this.check(Ka(e))},trim(){return this.check(Qa())},normalize(...e){return this.check(Za(...e))},toLowerCase(){return this.check($a())},toUpperCase(){return this.check(eo())},slugify(){return this.check(to())}})),ws=C(`ZodString`,(e,t)=>{gr.init(e,t),Cs.init(e,t)},{email(e){return this.check(aa(ks,e))},url(e){return this.check(da(Ms,e))},jwt(e){return this.check(Ea(qs,e))},emoji(e){return this.check(fa(Ns,e))},guid(e){return this.check(oa(As,e))},uuid(e){return this.check(sa(js,e))},uuidv4(e){return this.check(ca(js,e))},uuidv6(e){return this.check(la(js,e))},uuidv7(e){return this.check(ua(js,e))},nanoid(e){return this.check(pa(Ps,e))},cuid(e){return this.check(ma(Fs,e))},cuid2(e){return this.check(ha(Is,e))},ulid(e){return this.check(ga(Ls,e))},base64(e){return this.check(Ca(Ws,e))},base64url(e){return this.check(wa(Gs,e))},xid(e){return this.check(_a(Rs,e))},ksuid(e){return this.check(va(zs,e))},ipv4(e){return this.check(ya(Bs,e))},ipv6(e){return this.check(ba(Vs,e))},cidrv4(e){return this.check(xa(Hs,e))},cidrv6(e){return this.check(Sa(Us,e))},e164(e){return this.check(Ta(Ks,e))},datetime(e){return this.check(Da(Ts,e))},date(e){return this.check(Oa(Es,e))},time(e){return this.check(ka(Ds,e))},duration(e){return this.check(Aa(Os,e))}});function P(e){return ia(ws,e)}const F=C(`ZodStringFormat`,(e,t)=>{O.init(e,t),Cs.init(e,t)}),Ts=C(`ZodISODateTime`,(e,t)=>{Nr.init(e,t),F.init(e,t)}),Es=C(`ZodISODate`,(e,t)=>{Pr.init(e,t),F.init(e,t)}),Ds=C(`ZodISOTime`,(e,t)=>{Fr.init(e,t),F.init(e,t)}),Os=C(`ZodISODuration`,(e,t)=>{Ir.init(e,t),F.init(e,t)}),ks=C(`ZodEmail`,(e,t)=>{yr.init(e,t),F.init(e,t)}),As=C(`ZodGUID`,(e,t)=>{_r.init(e,t),F.init(e,t)}),js=C(`ZodUUID`,(e,t)=>{vr.init(e,t),F.init(e,t)}),Ms=C(`ZodURL`,(e,t)=>{Tr.init(e,t),F.init(e,t)}),Ns=C(`ZodEmoji`,(e,t)=>{Er.init(e,t),F.init(e,t)}),Ps=C(`ZodNanoID`,(e,t)=>{Dr.init(e,t),F.init(e,t)}),Fs=C(`ZodCUID`,(e,t)=>{Or.init(e,t),F.init(e,t)}),Is=C(`ZodCUID2`,(e,t)=>{kr.init(e,t),F.init(e,t)}),Ls=C(`ZodULID`,(e,t)=>{Ar.init(e,t),F.init(e,t)}),Rs=C(`ZodXID`,(e,t)=>{jr.init(e,t),F.init(e,t)}),zs=C(`ZodKSUID`,(e,t)=>{Mr.init(e,t),F.init(e,t)}),Bs=C(`ZodIPv4`,(e,t)=>{Lr.init(e,t),F.init(e,t)}),Vs=C(`ZodIPv6`,(e,t)=>{Br.init(e,t),F.init(e,t)}),Hs=C(`ZodCIDRv4`,(e,t)=>{Vr.init(e,t),F.init(e,t)}),Us=C(`ZodCIDRv6`,(e,t)=>{Ur.init(e,t),F.init(e,t)}),Ws=C(`ZodBase64`,(e,t)=>{Kr.init(e,t),F.init(e,t)}),Gs=C(`ZodBase64URL`,(e,t)=>{Yr.init(e,t),F.init(e,t)}),Ks=C(`ZodE164`,(e,t)=>{Xr.init(e,t),F.init(e,t)}),qs=C(`ZodJWT`,(e,t)=>{Qr.init(e,t),F.init(e,t)}),Js=C(`ZodNumber`,(e,t)=>{$r.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.isFinite=!0},wt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=j(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=j(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=j(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>j(e).format??null},{gt(e,t){return this.check(Ra(e,t))},gte(e,t){return this.check(za(e,t))},min(e,t){return this.check(za(e,t))},lt(e,t){return this.check(Ia(e,t))},lte(e,t){return this.check(La(e,t))},max(e,t){return this.check(La(e,t))},int(e){return this.check(Zs(e))},safe(e){return this.check(Zs(e))},positive(e){return this.check(Ra(0,e))},nonnegative(e){return this.check(za(0,e))},negative(e){return this.check(Ia(0,e))},nonpositive(e){return this.check(La(0,e))},multipleOf(e,t){return this.check(Ba(e,t))},step(e,t){return this.check(Ba(e,t))},finite(){return this}}));function Ys(e){return ja(Js,e)}const Xs=C(`ZodNumberFormat`,(e,t)=>{ei.init(e,t),Js.init(e,t)});function Zs(e){return Ma(Xs,e)}const Qs=C(`ZodBoolean`,(e,t)=>{ti.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function $s(e){return Na(Qs,e)}const ec=C(`ZodUnknown`,(e,t)=>{ni.init(e,t),N.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function tc(){return Pa(ec)}const nc=C(`ZodNever`,(e,t)=>{ri.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r)});function rc(e){return Fa(nc,e)}const ic=C(`ZodArray`,(e,t)=>{Ss(),ai.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Ha(e,t))},nonempty(e){return this.check(Ha(1,e))},max(e,t){return this.check(Va(e,t))},length(e,t){return this.check(Ua(e,t))},unwrap(){return this.element}});function ac(e,t){return no(ic,e,t)}const oc=C(`ZodObject`,(e,t)=>{Ss(),di.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r),At(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return hc(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(b(this._zod.def,{catchall:e}))},passthrough(){return this.clone(b(this._zod.def,{catchall:tc()}))},loose(){return this.clone(b(this._zod.def,{catchall:tc()}))},strict(){return this.clone(b(this._zod.def,{catchall:rc()}))},strip(){return this.clone(b(this._zod.def,{catchall:void 0}))},extend(e){return it(this,e)},safeExtend(e){return ot(this,e)},merge(e){return st(this,e)},pick(e){return tt(this,e)},omit(e){return rt(this,e)},partial(...e){return ct(vc,this,e[0])},exactPartial(...e){return ct(bc,this,e[0],`exactPartial`)},required(...e){return lt(Oc,this,e[0])}});function I(e,t){return new oc({type:`object`,shape:e,catchall:rc(),...x(t)})}function sc(e,t){return new oc({type:`object`,shape:e,catchall:tc(),...x(t)})}const cc=C(`ZodUnion`,(e,t)=>{pi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r),e.options=t.options});function lc(e,t){return new cc({type:`union`,options:e,...x(t)})}const uc=C(`ZodIntersection`,(e,t)=>{mi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ko(e,t,n,r)});function dc(e,t){return new uc({type:`intersection`,left:e,right:t})}const fc=C(`ZodRecord`,(e,t)=>{Ss(),_i.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function pc(e,t,n){return!t||!t._zod?new fc({type:`record`,keyType:P(),valueType:e,...x(t)}):new fc({type:`record`,keyType:e,valueType:t,...x(n)})}const mc=C(`ZodEnum`,(e,t)=>{vi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new mc({...t,checks:[],...x(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new mc({...t,checks:[],...x(r),entries:i})}});function hc(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new mc({type:`enum`,entries:n,...x(t)})}const gc=C(`ZodTransform`,(e,t)=>{Ss(),yi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Lt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(bt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(bt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function _c(e){return new gc({type:`transform`,transform:e})}const vc=C(`ZodOptional`,(e,t)=>{xi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function yc(e){return new vc({type:`optional`,innerType:e})}const bc=C(`ZodExactOptional`,(e,t)=>{Si.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function xc(e){return new bc({type:`optional`,innerType:e})}const Sc=C(`ZodNullable`,(e,t)=>{Ci.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Cc(e){return new Sc({type:`nullable`,innerType:e})}const wc=C(`ZodDefault`,(e,t)=>{wi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Tc(e,t){return new wc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():qe(t)}})}const Ec=C(`ZodPrefault`,(e,t)=>{Ei.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Dc(e,t){return new Ec({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():qe(t)}})}const Oc=C(`ZodNonOptional`,(e,t)=>{Di.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function kc(e,t){return new Oc({type:`nonoptional`,innerType:e,...x(t)})}const Ac=C(`ZodCatch`,(e,t)=>{Ai.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function jc(e,t){return new Ac({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:jt(t)})}const Mc=C(`ZodPipe`,(e,t)=>{ji.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.in=t.in,e.out=t.out});function Nc(e,t){return new Mc({type:`pipe`,in:e,out:t})}const Pc=C(`ZodPreprocess`,(e,t)=>{Mc.init(e,t),Ni.init(e,t)}),Fc=C(`ZodReadonly`,(e,t)=>{Pi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e){return new Fc({type:`readonly`,innerType:e})}const Lc=C(`ZodCustom`,(e,t)=>{Ii.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r)});function Rc(e,t={}){return ro(Lc,e,t)}function zc(e,t){return io(e,t)}function Bc(e,t){return new Pc({type:`pipe`,in:_c(e),out:t})}function Vc(e){return Da(Ts,e)}const Hc=new Set([`__proto__`,`constructor`,`prototype`]),Uc=(e,t,n)=>Bc((n,r)=>{if(typeof n==`object`&&n)for(let i of Reflect.ownKeys(n))(typeof i!=`string`||!e(i))&&r.addIssue({code:`custom`,message:t(String(i)),path:[String(i)]});return n},n),Wc=e=>e.length>0&&!Hc.has(e),Gc=e=>Uc(Wc,()=>`package key must be non-empty and not "__proto__", "constructor", or "prototype"`,pc(P().min(1),e)),Kc=e=>Wc(e),qc=[`blobless`,`full`],Jc=[`ssh`,`https`],Yc=/^(?!\.{1,2}$)[^/\\%:]+$/u,Xc=/^[a-z0-9][a-z0-9.-]*(?:_[1-9]\d{0,4})?$/u,Zc=/^(?<amount>[1-9]\d{0,3})(?<unit>[mhd])$/u,Qc={d:864e5,h:36e5,m:6e4},$c=e=>e!==``&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e),el=e=>{if(e===void 0)return!0;let t=Number(e);return t>=1&&t<=65535},tl=e=>{let[t=``,n]=e.split(`_`);return el(n)?t.split(`.`).every(e=>$c(e)):!1},nl=e=>e.isWellFormed(),rl=e=>{let[t,...n]=e.split(`/`);return t===void 0||n.length<2||!Xc.test(t)||!tl(t)?!1:n.every(e=>Yc.test(e))},il=P().refine(e=>nl(e)&&rl(e),`ref key must be host/path…/repo with safe, non-empty segments`).brand(),al=P().regex(Zc,`duration must be <n>m, <n>h, or <n>d`).brand(),ol=e=>{let t=Zc.exec(e);if(t===null)throw Error(`invalid duration: ${e}`);let{amount:n,unit:r}=t.groups??{};if(!n||!r)throw Error(`invalid duration: ${e}`);return Number(n)*Qc[r]},sl=hc(qc),cl=hc(Jc),ll=P().refine(e=>e.includes(`{version}`),`tag format must contain {version}`),ul=P().refine(e=>{if(e===`.`)return!0;let t=e.split(`/`);return t.length>0&&t.every(e=>Yc.test(e)&&e!==`.`)},`package path must be "." or a normalized relative path without traversal`),dl={clone_mode:`blobless`,git_transport:`https`,sync_ttl:`1h`},fl=I({clone_mode:sl.default(dl.clone_mode),git_transport:cl.default(dl.git_transport),sync_ttl:al.default(al.parse(dl.sync_ttl))}),pl=I((e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.removeDefault().optional()])))(fl.shape)),ml=I({name:P().min(1),path:ul}),hl=I({description:P().min(1),path:ul,tag_format:ll.optional()}),gl=I({declined_packages:ac(ml).optional(),default_branch:P().min(1),description:P().min(1),packages:Gc(hl).optional(),tag_format:ll.optional(),url:P().min(1),...pl.shape}),_l=sc({cli_version:P().min(1),schema_version:Ys().int().positive()}),vl=Uc(e=>il.safeParse(e).success,()=>`ref key must be host/path…/repo with safe, non-empty segments`,pc(P(),gl)),yl=I({check:$s().default(!0),notify:$s().default(!0)}),bl=I({meta:_l,refs:vl.default({}),settings:fl,updates:yl.optional()});
58
58
  /*!
59
59
  * Copyright (c) Squirrel Chat et al., All rights reserved.
60
60
  * SPDX-License-Identifier: BSD-3-Clause
@@ -82,7 +82,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
82
82
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
83
83
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
84
84
  */
85
- let yl=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var bl=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(yl);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
85
+ let xl=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var Sl=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(xl);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
86
86
  /*!
87
87
  * Copyright (c) Squirrel Chat et al., All rights reserved.
88
88
  * SPDX-License-Identifier: BSD-3-Clause
@@ -110,9 +110,9 @@ let yl=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]
110
110
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
111
111
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
112
112
  */
113
- function xl(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Sl(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
113
+ function Cl(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function wl(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
114
114
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
115
- `))}return i}var R=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=xl(t.toml,t.ptr),i=Sl(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
115
+ `))}return i}var L=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Cl(t.toml,t.ptr),i=wl(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
116
116
  /*!
117
117
  * Copyright (c) Squirrel Chat et al., All rights reserved.
118
118
  * SPDX-License-Identifier: BSD-3-Clause
@@ -140,8 +140,8 @@ function xl(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop()
140
140
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
141
141
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
142
142
  */
143
- function Cl(e,t=0){let n=e.indexOf(`
144
- `,t);return e.charCodeAt(n-1)===13&&n--,n}function wl(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)throw new R(`control characters are not allowed in comments`,{toml:e.s,ptr:e.p})}}function Tl(e,t,n){let r;for(;;){for(;(r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10);)e.p++;if(n||r!==35)break;wl(e)}}function El(e,t,n){let r=e.p;if(!n){r=Cl(e.s,r),e.p=r<0?e.s.length:r;return}for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===35)wl(e);else if(r===n||r===t)return}throw new R(`cannot find end of structure`,{toml:e.s,ptr:r})}
143
+ function Tl(e,t=0){let n=e.indexOf(`
144
+ `,t);return e.charCodeAt(n-1)===13&&n--,n}function El(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)throw new L(`control characters are not allowed in comments`,{toml:e.s,ptr:e.p})}}function Dl(e,t,n){let r;for(;;){for(;(r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10);)e.p++;if(n||r!==35)break;El(e)}}function Ol(e,t,n){let r=e.p;if(!n){r=Tl(e.s,r),e.p=r<0?e.s.length:r;return}for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===35)El(e);else if(r===n||r===t)return}throw new L(`cannot find end of structure`,{toml:e.s,ptr:r})}
145
145
  /*!
146
146
  * Copyright (c) Squirrel Chat et al., All rights reserved.
147
147
  * SPDX-License-Identifier: BSD-3-Clause
@@ -169,8 +169,8 @@ function Cl(e,t=0){let n=e.indexOf(`
169
169
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
170
170
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
171
171
  */
172
- let Dl=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Ol=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,kl=/^[+-]?0[0-9_]/;function Al(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)throw new R(`control characters are not allowed in strings`,{toml:e.s,ptr:e.p});else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r))return a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),c||(o+=e.s.slice(s,e.p)),e.p+=a?3:1,o;else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1){if(n===120||n===117||n===85){let t=0,r=n===120?2:n===117?4:8;for(let n=0;n<r;n++,e.p++){let n=e.s.charCodeAt(e.p+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new R(`invalid non-hex character in unicode escape`,{toml:e.s,ptr:e.p+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new R(`invalid unicode escape`,{toml:e.s,ptr:e.p});o+=String.fromCodePoint(t),s=e.p+1,c=0}else if(n===32||n===9)c=2;else{if(n===98)o+=`\b`;else if(n===116)o+=` `;else if(n===110)o+=`
173
- `;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new R(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new R(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new R(`unfinished string`,{toml:e.s,ptr:t})}function jl(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(wl({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Ml(e,t,n){let r=e.p,i={toml:e.s,ptr:r};El(e,44,n);let a=jl(e,r,e.p);if(!a)throw new R(`incomplete declaration: value expected`,i);if(a===`-inf`)return-1/0;if(a===`inf`||a===`+inf`)return 1/0;if(a===`nan`||a===`+nan`||a===`-nan`)return NaN;if(a===`-0`)return t?0n:0;let o=Dl.test(a);if(o||Ol.test(a)){if(kl.test(a))throw new R(`leading zeroes are not allowed`,i);a=a.replace(/_/g,``);let e=+a;if(isNaN(e))throw new R(`invalid number`,i);if(o){if((o=!Number.isSafeInteger(e))&&!t)throw new R(`integer value cannot be represented losslessly`,i);(o||t===!0)&&(e=BigInt(a))}return e}let s=new bl(a);if(!s.isValid())throw new R(`invalid value`,i);return s}
172
+ let kl=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Al=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,jl=/^[+-]?0[0-9_]/;function Ml(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)throw new L(`control characters are not allowed in strings`,{toml:e.s,ptr:e.p});else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r))return a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),c||(o+=e.s.slice(s,e.p)),e.p+=a?3:1,o;else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1){if(n===120||n===117||n===85){let t=0,r=n===120?2:n===117?4:8;for(let n=0;n<r;n++,e.p++){let n=e.s.charCodeAt(e.p+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new L(`invalid non-hex character in unicode escape`,{toml:e.s,ptr:e.p+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new L(`invalid unicode escape`,{toml:e.s,ptr:e.p});o+=String.fromCodePoint(t),s=e.p+1,c=0}else if(n===32||n===9)c=2;else{if(n===98)o+=`\b`;else if(n===116)o+=` `;else if(n===110)o+=`
173
+ `;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new L(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new L(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new L(`unfinished string`,{toml:e.s,ptr:t})}function Nl(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(El({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Pl(e,t,n){let r=e.p,i={toml:e.s,ptr:r};Ol(e,44,n);let a=Nl(e,r,e.p);if(!a)throw new L(`incomplete declaration: value expected`,i);if(a===`-inf`)return-1/0;if(a===`inf`||a===`+inf`)return 1/0;if(a===`nan`||a===`+nan`||a===`-nan`)return NaN;if(a===`-0`)return t?0n:0;let o=kl.test(a);if(o||Al.test(a)){if(jl.test(a))throw new L(`leading zeroes are not allowed`,i);a=a.replace(/_/g,``);let e=+a;if(isNaN(e))throw new L(`invalid number`,i);if(o){if((o=!Number.isSafeInteger(e))&&!t)throw new L(`integer value cannot be represented losslessly`,i);(o||t===!0)&&(e=BigInt(a))}return e}let s=new Sl(a);if(!s.isValid())throw new L(`invalid value`,i);return s}
174
174
  /*!
175
175
  * Copyright (c) Squirrel Chat et al., All rights reserved.
176
176
  * SPDX-License-Identifier: BSD-3-Clause
@@ -198,7 +198,7 @@ let Dl=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Ol=/^[+-]?
198
198
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
199
199
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
200
200
  */
201
- function Nl(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)throw new R(`document contains excessively nested structures. aborting.`,{toml:e.s,ptr:r});let t=i===91?Ll(e,n):Il(e,n);return e.d++,t}if(i===34||i===39)return Al(e);if(i===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)throw new R(`invalid value`,{toml:e.s,ptr:r});return e.p++,!0}if(i===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)throw new R(`invalid value`,{toml:e.s,ptr:r});return e.p++,!1}return Ml(e,n,t)}
201
+ function Fl(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)throw new L(`document contains excessively nested structures. aborting.`,{toml:e.s,ptr:r});let t=i===91?zl(e,n):Rl(e,n);return e.d++,t}if(i===34||i===39)return Ml(e);if(i===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)throw new L(`invalid value`,{toml:e.s,ptr:r});return e.p++,!0}if(i===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)throw new L(`invalid value`,{toml:e.s,ptr:r});return e.p++,!1}return Pl(e,n,t)}
202
202
  /*!
203
203
  * Copyright (c) Squirrel Chat et al., All rights reserved.
204
204
  * SPDX-License-Identifier: BSD-3-Clause
@@ -226,7 +226,7 @@ function Nl(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)t
226
226
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
227
227
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
228
228
  */
229
- let Pl=/^[a-zA-Z0-9-_]+[ \t]*$/;function Fl(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.indexOf(t,n);if(a<0)throw new R(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});do{let o=e.s.charCodeAt(e.p=++r);if(o!==32&&o!==9){if(o===34||o===39){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))throw new R(`multiline strings are not allowed in keys`,{toml:e.s,ptr:e.p});let s=Al(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=Cl(c);if(l>-1)throw new R(`newlines are not allowed in keys`,{toml:e.s,ptr:l});if(c.trimStart())throw new R(`found extra tokens after the string part`,{toml:e.s,ptr:e.p});if(a<e.p&&(a=e.s.indexOf(t,e.p),a<0))throw new R(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});i.push(s)}else{r=e.s.indexOf(`.`,e.p);let t=e.s.slice(e.p,r<0||r>a?a:r);if(!Pl.test(t))throw new R(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e.s,ptr:e.p});i.push(t.trimEnd())}}}while(r+1&&r<a);return e.p=a+1,Tl(e,!0,!0),i}function Il(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Tl(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Fl(e);for(let t=0;t<l.length;t++){if(t&&(o=s?o[a]:o[a]={}),a=l[t],(s=Object.hasOwn(o,a))&&(typeof o[a]!=`object`||r.has(o[a])))throw new R(`trying to redefine an already defined value`,{toml:e.s,ptr:c});!s&&a===`__proto__`&&Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})}if(s)throw new R(`trying to redefine an already defined value`,{toml:e.s,ptr:e.p});let u=Nl(e,125,t);if(r.add(o[a]=u),Tl(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)throw new R(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new R(`unfinished table encountered`,{toml:e.s,ptr:e.p})}function Ll(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Tl(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Nl(e,93,t)),Tl(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)throw new R(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new R(`unfinished array encountered`,{toml:e.s,ptr:e.p})}
229
+ let Il=/^[a-zA-Z0-9-_]+[ \t]*$/;function Ll(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.indexOf(t,n);if(a<0)throw new L(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});do{let o=e.s.charCodeAt(e.p=++r);if(o!==32&&o!==9){if(o===34||o===39){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))throw new L(`multiline strings are not allowed in keys`,{toml:e.s,ptr:e.p});let s=Ml(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=Tl(c);if(l>-1)throw new L(`newlines are not allowed in keys`,{toml:e.s,ptr:l});if(c.trimStart())throw new L(`found extra tokens after the string part`,{toml:e.s,ptr:e.p});if(a<e.p&&(a=e.s.indexOf(t,e.p),a<0))throw new L(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});i.push(s)}else{r=e.s.indexOf(`.`,e.p);let t=e.s.slice(e.p,r<0||r>a?a:r);if(!Il.test(t))throw new L(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e.s,ptr:e.p});i.push(t.trimEnd())}}}while(r+1&&r<a);return e.p=a+1,Dl(e,!0,!0),i}function Rl(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Dl(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Ll(e);for(let t=0;t<l.length;t++){if(t&&(o=s?o[a]:o[a]={}),a=l[t],(s=Object.hasOwn(o,a))&&(typeof o[a]!=`object`||r.has(o[a])))throw new L(`trying to redefine an already defined value`,{toml:e.s,ptr:c});!s&&a===`__proto__`&&Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})}if(s)throw new L(`trying to redefine an already defined value`,{toml:e.s,ptr:e.p});let u=Fl(e,125,t);if(r.add(o[a]=u),Dl(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)throw new L(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new L(`unfinished table encountered`,{toml:e.s,ptr:e.p})}function zl(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Dl(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Fl(e,93,t)),Dl(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)throw new L(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new L(`unfinished array encountered`,{toml:e.s,ptr:e.p})}
230
230
  /*!
231
231
  * Copyright (c) Squirrel Chat et al., All rights reserved.
232
232
  * SPDX-License-Identifier: BSD-3-Clause
@@ -254,7 +254,7 @@ let Pl=/^[a-zA-Z0-9-_]+[ \t]*$/;function Fl(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.
254
254
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
255
255
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
256
256
  */
257
- function Rl(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function zl(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Tl(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Fl(r,`]`);if(t){if(e.charCodeAt(r.p-1)!==93)throw new R(`expected end of table declaration`,{toml:e,ptr:r.p-1});r.p++}let l=Rl(n,i,a,t?2:1);if(!l)throw new R(`trying to redefine an already defined table or value`,{toml:e,ptr:o});c=l[2],s=l[1]}else{o=r.p;let t=Rl(Fl(r),s,c,0);if(!t)throw new R(`trying to redefine an already defined table or value`,{toml:e,ptr:o});t[1][t[0]]=Nl(r,void 0,n)}if(Tl(r,!0),r.p<e.length&&(o=e.charCodeAt(r.p))!==10&&o!==13)throw new R(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:r.p});Tl(r)}return i}
257
+ function Bl(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function Vl(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Dl(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Ll(r,`]`);if(t){if(e.charCodeAt(r.p-1)!==93)throw new L(`expected end of table declaration`,{toml:e,ptr:r.p-1});r.p++}let l=Bl(n,i,a,t?2:1);if(!l)throw new L(`trying to redefine an already defined table or value`,{toml:e,ptr:o});c=l[2],s=l[1]}else{o=r.p;let t=Bl(Ll(r),s,c,0);if(!t)throw new L(`trying to redefine an already defined table or value`,{toml:e,ptr:o});t[1][t[0]]=Fl(r,void 0,n)}if(Dl(r,!0),r.p<e.length&&(o=e.charCodeAt(r.p))!==10&&o!==13)throw new L(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:r.p});Dl(r)}return i}
258
258
  /*!
259
259
  * Copyright (c) Squirrel Chat et al., All rights reserved.
260
260
  * SPDX-License-Identifier: BSD-3-Clause
@@ -282,13 +282,13 @@ function Rl(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i
282
282
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
283
283
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
284
284
  */
285
- let Bl=/^[a-z0-9-_]+$/i;function Vl(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(typeof e?.getUTCDate==`function`&&e instanceof Date)return`date`;if(globalThis.Temporal&&typeof e?.since==`function`&&(e instanceof Temporal.Instant||e instanceof Temporal.PlainDate||e instanceof Temporal.PlainDateTime||e instanceof Temporal.PlainTime||e instanceof Temporal.ZonedDateTime))return`temporal`}return t}function Hl(e){for(let t=0;t<e.length;t++)if(Vl(e[t])!==`object`)return!1;return e.length!=0}function Ul(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function Wl(e){return e.toString({calendarName:`never`,timeZoneName:`never`})}function Gl(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);switch(t){case`number`:if(isNaN(e))return`nan`;if(e===1/0)return`inf`;if(e===-1/0)return`-inf`;if(Number.isInteger(e)&&(r||!Number.isSafeInteger(e)))return e.toFixed(1);case`bigint`:case`boolean`:return e.toString();case`string`:return Ul(e);case`date`:if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString();case`object`:return Kl(e,n,r);case`array`:return ql(e,n,r);case`temporal`:return Wl(e)}}function Kl(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=Bl.test(o)?o:Ul(o),i+=` = `,i+=Gl(e[o],Vl(e[o]),t-1,n)}return i+` }`}function ql(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=Gl(e[i],Vl(e[i]),t-1,n)}return r+` ]`}function Jl(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
286
- `}[[${t}]]\n`,i+=Yl(0,e[a],t,n,r);return i}function Yl(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=Vl(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=Bl.test(c)?c:Ul(c);if(e===`array`&&Hl(t[c]))o+=(o&&`
287
- `)+Jl(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
288
- `)+Yl(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=Gl(t[c],e,r,i),a+=`
289
- `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function Xl(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(Vl(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=Yl(0,e,``,t,n);return r[r.length-1]===`
285
+ let Hl=/^[a-z0-9-_]+$/i;function Ul(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(typeof e?.getUTCDate==`function`&&e instanceof Date)return`date`;if(globalThis.Temporal&&typeof e?.since==`function`&&(e instanceof Temporal.Instant||e instanceof Temporal.PlainDate||e instanceof Temporal.PlainDateTime||e instanceof Temporal.PlainTime||e instanceof Temporal.ZonedDateTime))return`temporal`}return t}function Wl(e){for(let t=0;t<e.length;t++)if(Ul(e[t])!==`object`)return!1;return e.length!=0}function Gl(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function Kl(e){return e.toString({calendarName:`never`,timeZoneName:`never`})}function ql(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);switch(t){case`number`:if(isNaN(e))return`nan`;if(e===1/0)return`inf`;if(e===-1/0)return`-inf`;if(Number.isInteger(e)&&(r||!Number.isSafeInteger(e)))return e.toFixed(1);case`bigint`:case`boolean`:return e.toString();case`string`:return Gl(e);case`date`:if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString();case`object`:return Jl(e,n,r);case`array`:return Yl(e,n,r);case`temporal`:return Kl(e)}}function Jl(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=Hl.test(o)?o:Gl(o),i+=` = `,i+=ql(e[o],Ul(e[o]),t-1,n)}return i+` }`}function Yl(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=ql(e[i],Ul(e[i]),t-1,n)}return r+` ]`}function Xl(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
286
+ `}[[${t}]]\n`,i+=Zl(0,e[a],t,n,r);return i}function Zl(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=Ul(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=Hl.test(c)?c:Gl(c);if(e===`array`&&Wl(t[c]))o+=(o&&`
287
+ `)+Xl(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
288
+ `)+Zl(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=ql(t[c],e,r,i),a+=`
289
+ `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function Ql(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(Ul(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=Zl(0,e,``,t,n);return r[r.length-1]===`
290
290
  `?r:r+`
291
- `}const z=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,Zl=async(e,t)=>{await a(ie(e),{recursive:!0});let n=`${e}.tmp-${de()}`;await te(n,t,`utf8`),await u(n,e)},B=e=>{let t=ce(e.REFS_HOME??m(he(),`.kaisers-io`,`refs`));return{cacheDir:m(t,`cache`),configPath:m(t,`config.toml`),hooksDir:m(t,`hooks`),locksDir:m(t,`locks`),root:t,sourcesDir:m(t,`sources`),statePath:m(t,`state.json`),updateCachePath:m(t,`cache`,`update-check.json`)}},V=(e,t)=>m(e.sourcesDir,...t.split(`/`)),Ql=e=>`${e.configPath}.bak`,$l=e=>{let t=[],n=e;for(;!pe(n);){let e=ie(n);if(e===n)break;t.unshift(re(n)),n=e}return{ancestor:n,missing:t}},eu=e=>{let{ancestor:t,missing:n}=$l(e),r=me(t);return n.length===0?r:m(r,...n)},tu=(e,t,n)=>{let r=eu(e),i=eu(t),a=se(r,i),o=a===`..`||a.startsWith(`..`+le);if(a===``||o||ae(a))throw b(`path escapes ${n} (containment violation): ${t}`)},nu=(e,t)=>{tu(e.sourcesDir,t,`sources directory`)},ru=e=>typeof e==`object`&&!!e&&!Array.isArray(e),iu=(e,t)=>ru(e)?e:t,au=async e=>{try{return await s(e.configPath,`utf8`)}catch(e){throw z(e)?v(`no config found — run: refs init`):e}},ou=(e,t)=>{try{return zl(e)}catch(e){throw e instanceof R?b(`invalid TOML in ${t}: ${e.message}`):e}},su=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,cu=e=>{let{meta:t}=e;if(!ru(t))return;let n=t.schema_version;if(su(n))return n},lu=(e,t)=>{let n=cu(e);if(n===void 0)throw b(`config schema version is missing or invalid in ${t} — run: refs migrate`);if(n>1)throw b(`config schema ${n} is newer than this CLI supports — upgrade refs`);if(n<1)throw b(`config schema ${n} is older than expected 1 — run: refs migrate`)},H=async e=>{let t=await au(e),n=ou(t,e.configPath);lu(n,e.configPath);let r=vl.safeParse(n);if(!r.success)throw b(E(r.error));return r.data},uu=async(e,t)=>{let n=vl.safeParse(t);if(!n.success)throw b(E(n.error));await Zl(e.configPath,Xl(n.data))},du=async e=>{try{return await p(e),!0}catch(e){if(z(e))return!1;throw e}},fu=async(e,t)=>await du(e.configPath)?`noop`:(await Zl(e.configPath,`# refs configuration
291
+ `}const R=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,$l=async(e,t)=>{await a(ie(e),{recursive:!0});let n=`${e}.tmp-${de()}`;await te(n,t,`utf8`),await u(n,e)},z=e=>{let t=ce(e.REFS_HOME??m(he(),`.kaisers-io`,`refs`));return{cacheDir:m(t,`cache`),configPath:m(t,`config.toml`),hooksDir:m(t,`hooks`),locksDir:m(t,`locks`),root:t,sourcesDir:m(t,`sources`),statePath:m(t,`state.json`),updateCachePath:m(t,`cache`,`update-check.json`)}},B=(e,t)=>m(e.sourcesDir,...t.split(`/`)),eu=e=>`${e.configPath}.bak`,tu=e=>{let t=[],n=e;for(;!pe(n);){let e=ie(n);if(e===n)break;t.unshift(re(n)),n=e}return{ancestor:n,missing:t}},nu=e=>{let{ancestor:t,missing:n}=tu(e),r=me(t);return n.length===0?r:m(r,...n)},ru=(e,t,n)=>{let r=nu(e),i=nu(t),a=se(r,i),o=a===`..`||a.startsWith(`..`+le);if(a===``||o||ae(a))throw y(`path escapes ${n} (containment violation): ${t}`)},iu=(e,t)=>{ru(e.sourcesDir,t,`sources directory`)},au=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ou=(e,t)=>au(e)?e:t,su=async e=>{try{return await s(e.configPath,`utf8`)}catch(e){throw R(e)?_(`no config found — run: refs init`):e}},cu=(e,t)=>{try{return Vl(e)}catch(e){throw e instanceof L?y(`invalid TOML in ${t}: ${e.message}`):e}},lu=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,uu=e=>{let{meta:t}=e;if(!au(t))return;let n=t.schema_version;if(lu(n))return n},du=(e,t)=>{let n=uu(e);if(n===void 0)throw y(`config schema version is missing or invalid in ${t} — run: refs migrate`);if(n>1)throw y(`config schema ${n} is newer than this CLI supports — upgrade refs`);if(n<1)throw y(`config schema ${n} is older than expected 1 — run: refs migrate`)},V=async e=>{let t=await su(e),n=cu(t,e.configPath);du(n,e.configPath);let r=bl.safeParse(n);if(!r.success)throw y(T(r.error));return r.data},fu=async(e,t)=>{let n=bl.safeParse(t);if(!n.success)throw y(T(n.error));await $l(e.configPath,Ql(n.data))},pu=async e=>{try{return await p(e),!0}catch(e){if(R(e))return!1;throw e}},mu=async(e,t)=>await pu(e.configPath)?`noop`:(await $l(e.configPath,`# refs configuration
292
292
  #
293
293
  # Every global setting under [settings] can also be set per-ref: add the same
294
294
  # key directly inside a [refs."host/owner/repo"] table to override it just for
@@ -319,38 +319,38 @@ sync_ttl = "1h"
319
319
  # tag_format = "v{version}"
320
320
  # # Per-ref overrides of [settings] go in the same table, e.g.:
321
321
  # # clone_mode = "full"
322
- `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),pu=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:ru(t)&&ru(r)&&(n[e]=pu(t,r))}return n},mu={meta:{},refs:{},settings:{}},hu=async e=>{try{return await au(e)}catch(e){if(e instanceof _&&e.code===`not_found`)return;throw e}},gu=e=>{if(e!==void 0&&e>1)throw b(`config schema ${e} is newer than this CLI supports — upgrade refs`)},_u=async(e,t,n)=>{let r=iu(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await Zl(e.configPath,Xl(i))},vu=async(e,t,n)=>{await r(e.configPath,Ql(e));let i=pu(t,mu),a=iu(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=vl.safeParse(o);if(!s.success)throw b(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${Ql(e)}): ${E(s.error)}`);await Zl(e.configPath,Xl(o))},yu=async(e,t,n)=>{let r=ou(t,e.configPath),i=cu(r);return gu(i),i===1?(await _u(e,r,n),`noop`):(await vu(e,r,n),`migrated`)},bu=async(e,t)=>{let n=await hu(e);return n===void 0?(await fu(e,t),`seeded`):yu(e,n,t)},xu=new Set([`ENOENT`,`ENOTDIR`]),Su=e=>e.code??String(e),Cu=async e=>{try{return await i(e),!0}catch{return!1}},wu=(e,t)=>{let n=se(e,t);return n===``||n!==`..`&&!n.startsWith(`..`+le)&&!ae(n)},Tu=async e=>{try{return{real:await l(e)}}catch(e){return{code:Su(e)}}},Eu=async(e,t)=>{let n=await Tu(e);if(`code`in n)return{code:n.code,kind:`unreadable`};let r=await Tu(t);return`code`in r?xu.has(r.code)?await Cu(t)?{code:r.code,kind:`unreadable`}:{kind:`missing`}:{code:r.code,kind:`unreadable`}:wu(n.real,r.real)?{kind:`inside`,real:r.real}:{kind:`outside`}},Du=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,Ou=/^packages:\s*(?:#.*)?$/u,ku=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Au=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!ku(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},ju=Symbol(`end-of-section`),Mu=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!Ou.test(e))return ju;if(!t.startsWith(`-`))return;let n=Du.exec(e)?.groups?.pattern?.trim();if(n)return n},Nu=e=>{let t=[];for(let n of e){let e=Mu(n);if(e===ju)break;e!==void 0&&t.push(e)}return t},Pu=e=>{let t=e.findIndex(e=>Ou.test(e));return t===-1?[]:Nu(e.slice(t+1))},Fu=e=>{let{name:t}=e;if(typeof t==`string`)return t},Iu=async(e,t)=>{let n=await Eu(e,t);if(n.kind===`missing`)return{ok:!0};if(n.kind!==`inside`)return{ok:!1};try{return{content:await s(n.real,`utf8`),ok:!0}}catch{return{ok:!1}}},Lu=async(e,t)=>{let n=await Iu(e,t);return n.ok?n.content===void 0?{ok:!0,patterns:[]}:Ru(n.content):{ok:!1,patterns:[]}},Ru=e=>{try{let t=JSON.parse(e);return{ok:!0,patterns:Au(t.workspaces)}}catch{return{ok:!1,patterns:[]}}},zu=/^packages:/mu,Bu=(e,t)=>t.length===0&&zu.test(e),Vu=async(e,t)=>{let n=await Iu(e,t);if(!n.ok)return{ok:!1,patterns:[]};if(n.content===void 0)return{ok:!0,patterns:[]};let r=Pu(n.content.split(`
323
- `));return{ok:!0,patterns:r,unparsed:Bu(n.content,r)}},Hu=async e=>{let[t,n]=await Promise.all([Lu(e,m(e,`package.json`)),Vu(e,m(e,`pnpm-workspace.yaml`))]),r=[];return t.ok||r.push({file:`package.json`,kind:`workspace_file_unreadable`}),n.ok||r.push({file:`pnpm-workspace.yaml`,kind:`workspace_file_unreadable`}),n.unparsed===!0&&r.push({file:`pnpm-workspace.yaml`,kind:`workspace_declaration_unparsed`}),{diagnostics:r,npm:t.patterns,pnpm:n.patterns}},Uu=`\0unreadable`,Wu=`pnpm-workspace.yaml`,Gu=async(e,t)=>{let n=await e.run(`git`,[`ls-tree`,`-z`,`--name-only`,t.rev,`--`,t.path],{cwd:t.dir});return n.exitCode===0?n.stdout.includes(t.path):void 0},Ku=async(e,t)=>{let n=await Gu(e,t);if(n===void 0)return{kind:`unreadable`};if(!n)return{kind:`absent`};let r=await e.run(`git`,[`show`,`${t.rev}:${t.path}`],{cwd:t.dir});return r.exitCode===0?{contents:r.stdout}:{kind:`unreadable`}},qu=async(e,t,n)=>{let r=await Ku(e,{dir:t.dir,path:`package.json`,rev:n});if(`kind`in r)return r.kind===`absent`?[]:[Uu];try{let e=JSON.parse(r.contents);return Au(e.workspaces)}catch{return[Uu]}},Ju=async(e,t,n)=>{let r=await Ku(e,{dir:t.dir,path:Wu,rev:n});if(`kind`in r)return r.kind===`absent`?[]:[Uu];let{contents:i}=r,a=Pu(i.split(`
324
- `));return Bu(i,a)?[Uu]:a},Yu=async(e,t,n)=>{let[r,i]=await Promise.all([qu(e,t,n),Ju(e,t,n)]);return{npm:r,pnpm:i}},Xu=(e,t)=>{let n=0;for(let r of t)if(n<e.length&&e[n]===r)n+=1;else if(r.startsWith(`!`))return!1;return n===e.length},Zu=async(e,t)=>{if(!t.touched)return!1;let[n,r]=await Promise.all([Yu(e,t,t.from),Yu(e,t,t.to)]);return!Xu(n.npm,r.npm)||!Xu(n.pnpm,r.pnpm)},Qu=e=>re(e)===`package.json`,$u=async(e,t,n)=>{let r=await e.run(`git`,[...n],{cwd:t});return r.exitCode===0?r.stdout:void 0},ed=e=>e.split(`\0`).filter(e=>e.length>0&&Qu(e)),td=async(e,t)=>{let n=await $u(e,t.dir,[`diff`,`--name-only`,`-z`,`--no-renames`,`${t.from}..${t.to}`,`--`,`*package.json`,Wu]);return n===void 0?void 0:n.split(`\0`).filter(e=>e.length>0)},nd=async(e,t)=>{if(t.paths.length===0)return new Set;let n=await $u(e,t.dir,[`ls-tree`,`-r`,`-z`,`--name-only`,t.rev,`--`,...t.paths]);return n===void 0?void 0:new Set(ed(n))},rd=async(e,t)=>{let n=await $u(e,t.dir,[`show`,`${t.rev}:${t.path}`]);if(n!==void 0)try{let e=JSON.parse(n);return{name:Fu(e)}}catch{return}},id=async(e,t,n)=>{let r=[];for(let i of n){let n=await rd(e,{dir:t.dir,path:i,rev:t.rev});if(n===void 0)return;n.name!==void 0&&r.push(n.name)}return r},ad={changedDirs:[],namesBefore:[]},od=(e,t,n)=>Zu(e,{...t,touched:n.some(e=>e===`pnpm-workspace.yaml`||e===`package.json`)}),sd=e=>[...new Set(e.map(e=>ie(e)))].filter(e=>e!==`.`).toSorted(),cd=async(e,t,n)=>{let r=await nd(e,{dir:t.dir,paths:n,rev:t.from});if(r!==void 0)return id(e,{dir:t.dir,rev:t.from},n.filter(e=>r.has(e)))},ld=async(e,t)=>{if(t.from===t.to)return ad;let n=await td(e,t);if(n===void 0||await od(e,t,n))return;let r=n.filter(e=>Qu(e));if(r.length>200)return;let i=await cd(e,t,r);return i===void 0?void 0:{changedDirs:sd(r),namesBefore:i}},ud=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
325
- `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},dd=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,fd=(e,t)=>{let n=[];if(e&&n.push(`checkout had local changes (managed checkouts are read-only) — discarded and restored to the remote state`),t!==void 0&&n.push(t),n.length!==0)return n.join(` | `)},pd=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:dd(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=fd(n,r);return o!==void 0&&(a.warning=o),a},md=(e,t,n)=>{let r={dirty:t,shas:n};return e.branchRenamedTo!==void 0&&(r.branchRenamedTo=e.branchRenamedTo),e.warning!==void 0&&(r.setHeadWarning=e.warning),r},U=e=>pe(m(e,`.git`)),hd=e=>`refusing to sync ${e}: not a refs-managed checkout`,gd=async(e,t)=>{if(!U(t))throw b(hd(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw b(hd(t))},_d=/filtering not recognized/iu,vd=e=>e===void 0?{}:{cwd:e},yd=(e,t,n)=>({action:e,args:t,cmd:`git`,...vd(n)}),bd=async(e,t)=>{let n=await e.run(t.cmd,t.args,vd(t.cwd));if(n.exitCode===0)return n;let r=n.stderr.trim()||n.stdout.trim()||`exit code ${n.exitCode}`;throw b(`${t.action} failed: ${r}`)},xd=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await bd(e,yd(`git clone`,n));return await bd(e,yd(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&_d.test(r.stderr)?{effectiveMode:`full`,warning:`server did not honour the partial-clone filter (blob:none); fell back to a full clone`}:{effectiveMode:t.mode}},Sd=async(e,t)=>{let n=await e.run(`git`,[`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],{cwd:t});if(n.exitCode!==0)return;let r=n.stdout.trim();return r.startsWith(`origin/`)?r.slice(7):r},Cd=async(e,t)=>{let n=await Sd(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await Sd(e,t);if(r!==void 0)return r;throw b(`could not detect the default branch for checkout: ${t}`)},wd=async(e,t)=>(await bd(e,yd(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),Td=async(e,t)=>(await bd(e,yd(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,Ed=async(e,t)=>{await bd(e,yd(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await Cd(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${ud(n)}`),i},Dd=e=>[yd(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),yd(`git clean -fd`,[`clean`,`-fd`],e)],Od=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...Dd(r)),a.push(yd(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),yd(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await bd(e,t)},kd=async(e,t)=>{await gd(e,t.dir);let n=await wd(e,t.dir),r=await Ed(e,t),i=await Td(e,t.dir);await Od(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await wd(e,t.dir);return pd(md(r,i,{newSha:a,oldSha:n}))},Ad=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,jd=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
326
- `),Md=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=m(e.hooksDir,n);await Zl(r,jd),await t(r,493)}))},Nd=async(e,t,n)=>{let r=await bd(e,yd(`git tag`,[`tag`,`--sort=-version:refname`],t)),i=r.stdout.split(`
327
- `).map(e=>e.trim()).filter(e=>e!==``),a=!r.stderr.includes(`refs: stdout exceeded`);return n===void 0?{complete:a,tags:i}:{complete:a&&i.length<=n,tags:i.slice(0,n)}},Pd=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Fd=/\d+\.\d+\.\d+/gu,Id=e=>cl.safeParse(e).success,Ld=e=>{let t=e.match(Fd);return t!==null&&t.length>1},Rd=e=>{let t=Pd.exec(e);if(!t||Ld(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Id(r))return r},zd=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},Bd=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=Rd(r);e&&zd(t,e,n)}return t},Vd=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Hd=e=>{let t=[...e.entries()],[n]=t;if(n===void 0)return null;let[r,i]=n;return t.slice(1).reduce(({format:e,data:t},[n,r])=>Vd(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Ud=e=>{let t=Bd(e);return Hd(t)},Wd=(e,t)=>e.replaceAll(`{version}`,()=>t),Gd=async(e,t,n,r)=>{let i=Wd(n,r);if(!await Ad(e,t,i))throw v(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Kd=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,W=e=>{let t=e.replace(Kd,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},qd=/\.git$/u,Jd=e=>e.replace(qd,``),Yd=e=>{let t=0,n=e.length;for(;t<n&&e.charAt(t)===`/`;)t+=1;for(;n>t&&e.charAt(n-1)===`/`;)--n;return e.slice(t,n)},Xd=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,Zd=/^git\+/u,Qd={"https:":`443`,"ssh:":`22`},$d=e=>e.split(`/`).some(e=>e===`.`||e===`..`),ef=e=>e.includes(`\\`),tf=e=>e.includes(`%`),nf=e=>{let t=rl.safeParse(e);if(!t.success)throw b(`not a supported git url: derived key '${W(e)}' is invalid`);return t.data},rf=({host:e,port:t,protocol:n})=>{let r=Qd[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},af=e=>{let t=Jd(Yd(e.path));return nf(`${rf(e)}/${t}`)},of=e=>{let t=decodeURIComponent(e).split(`/`).filter(e=>e!==``);if(t.length<2)throw b(`not a supported git url: file url path must have at least 2 segments`);let n=t.at(-2)??``,r=t.at(-1)??``;return nf(`local/${n}/${r}`)},sf=(e,t)=>{try{return new URL(e)}catch{throw b(`not a supported git url: ${W(t)}`)}},cf=e=>{if(e.password!==``)throw b(`not a supported git url: credentials embedded in url`);if(e.protocol===`https:`&&e.username!==``)throw b(`not a supported git url: credentials embedded in https url`)},lf=(e,t)=>{if(e.protocol===`file:`){if(!t)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return of(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return cf(e),af({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},uf=(e,t)=>{if(tf(e))throw b(`not a supported git url: percent-encoding not supported in ${W(t)}`);if(e.includes(`:`))throw b(`not a supported git url: ambiguous ':' in scp-style path ${W(t)}; use the ssh:// url form instead`);if(e.startsWith(`/`)||e.startsWith(`~`))throw b(`not a supported git url: ambiguous absolute/home-relative scp path in ${W(t)}; use the ssh:// url form instead`)},df=(e,t)=>{let n=e.groups?.path??``;return uf(n,t),af({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},ff=(e,t)=>{if(ef(e))throw b(`not a supported git url: backslash not allowed in ${W(t)}`)},pf=(e,t)=>{if($d(e))throw b(`not a supported git url: path traversal segment in ${W(t)}`)},mf=(e,t,n)=>{if(e.protocol!==`file:`&&tf(t))throw b(`not a supported git url: percent-encoding not supported in ${W(n)}`)},hf=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(Zd,``);ff(r,e),pf(r,e);let i=Xd.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:df(i,e)};let a=sf(r,e);return mf(a,r,e),{cloneUrl:r,key:lf(a,n)}},gf=`.git`,_f=e=>e.endsWith(gf)?e:`${e}${gf}`,vf=(e,t)=>`https://${e.toLowerCase()}/${Yd(t)}`,yf=(e,t)=>`git@${e.toLowerCase()}:${_f(Yd(t))}`,bf=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw b(`not a supported git url: unsupported protocol ${e}`)},xf=(e,t,n)=>{let r=Qd[e.protocol];if(e.port!==``&&e.port!==r)throw b(`cannot apply git_transport=${t} to ${W(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},Sf=(e,t)=>t===`https`?vf(e.hostname,e.pathname):yf(e.hostname,e.pathname),Cf=(e,t,n)=>{let r=hf(t).key;if(r!==n)throw b(`git_transport transform changed repo identity: '${W(e)}' → '${t}' (key '${n}' → '${r}')`);return t},wf=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return Cf(t.cloneUrl,vf(n,r),t.originalKey)},Tf=e=>{let t=sf(e.cloneUrl,e.cloneUrl);return bf(t.protocol)===e.transport?e.cloneUrl:(xf(t,e.transport,e.cloneUrl),Cf(e.cloneUrl,Sf(t,e.transport),e.originalKey))},Ef=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:hf(e).key,transport:t},r=Xd.exec(e);return r?.groups===void 0?Tf(n):wf(r,n)},Df=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,Of=(e,t)=>{if(Df.test(t))return m(e,`lease-${t}`)},kf=async(e,t)=>{let n=Of(e,t);n!==void 0&&await(await o(n,`w`)).close()},Af=async(e,t)=>{let n=Of(e,t);if(n===void 0)return`gone`;let r=new Date;try{await ee(n,r,r)}catch(e){if(z(e))return`gone`;throw e}return`renewed`},jf=async(e,t)=>{let n=Of(e,t);if(n===void 0)return{state:`absent`};try{return{mtimeMs:(await p(n)).mtimeMs,state:`ok`}}catch(e){return{state:z(e)?`absent`:`unreadable`}}},Mf=`meta.json`,Nf=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},Pf=e=>{try{return process.kill(e,0),!0}catch(e){return Nf(e)!==`ESRCH`}},Ff=e=>{try{return JSON.parse(e)}catch{return}},If=async e=>{try{return await s(e,`utf8`)}catch{return}},Lf=new Set([`ENOENT`,`ENOTDIR`]),Rf=async e=>{try{return{state:`read`,text:await s(e,`utf8`)}}catch(e){let t=Nf(e);return{state:t!==void 0&&Lf.has(t)?`missing`:`unreadable`}}},zf=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},Bf=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},Vf=e=>{if(!(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>2147483647))return e},Hf=e=>{if(typeof e!=`object`||!e)return;let t=e,n=Vf(t.pid),r=zf(t.acquired_at);if(n===void 0||r===void 0)return;let i=Bf(e);return{acquiredAtMs:r,pid:n,...i===void 0?{}:{token:i}}},Uf=async e=>{let t=await If(m(e,Mf));if(t!==void 0)return Bf(Ff(t))},Wf=async e=>{let t=await Rf(m(e,Mf));if(t.state!==`read`)return{state:t.state};let n=Hf(Ff(t.text));return n===void 0?{state:`malformed`}:{meta:n,state:`valid`}},Gf=async e=>{try{return{mtimeMs:(await p(e)).mtimeMs,state:`ok`}}catch(e){return{state:Nf(e)===`ENOENT`?`gone`:`unreadable`}}},Kf=async(e,t)=>{let n=m(e,Mf),r=`${n}.tmp-${de()}`;await te(r,t,`utf8`),await u(r,n)},qf=()=>de(),Jf=async(e,t)=>{await kf(e,t),await Kf(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Yf=5e3,Xf=async(e,t,n)=>{if(t===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let r=await Gf(e);if(r.state===`gone`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`none`,stale:!1};if(r.state===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let i=n-r.mtimeMs;return{ageMs:i,budgetMs:Yf,meta:t,observedAtMs:n,pidState:`unknown`,policy:`grace`,stale:i>Yf}},Zf=async(e,t,n)=>{let r=t.token===void 0?{state:`absent`}:await jf(e,t.token);return r.state===`unreadable`?{policy:`unknown`}:r.state===`absent`?{ageMs:n-t.acquiredAtMs,budgetMs:6e5,policy:`legacy`}:{ageMs:n-r.mtimeMs,budgetMs:12e4,policy:`lease`}},Qf=async(e,t)=>{let n=await Wf(e);if(n.state!==`valid`)return Xf(e,n.state,t);let{meta:r}=n,i=await Zf(e,r,t),a=!Pf(r.pid),o=i.ageMs!==void 0&&i.budgetMs!==void 0&&i.ageMs>i.budgetMs;return{...i,meta:`valid`,observedAtMs:t,pid:r.pid,pidState:a?`definitely-dead`:`present-or-unknown`,stale:a||o,...r.token===void 0?{}:{token:r.token}}},$f=e=>e.meta===`valid`&&e.pidState===`definitely-dead`&&e.token!==void 0,ep=async(e,t)=>await Uf(e)===t?await Af(e,t)===`gone`?`lost`:`renewed`:`lost`,tp=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),np=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),rp=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=Nf(e);if(t!==void 0&&tp.has(t))return!1;throw e}},ip=async(e,t)=>{try{return await u(e,t),!0}catch(e){let t=Nf(e);if(t!==void 0&&np.has(t))return!1;throw e}},ap=`.claims`,op=`.tombstones`,sp=(e,t)=>({lockPath:m(e,t),locksDir:e,name:t}),cp=e=>m(e.locksDir,ap,e.name),lp=e=>m(e.locksDir,op,de()),up=async e=>{await a(m(e,ap),{recursive:!0}),await a(m(e,op),{recursive:!0})},dp=e=>rp(e),fp=async e=>{try{await f(e)}catch{}},pp=async e=>{let t=lp(e);return await ip(e.lockPath,t)?t:void 0},mp=async e=>{let t=await Qf(e.lockPath,Date.now());if(!$f(t)||await Uf(e.lockPath)!==t.token)return!1;let n=await pp(e);return n!==void 0&&(await d(n,{force:!0,recursive:!0}),!0)},hp=async e=>{await up(e.locksDir);let t=cp(e);if(!await dp(t))return!1;let n=await mp(e).then(e=>({ok:!0,stolen:e}),e=>({error:e,ok:!1}));if(await fp(t),!n.ok)throw n.error;return n.stolen},gp=async e=>{try{return(await c(e,{withFileTypes:!0})).map(e=>({isDir:e.isDirectory(),name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}catch(e){if(z(e))return[];throw e}},_p=async e=>(await gp(e)).filter(e=>!e.name.startsWith(`.`)),vp=async(e,t,n)=>{let r=await Qf(m(e,t.name),n);if(r.policy!==`none`)return{diagnosis:r,isDirectory:t.isDir,kind:`lock`,name:t.name}},yp=async(e,t)=>{let n=m(e,ap),r=await gp(n);return(await Promise.all(r.map(async e=>({diagnosis:await Qf(m(n,e.name),t),isDirectory:e.isDir,kind:`claim`,name:e.name})))).filter(e=>e.diagnosis.policy!==`none`)},bp=async e=>{let t=Date.now(),n=await _p(e.locksDir),[r,i]=await Promise.all([Promise.all(n.map(n=>vp(e.locksDir,n,t))),yp(e.locksDir,t)]);return[...r.filter(e=>e!==void 0),...i]},xp=e=>{let t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60),i=r%60,a=Math.floor(r/60);return a>0?i===0?`${a}h`:`${a}h ${i}m`:r>0?n===0?`${r}m`:`${r}m ${n}s`:`${n}s`},Sp=e=>e.pid===void 0?`owner unknown (metadata ${e.meta})`:e.pidState===`definitely-dead`?`recorded pid ${e.pid} is not running`:`recorded pid ${e.pid} is present (identity not verified)`,Cp={grace:`created`,lease:`lease renewed`,legacy:`acquired`,none:`observed`,unknown:`observed`},wp={grace:`from creation, while its metadata has not been published`,lease:`from the last renewal`,legacy:`from acquisition (no renewable lease)`,none:``,unknown:``},Tp=e=>{let{ageMs:t,budgetMs:n,policy:r}=e;return t===void 0||n===void 0?``:t<0?`, but its recorded time is in the future — check the system clock`:`, ${Cp[r]} ${xp(t)} ago; its window is ${xp(n)} ${wp[r]}`},Ep=(e,t)=>{if(t.policy===`none`)return`lock ${e} could not be acquired before the timeout, but it was released while the failure was being diagnosed. Retry the operation.`;let n=`lock ${e} is held: ${Sp(t)}`;return $f(t)?`${n}, and refs is entitled to reclaim it — it could not do so before the timeout. Retry; if it persists, run refs doctor.`:t.stale?`${n}${Tp(t)}. refs does not reclaim this automatically: only a recorded process the operating system reports as gone is reclaimed, and this one is not. Run refs doctor for what to do about it.`:`${n}${Tp(t)}. Retry once the other refs command finishes.`},Dp=(e,t)=>{if(t.stopped)return;let n=setTimeout(()=>{t.stopped||(t.inFlight=Op(e,t))},e.intervalMs);n.unref(),t.timer=n},Op=async(e,t)=>{try{if(await e.renew()===`lost`){t.lost=!0,t.stopped=!0;return}}catch{}Dp(e,t)},kp=e=>{let t={inFlight:Promise.resolve(),lost:!1,stopped:!1};return Dp(e,t),{ownershipLost:()=>t.lost,stop:async()=>{t.stopped=!0,t.timer!==void 0&&clearTimeout(t.timer),await t.inFlight}}},Ap=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,jp=async(e,t)=>{try{await Jf(e,t)}catch(e){if(Nf(e)===`ENOENT`)return`retry`;throw e}return t},Mp=async(e,t)=>{if(!await rp(e))return;let n=await jp(e,qf());return n===`retry`?Date.now()>=t?void 0:Mp(e,t):n},Np=async(e,t)=>{if(!await hp(e)){if(Date.now()>=t){let t=await Qf(e.lockPath,Date.now());throw Se(Ep(e.name,t))}await ge(100)}},Pp=async(e,t)=>{let n=await Mp(e.lockPath,t);return n===void 0?(await Np(e,t),Pp(e,t)):n},Fp=async(e,t)=>await Uf(e)===t&&(await d(e,{force:!0,recursive:!0}),!0),Ip=async e=>{try{return{ok:!0,value:await e()}}catch(e){return{error:e,ok:!1}}},Lp=async(e,t,n,r)=>{await n.stop();let i=await Ip(()=>Fp(e.lockPath,t));if(!r.ok)throw r.error;if(!i.ok)throw i.error;if(n.ownershipLost()||!i.value)throw Se(`lock ${e.name} was lost while the operation was running`);return r.value},Rp=e=>e!==`.`&&e!==`..`&&Ap.test(e),zp=e=>{if(!Rp(e))throw b(`lock name must not contain "/" or other unsafe characters — only letters, digits, and "_.-" are allowed, and it may not be "." or "..": ${e}`)},G=async(e,t,n,r)=>{zp(t);let i=sp(e.locksDir,t);await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await Pp(i,o),c=kp({intervalMs:3e4,renew:()=>ep(i.lockPath,s)});return Lp(i,s,c,await Ip(n))},Bp=oc({directory:F().optional(),url:F().optional()}),Vp=oc({repository:cc([F(),Bp]).optional()}),Hp=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,Up=new Set([`node_modules`,`favicon.ico`]),Wp=e=>v(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),Gp=e=>{let[t,n]=e.split(`/`);return n??t??e},Kp=e=>{if(e.length>214)throw y(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!Hp.test(e))throw y(`invalid package name: '${e}' does not match npm naming rules`);let t=Gp(e);if(Up.has(t))throw y(`invalid package name: '${e}' uses a reserved name`)},qp=e=>e.replaceAll(`/`,`%2F`),Jp=e=>typeof e==`string`?e:e?.url,Yp=e=>{if(typeof e==`object`&&e?.directory){let t=ll.safeParse(e.directory);if(t.success)return t.data}},Xp=async(e,t)=>{try{return await e.json()}catch{throw b(`invalid npm registry response for '${t}': not parseable JSON`)}},Zp=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${qp(t)}`);if(n.status===404)throw v(`npm package '${t}' not found`);if(n.status!==200)throw b(`failed to fetch npm package '${t}': status ${n.status}`);let r=await Xp(n,t),i=Vp.safeParse(r);if(!i.success)throw b(`invalid npm package response for '${t}'`);return i.data},Qp=(e,t)=>{try{return hf(e)}catch{throw Wp(t)}},$p=async(e,t)=>{Kp(t);let n=await Zp(e,t),r=Jp(n.repository);if(r===void 0||r===``)throw Wp(t);let{cloneUrl:i,key:a}=Qp(r,t),o=Yp(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},em=(e,t,n)=>{let r=e instanceof RegExp?tm(e,n):e,i=t instanceof RegExp?tm(t,n):t,a=r!==null&&i!=null&&nm(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},tm=(e,t)=>{let n=t.match(e);return n?n[0]:null},nm=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},rm=`\0SLASH`+Math.random()+`\0`,im=`\0OPEN`+Math.random()+`\0`,am=`\0CLOSE`+Math.random()+`\0`,om=`\0COMMA`+Math.random()+`\0`,sm=`\0PERIOD`+Math.random()+`\0`,cm=new RegExp(rm,`g`),lm=new RegExp(im,`g`),um=new RegExp(am,`g`),dm=new RegExp(om,`g`),fm=new RegExp(sm,`g`),pm=/\\\\/g,mm=/\\{/g,hm=/\\}/g,gm=/\\,/g,_m=/\\\./g;function vm(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function ym(e){return e.replace(pm,rm).replace(mm,im).replace(hm,am).replace(gm,om).replace(_m,sm)}function bm(e){return e.replace(cm,`\\`).replace(lm,`{`).replace(um,`}`).replace(dm,`,`).replace(fm,`.`)}function xm(e){if(!e)return[``];let t=[],n=em(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=xm(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function Sm(e,t={}){if(!e)return[];let{max:n=1e5,maxLength:r=4e6}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),km(ym(e),n,r,!0).map(bm)}function Cm(e){return`{`+e+`}`}function wm(e){return/^-?0\d/.test(e)}function Tm(e,t){return e<=t}function Em(e,t){return e>=t}function Dm(e,t,n,r,i,a){let o=[],s=0;for(let c=0;c<e.length;c++)for(let l=0;l<n.length;l++){if(o.length>=r)return o;let u=e[c]+t+n[l];if(!a||u){if(s+u.length>i)return o;o.push(u),s+=u.length}}return o}function Om(e,t,n,r){let i=e.split(/\.\./),a=[];if(i[0]===void 0||i[1]===void 0)return a;let o=vm(i[0]),s=vm(i[1]),c=Math.max(i[0].length,i[1].length),l=i.length===3&&i[2]!==void 0?Math.max(Math.abs(vm(i[2])),1):1,u=Tm;s<o&&(l*=-1,u=Em);let d=i.some(wm),f=0;for(let e=o;u(e,s)&&a.length<n;e+=l){let n;if(t)n=String.fromCharCode(e),n===`\\`&&(n=``);else if(n=String(e),d){let t=c-n.length;if(t>0){let r=Array(t+1).join(`0`);n=e<0?`-`+r+n.slice(1):r+n}}if(f+n.length>r)break;a.push(n),f+=n.length}return a}function km(e,t,n,r){let i=[``],a=!1,o=!0;for(;;){let s=em(`{`,`}`,e);if(!s)return Dm(i,e,[``],t,n,a);let c=s.pre;if(/\$$/.test(c)){if(i=Dm(i,c+`{`+s.body+`}`,[``],t,n,a&&!s.post.length),o=!1,!s.post.length)break;e=s.post;continue}let l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),d=l||u,f=s.body.indexOf(`,`)>=0;if(!d&&!f){if(s.post.match(/,(?!,).*\}/)){e=s.pre+`{`+s.body+am+s.post,r=!0;continue}return Dm(i,c+`{`+s.body+`}`+s.post,[``],t,n,a)}o&&=(a=r&&!d,!1);let p;if(d)p=Om(s.body,u,t,n);else{let r=xm(s.body);if(r.length===1&&r[0]!==void 0&&(r=km(r[0],t,n,!1).map(Cm),r.length===1)){if(i=Dm(i,c+r[0],[``],t,n,a&&!s.post.length),!s.post.length)break;e=s.post;continue}let o=a&&!s.post.length&&!c;for(let e=0;o&&e<i.length;e++)i[e]&&(o=!1);p=[];let l=0;outer:for(let e=0;e<r.length;e++){let i=km(r[e],t,n,!1);for(let e=0;e<i.length;e++){let r=i[e];if(!o||r){if(p.length>=t||l+r.length>n)break outer;p.push(r),l+=r.length}}}}if(i=Dm(i,c,p,t,n,a&&!s.post.length),!s.post.length)break;e=s.post}return i}const Am=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},jm={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},Mm=e=>e.replace(/[[\]\\-]/g,`\\$&`),Nm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Pm=e=>e.join(``),Fm=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(jm))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue WHILE}}if(c=!1,d){t>d?r.push(Mm(d)+`-`+Mm(t)):t===d&&r.push(Mm(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(Mm(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(Mm(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l){let e=r[0].length===2?r[0].slice(-1):r[0];return[Nm(e),!1,u-n,!1]}let f=`[`+(l?`^`:``)+Pm(r)+`]`,p=`[`+(l?``:`^`)+Pm(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},Im=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var K;const Lm=new Set([`!`,`?`,`+`,`*`,`@`]),Rm=e=>Lm.has(e),zm=e=>Rm(e.type),Bm=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),Vm=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),Hm=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),Um=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),Wm=`(?!\\.)`,Gm=new Set([`[`,`.`]),Km=new Set([`..`,`.`]),qm=new Set(`().*{}+?[]^$\\!`),Jm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Ym=`[^/]+?`;let Xm=0;var Zm=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++Xm;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.#l=this.type?this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==``){if(typeof t!=`string`&&!(t instanceof K&&t.#i===this))throw Error(`invalid part: `+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;t<this.#a;t++){let n=e.#r[t];if(!(n instanceof K&&n.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(e){let t=new K(this.type,e);for(let e of this.#r)t.copyIn(e);return t}static#f(e,t,n,r,i){let a=r.maxExtglobRecursion??2,o=!1,s=!1,c=-1,l=!1;if(t.type===null){let u=n,d=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,d+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),d+=n;continue}if(n===`[`){s=!0,c=u,l=!1,d+=n;continue}if(!r.noext&&Rm(n)&&e.charAt(u)===`(`&&i<=a){t.push(d),d=``;let a=new K(n,t);u=K.#f(e,a,u,r,i+1),t.push(a);continue}d+=n}return t.push(d),u}let u=n+1,d=new K(null,t),f=[],p=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,p+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),p+=n;continue}if(n===`[`){s=!0,c=u,l=!1,p+=n;continue}if(!r.noext&&Rm(n)&&e.charAt(u)===`(`&&(i<=a||t&&t.#h(n))){let a=t&&t.#h(n)?0:1;d.push(p),p=``;let o=new K(n,d);d.push(o),u=K.#f(e,o,u,r,i+a);continue}if(n===`|`){d.push(p),p=``,f.push(d),d=new K(null,t);continue}if(n===`)`)return p===``&&t.#r.length===0&&(t.#u=!0),d.push(p),p=``,t.push(...f,d),u;p+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],u}#p(e){return this.#m(e,Vm)}#m(e,t=Bm){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null)return!1;let n=e.#r[0];return!n||typeof n!=`object`||n.type===null?!1:this.#h(n.type,t)}#h(e,t=Hm){return!!t.get(this.type)?.includes(e)}#g(e,t){let n=e.#r[0],r=new K(null,n,this.options);r.#r.push(``),n.push(r),this.#_(e,t)}#_(e,t){let n=e.#r[0];this.#r.splice(t,1,...n.#r);for(let e of n.#r)typeof e==`object`&&(e.#i=this);this.#l=void 0}#v(e){return!!Um.get(this.type)?.has(e)}#y(e){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let t=e.#r[0];return!t||typeof t!=`object`||t.type===null?!1:this.#v(t.type)}#b(e){let t=Um.get(this.type),n=e.#r[0],r=t?.get(n.type);if(!r)return!1;this.#r=n.#r;for(let e of this.#r)typeof e==`object`&&(e.#i=this);this.type=r,this.#l=void 0,this.#u=!1}static fromGlob(e,t={}){let n=new K(null,void 0,t);return K.#f(e,n,0,t,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(e){let t=e??!!this.#c.dot;if(this.#e===this&&(this.#x(),this.#d()),!zm(this)){let n=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?K.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&Km.has(this.#r[0]))){let n=Gm,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?Wm:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,Im(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,Im(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?Wm:``)+Ym;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?Wm:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,Im(i),this.#t=!!this.#t,this.#n]}#x(){if(zm(this)){let e=0,t=!1;do{t=!0;for(let e=0;e<this.#r.length;e++){let n=this.#r[e];typeof n==`object`&&(n.#x(),this.#m(n)?(t=!1,this.#_(n,e)):this.#p(n)?(t=!1,this.#g(n,e)):this.#y(n)&&(t=!1,this.#b(n)))}}while(!t&&++e<10)}else for(let e of this.#r)typeof e==`object`&&e.#x();this.#l=void 0}#S(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(qm.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?Ym:`[^/]*?`,t=!0;continue}if(o=!1,c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=Fm(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=`[^/]`,t=!0;continue}i+=Jm(c)}return[i,Im(e),!!t,a]}};K=Zm;const Qm=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),q=(e,t,n={})=>(Am(t),!n.nocomment&&t.charAt(0)===`#`?!1:new wh(t,n).match(e)),$m=/^\*+([^+@!?*[(]*)$/,eh=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),th=e=>t=>t.endsWith(e),nh=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),rh=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ih=/^\*+\.\*+$/,ah=e=>!e.startsWith(`.`)&&e.includes(`.`),oh=e=>e!==`.`&&e!==`..`&&e.includes(`.`),sh=/^\.\*+$/,ch=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),lh=/^\*+$/,uh=e=>e.length!==0&&!e.startsWith(`.`),dh=e=>e.length!==0&&e!==`.`&&e!==`..`,fh=/^\?+([^+@!?*[(]*)?$/,ph=([e,t=``])=>{let n=_h([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},mh=([e,t=``])=>{let n=vh([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},hh=([e,t=``])=>{let n=vh([e]);return t?e=>n(e)&&e.endsWith(t):n},gh=([e,t=``])=>{let n=_h([e]);return t?e=>n(e)&&e.endsWith(t):n},_h=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},vh=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},yh=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,bh={win32:{sep:`\\`},posix:{sep:`/`}};q.sep=yh===`win32`?bh.win32.sep:bh.posix.sep;const J=Symbol(`globstar **`);q.GLOBSTAR=J,q.filter=(e,t={})=>n=>q(n,e,t);const Y=(e,t={})=>Object.assign({},e,t);q.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return q;let t=q;return Object.assign((n,r,i={})=>t(n,r,Y(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,Y(e,n))}static defaults(n){return t.defaults(Y(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,Y(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,Y(e,r))}},unescape:(n,r={})=>t.unescape(n,Y(e,r)),escape:(n,r={})=>t.escape(n,Y(e,r)),filter:(n,r={})=>t.filter(n,Y(e,r)),defaults:n=>t.defaults(Y(e,n)),makeRe:(n,r={})=>t.makeRe(n,Y(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,Y(e,r)),match:(n,r,i={})=>t.match(n,r,Y(e,i)),sep:t.sep,GLOBSTAR:J})};const xh=(e,t={})=>(Am(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Sm(e,{max:t.braceExpandMax}));q.braceExpand=xh,q.makeRe=(e,t={})=>new wh(e,t).makeRe(),q.match=(e,t,n={})=>{let r=new wh(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const Sh=/[?*]|[+@!]\(.*?\)|\[|\]/,Ch=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var wh=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){Am(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||yh,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!Sh.test(e[2]))&&!Sh.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t of e)for(let e=0;e<t.length;e++)t[e]===`**`&&(t[e]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];(n!==1||r!==``||e[0]!==``)&&(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&!(this.isWindows&&/^[a-z]:$/i.test(r))&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];(e!==1||r!==``||n[0]!==``)&&(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=0,i=0;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),a=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),o=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),s=!o&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),c=a?3:n?0:void 0,l=s?3:o?0:void 0;if(typeof c==`number`&&typeof l==`number`){let[n,a]=[e[c],t[l]];n.toLowerCase()===a.toLowerCase()&&(t[l]=n,i=l,r=c)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(J)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(J,i),o=t.lastIndexOf(J),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n<e.length-u;n++){let r=String(e[n]);if(t=!0,r===`.`||r===`..`||!this.options.dot&&r.startsWith(`.`))return!1}return n||t}let d=[[[],0]],f=d[0],p=0,ee=[0];for(let e of c)e===J?(ee.push(p),f=[[],0],d.push(f)):(f[0].push(e),p++);let te=d.length-1,ne=e.length-u;for(let e of d)e[1]=ne-(ee[te--]+e[0].length);return!!this.#t(e,d,r,0,n,0,!!u)}#t(e,t,n,r,i,a,o){let s=t[r];if(!s){for(let t=n;t<e.length;t++){o=!0;let n=e[t];if(n===`.`||n===`..`||!this.options.dot&&n.startsWith(`.`))return!1}return o}let[c,l]=s;for(;n<=l;){if(this.#n(e.slice(0,n+c.length),c,i,n,0)&&a<this.maxGlobstarRecursion){let s=this.#t(e,t,n+c.length,r+1,i,a+1,o);if(s!==!1)return s}let s=e[n];if(s===`.`||s===`..`||!this.options.dot&&s.startsWith(`.`))return!1;n++}return i||null}#n(e,t,n,r,i){let a,o,s,c;for(a=r,o=i,c=e.length,s=t.length;a<c&&o<s;a++,o++){this.debug(`matchOne loop`);let n=t[o],r=e[a];if(this.debug(t,n,r),n===!1||n===J)return!1;let i;if(typeof n==`string`?(i=r===n,this.debug(`string match`,n,r,i)):(i=n.test(r),this.debug(`pattern match`,n,r,i)),!i)return!1}if(a===c&&o===s)return!0;if(a===c)return n;if(o===s)return a===c-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return xh(this.pattern,this.options)}parse(e){Am(e);let t=this.options;if(e===`**`)return J;if(e===``)return``;let n,r=null;(n=e.match(lh))?r=t.dot?dh:uh:(n=e.match($m))?r=(t.nocase?t.dot?rh:nh:t.dot?th:eh)(n[1]):(n=e.match(fh))?r=(t.nocase?t.dot?mh:ph:t.dot?hh:gh)(n):(n=e.match(ih))?r=t.dot?oh:ah:(n=e.match(sh))&&(r=ch);let i=Zm.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?`[^/]*?`:t.dot?`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`:`(?:(?!(?:\\/|^)\\.).)*?`,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?Ch(e):e===J?J:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e===J&&a!==J&&(a===void 0?i!==void 0&&i!==J?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==J&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=J))});let i=t.filter(e=>e!==J);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return q.defaults(e).Minimatch}};q.AST=Zm,q.Minimatch=wh,q.escape=Qm,q.unescape=Im;const Th=/[/\\]/u,Eh={kind:`ignore`},Dh=e=>!ae(e)&&e.split(Th).every(e=>e!==`.`&&e!==`..`),Oh=/^!+/u,kh=/^\.?\/+/u,Ah=e=>{let t=Oh.exec(e)?.[0]??``;return{body:e.slice(t.length).replace(kh,``),negated:t.length%2==1}},jh=e=>Ah(e).negated,Mh=e=>Ah(e).body,Nh=/[?[\]{}()]/u,Ph=e=>Dh(e)&&!jh(e)&&!e.includes(`**`)&&!Nh.test(e)&&(e.match(/\*/gu)??[]).length<=1,Fh=(e,t)=>q(e,t),Ih=e=>e.replaceAll(/\/+/gu,`/`).replace(/\/$/u,``),Lh=e=>{let t=Ih(e).split(`/`),n=t.findIndex(e=>e.includes(`*`));return n===-1?Eh:{baseDir:n===0?`.`:t.slice(0,n).join(`/`),kind:`expand-children`,pattern:Ih(e),suffix:t.slice(n+1).join(`/`)}},Rh=e=>Ph(e)?e.includes(`*`)?Lh(e):{dir:e,kind:`probe-dir`,pattern:e}:Eh,zh=new Set([`candidate_not_inspected`,`manifest_unreadable`,`unsupported_pattern`,`workspace_declaration_unparsed`,`workspace_dir_unreadable`,`workspace_file_unreadable`]),Bh=(e,t)=>t?.name?{name:t.name,path:e}:void 0,Vh=e=>{let t=e.map(e=>[e.path,e]),n=[...new Map(t).values()];return n.sort((e,t)=>e.path.localeCompare(t.path)),n},Hh=e=>!e.diagnostics.some(e=>zh.has(e.kind)),Uh=e=>!e.diagnostics.some(e=>e.kind===`no_workspace_declaration`),Wh=(e,t)=>e<t?-1:+(e>t),Gh=e=>`path`in e?`${e.kind} ${e.path}`:`file`in e?`${e.kind} ${e.file}`:`pattern`in e?`${e.kind} ${e.pattern}`:e.kind,Kh=e=>e.toSorted((e,t)=>Wh(Gh(e),Gh(t))),qh=e=>!ae(e)&&!e.split(/[/\\]/u).includes(`..`),Jh=(e,t)=>e.kind===`missing`?{kind:`absent`}:e.kind===`outside`?{kind:`unreadable`,reason:`${t} escapes the checkout`}:{kind:`unreadable`,reason:e.code},Yh=async(e,t,n)=>{if(!qh(t))return{kind:`unreadable`,reason:`path escapes the checkout`};let r=await Xh(e,t);if(`probe`in r)return r.probe;let i=await Zh(r.real);return`reason`in i?{kind:`unreadable`,reason:i.reason}:i.found===n?{kind:`match`}:{found:i.found,kind:`mismatch`}},Xh=async(e,t)=>{let n=await Eu(e,m(e,t));if(n.kind!==`inside`)return{probe:Jh(n,`path`)};let r=await Eu(e,m(n.real,`package.json`));return r.kind===`inside`?{real:r.real}:{probe:Jh(r,`manifest`)}},Zh=async e=>{try{let t=JSON.parse(await s(e,`utf8`));return{found:Fu(t)}}catch(e){return{reason:e.code??String(e)}}},Qh=(e,t)=>{let n=e.filter(e=>e.name===t).map(e=>e.path);return n.length===0?{kind:`absent`}:n.length===1?{kind:`found`,path:n[0]}:{kind:`ambiguous`,paths:n.toSorted(Wh)}},$h=new Set;let eg=!1;const tg=()=>{for(let e of $h)try{e.kill(`SIGKILL`)}catch{}},ng=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],rg=e=>{let t=()=>{tg(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},ig=()=>{eg||(eg=!0,ng.forEach(e=>{rg(e)}),process.on(`exit`,tg))},ag=()=>{let e=[],t=0,n=!1;return{finish:()=>({text:Buffer.concat(e).toString(`utf8`),truncated:n}),push:r=>{if(n)return;let i=67108864-t;if(r.length<=i){e.push(r),t+=r.length;return}i>0&&e.push(r.subarray(0,i)),n=!0}}},og=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
328
- `),sg=(e,t,n)=>{let r=e;return t.truncated&&(r=og(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=og(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},cg={clear:()=>{},markedTimedOut:()=>!1},lg=(e,t)=>{if(t===void 0)return cg;let n=!1,r,i=setTimeout(()=>{n=!0,e.kill(`SIGTERM`),r=setTimeout(()=>{e.kill(`SIGKILL`)},2e3)},t);return{clear:()=>{clearTimeout(i),r!==void 0&&clearTimeout(r)},markedTimedOut:()=>n}},ug=e=>e===void 0?{}:{cwd:e},dg=(e,t)=>og(e,`refs: command timed out after ${String(t)}ms`),fg=(e,t)=>({exitCode:124,stderr:dg(e,t),stdout:``,timedOut:!0}),pg=(e,t,n)=>{let r=be(e,t,{...ug(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});$h.add(r);let i=ag(),a=ag();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:lg(r,n?.timeoutMs)}},mg=(e,t,n)=>{try{return pg(e,t,n)}catch(e){return{exitCode:127,stderr:gg(e),stdout:``}}},hg=e=>!(`child`in e),gg=e=>e instanceof Error?e.message:String(e),_g=async e=>{try{let[t]=await ve(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:gg(e)}}},vg=e=>e===null?1:e,yg=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,bg=e=>e.timedOut?fg(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?yg({exitCode:vg(e.code),stderr:sg(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):yg({exitCode:127,stderr:og(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var xg=class{async run(e,t,n){ig();let r=mg(e,t,n);if(hg(r))return r;let i=await _g(r.child);return $h.delete(r.child),r.timeout.clear(),bg({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Sg=pl.partial({description:!0}),Cg=L({default_branch:F().min(1),key:rl,tag_format_candidate:cl.nullable(),url:F().min(1)});Cg.extend({description:F().default(``),packages:Wc(Sg)});const wg=Cg.extend({description:F().min(1),packages:Wc(pl)}),Tg=L({effective_clone_mode:ol.optional(),head_sha:F().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:F().optional(),last_fetched_at:Bc().optional(),pending_proposal_at:Bc().optional()}),Eg=L({refs:Hc(e=>e.length>0&&!Vc.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,fc(F(),Tg)).default({})}),Dg=(e,t,n)=>t?.[e]??n[e],Og=async e=>{try{return await s(e.statePath,`utf8`)}catch(e){if(z(e))return;throw e}},kg=e=>{try{return JSON.parse(e)}catch{return}},Ag=async e=>{let t=await Og(e);if(t===void 0)return Eg.parse({});let n=kg(t);if(n===void 0)return Eg.parse({});let r=Eg.safeParse(n);return r.success?r.data:Eg.parse({})},jg=async(e,t)=>{let n=Eg.safeParse(t);if(!n.success)throw b(E(n.error));await Zl(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},Mg=/^\d+\.\d+\.\d+$/u,Ng=/^0+(?=\d)/u,Pg=(e,t)=>{let n=e.replace(Ng,``),r=t.replace(Ng,``);return n.length===r.length?n===r?0:n<r?-1:1:n.length<r.length?-1:1},Fg=(e,t)=>{if(!Mg.test(e)||!Mg.test(t))return;let n=e.split(`.`),r=t.split(`.`);return n.map((e,t)=>Pg(e,r[t]??``)).find(e=>e!==0)??0},Ig=oc({version:F().regex(Mg)}),Lg=L({checked_at:Bc(),latest_version:F().regex(Mg)}),Rg=async e=>{try{let t=Lg.safeParse(JSON.parse(await s(e.updateCachePath,`utf8`)));return t.success?t.data:void 0}catch{return}},zg=async(e,t)=>{try{await p(e.root),await Zl(e.updateCachePath,`${JSON.stringify(t,void 0,2)}\n`)}catch{}},Bg=(e,t)=>{let n=t-Date.parse(e.checked_at);return n>=0&&n<864e5},Vg=async e=>{try{let t=await e(`https://registry.npmjs.org/@kaisers-io%2Frefs/latest`,{signal:AbortSignal.timeout(2e3)});if(t.status!==200)return;let n=Ig.safeParse(await t.json());return n.success?n.data.version:void 0}catch{return}},Hg=async e=>{let t=await Rg(e.home);if(t!==void 0&&Bg(t,e.nowMs))return{latest:t.latest_version,refreshed:!1,stale:!1};let n=await Vg(e.fetch);return n===void 0?{latest:t?.latest_version,refreshed:!1,stale:!0}:(await zg(e.home,{checked_at:new Date(e.nowMs).toISOString(),latest_version:n}),{latest:n,refreshed:!0,stale:!1})},Ug=(e,t)=>{let n=Fg(e,t);return n!==void 0&&n<0},Wg=(e,t)=>`refs ${t} is available (this is ${e}) — update: npm i -g @kaisers-io/refs@latest`,Gg=e=>{let t=e.REFS_UPDATE_CHECK?.trim();if(t===`0`)return!1;if(t===`1`)return!0},Kg=e=>{let t=e.CI?.trim().toLowerCase();return t!==void 0&&t!==``&&t!==`false`&&t!==`0`},qg={check:!0,notify:!0},Jg=e=>{let t=Gg(e.env);return t===void 0?(e.updates??qg).check?Kg(e.env)?`ci`:`on`:`config`:t?`on`:`env`},Yg=e=>Jg(e)===`on`,Xg=e=>Yg(e)&&(e.updates??qg).notify,Zg=async(e,t)=>{let n=await Eu(e,m(t,`package.json`));if(n.kind===`inside`)try{let e=JSON.parse(await s(n.real,`utf8`));return{name:Fu(e)}}catch{return}},Qg=async(e,t)=>{let n=await Zg(e,m(e,t));if(n===void 0)return{diagnostic:{kind:`manifest_unreadable`,path:t}};let r=Bh(t,n);return r===void 0?{diagnostic:{kind:`manifest_missing_name`,path:t}}:{pkg:r}},$g=e=>{let t=[],n=[];for(let r of e)r.diagnostic!==void 0&&t.push(r.diagnostic),r.pkg!==void 0&&n.push(r.pkg);return{diagnostics:t,packages:n}},e_=new Set([`ENOENT`,`ENOTDIR`]),t_=async(e,t)=>{let n=await Eu(e,m(t,`package.json`));if(n.kind===`missing`)return`none`;if(n.kind!==`inside`)return`rejected`;try{return await s(n.real,`utf8`),`manifest`}catch{return`rejected`}},n_=async e=>{try{return{entries:await c(e,{withFileTypes:!0})}}catch(e){return{code:e.code??``}}},r_=e=>Promise.all(e.entries.map(t=>t_(e.repoDir,m(e.fullPath,t.name,e.suffix)))),i_=(e,t,n)=>e.filter((e,r)=>n(t[r])).map(e=>e.name),a_=async e=>{let{baseDir:t,dirs:n,fullPath:r,repoDir:i,suffix:a,symlinks:o}=e,s=e=>oe.join(t===`.`?``:t,e,a),[c,l]=await Promise.all([r_({entries:n,fullPath:r,repoDir:i,suffix:a}),r_({entries:o,fullPath:r,repoDir:i,suffix:a})]);return{diagnostics:[...i_(n,c,e=>e===`rejected`).map(e=>({kind:`manifest_unreadable`,path:s(e)})),...i_(o,l,e=>e!==`none`).map(e=>({kind:`candidate_not_inspected`,path:s(e)}))],dirs:i_(n,c,e=>e===`manifest`).map(e=>s(e))}},o_=async e=>{let t=await Qg(e,`.`);return`pkg`in t?[t]:[]},s_=e=>{let t=e.find(e=>e.path===`.`);return t===void 0?[...e]:e.some(e=>e.path!==`.`&&e.name===t.name)?e.filter(e=>e!==t):[...e]},c_=async e=>{let[t]=await o_(e);return t!==void 0&&`pkg`in t?t.pkg:void 0},l_=(e,t)=>oe.join(e.baseDir===`.`?``:e.baseDir,t,e.suffix),u_=(e,t)=>Fh(l_(t,e.name),t.pattern),d_=async(e,t)=>{let n=m(e,t),r=await Eu(e,n);if(r.kind===`missing`)return{result:{diagnostics:[],dirs:[]}};if(r.kind!==`inside`)return{result:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}};let i=await n_(n);return`code`in i?{result:e_.has(i.code)?{diagnostics:[],dirs:[]}:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}}:{entries:i.entries}},f_=async(e,t,n)=>{let{baseDir:r}=t,i=await d_(e,r);if(`result`in i)return i.result;let a=e=>u_(e,t)&&!n.has(l_(t,e.name)),o={entries:i.entries};return a_({baseDir:r,dirs:o.entries.filter(e=>e.isDirectory()&&a(e)),fullPath:m(e,r),repoDir:e,suffix:t.suffix,symlinks:o.entries.filter(e=>e.isSymbolicLink()&&a(e))})},p_=async(e,t)=>{let n=await t_(e,m(e,t));return n===`manifest`?{diagnostics:[],dirs:[Ih(t)]}:n===`rejected`?{diagnostics:[{kind:`manifest_unreadable`,path:t}],dirs:[]}:{diagnostics:[],dirs:[]}},m_=(e,t,n)=>{let r=Rh(t.body);return r.kind===`expand-children`?f_(e,r,n):r.kind===`probe-dir`?n.has(Ih(r.dir))?Promise.resolve({diagnostics:[],dirs:[]}):p_(e,r.dir):Promise.resolve({diagnostics:[{kind:`unsupported_pattern`,pattern:t.declared}],dirs:[]})},h_=(e,t)=>Fh(Mh(e),Mh(t)),g_=e=>({negations:e.filter(e=>jh(e)),patterns:e.filter(e=>!jh(e))}),__=e=>{let t=e.reduce((e,t)=>jh(t)?{negations:[...e.negations,t],patterns:e.patterns}:{negations:e.negations.filter(e=>!h_(t,e)),patterns:[...e.patterns,t]},{negations:[],patterns:[]});return{negations:t.negations,patterns:t.patterns.filter(e=>!t.negations.some(t=>h_(e,t)))}},v_=e=>e.endsWith(`/`)?e:`${e}/`,y_=(e,t)=>e.some(e=>Fh(v_(t),v_(Mh(e)))),b_=e=>{let t=new Set,n=[];for(let r of e)r.dirs.forEach(e=>t.add(e)),n.push(...r.diagnostics);return{diagnostics:n,dirs:[...t]}},x_=async(e,t)=>{let{negations:n,patterns:r}=t,i={has:e=>y_(n,e)},a=b_(await Promise.all(r.map(t=>m_(e,{body:Mh(t),declared:t},i))));return{diagnostics:a.diagnostics,dirs:a.dirs}},S_=async(e,t)=>{let n=__(t.npm),r=g_(t.pnpm),i=await Promise.all([x_(e,n),x_(e,r)]);return b_(i)},C_=async e=>{let t=await Hu(e);if(t.npm.length===0&&t.pnpm.length===0)return{diagnostics:Kh([...t.diagnostics,{kind:`no_workspace_declaration`}]),packages:[]};let n=await S_(e,t),[r,i]=await Promise.all([o_(e),Promise.all(n.dirs.map(t=>Qg(e,t)))]),a=$g([...r,...i]);return{diagnostics:Kh([...t.diagnostics,...n.diagnostics,...a.diagnostics]),packages:s_(Vh(a.packages))}};var w_=`0.13.1`;const T_=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},E_=()=>{try{return he()}catch{return``}},D_=()=>({cliVersion:w_,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:(e,t)=>fetch(e,t),homedir:E_(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:T_,runner:new xg});var O_=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},k_=class extends O_{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},A_=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new k_(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function j_(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var M_=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(e=>j_(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(t?` `+t:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
322
+ `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),hu=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:au(t)&&au(r)&&(n[e]=hu(t,r))}return n},gu={meta:{},refs:{},settings:{}},_u=async e=>{try{return await su(e)}catch(e){if(e instanceof g&&e.code===`not_found`)return;throw e}},vu=e=>{if(e!==void 0&&e>1)throw y(`config schema ${e} is newer than this CLI supports — upgrade refs`)},yu=async(e,t,n)=>{let r=ou(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await $l(e.configPath,Ql(i))},bu=async(e,t,n)=>{await r(e.configPath,eu(e));let i=hu(t,gu),a=ou(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=bl.safeParse(o);if(!s.success)throw y(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${eu(e)}): ${T(s.error)}`);await $l(e.configPath,Ql(o))},xu=async(e,t,n)=>{let r=cu(t,e.configPath),i=uu(r);return vu(i),i===1?(await yu(e,r,n),`noop`):(await bu(e,r,n),`migrated`)},Su=async(e,t)=>{let n=await _u(e);return n===void 0?(await mu(e,t),`seeded`):xu(e,n,t)},Cu=new Set([`ENOENT`,`ENOTDIR`]),wu=e=>e.code??String(e),Tu=async e=>{try{return await i(e),!0}catch{return!1}},Eu=(e,t)=>{let n=se(e,t);return n===``||n!==`..`&&!n.startsWith(`..`+le)&&!ae(n)},Du=async e=>{try{return{real:await l(e)}}catch(e){return{code:wu(e)}}},Ou=async(e,t)=>{let n=await Du(e);if(`code`in n)return{code:n.code,kind:`unreadable`};let r=await Du(t);return`code`in r?Cu.has(r.code)?await Tu(t)?{code:r.code,kind:`unreadable`}:{kind:`missing`}:{code:r.code,kind:`unreadable`}:Eu(n.real,r.real)?{kind:`inside`,real:r.real}:{kind:`outside`}},ku=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,Au=/^packages:\s*(?:#.*)?$/u,ju=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Mu=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!ju(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},Nu=Symbol(`end-of-section`),Pu=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!Au.test(e))return Nu;if(!t.startsWith(`-`))return;let n=ku.exec(e)?.groups?.pattern?.trim();if(n)return n},Fu=e=>{let t=[];for(let n of e){let e=Pu(n);if(e===Nu)break;e!==void 0&&t.push(e)}return t},Iu=e=>{let t=e.findIndex(e=>Au.test(e));return t===-1?[]:Fu(e.slice(t+1))},Lu=e=>{let{name:t}=e;if(typeof t==`string`)return t},Ru=async(e,t)=>{let n=await Ou(e,t);if(n.kind===`missing`)return{ok:!0};if(n.kind!==`inside`)return{ok:!1};try{return{content:await s(n.real,`utf8`),ok:!0}}catch{return{ok:!1}}},zu=async(e,t)=>{let n=await Ru(e,t);return n.ok?n.content===void 0?{ok:!0,patterns:[]}:Bu(n.content):{ok:!1,patterns:[]}},Bu=e=>{try{let t=JSON.parse(e);return{ok:!0,patterns:Mu(t.workspaces)}}catch{return{ok:!1,patterns:[]}}},Vu=/^packages:/mu,Hu=(e,t)=>t.length===0&&Vu.test(e),Uu=async(e,t)=>{let n=await Ru(e,t);if(!n.ok)return{ok:!1,patterns:[]};if(n.content===void 0)return{ok:!0,patterns:[]};let r=Iu(n.content.split(`
323
+ `));return{ok:!0,patterns:r,unparsed:Hu(n.content,r)}},Wu=async e=>{let[t,n]=await Promise.all([zu(e,m(e,`package.json`)),Uu(e,m(e,`pnpm-workspace.yaml`))]),r=[];return t.ok||r.push({file:`package.json`,kind:`workspace_file_unreadable`}),n.ok||r.push({file:`pnpm-workspace.yaml`,kind:`workspace_file_unreadable`}),n.unparsed===!0&&r.push({file:`pnpm-workspace.yaml`,kind:`workspace_declaration_unparsed`}),{diagnostics:r,npm:t.patterns,pnpm:n.patterns}},Gu=`\0unreadable`,Ku=`pnpm-workspace.yaml`,qu=async(e,t)=>{let n=await e.run(`git`,[`ls-tree`,`-z`,`--name-only`,t.rev,`--`,t.path],{cwd:t.dir});return n.exitCode===0?n.stdout.includes(t.path):void 0},Ju=async(e,t)=>{let n=await qu(e,t);if(n===void 0)return{kind:`unreadable`};if(!n)return{kind:`absent`};let r=await e.run(`git`,[`show`,`${t.rev}:${t.path}`],{cwd:t.dir});return r.exitCode===0?{contents:r.stdout}:{kind:`unreadable`}},Yu=async(e,t,n)=>{let r=await Ju(e,{dir:t.dir,path:`package.json`,rev:n});if(`kind`in r)return r.kind===`absent`?[]:[Gu];try{let e=JSON.parse(r.contents);return Mu(e.workspaces)}catch{return[Gu]}},Xu=async(e,t,n)=>{let r=await Ju(e,{dir:t.dir,path:Ku,rev:n});if(`kind`in r)return r.kind===`absent`?[]:[Gu];let{contents:i}=r,a=Iu(i.split(`
324
+ `));return Hu(i,a)?[Gu]:a},Zu=async(e,t,n)=>{let[r,i]=await Promise.all([Yu(e,t,n),Xu(e,t,n)]);return{npm:r,pnpm:i}},Qu=(e,t)=>{let n=0;for(let r of t)if(n<e.length&&e[n]===r)n+=1;else if(r.startsWith(`!`))return!1;return n===e.length},$u=async(e,t)=>{if(!t.touched)return!1;let[n,r]=await Promise.all([Zu(e,t,t.from),Zu(e,t,t.to)]);return!Qu(n.npm,r.npm)||!Qu(n.pnpm,r.pnpm)},ed=e=>re(e)===`package.json`,td=async(e,t,n)=>{let r=await e.run(`git`,[...n],{cwd:t});return r.exitCode===0?r.stdout:void 0},nd=e=>e.split(`\0`).filter(e=>e.length>0&&ed(e)),rd=async(e,t)=>{let n=await td(e,t.dir,[`diff`,`--name-only`,`-z`,`--no-renames`,`${t.from}..${t.to}`,`--`,`*package.json`,Ku]);return n===void 0?void 0:n.split(`\0`).filter(e=>e.length>0)},id=async(e,t)=>{if(t.paths.length===0)return new Set;let n=await td(e,t.dir,[`ls-tree`,`-r`,`-z`,`--name-only`,t.rev,`--`,...t.paths]);return n===void 0?void 0:new Set(nd(n))},ad=async(e,t)=>{let n=await td(e,t.dir,[`show`,`${t.rev}:${t.path}`]);if(n!==void 0)try{let e=JSON.parse(n);return{name:Lu(e)}}catch{return}},od=async(e,t,n)=>{let r=[];for(let i of n){let n=await ad(e,{dir:t.dir,path:i,rev:t.rev});if(n===void 0)return;n.name!==void 0&&r.push(n.name)}return r},sd={changedDirs:[],namesBefore:[]},cd=(e,t,n)=>$u(e,{...t,touched:n.some(e=>e===`pnpm-workspace.yaml`||e===`package.json`)}),ld=e=>[...new Set(e.map(e=>ie(e)))].filter(e=>e!==`.`).toSorted(),ud=async(e,t,n)=>{let r=await id(e,{dir:t.dir,paths:n,rev:t.from});if(r!==void 0)return od(e,{dir:t.dir,rev:t.from},n.filter(e=>r.has(e)))},dd=async(e,t)=>{if(t.from===t.to)return sd;let n=await rd(e,t);if(n===void 0||await cd(e,t,n))return;let r=n.filter(e=>ed(e));if(r.length>200)return;let i=await ud(e,t,r);return i===void 0?void 0:{changedDirs:ld(r),namesBefore:i}},fd=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
325
+ `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},pd=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,md=(e,t)=>{let n=[];if(e&&n.push(`checkout had local changes (managed checkouts are read-only) — discarded and restored to the remote state`),t!==void 0&&n.push(t),n.length!==0)return n.join(` | `)},hd=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:pd(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=md(n,r);return o!==void 0&&(a.warning=o),a},gd=(e,t,n)=>{let r={dirty:t,shas:n};return e.branchRenamedTo!==void 0&&(r.branchRenamedTo=e.branchRenamedTo),e.warning!==void 0&&(r.setHeadWarning=e.warning),r},H=e=>pe(m(e,`.git`)),_d=e=>`refusing to sync ${e}: not a refs-managed checkout`,vd=async(e,t)=>{if(!H(t))throw y(_d(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw y(_d(t))},yd=/filtering not recognized/iu,bd=e=>e===void 0?{}:{cwd:e},xd=(e,t,n)=>({action:e,args:t,cmd:`git`,...bd(n)}),Sd=async(e,t)=>{let n=await e.run(t.cmd,t.args,bd(t.cwd));if(n.exitCode===0)return n;let r=n.stderr.trim()||n.stdout.trim()||`exit code ${n.exitCode}`;throw y(`${t.action} failed: ${r}`)},Cd=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await Sd(e,xd(`git clone`,n));return await Sd(e,xd(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&yd.test(r.stderr)?{effectiveMode:`full`,warning:`server did not honour the partial-clone filter (blob:none); fell back to a full clone`}:{effectiveMode:t.mode}},wd=async(e,t)=>{let n=await e.run(`git`,[`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],{cwd:t});if(n.exitCode!==0)return;let r=n.stdout.trim();return r.startsWith(`origin/`)?r.slice(7):r},Td=async(e,t)=>{let n=await wd(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await wd(e,t);if(r!==void 0)return r;throw y(`could not detect the default branch for checkout: ${t}`)},Ed=async(e,t)=>(await Sd(e,xd(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),Dd=async(e,t)=>(await Sd(e,xd(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,Od=async(e,t)=>{await Sd(e,xd(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await Td(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${fd(n)}`),i},kd=e=>[xd(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),xd(`git clean -fd`,[`clean`,`-fd`],e)],Ad=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...kd(r)),a.push(xd(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),xd(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await Sd(e,t)},jd=async(e,t)=>{await vd(e,t.dir);let n=await Ed(e,t.dir),r=await Od(e,t),i=await Dd(e,t.dir);await Ad(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await Ed(e,t.dir);return hd(gd(r,i,{newSha:a,oldSha:n}))},Md=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,Nd=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
326
+ `),Pd=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=m(e.hooksDir,n);await $l(r,Nd),await t(r,493)}))},Fd=async(e,t,n)=>{let r=await Sd(e,xd(`git tag`,[`tag`,`--sort=-version:refname`],t)),i=r.stdout.split(`
327
+ `).map(e=>e.trim()).filter(e=>e!==``),a=!r.stderr.includes(`refs: stdout exceeded`);return n===void 0?{complete:a,tags:i}:{complete:a&&i.length<=n,tags:i.slice(0,n)}},Id=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Ld=/\d+\.\d+\.\d+/gu,Rd=e=>ll.safeParse(e).success,zd=e=>{let t=e.match(Ld);return t!==null&&t.length>1},Bd=e=>{let t=Id.exec(e);if(!t||zd(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Rd(r))return r},Vd=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},Hd=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=Bd(r);e&&Vd(t,e,n)}return t},Ud=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Wd=e=>{let t=[...e.entries()],[n]=t;if(n===void 0)return null;let[r,i]=n;return t.slice(1).reduce(({format:e,data:t},[n,r])=>Ud(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Gd=e=>{let t=Hd(e);return Wd(t)},Kd=(e,t)=>e.replaceAll(`{version}`,()=>t),qd=async(e,t,n,r)=>{let i=Kd(n,r);if(!await Md(e,t,i))throw _(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Jd=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,U=e=>{let t=e.replace(Jd,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},Yd=/\.git$/u,Xd=e=>e.replace(Yd,``),Zd=e=>{let t=0,n=e.length;for(;t<n&&e.charAt(t)===`/`;)t+=1;for(;n>t&&e.charAt(n-1)===`/`;)--n;return e.slice(t,n)},Qd=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,$d=/^git\+/u,ef={"https:":`443`,"ssh:":`22`},tf=e=>e.split(`/`).some(e=>e===`.`||e===`..`),nf=e=>e.includes(`\\`),rf=e=>e.includes(`%`),af=e=>{let t=il.safeParse(e);if(!t.success)throw y(`not a supported git url: derived key '${U(e)}' is invalid`);return t.data},of=({host:e,port:t,protocol:n})=>{let r=ef[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},sf=e=>{let t=Xd(Zd(e.path));return af(`${of(e)}/${t}`)},cf=e=>{let t=decodeURIComponent(e).split(`/`).filter(e=>e!==``);if(t.length<2)throw y(`not a supported git url: file url path must have at least 2 segments`);let n=t.at(-2)??``,r=t.at(-1)??``;return af(`local/${n}/${r}`)},lf=(e,t)=>{try{return new URL(e)}catch{throw y(`not a supported git url: ${U(t)}`)}},uf=e=>{if(e.password!==``)throw y(`not a supported git url: credentials embedded in url`);if(e.protocol===`https:`&&e.username!==``)throw y(`not a supported git url: credentials embedded in https url`)},df=(e,t)=>{if(e.protocol===`file:`){if(!t)throw y(`not a supported git url: unsupported protocol ${e.protocol}`);return cf(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw y(`not a supported git url: unsupported protocol ${e.protocol}`);return uf(e),sf({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},ff=(e,t)=>{if(rf(e))throw y(`not a supported git url: percent-encoding not supported in ${U(t)}`);if(e.includes(`:`))throw y(`not a supported git url: ambiguous ':' in scp-style path ${U(t)}; use the ssh:// url form instead`);if(e.startsWith(`/`)||e.startsWith(`~`))throw y(`not a supported git url: ambiguous absolute/home-relative scp path in ${U(t)}; use the ssh:// url form instead`)},pf=(e,t)=>{let n=e.groups?.path??``;return ff(n,t),sf({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},mf=(e,t)=>{if(nf(e))throw y(`not a supported git url: backslash not allowed in ${U(t)}`)},hf=(e,t)=>{if(tf(e))throw y(`not a supported git url: path traversal segment in ${U(t)}`)},gf=(e,t,n)=>{if(e.protocol!==`file:`&&rf(t))throw y(`not a supported git url: percent-encoding not supported in ${U(n)}`)},_f=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace($d,``);mf(r,e),hf(r,e);let i=Qd.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:pf(i,e)};let a=lf(r,e);return gf(a,r,e),{cloneUrl:r,key:df(a,n)}},vf=`.git`,yf=e=>e.endsWith(vf)?e:`${e}${vf}`,bf=(e,t)=>`https://${e.toLowerCase()}/${Zd(t)}`,xf=(e,t)=>`git@${e.toLowerCase()}:${yf(Zd(t))}`,Sf=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw y(`not a supported git url: unsupported protocol ${e}`)},Cf=(e,t,n)=>{let r=ef[e.protocol];if(e.port!==``&&e.port!==r)throw y(`cannot apply git_transport=${t} to ${U(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},wf=(e,t)=>t===`https`?bf(e.hostname,e.pathname):xf(e.hostname,e.pathname),Tf=(e,t,n)=>{let r=_f(t).key;if(r!==n)throw y(`git_transport transform changed repo identity: '${U(e)}' → '${t}' (key '${n}' → '${r}')`);return t},Ef=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return Tf(t.cloneUrl,bf(n,r),t.originalKey)},Df=e=>{let t=lf(e.cloneUrl,e.cloneUrl);return Sf(t.protocol)===e.transport?e.cloneUrl:(Cf(t,e.transport,e.cloneUrl),Tf(e.cloneUrl,wf(t,e.transport),e.originalKey))},Of=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:_f(e).key,transport:t},r=Qd.exec(e);return r?.groups===void 0?Df(n):Ef(r,n)},kf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,Af=(e,t)=>{if(kf.test(t))return m(e,`lease-${t}`)},jf=async(e,t)=>{let n=Af(e,t);n!==void 0&&await(await o(n,`w`)).close()},Mf=async(e,t)=>{let n=Af(e,t);if(n===void 0)return`gone`;let r=new Date;try{await ee(n,r,r)}catch(e){if(R(e))return`gone`;throw e}return`renewed`},Nf=async(e,t)=>{let n=Af(e,t);if(n===void 0)return{state:`absent`};try{return{mtimeMs:(await p(n)).mtimeMs,state:`ok`}}catch(e){return{state:R(e)?`absent`:`unreadable`}}},Pf=`meta.json`,Ff=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},If=e=>{try{return process.kill(e,0),!0}catch(e){return Ff(e)!==`ESRCH`}},Lf=e=>{try{return JSON.parse(e)}catch{return}},Rf=async e=>{try{return await s(e,`utf8`)}catch{return}},zf=new Set([`ENOENT`,`ENOTDIR`]),Bf=async e=>{try{return{state:`read`,text:await s(e,`utf8`)}}catch(e){let t=Ff(e);return{state:t!==void 0&&zf.has(t)?`missing`:`unreadable`}}},Vf=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},Hf=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},Uf=e=>{if(!(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>2147483647))return e},Wf=e=>{if(typeof e!=`object`||!e)return;let t=e,n=Uf(t.pid),r=Vf(t.acquired_at);if(n===void 0||r===void 0)return;let i=Hf(e);return{acquiredAtMs:r,pid:n,...i===void 0?{}:{token:i}}},Gf=async e=>{let t=await Rf(m(e,Pf));if(t!==void 0)return Hf(Lf(t))},Kf=async e=>{let t=await Bf(m(e,Pf));if(t.state!==`read`)return{state:t.state};let n=Wf(Lf(t.text));return n===void 0?{state:`malformed`}:{meta:n,state:`valid`}},qf=async e=>{try{return{mtimeMs:(await p(e)).mtimeMs,state:`ok`}}catch(e){return{state:Ff(e)===`ENOENT`?`gone`:`unreadable`}}},Jf=async(e,t)=>{let n=m(e,Pf),r=`${n}.tmp-${de()}`;await te(r,t,`utf8`),await u(r,n)},Yf=()=>de(),Xf=async(e,t)=>{await jf(e,t),await Jf(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Zf=5e3,Qf=async(e,t,n)=>{if(t===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let r=await qf(e);if(r.state===`gone`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`none`,stale:!1};if(r.state===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let i=n-r.mtimeMs;return{ageMs:i,budgetMs:Zf,meta:t,observedAtMs:n,pidState:`unknown`,policy:`grace`,stale:i>Zf}},$f=async(e,t,n)=>{let r=t.token===void 0?{state:`absent`}:await Nf(e,t.token);return r.state===`unreadable`?{policy:`unknown`}:r.state===`absent`?{ageMs:n-t.acquiredAtMs,budgetMs:6e5,policy:`legacy`}:{ageMs:n-r.mtimeMs,budgetMs:12e4,policy:`lease`}},ep=async(e,t)=>{let n=await Kf(e);if(n.state!==`valid`)return Qf(e,n.state,t);let{meta:r}=n,i=await $f(e,r,t),a=!If(r.pid),o=i.ageMs!==void 0&&i.budgetMs!==void 0&&i.ageMs>i.budgetMs;return{...i,meta:`valid`,observedAtMs:t,pid:r.pid,pidState:a?`definitely-dead`:`present-or-unknown`,stale:a||o,...r.token===void 0?{}:{token:r.token}}},tp=e=>e.meta===`valid`&&e.pidState===`definitely-dead`&&e.token!==void 0,np=async(e,t)=>await Gf(e)===t?await Mf(e,t)===`gone`?`lost`:`renewed`:`lost`,rp=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),ip=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),ap=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=Ff(e);if(t!==void 0&&rp.has(t))return!1;throw e}},op=async(e,t)=>{try{return await u(e,t),!0}catch(e){let t=Ff(e);if(t!==void 0&&ip.has(t))return!1;throw e}},sp=`.claims`,cp=`.tombstones`,lp=(e,t)=>({lockPath:m(e,t),locksDir:e,name:t}),up=e=>m(e.locksDir,sp,e.name),dp=e=>m(e.locksDir,cp,de()),fp=async e=>{await a(m(e,sp),{recursive:!0}),await a(m(e,cp),{recursive:!0})},pp=e=>ap(e),mp=async e=>{try{await f(e)}catch{}},hp=async e=>{let t=dp(e);return await op(e.lockPath,t)?t:void 0},gp=async e=>{let t=await ep(e.lockPath,Date.now());if(!tp(t)||await Gf(e.lockPath)!==t.token)return!1;let n=await hp(e);return n!==void 0&&(await d(n,{force:!0,recursive:!0}),!0)},_p=async e=>{await fp(e.locksDir);let t=up(e);if(!await pp(t))return!1;let n=await gp(e).then(e=>({ok:!0,stolen:e}),e=>({error:e,ok:!1}));if(await mp(t),!n.ok)throw n.error;return n.stolen},vp=async e=>{try{return(await c(e,{withFileTypes:!0})).map(e=>({isDir:e.isDirectory(),name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}catch(e){if(R(e))return[];throw e}},yp=async e=>(await vp(e)).filter(e=>!e.name.startsWith(`.`)),bp=async(e,t,n)=>{let r=await ep(m(e,t.name),n);if(r.policy!==`none`)return{diagnosis:r,isDirectory:t.isDir,kind:`lock`,name:t.name}},xp=async(e,t)=>{let n=m(e,sp),r=await vp(n);return(await Promise.all(r.map(async e=>({diagnosis:await ep(m(n,e.name),t),isDirectory:e.isDir,kind:`claim`,name:e.name})))).filter(e=>e.diagnosis.policy!==`none`)},Sp=async e=>{let t=Date.now(),n=await yp(e.locksDir),[r,i]=await Promise.all([Promise.all(n.map(n=>bp(e.locksDir,n,t))),xp(e.locksDir,t)]);return[...r.filter(e=>e!==void 0),...i]},Cp=e=>{let t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60),i=r%60,a=Math.floor(r/60);return a>0?i===0?`${a}h`:`${a}h ${i}m`:r>0?n===0?`${r}m`:`${r}m ${n}s`:`${n}s`},wp=e=>e.pid===void 0?`owner unknown (metadata ${e.meta})`:e.pidState===`definitely-dead`?`recorded pid ${e.pid} is not running`:`recorded pid ${e.pid} is present (identity not verified)`,Tp={grace:`created`,lease:`lease renewed`,legacy:`acquired`,none:`observed`,unknown:`observed`},Ep={grace:`from creation, while its metadata has not been published`,lease:`from the last renewal`,legacy:`from acquisition (no renewable lease)`,none:``,unknown:``},Dp=e=>{let{ageMs:t,budgetMs:n,policy:r}=e;return t===void 0||n===void 0?``:t<0?`, but its recorded time is in the future — check the system clock`:`, ${Tp[r]} ${Cp(t)} ago; its window is ${Cp(n)} ${Ep[r]}`},Op=(e,t)=>{if(t.policy===`none`)return`lock ${e} could not be acquired before the timeout, but it was released while the failure was being diagnosed. Retry the operation.`;let n=`lock ${e} is held: ${wp(t)}`;return tp(t)?`${n}, and refs is entitled to reclaim it — it could not do so before the timeout. Retry; if it persists, run refs doctor.`:t.stale?`${n}${Dp(t)}. refs does not reclaim this automatically: only a recorded process the operating system reports as gone is reclaimed, and this one is not. Run refs doctor for what to do about it.`:`${n}${Dp(t)}. Retry once the other refs command finishes.`},kp=(e,t)=>{if(t.stopped)return;let n=setTimeout(()=>{t.stopped||(t.inFlight=Ap(e,t))},e.intervalMs);n.unref(),t.timer=n},Ap=async(e,t)=>{try{if(await e.renew()===`lost`){t.lost=!0,t.stopped=!0;return}}catch{}kp(e,t)},jp=e=>{let t={inFlight:Promise.resolve(),lost:!1,stopped:!1};return kp(e,t),{ownershipLost:()=>t.lost,stop:async()=>{t.stopped=!0,t.timer!==void 0&&clearTimeout(t.timer),await t.inFlight}}},Mp=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,Np=async(e,t)=>{try{await Xf(e,t)}catch(e){if(Ff(e)===`ENOENT`)return`retry`;throw e}return t},Pp=async(e,t)=>{if(!await ap(e))return;let n=await Np(e,Yf());return n===`retry`?Date.now()>=t?void 0:Pp(e,t):n},Fp=async(e,t)=>{if(!await _p(e)){if(Date.now()>=t){let t=await ep(e.lockPath,Date.now());throw Ce(Op(e.name,t))}await ge(100)}},Ip=async(e,t)=>{let n=await Pp(e.lockPath,t);return n===void 0?(await Fp(e,t),Ip(e,t)):n},Lp=async(e,t)=>await Gf(e)===t&&(await d(e,{force:!0,recursive:!0}),!0),Rp=async e=>{try{return{ok:!0,value:await e()}}catch(e){return{error:e,ok:!1}}},zp=async(e,t,n,r)=>{await n.stop();let i=await Rp(()=>Lp(e.lockPath,t));if(!r.ok)throw r.error;if(!i.ok)throw i.error;if(n.ownershipLost()||!i.value)throw Ce(`lock ${e.name} was lost while the operation was running`);return r.value},Bp=e=>e!==`.`&&e!==`..`&&Mp.test(e),Vp=e=>{if(!Bp(e))throw y(`lock name must not contain "/" or other unsafe characters — only letters, digits, and "_.-" are allowed, and it may not be "." or "..": ${e}`)},W=async(e,t,n,r)=>{Vp(t);let i=lp(e.locksDir,t);await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await Ip(i,o),c=jp({intervalMs:3e4,renew:()=>np(i.lockPath,s)});return zp(i,s,c,await Rp(n))},Hp=sc({directory:P().optional(),url:P().optional()}),Up=sc({repository:lc([P(),Hp]).optional()}),Wp=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,Gp=new Set([`node_modules`,`favicon.ico`]),Kp=e=>_(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),qp=e=>{let[t,n]=e.split(`/`);return n??t??e},Jp=e=>{if(e.length>214)throw v(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!Wp.test(e))throw v(`invalid package name: '${e}' does not match npm naming rules`);let t=qp(e);if(Gp.has(t))throw v(`invalid package name: '${e}' uses a reserved name`)},Yp=e=>e.replaceAll(`/`,`%2F`),Xp=e=>typeof e==`string`?e:e?.url,Zp=e=>{if(typeof e==`object`&&e?.directory){let t=ul.safeParse(e.directory);if(t.success)return t.data}},Qp=async(e,t)=>{try{return await e.json()}catch{throw y(`invalid npm registry response for '${t}': not parseable JSON`)}},$p=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${Yp(t)}`);if(n.status===404)throw _(`npm package '${t}' not found`);if(n.status!==200)throw y(`failed to fetch npm package '${t}': status ${n.status}`);let r=await Qp(n,t),i=Up.safeParse(r);if(!i.success)throw y(`invalid npm package response for '${t}'`);return i.data},em=(e,t)=>{try{return _f(e)}catch{throw Kp(t)}},tm=async(e,t)=>{Jp(t);let n=await $p(e,t),r=Xp(n.repository);if(r===void 0||r===``)throw Kp(t);let{cloneUrl:i,key:a}=em(r,t),o=Zp(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},nm=(e,t,n)=>{let r=e instanceof RegExp?rm(e,n):e,i=t instanceof RegExp?rm(t,n):t,a=r!==null&&i!=null&&im(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},rm=(e,t)=>{let n=t.match(e);return n?n[0]:null},im=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},am=`\0SLASH`+Math.random()+`\0`,om=`\0OPEN`+Math.random()+`\0`,sm=`\0CLOSE`+Math.random()+`\0`,cm=`\0COMMA`+Math.random()+`\0`,lm=`\0PERIOD`+Math.random()+`\0`,um=new RegExp(am,`g`),dm=new RegExp(om,`g`),fm=new RegExp(sm,`g`),pm=new RegExp(cm,`g`),mm=new RegExp(lm,`g`),hm=/\\\\/g,gm=/\\{/g,_m=/\\}/g,vm=/\\,/g,ym=/\\\./g;function bm(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function xm(e){return e.replace(hm,am).replace(gm,om).replace(_m,sm).replace(vm,cm).replace(ym,lm)}function Sm(e){return e.replace(um,`\\`).replace(dm,`{`).replace(fm,`}`).replace(pm,`,`).replace(mm,`.`)}function Cm(e){if(!e)return[``];let t=[],n=nm(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=Cm(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function wm(e,t={}){if(!e)return[];let{max:n=1e5,maxLength:r=4e6}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),jm(xm(e),n,r,!0).map(Sm)}function Tm(e){return`{`+e+`}`}function Em(e){return/^-?0\d/.test(e)}function Dm(e,t){return e<=t}function Om(e,t){return e>=t}function km(e,t,n,r,i,a){let o=[],s=0;for(let c=0;c<e.length;c++)for(let l=0;l<n.length;l++){if(o.length>=r)return o;let u=e[c]+t+n[l];if(!a||u){if(s+u.length>i)return o;o.push(u),s+=u.length}}return o}function Am(e,t,n,r){let i=e.split(/\.\./),a=[];if(i[0]===void 0||i[1]===void 0)return a;let o=bm(i[0]),s=bm(i[1]),c=Math.max(i[0].length,i[1].length),l=i.length===3&&i[2]!==void 0?Math.max(Math.abs(bm(i[2])),1):1,u=Dm;s<o&&(l*=-1,u=Om);let d=i.some(Em),f=0;for(let e=o;u(e,s)&&a.length<n;e+=l){let n;if(t)n=String.fromCharCode(e),n===`\\`&&(n=``);else if(n=String(e),d){let t=c-n.length;if(t>0){let r=Array(t+1).join(`0`);n=e<0?`-`+r+n.slice(1):r+n}}if(f+n.length>r)break;a.push(n),f+=n.length}return a}function jm(e,t,n,r){let i=[``],a=!1,o=!0;for(;;){let s=nm(`{`,`}`,e);if(!s)return km(i,e,[``],t,n,a);let c=s.pre;if(/\$$/.test(c)){if(i=km(i,c+`{`+s.body+`}`,[``],t,n,a&&!s.post.length),o=!1,!s.post.length)break;e=s.post;continue}let l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),d=l||u,f=s.body.indexOf(`,`)>=0;if(!d&&!f){if(s.post.match(/,(?!,).*\}/)){e=s.pre+`{`+s.body+sm+s.post,r=!0;continue}return km(i,c+`{`+s.body+`}`+s.post,[``],t,n,a)}o&&=(a=r&&!d,!1);let p;if(d)p=Am(s.body,u,t,n);else{let r=Cm(s.body);if(r.length===1&&r[0]!==void 0&&(r=jm(r[0],t,n,!1).map(Tm),r.length===1)){if(i=km(i,c+r[0],[``],t,n,a&&!s.post.length),!s.post.length)break;e=s.post;continue}let o=a&&!s.post.length&&!c;for(let e=0;o&&e<i.length;e++)i[e]&&(o=!1);p=[];let l=0;outer:for(let e=0;e<r.length;e++){let i=jm(r[e],t,n,!1);for(let e=0;e<i.length;e++){let r=i[e];if(!o||r){if(p.length>=t||l+r.length>n)break outer;p.push(r),l+=r.length}}}}if(i=km(i,c,p,t,n,a&&!s.post.length),!s.post.length)break;e=s.post}return i}const Mm=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},Nm={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},Pm=e=>e.replace(/[[\]\\-]/g,`\\$&`),Fm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Im=e=>e.join(``),Lm=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(Nm))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue WHILE}}if(c=!1,d){t>d?r.push(Pm(d)+`-`+Pm(t)):t===d&&r.push(Pm(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(Pm(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(Pm(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l){let e=r[0].length===2?r[0].slice(-1):r[0];return[Fm(e),!1,u-n,!1]}let f=`[`+(l?`^`:``)+Im(r)+`]`,p=`[`+(l?``:`^`)+Im(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},Rm=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var G;const zm=new Set([`!`,`?`,`+`,`*`,`@`]),Bm=e=>zm.has(e),Vm=e=>Bm(e.type),Hm=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),Um=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),Wm=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),Gm=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),Km=`(?!\\.)`,qm=new Set([`[`,`.`]),Jm=new Set([`..`,`.`]),Ym=new Set(`().*{}+?[]^$\\!`),Xm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Zm=`[^/]+?`;let Qm=0;var $m=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++Qm;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.#l=this.type?this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==``){if(typeof t!=`string`&&!(t instanceof G&&t.#i===this))throw Error(`invalid part: `+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;t<this.#a;t++){let n=e.#r[t];if(!(n instanceof G&&n.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(e){let t=new G(this.type,e);for(let e of this.#r)t.copyIn(e);return t}static#f(e,t,n,r,i){let a=r.maxExtglobRecursion??2,o=!1,s=!1,c=-1,l=!1;if(t.type===null){let u=n,d=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,d+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),d+=n;continue}if(n===`[`){s=!0,c=u,l=!1,d+=n;continue}if(!r.noext&&Bm(n)&&e.charAt(u)===`(`&&i<=a){t.push(d),d=``;let a=new G(n,t);u=G.#f(e,a,u,r,i+1),t.push(a);continue}d+=n}return t.push(d),u}let u=n+1,d=new G(null,t),f=[],p=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,p+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),p+=n;continue}if(n===`[`){s=!0,c=u,l=!1,p+=n;continue}if(!r.noext&&Bm(n)&&e.charAt(u)===`(`&&(i<=a||t&&t.#h(n))){let a=t&&t.#h(n)?0:1;d.push(p),p=``;let o=new G(n,d);d.push(o),u=G.#f(e,o,u,r,i+a);continue}if(n===`|`){d.push(p),p=``,f.push(d),d=new G(null,t);continue}if(n===`)`)return p===``&&t.#r.length===0&&(t.#u=!0),d.push(p),p=``,t.push(...f,d),u;p+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],u}#p(e){return this.#m(e,Um)}#m(e,t=Hm){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null)return!1;let n=e.#r[0];return!n||typeof n!=`object`||n.type===null?!1:this.#h(n.type,t)}#h(e,t=Wm){return!!t.get(this.type)?.includes(e)}#g(e,t){let n=e.#r[0],r=new G(null,n,this.options);r.#r.push(``),n.push(r),this.#_(e,t)}#_(e,t){let n=e.#r[0];this.#r.splice(t,1,...n.#r);for(let e of n.#r)typeof e==`object`&&(e.#i=this);this.#l=void 0}#v(e){return!!Gm.get(this.type)?.has(e)}#y(e){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let t=e.#r[0];return!t||typeof t!=`object`||t.type===null?!1:this.#v(t.type)}#b(e){let t=Gm.get(this.type),n=e.#r[0],r=t?.get(n.type);if(!r)return!1;this.#r=n.#r;for(let e of this.#r)typeof e==`object`&&(e.#i=this);this.type=r,this.#l=void 0,this.#u=!1}static fromGlob(e,t={}){let n=new G(null,void 0,t);return G.#f(e,n,0,t,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(e){let t=e??!!this.#c.dot;if(this.#e===this&&(this.#x(),this.#d()),!Vm(this)){let n=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?G.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&Jm.has(this.#r[0]))){let n=qm,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?Km:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,Rm(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,Rm(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?Km:``)+Zm;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?Km:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,Rm(i),this.#t=!!this.#t,this.#n]}#x(){if(Vm(this)){let e=0,t=!1;do{t=!0;for(let e=0;e<this.#r.length;e++){let n=this.#r[e];typeof n==`object`&&(n.#x(),this.#m(n)?(t=!1,this.#_(n,e)):this.#p(n)?(t=!1,this.#g(n,e)):this.#y(n)&&(t=!1,this.#b(n)))}}while(!t&&++e<10)}else for(let e of this.#r)typeof e==`object`&&e.#x();this.#l=void 0}#S(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(Ym.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?Zm:`[^/]*?`,t=!0;continue}if(o=!1,c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=Lm(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=`[^/]`,t=!0;continue}i+=Xm(c)}return[i,Rm(e),!!t,a]}};G=$m;const eh=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),K=(e,t,n={})=>(Mm(t),!n.nocomment&&t.charAt(0)===`#`?!1:new Eh(t,n).match(e)),th=/^\*+([^+@!?*[(]*)$/,nh=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),rh=e=>t=>t.endsWith(e),ih=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),ah=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),oh=/^\*+\.\*+$/,sh=e=>!e.startsWith(`.`)&&e.includes(`.`),ch=e=>e!==`.`&&e!==`..`&&e.includes(`.`),lh=/^\.\*+$/,uh=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),dh=/^\*+$/,fh=e=>e.length!==0&&!e.startsWith(`.`),ph=e=>e.length!==0&&e!==`.`&&e!==`..`,mh=/^\?+([^+@!?*[(]*)?$/,hh=([e,t=``])=>{let n=yh([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},gh=([e,t=``])=>{let n=bh([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},_h=([e,t=``])=>{let n=bh([e]);return t?e=>n(e)&&e.endsWith(t):n},vh=([e,t=``])=>{let n=yh([e]);return t?e=>n(e)&&e.endsWith(t):n},yh=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},bh=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},xh=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,Sh={win32:{sep:`\\`},posix:{sep:`/`}};K.sep=xh===`win32`?Sh.win32.sep:Sh.posix.sep;const q=Symbol(`globstar **`);K.GLOBSTAR=q,K.filter=(e,t={})=>n=>K(n,e,t);const J=(e,t={})=>Object.assign({},e,t);K.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return K;let t=K;return Object.assign((n,r,i={})=>t(n,r,J(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,J(e,n))}static defaults(n){return t.defaults(J(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,J(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,J(e,r))}},unescape:(n,r={})=>t.unescape(n,J(e,r)),escape:(n,r={})=>t.escape(n,J(e,r)),filter:(n,r={})=>t.filter(n,J(e,r)),defaults:n=>t.defaults(J(e,n)),makeRe:(n,r={})=>t.makeRe(n,J(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,J(e,r)),match:(n,r,i={})=>t.match(n,r,J(e,i)),sep:t.sep,GLOBSTAR:q})};const Ch=(e,t={})=>(Mm(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:wm(e,{max:t.braceExpandMax}));K.braceExpand=Ch,K.makeRe=(e,t={})=>new Eh(e,t).makeRe(),K.match=(e,t,n={})=>{let r=new Eh(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const wh=/[?*]|[+@!]\(.*?\)|\[|\]/,Th=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var Eh=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){Mm(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||xh,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!wh.test(e[2]))&&!wh.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t of e)for(let e=0;e<t.length;e++)t[e]===`**`&&(t[e]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];(n!==1||r!==``||e[0]!==``)&&(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&!(this.isWindows&&/^[a-z]:$/i.test(r))&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];(e!==1||r!==``||n[0]!==``)&&(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=0,i=0;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),a=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),o=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),s=!o&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),c=a?3:n?0:void 0,l=s?3:o?0:void 0;if(typeof c==`number`&&typeof l==`number`){let[n,a]=[e[c],t[l]];n.toLowerCase()===a.toLowerCase()&&(t[l]=n,i=l,r=c)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(q)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(q,i),o=t.lastIndexOf(q),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n<e.length-u;n++){let r=String(e[n]);if(t=!0,r===`.`||r===`..`||!this.options.dot&&r.startsWith(`.`))return!1}return n||t}let d=[[[],0]],f=d[0],p=0,ee=[0];for(let e of c)e===q?(ee.push(p),f=[[],0],d.push(f)):(f[0].push(e),p++);let te=d.length-1,ne=e.length-u;for(let e of d)e[1]=ne-(ee[te--]+e[0].length);return!!this.#t(e,d,r,0,n,0,!!u)}#t(e,t,n,r,i,a,o){let s=t[r];if(!s){for(let t=n;t<e.length;t++){o=!0;let n=e[t];if(n===`.`||n===`..`||!this.options.dot&&n.startsWith(`.`))return!1}return o}let[c,l]=s;for(;n<=l;){if(this.#n(e.slice(0,n+c.length),c,i,n,0)&&a<this.maxGlobstarRecursion){let s=this.#t(e,t,n+c.length,r+1,i,a+1,o);if(s!==!1)return s}let s=e[n];if(s===`.`||s===`..`||!this.options.dot&&s.startsWith(`.`))return!1;n++}return i||null}#n(e,t,n,r,i){let a,o,s,c;for(a=r,o=i,c=e.length,s=t.length;a<c&&o<s;a++,o++){this.debug(`matchOne loop`);let n=t[o],r=e[a];if(this.debug(t,n,r),n===!1||n===q)return!1;let i;if(typeof n==`string`?(i=r===n,this.debug(`string match`,n,r,i)):(i=n.test(r),this.debug(`pattern match`,n,r,i)),!i)return!1}if(a===c&&o===s)return!0;if(a===c)return n;if(o===s)return a===c-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return Ch(this.pattern,this.options)}parse(e){Mm(e);let t=this.options;if(e===`**`)return q;if(e===``)return``;let n,r=null;(n=e.match(dh))?r=t.dot?ph:fh:(n=e.match(th))?r=(t.nocase?t.dot?ah:ih:t.dot?rh:nh)(n[1]):(n=e.match(mh))?r=(t.nocase?t.dot?gh:hh:t.dot?_h:vh)(n):(n=e.match(oh))?r=t.dot?ch:sh:(n=e.match(lh))&&(r=uh);let i=$m.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?`[^/]*?`:t.dot?`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`:`(?:(?!(?:\\/|^)\\.).)*?`,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?Th(e):e===q?q:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e===q&&a!==q&&(a===void 0?i!==void 0&&i!==q?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==q&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=q))});let i=t.filter(e=>e!==q);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return K.defaults(e).Minimatch}};K.AST=$m,K.Minimatch=Eh,K.escape=eh,K.unescape=Rm;const Dh=/[/\\]/u,Oh={kind:`ignore`},kh=e=>!ae(e)&&e.split(Dh).every(e=>e!==`.`&&e!==`..`),Ah=/^!+/u,jh=/^\.?\/+/u,Mh=e=>{let t=Ah.exec(e)?.[0]??``;return{body:e.slice(t.length).replace(jh,``),negated:t.length%2==1}},Nh=e=>Mh(e).negated,Ph=e=>Mh(e).body,Fh=/[?[\]{}()]/u,Ih=e=>kh(e)&&!Nh(e)&&!Fh.test(e),Lh=(e,t)=>K(e,t),Rh=e=>e.replaceAll(/\/+/gu,`/`).replace(/\/$/u,``),zh=e=>{let t=Rh(e).split(`/`),n=t.findIndex(e=>e.includes(`*`));return n===-1?Oh:{baseDir:n===0?`.`:t.slice(0,n).join(`/`),kind:`expand-children`,pattern:Rh(e),suffix:t.slice(n+1).join(`/`)}},Bh=e=>{let t=Rh(e).split(`/`).filter(e=>e.includes(`*`));return t.length<=1&&!t.includes(`**`)},Vh=e=>{let t=Rh(e).split(`/`),n=t.findIndex(e=>e.includes(`*`));return n<=0?`.`:t.slice(0,n).join(`/`)},Hh=e=>Ih(e)?e.includes(`*`)?Bh(e)?zh(e):{baseDir:Vh(e),kind:`expand-recursive`,pattern:Rh(e)}:{dir:e,kind:`probe-dir`,pattern:e}:Oh,Uh=new Set([`candidate_not_inspected`,`scan_budget_exhausted`,`manifest_unreadable`,`unsupported_pattern`,`workspace_declaration_unparsed`,`workspace_dir_unreadable`,`workspace_file_unreadable`]),Wh=(e,t)=>t?.name?{name:t.name,path:e}:void 0,Gh=e=>{let t=e.map(e=>[e.path,e]),n=[...new Map(t).values()];return n.sort((e,t)=>e.path.localeCompare(t.path)),n},Kh=e=>!e.diagnostics.some(e=>Uh.has(e.kind)),qh=e=>!e.diagnostics.some(e=>e.kind===`no_workspace_declaration`),Jh=(e,t)=>e<t?-1:+(e>t),Yh=e=>`path`in e?`${e.kind} ${e.path}`:`file`in e?`${e.kind} ${e.file}`:`pattern`in e?`${e.kind} ${e.pattern}`:e.kind,Xh=e=>e.toSorted((e,t)=>Jh(Yh(e),Yh(t))),Zh=e=>!ae(e)&&!e.split(/[/\\]/u).includes(`..`),Qh=(e,t)=>e.kind===`missing`?{kind:`absent`}:e.kind===`outside`?{kind:`unreadable`,reason:`${t} escapes the checkout`}:{kind:`unreadable`,reason:e.code},$h=async(e,t,n)=>{if(!Zh(t))return{kind:`unreadable`,reason:`path escapes the checkout`};let r=await eg(e,t);if(`probe`in r)return r.probe;let i=await tg(r.real);return`reason`in i?{kind:`unreadable`,reason:i.reason}:i.found===n?{kind:`match`}:{found:i.found,kind:`mismatch`}},eg=async(e,t)=>{let n=await Ou(e,m(e,t));if(n.kind!==`inside`)return{probe:Qh(n,`path`)};let r=await Ou(e,m(n.real,`package.json`));return r.kind===`inside`?{real:r.real}:{probe:Qh(r,`manifest`)}},tg=async e=>{try{let t=JSON.parse(await s(e,`utf8`));return{found:Lu(t)}}catch(e){return{reason:e.code??String(e)}}},ng=(e,t)=>{let n=e.filter(e=>e.name===t).map(e=>e.path);return n.length===0?{kind:`absent`}:n.length===1?{kind:`found`,path:n[0]}:{kind:`ambiguous`,paths:n.toSorted(Jh)}},rg=new Set;let ig=!1;const ag=()=>{for(let e of rg)try{e.kill(`SIGKILL`)}catch{}},og=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],sg=e=>{let t=()=>{ag(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},cg=()=>{ig||(ig=!0,og.forEach(e=>{sg(e)}),process.on(`exit`,ag))},lg=()=>{let e=[],t=0,n=!1;return{finish:()=>({text:Buffer.concat(e).toString(`utf8`),truncated:n}),push:r=>{if(n)return;let i=67108864-t;if(r.length<=i){e.push(r),t+=r.length;return}i>0&&e.push(r.subarray(0,i)),n=!0}}},ug=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
328
+ `),dg=(e,t,n)=>{let r=e;return t.truncated&&(r=ug(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=ug(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},fg={clear:()=>{},markedTimedOut:()=>!1},pg=(e,t)=>{if(t===void 0)return fg;let n=!1,r,i=setTimeout(()=>{n=!0,e.kill(`SIGTERM`),r=setTimeout(()=>{e.kill(`SIGKILL`)},2e3)},t);return{clear:()=>{clearTimeout(i),r!==void 0&&clearTimeout(r)},markedTimedOut:()=>n}},mg=e=>e===void 0?{}:{cwd:e},hg=(e,t)=>ug(e,`refs: command timed out after ${String(t)}ms`),gg=(e,t)=>({exitCode:124,stderr:hg(e,t),stdout:``,timedOut:!0}),_g=(e,t,n)=>{let r=be(e,t,{...mg(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});rg.add(r);let i=lg(),a=lg();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:pg(r,n?.timeoutMs)}},vg=(e,t,n)=>{try{return _g(e,t,n)}catch(e){return{exitCode:127,stderr:bg(e),stdout:``}}},yg=e=>!(`child`in e),bg=e=>e instanceof Error?e.message:String(e),xg=async e=>{try{let[t]=await ve(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:bg(e)}}},Sg=e=>e===null?1:e,Cg=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,wg=e=>e.timedOut?gg(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?Cg({exitCode:Sg(e.code),stderr:dg(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):Cg({exitCode:127,stderr:ug(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var Tg=class{async run(e,t,n){cg();let r=vg(e,t,n);if(yg(r))return r;let i=await xg(r.child);return rg.delete(r.child),r.timeout.clear(),wg({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Eg=hl.partial({description:!0}),Dg=I({default_branch:P().min(1),key:il,tag_format_candidate:ll.nullable(),url:P().min(1)});Dg.extend({description:P().default(``),packages:Gc(Eg)});const Og=Dg.extend({description:P().min(1),packages:Gc(hl)}),kg=I({effective_clone_mode:sl.optional(),head_sha:P().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:P().optional(),last_fetched_at:Vc().optional(),pending_proposal_at:Vc().optional()}),Ag=I({refs:Uc(e=>e.length>0&&!Hc.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,pc(P(),kg)).default({})}),jg=(e,t,n)=>t?.[e]??n[e],Mg=async e=>{try{return await s(e.statePath,`utf8`)}catch(e){if(R(e))return;throw e}},Ng=e=>{try{return JSON.parse(e)}catch{return}},Pg=async e=>{let t=await Mg(e);if(t===void 0)return Ag.parse({});let n=Ng(t);if(n===void 0)return Ag.parse({});let r=Ag.safeParse(n);return r.success?r.data:Ag.parse({})},Fg=async(e,t)=>{let n=Ag.safeParse(t);if(!n.success)throw y(T(n.error));await $l(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},Ig=/^\d+\.\d+\.\d+$/u,Lg=/^0+(?=\d)/u,Rg=(e,t)=>{let n=e.replace(Lg,``),r=t.replace(Lg,``);return n.length===r.length?n===r?0:n<r?-1:1:n.length<r.length?-1:1},zg=(e,t)=>{if(!Ig.test(e)||!Ig.test(t))return;let n=e.split(`.`),r=t.split(`.`);return n.map((e,t)=>Rg(e,r[t]??``)).find(e=>e!==0)??0},Bg=sc({version:P().regex(Ig)}),Vg=I({checked_at:Vc(),latest_version:P().regex(Ig)}),Hg=async e=>{try{let t=Vg.safeParse(JSON.parse(await s(e.updateCachePath,`utf8`)));return t.success?t.data:void 0}catch{return}},Ug=async(e,t)=>{try{await p(e.root),await $l(e.updateCachePath,`${JSON.stringify(t,void 0,2)}\n`)}catch{}},Wg=(e,t)=>{let n=t-Date.parse(e.checked_at);return n>=0&&n<864e5},Gg=async e=>{try{let t=await e(`https://registry.npmjs.org/@kaisers-io%2Frefs/latest`,{signal:AbortSignal.timeout(2e3)});if(t.status!==200)return;let n=Bg.safeParse(await t.json());return n.success?n.data.version:void 0}catch{return}},Kg=async e=>{let t=await Hg(e.home);if(t!==void 0&&Wg(t,e.nowMs))return{latest:t.latest_version,refreshed:!1,stale:!1};let n=await Gg(e.fetch);return n===void 0?{latest:t?.latest_version,refreshed:!1,stale:!0}:(await Ug(e.home,{checked_at:new Date(e.nowMs).toISOString(),latest_version:n}),{latest:n,refreshed:!0,stale:!1})},qg=(e,t)=>{let n=zg(e,t);return n!==void 0&&n<0},Jg=(e,t)=>`refs ${t} is available (this is ${e}) — update: npm i -g @kaisers-io/refs@latest`,Yg=e=>{let t=e.REFS_UPDATE_CHECK?.trim();if(t===`0`)return!1;if(t===`1`)return!0},Xg=e=>{let t=e.CI?.trim().toLowerCase();return t!==void 0&&t!==``&&t!==`false`&&t!==`0`},Zg={check:!0,notify:!0},Qg=e=>{let t=Yg(e.env);return t===void 0?(e.updates??Zg).check?Xg(e.env)?`ci`:`on`:`config`:t?`on`:`env`},$g=e=>Qg(e)===`on`,e_=e=>$g(e)&&(e.updates??Zg).notify,t_=async(e,t)=>{let n=await Ou(e,m(t,`package.json`));if(n.kind===`inside`)try{let e=JSON.parse(await s(n.real,`utf8`));return{name:Lu(e)}}catch{return}},n_=async(e,t)=>{let n=await t_(e,m(e,t));if(n===void 0)return{diagnostic:{kind:`manifest_unreadable`,path:t}};let r=Wh(t,n);return r===void 0?{diagnostic:{kind:`manifest_missing_name`,path:t}}:{pkg:r}},r_=e=>{let t=[],n=[];for(let r of e)r.diagnostic!==void 0&&t.push(r.diagnostic),r.pkg!==void 0&&n.push(r.pkg);return{diagnostics:t,packages:n}},i_=new Set([`ENOENT`,`ENOTDIR`]),a_=async(e,t)=>{let n=await Ou(e,m(t,`package.json`));if(n.kind===`missing`)return`none`;if(n.kind!==`inside`)return`rejected`;try{return await s(n.real,`utf8`),`manifest`}catch{return`rejected`}},o_=async e=>{try{return{entries:await c(e,{withFileTypes:!0})}}catch(e){return{code:e.code??``}}},s_=e=>Promise.all(e.entries.map(t=>a_(e.repoDir,m(e.fullPath,t.name,e.suffix)))),c_=(e,t,n)=>e.filter((e,r)=>n(t[r])).map(e=>e.name),l_=async e=>{let{baseDir:t,dirs:n,fullPath:r,repoDir:i,suffix:a,symlinks:o}=e,s=e=>oe.join(t===`.`?``:t,e,a),[c,l]=await Promise.all([s_({entries:n,fullPath:r,repoDir:i,suffix:a}),s_({entries:o,fullPath:r,repoDir:i,suffix:a})]);return{diagnostics:[...c_(n,c,e=>e===`rejected`).map(e=>({kind:`manifest_unreadable`,path:s(e)})),...c_(o,l,e=>e!==`none`).map(e=>({kind:`candidate_not_inspected`,path:s(e)}))],dirs:c_(n,c,e=>e===`manifest`).map(e=>s(e))}},u_=async e=>{let t=await n_(e,`.`);return`pkg`in t?[t]:[]},d_=e=>{let t=e.find(e=>e.path===`.`);return t===void 0?[...e]:e.some(e=>e.path!==`.`&&e.name===t.name)?e.filter(e=>e!==t):[...e]},f_=async e=>{let[t]=await u_(e);return t!==void 0&&`pkg`in t?t.pkg:void 0},p_=`package.json`,m_=e=>{let t=Rh(e).split(`/`);return t.includes(`**`)?void 0:t.length},h_=e=>Rh(e).split(`/`).some(e=>e.startsWith(`.`)),g_=e=>e===`.`?0:e.split(`/`).length,__=e=>{let t=Rh(e),n=new Eh(`${t}/${p_}`),r=new Eh(t);return{couldHold:e=>r.match(e,!0),selects:e=>n.match(oe.join(e,p_))}},v_=e=>({...__(e),maxDepth:m_(e),selectsHidden:h_(e)}),y_=new Set([`ENOENT`,`ENOTDIR`]),b_=()=>({dirs:2e4,entries:2e5}),x_=new Set([`.git`,`node_modules`]),S_=(e,t)=>{e.diagnostics.push({kind:`scan_budget_exhausted`,path:t,pattern:e.pattern})},C_=async(e,t,n)=>{if(!e.selects(t)||n.has(t))return;let r=await a_(e.repoDir,m(e.repoDir,t));r===`manifest`&&e.dirs.push(t),r===`rejected`&&e.diagnostics.push({kind:`manifest_unreadable`,path:t})},w_=(e,t)=>!e.selectsHidden&&t.excluded.coversSubtree(t.relPath),T_=async(e,t,n)=>!e.couldHold(n.relPath)||x_.has(t.name)||w_(e,n)?!1:t.isSymbolicLink()?(w_(e,n)||await E_(e,n.relPath),!1):t.isDirectory(),E_=async(e,t)=>{let n=await Ou(e.repoDir,m(e.repoDir,t));if(n.kind===`outside`||n.kind===`missing`)return;if(n.kind===`unreadable`){e.diagnostics.push({kind:`candidate_not_inspected`,path:t});return}let r=await o_(n.real);(!(`code`in r)||!y_.has(r.code))&&e.diagnostics.push({kind:`candidate_not_inspected`,path:t})},D_=async(e,t)=>{let n=await o_(m(e.repoDir,t));if(`code`in n){i_.has(n.code)||e.diagnostics.push({kind:`workspace_dir_unreadable`,path:t});return}if(e.budget.entries-=n.entries.length,e.budget.entries<0){S_(e,t);return}return n.entries},O_=async(e,t,n)=>{if(e.budget.dirs<=0){S_(e,t.relPath);return}if(--e.budget.dirs,await C_(e,t.relPath,n),e.maxDepth!==void 0&&g_(t.relPath)>=e.maxDepth)return;let r=await D_(e,t.relPath);r!==void 0&&await A_(e,{depth:t.depth,entries:r,relPath:t.relPath},n)},k_=(e,t)=>oe.join(e===`.`?``:e,t),A_=async(e,t,n)=>{for(let r of t.entries){let i=k_(t.relPath,r.name);await T_(e,r,{excluded:n,relPath:i})&&(t.depth+1>32?S_(e,i):await O_(e,{depth:t.depth+1,relPath:i},n))}},j_=async(e,t)=>{let n=await Ou(e,m(e,t));if(n.kind!==`inside`)return n.kind===`missing`?{diagnostics:[],dirs:[]}:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}},M_=async(e,t,n)=>{let r=await j_(e,t.baseDir);if(r!==void 0)return r;let i={...v_(t.pattern),budget:n.budget,diagnostics:[],dirs:[],pattern:t.pattern,repoDir:e};return await O_(i,{depth:1,relPath:t.baseDir},n.excluded),{diagnostics:i.diagnostics,dirs:i.dirs}},N_=(e,t)=>oe.join(e.baseDir===`.`?``:e.baseDir,t,e.suffix),P_=(e,t)=>Lh(N_(t,e.name),t.pattern),F_=async(e,t)=>{let n=m(e,t),r=await Ou(e,n);if(r.kind===`missing`)return{result:{diagnostics:[],dirs:[]}};if(r.kind!==`inside`)return{result:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}};let i=await o_(n);return`code`in i?{result:i_.has(i.code)?{diagnostics:[],dirs:[]}:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}}:{entries:i.entries}},I_=async(e,t,n)=>{let{baseDir:r}=t,i=await F_(e,r);if(`result`in i)return i.result;let a=e=>P_(e,t)&&!n.has(N_(t,e.name)),o={entries:i.entries};return l_({baseDir:r,dirs:o.entries.filter(e=>e.isDirectory()&&a(e)),fullPath:m(e,r),repoDir:e,suffix:t.suffix,symlinks:o.entries.filter(e=>e.isSymbolicLink()&&a(e))})},L_=async(e,t)=>{let n=await a_(e,m(e,t));return n===`manifest`?{diagnostics:[],dirs:[Rh(t)]}:n===`rejected`?{diagnostics:[{kind:`manifest_unreadable`,path:t}],dirs:[]}:{diagnostics:[],dirs:[]}},R_=(e,t,n)=>{let{excluded:r}=n,i=Hh(t.body);return i.kind===`expand-children`?I_(e,i,r):i.kind===`expand-recursive`?M_(e,i,n):i.kind===`probe-dir`?r.has(Rh(i.dir))?Promise.resolve({diagnostics:[],dirs:[]}):L_(e,i.dir):Promise.resolve({diagnostics:[{kind:`unsupported_pattern`,pattern:t.declared}],dirs:[]})},z_=(e,t)=>Lh(Ph(e),Ph(t)),B_=e=>({negations:e.filter(e=>Nh(e)),patterns:e.filter(e=>!Nh(e))}),V_=e=>{let t=e.reduce((e,t)=>Nh(t)?{negations:[...e.negations,t],patterns:e.patterns}:{negations:e.negations.filter(e=>!z_(t,e)),patterns:[...e.patterns,t]},{negations:[],patterns:[]});return{negations:t.negations,patterns:t.patterns.filter(e=>!t.negations.some(t=>z_(e,t)))}},H_=e=>e.endsWith(`/`)?e:`${e}/`,U_=(e,t)=>e.some(e=>Lh(H_(t),H_(Ph(e)))),W_=(e,t)=>{let n=Ph(e);return n.endsWith(`/**`)&&Lh(t,n.slice(0,-3))},G_=e=>({coversSubtree:t=>e.some(e=>W_(e,t)),has:t=>U_(e,t)}),K_=e=>{let t=new Set,n=[];for(let r of e)r.dirs.forEach(e=>t.add(e)),n.push(...r.diagnostics);return{diagnostics:n,dirs:[...t]}},q_=async(e,t,n)=>{let{negations:r,patterns:i}=t,a=G_(r),o=K_(await Promise.all(i.map(t=>R_(e,{body:Ph(t),declared:t},{budget:n,excluded:a}))));return{diagnostics:o.diagnostics,dirs:o.dirs}},J_=async(e,t)=>{let n=V_(t.npm),r=B_(t.pnpm),i=b_(),a=await Promise.all([q_(e,n,i),q_(e,r,i)]);return K_(a)},Y_=async e=>{let t=await Wu(e);if(t.npm.length===0&&t.pnpm.length===0)return{diagnostics:Xh([...t.diagnostics,{kind:`no_workspace_declaration`}]),packages:[]};let n=await J_(e,t),[r,i]=await Promise.all([u_(e),Promise.all(n.dirs.map(t=>n_(e,t)))]),a=r_([...r,...i]);return{diagnostics:Xh([...t.diagnostics,...n.diagnostics,...a.diagnostics]),packages:d_(Gh(a.packages))}};var X_=`0.14.0`;const Z_=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},Q_=()=>{try{return he()}catch{return``}},$_=()=>({cliVersion:X_,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:(e,t)=>fetch(e,t),homedir:Q_(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:Z_,runner:new Tg});var ev=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},tv=class extends ev{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},nv=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new tv(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function rv(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var iv=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(e=>rv(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(t?` `+t:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
329
329
  `)}displayWidth(e){return xe(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
330
330
  `+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
331
- `)}},N_=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=I_(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new k_(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?F_(this.name().replace(/^no-/,``)):F_(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},P_=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function F_(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function I_(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
331
+ `)}},av=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=cv(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new tv(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?sv(this.name().replace(/^no-/,``)):sv(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ov=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function sv(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function cv(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
332
332
  - a short flag is a single dash and a single character
333
333
  - either use a single dash and a single character (for a short flag)
334
334
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
335
335
  - too many short flags`):i.test(t)?Error(`${n}
336
336
  - too many long flags`):Error(`${n}
337
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function L_(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function R_(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=L_(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var z_=class e extends _e{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>h.stdout.write(e),writeErr:e=>h.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,getOutHasColors:()=>V_()??(h.stdout.isTTY&&h.stdout.hasColors?.()),getErrHasColors:()=>V_()??(h.stderr.isTTY&&h.stderr.hasColors?.()),stripColor:e=>xe(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new M_,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
338
- - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new A_(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
339
- Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new O_(e,t,n)),h.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return r[n]=this._storeOptionsAsProperties?this:this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new N_(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
340
- - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof N_)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){h.versions?.electron&&(t.from=`electron`);let e=h.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=h.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:h.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
337
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function lv(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function uv(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=lv(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var dv=class e extends _e{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>h.stdout.write(e),writeErr:e=>h.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,getOutHasColors:()=>pv()??(h.stdout.isTTY&&h.stdout.hasColors?.()),getErrHasColors:()=>pv()??(h.stderr.isTTY&&h.stderr.hasColors?.()),stripColor:e=>xe(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new iv,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
338
+ - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new nv(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
339
+ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new ev(e,t,n)),h.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return r[n]=this._storeOptionsAsProperties?this:this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new av(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
340
+ - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof av)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){h.versions?.electron&&(t.from=`electron`);let e=h.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=h.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:h.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
341
341
  - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(fe.existsSync(e))return;let r=`'${e}' does not exist
342
342
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
343
343
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
344
- - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=ne.resolve(e,t);if(fe.existsSync(r))return r;if(n.includes(ne.extname(t)))return;let i=n.find(e=>fe.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||``;if(this._scriptPath){let e;try{e=fe.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=ne.resolve(ne.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=ne.basename(this._scriptPath,ne.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(ne.extname(i)),s;h.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=B_(h.execArgv).concat(t),s=ye.spawn(h.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=B_(h.execArgv).concat(t),s=ye.spawn(h.argv[0],t,{stdio:`inherit`})):s=ye.spawn(i,t,{stdio:`inherit`}),s.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{h.on(e,()=>{s.killed===!1&&s.exitCode===null&&s.kill(e)})});let c=this._exitCallback;s.on(`close`,e=>{e??=1,c?c(new O_(e,`commander.executeSubCommandAsync`,`(close)`)):h.exit(e)}),s.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(i,a,e._name);else if(t.code===`EACCES`)throw Error(`'${i}' not executable`);if(!c)h.exit(1);else{let e=new O_(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,c(e)}}),this.runningCommand=s}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
345
- `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in h.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,h.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new P_(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=R_(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=R_(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>j_(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=ne.basename(e,ne.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(h.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
346
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function B_(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function V_(){if(h.env.NO_COLOR||h.env.FORCE_COLOR===`0`||h.env.FORCE_COLOR===`false`)return!1;if(h.env.FORCE_COLOR||h.env.CLICOLOR_FORCE!==void 0)return!0}new z_;const H_=[],U_=e=>Array.isArray(e)?e:[e],W_=e=>e===void 0?H_:[e],G_=e=>e instanceof Error?e.message:String(e),X=e=>{let t=e.optsWithGlobals();return{json:t.json===!0,verbose:t.verbose===!0}},Z=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??H_};e.out(JSON.stringify(t));return}for(let t of U_(n))e.out(t);for(let t of i??H_)e.errLine(`refs: warning: ${t}`)},K_=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message,...n.reason===void 0?{}:{reason:n.reason}},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},q_=(e,t)=>{e.errLine(`refs: ${t}`)},Q=(e,t,n)=>async()=>{try{await n()}catch(n){let r=we(n,{verbose:t.verbose});K_(e,t,r),process.exitCode=r.exitCode}},J_=e=>`'${e.replaceAll(`'`,String.raw`'\''`)}'`,Y_=(e,t)=>{let n=t.some(e=>e.startsWith(`-`))?[`--`]:[];return[`refs edit`,...e,...n,...t.map(e=>J_(e))].join(` `)},X_=e=>`rm -rf -- ${J_(e)}`,Z_=e=>`rmdir -- ${J_(e)}`,Q_=e=>({path:e.path}),$_=e=>e.filter(e=>e.path!==`.`),ev=e=>e.find(e=>e.path===`.`),tv=e=>{let t=ev(e);return t===void 0?{}:{[t.name]:Q_(t)}},nv=(e,t,n)=>{let r=$_(e),i=tv(e);return r.length>0?{...i,...Object.fromEntries(r.map(e=>[e.name,Q_(e)]))}:n===void 0?i:{...i,[n]:{path:t??`.`}}},rv=e=>{let t=e.description??``;return e.tag_format===void 0?{description:t,path:e.path}:{description:t,path:e.path,tag_format:e.tag_format}},iv=(e,t)=>{let n=Object.entries(e);if(n.length!==0)return Object.fromEntries(n.map(([e,n])=>[e,rv(e===t.rootPackageName?ov(n,t.refDescription):n)]))},av=(e,t)=>{let[n]=Object.keys(tv(e));if(n!==void 0)return t[n]?.path===`.`?n:void 0},ov=(e,t)=>({...e,description:t}),sv=(e,t)=>Object.keys(e).filter(e=>e!==t).toSorted(),cv=(e,t,n)=>{if(sv(e,n).length!==0)throw b(`refs add --description cannot describe a package: it has one description, about the repository. Run the two-phase flow instead:
347
- refs add ${J_(t)} --dry-run --json > proposal.json\nFill in the ref's own description, and one written from its own source for each package below, then:
344
+ - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=ne.resolve(e,t);if(fe.existsSync(r))return r;if(n.includes(ne.extname(t)))return;let i=n.find(e=>fe.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||``;if(this._scriptPath){let e;try{e=fe.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=ne.resolve(ne.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=ne.basename(this._scriptPath,ne.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(ne.extname(i)),s;h.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=fv(h.execArgv).concat(t),s=ye.spawn(h.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=fv(h.execArgv).concat(t),s=ye.spawn(h.argv[0],t,{stdio:`inherit`})):s=ye.spawn(i,t,{stdio:`inherit`}),s.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{h.on(e,()=>{s.killed===!1&&s.exitCode===null&&s.kill(e)})});let c=this._exitCallback;s.on(`close`,e=>{e??=1,c?c(new ev(e,`commander.executeSubCommandAsync`,`(close)`)):h.exit(e)}),s.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(i,a,e._name);else if(t.code===`EACCES`)throw Error(`'${i}' not executable`);if(!c)h.exit(1);else{let e=new ev(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,c(e)}}),this.runningCommand=s}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
345
+ `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in h.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,h.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ov(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=uv(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=uv(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>rv(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=ne.basename(e,ne.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(h.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
346
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function fv(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function pv(){if(h.env.NO_COLOR||h.env.FORCE_COLOR===`0`||h.env.FORCE_COLOR===`false`)return!1;if(h.env.FORCE_COLOR||h.env.CLICOLOR_FORCE!==void 0)return!0}new dv;const mv=[],hv=e=>Array.isArray(e)?e:[e],gv=e=>e===void 0?mv:[e],_v=e=>e instanceof Error?e.message:String(e),Y=e=>{let t=e.optsWithGlobals();return{json:t.json===!0,verbose:t.verbose===!0}},X=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??mv};e.out(JSON.stringify(t));return}for(let t of hv(n))e.out(t);for(let t of i??mv)e.errLine(`refs: warning: ${t}`)},vv=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message,...n.reason===void 0?{}:{reason:n.reason}},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},yv=(e,t)=>{e.errLine(`refs: ${t}`)},Z=(e,t,n)=>async()=>{try{await n()}catch(n){let r=Te(n,{verbose:t.verbose});vv(e,t,r),process.exitCode=r.exitCode}},Q=e=>`'${e.replaceAll(`'`,String.raw`'\''`)}'`,bv=(e,t)=>{let n=t.some(e=>e.startsWith(`-`))?[`--`]:[];return[`refs edit`,...e,...n,...t.map(e=>Q(e))].join(` `)},xv=e=>`rm -rf -- ${Q(e)}`,Sv=e=>`rmdir -- ${Q(e)}`,Cv=e=>({path:e.path}),wv=e=>e.filter(e=>e.path!==`.`),Tv=e=>e.find(e=>e.path===`.`),Ev=e=>{let t=Tv(e);return t===void 0?{}:{[t.name]:Cv(t)}},Dv=(e,t,n)=>{let r=wv(e),i=Ev(e);return r.length>0?{...i,...Object.fromEntries(r.map(e=>[e.name,Cv(e)]))}:n===void 0?i:{...i,[n]:{path:t??`.`}}},Ov=e=>{let t=e.description??``;return e.tag_format===void 0?{description:t,path:e.path}:{description:t,path:e.path,tag_format:e.tag_format}},kv=(e,t)=>{let n=Object.entries(e);if(n.length!==0)return Object.fromEntries(n.map(([e,n])=>[e,Ov(e===t.rootPackageName?jv(n,t.refDescription):n)]))},Av=(e,t)=>{let[n]=Object.keys(Ev(e));if(n!==void 0)return t[n]?.path===`.`?n:void 0},jv=(e,t)=>({...e,description:t}),Mv=(e,t)=>Object.keys(e).filter(e=>e!==t).toSorted(),Nv=(e,t,n)=>{if(Mv(e,n).length!==0)throw y(`refs add --description cannot describe a package: it has one description, about the repository. Run the two-phase flow instead:
347
+ refs add ${Q(t)} --dry-run --json > proposal.json\nFill in the ref's own description, and one written from its own source for each package below, then:
348
348
  refs add --proposal proposal.json
349
- packages to describe: ${Object.keys(e).toSorted().join(`, `)}`)},lv=e=>{if(Object.keys(e).length!==0)return e},uv=e=>{let t={default_branch:e.default_branch,description:e.description,url:e.url};return e.packages!==void 0&&(t.packages=e.packages),e.tag_format!==void 0&&(t.tag_format=e.tag_format),t},dv=`ref.`,fv=`${dv}_`,pv=`${fv}_`,mv=e=>`${pv}${ue(`sha256`).update(e,`utf8`).digest(`hex`)}`,hv=e=>{let t=e.includes(`_`)?`${fv}${e.replaceAll(`_`,`_u`).replaceAll(`/`,`_s`)}`:`${dv}${e.replaceAll(`/`,`_`)}`;return Buffer.byteLength(t,`utf8`)<=212&&Rp(t)?t:mv(e)},gv=e=>e.REFS_ALLOW_FILE_URLS===`1`,_v=(e,t)=>{let n=hf(t,{allowFileUrls:gv(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},vv=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);q_(e,`resolving npm package '${t}'…`);let n=await $p(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},yv=(e,t)=>t.startsWith(`npm:`)?vv(e,t.slice(4)):Promise.resolve(_v(e,t)),bv=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Dg(`git_transport`,void 0,t);return{...e,cloneUrl:Ef(e.cloneUrl,n)}},xv=e=>`ref '${e}' already exists — use refs edit or refs remove`,Sv=(e,t)=>{if(e.refs[t]!==void 0)throw Se(xv(t))},Cv=async e=>{try{return await c(e,{withFileTypes:!0})}catch(e){if(z(e))return;throw e}},wv=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),Tv=async(e,t)=>{let n=await Cv(e);if(n===void 0)return{kind:`stop`};let r=wv(n);if(r.includes(t))return{kind:`continue`,nextDir:m(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},Ev=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await Tv(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):Ev(a.nextDir,i,[...n,r])},Dv=[],Ov=async(e,t)=>{let n=await Ev(e.sourcesDir,t.split(`/`),Dv);if(n!==void 0)throw Se(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},kv=e=>{switch(e.kind){case`candidate_not_inspected`:case`manifest_missing_name`:case`manifest_unreadable`:case`workspace_dir_unreadable`:return e.path;case`workspace_declaration_unparsed`:case`workspace_file_unreadable`:return e.file;case`unsupported_pattern`:return e.pattern;case`no_workspace_declaration`:return}},Av=e=>e.diagnostics.filter(e=>!Hh({diagnostics:[e],packages:[]})).map(e=>{let t=kv(e);return t===void 0?e.kind:`${t}: ${e.kind}`}).toSorted().join(`, `),jv=(e,t,n)=>`checkout at ${e} points at '${W(t)}' — expected '${W(n)}'; remove the checkout directory or run refs remove before retrying`,Mv=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,Nv=(e,t)=>{try{return hf(e,{allowFileUrls:t}).key}catch{return}},Pv=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=Mv(n),i=Nv(t.expectedUrl,t.allowFileUrls),a=Nv(r,t.allowFileUrls);if(i===void 0||a!==i)throw Se(jv(t.dest,r,t.expectedUrl))},Fv=e=>`checkout at ${e} exists but is not refs-managed — remove it (${X_(e)}) and retry`,Iv=async(e,t)=>{let n=await e.run(`git`,[`config`,`--local`,`core.hooksPath`],{cwd:t.dest});if(n.exitCode!==0||n.stdout.trim()!==t.hooksDir)throw Se(Fv(t.dest))},Lv=async(e,t)=>{await a(ie(t.dest),{recursive:!0}),q_(e,`cloning ${W(t.cloneUrl)} into ${t.dest}…`);let n=await xd(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},Rv=async(e,t)=>(nu(t.home,t.dest),U(t.dest)?(await Pv(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await Iv(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):Lv(e,t)),zv=(e,t)=>`checkout for '${e}' at ${t} is missing or corrupt (git rev-parse HEAD failed) — run: refs remove ${e}, then refs add <source> --dry-run again`,Bv=(e,t,n)=>`checkout for '${e}' at ${t} has a HEAD sha refs cannot store yet (${n.length} hex chars, expected 40) — only SHA-1 repositories are supported for now; \`--object-format=sha256\` repositories are not yet supported`,Vv=async(e,t)=>{await Pv(e,t),await Iv(e,{dest:t.dest,hooksDir:t.hooksDir});let n=await e.run(`git`,[`rev-parse`,`HEAD`],{cwd:t.dest});if(n.exitCode!==0)throw b(zv(t.key,t.dest));let r=n.stdout.trim();if(!Tg.shape.head_sha.safeParse(r).success)throw b(Bv(t.key,t.dest,r));return r},Hv=e=>Hh(e)?void 0:`workspace detection could not fully inspect the declared workspaces (${Av(e)}) — members may be missing from the detected packages; the repository's own workspace declaration is what settles it`,Uv=(e,t)=>{let n=nv(e.packages,t.resolved.npmDirectory,t.resolved.npmPkgName),r=av(e.packages,n),i=Hv(e);return{defaultBranch:t.defaultBranch,...i===void 0?{}:{detectionWarning:i},packages:n,...r===void 0?{}:{rootPackageName:r},tagFormatCandidate:t.tagFormatCandidate}},Wv=e=>e.complete?Ud(e.tags):null,Gv=async(e,t,n)=>{let r=await Cd(e.runner,t),i=await Nd(e.runner,t),a=Wv(i);q_(e,`detecting workspace packages…`);let o=await C_(t);return Uv(o,{defaultBranch:r,resolved:n,tagFormatCandidate:a})},Kv=(e,t)=>G(t.home,hv(t.resolved.key),async()=>{let n=await Rv(e,{allowFileUrls:gv(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await Gv(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),qv=(e,t)=>({default_branch:e.defaultBranch,description:``,key:t.key,packages:e.packages,tag_format_candidate:e.tagFormatCandidate,url:t.cloneUrl}),Jv=e=>{let{effectiveMode:t,fields:n,warning:r}=e.cloneResult;return{dest:e.dest,proposal:qv(n,e.resolved),...n.detectionWarning===void 0?{}:{detectionWarning:n.detectionWarning},...n.rootPackageName===void 0?{}:{rootPackageName:n.rootPackageName},...t===void 0?{}:{effectiveCloneMode:t},...r===void 0?{}:{warning:r}}},Yv=async(e,t)=>{let n=B(e.env),r=await H(n),i=bv(await yv(e,t),r.settings);Sv(r,i.key),await Ov(n,i.key);let a=V(n,i.key),o=Dg(`clone_mode`,void 0,r.settings),s=await Kv(e,{cloneMode:o,dest:a,home:n,resolved:i});return Jv({cloneResult:s,dest:a,resolved:i})},Xv=(e,t,n)=>G(e,`home`,async()=>{let r=await H(e);Sv(r,t);let i=await Ag(e),a=i.refs[t],o=n??a?.effective_clone_mode,s={...a,pending_proposal_at:new Date().toISOString()};o!==void 0&&(s.effective_clone_mode=o),i.refs[t]=s,await jg(e,i)}),Zv=(e,t)=>{let n=vl.safeParse(e);if(!n.success)throw b(E(n.error));let r=Eg.safeParse(t);if(!r.success)throw b(E(r.error));return{config:n.data,state:r.data}},Qv=async(e,t)=>{let n=await H(e.home);Sv(n,e.ref.key);let r=uv(e.ref);n.refs[e.ref.key]=r;let i=await Ag(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Dg(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...Zv(n,i),entry:r}},$v=async(e,t)=>{let n=gv(e.env),r=await G(t.home,hv(t.ref.key),()=>(nu(t.home,t.dest),Vv(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return G(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await Qv(t,r);return await jg(t.home,i),await uu(t.home,e),{entry:n,key:t.ref.key}})},ey=(e,t)=>t===`-`?e.readStdin():s(t,`utf8`),ty=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${G_(e)}`)}},ny=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ry=e=>ny(e)&&`ok`in e&&!(`key`in e),iy=e=>{if(!ry(e))return e;if(e.ok===!1)throw b(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(ny(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},ay=e=>e.code===`unrecognized_keys`,oy=e=>e.path.length===0,sy=(e,t)=>{let n=t.toSorted().map(e=>`"${e}"`).join(`, `);return e===``?`✖ unrecognized key(s) in proposal: ${n}`:`✖ unrecognized key(s) in proposal at ${e}: ${n}`},cy=e=>{let t=new Map;for(let n of e){let e=Jt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>sy(e,t))},ly=e=>`✖ invalid proposal: ${e.message}`,uy=e=>{let t=e.issues.filter(e=>ay(e)),n=e.issues.filter(e=>!ay(e)),r=n.filter(e=>oy(e));if(t.length===0&&r.length===0)return E(e);let i=n.filter(e=>!oy(e)),a=[...cy(t),...r.map(e=>ly(e))];return i.length>0&&a.push(E({issues:i})),a.join(`
350
- `)},dy=e=>{let t=wg.safeParse(e);if(!t.success)throw b(uy(t.error));return t.data},fy=async(e,t)=>{let n=await ey(e,t);return dy(iy(ty(n)))},py=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],my=e=>[...W_(e.warning),...W_(e.detectionWarning)],hy=async(e,t)=>{let n=await Yv(e,t),r=B(e.env);await Xv(r,n.proposal.key,n.effectiveCloneMode);let i=my(n);return{data:n.proposal,human:py(n.proposal.key,n.dest),warnings:i}},gy=e=>[`refs add: '${e}' added to config`],_y=e=>{let t={default_branch:e.default_branch,description:e.description,key:e.key,url:e.url};e.tag_format_candidate!==null&&(t.tag_format=e.tag_format_candidate);let n=lv(e.packages);return n!==void 0&&(t.packages=n),t},vy=async(e,t)=>{let n=await fy(e,t),r=B(e.env),i=V(r,n.key);if(!U(i))throw v(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let a=_y(n),{entry:o,key:s}=await $v(e,{dest:i,home:r,ref:a});return{data:{entry:o,key:s},human:gy(s),warnings:[]}},yy=(e,t,n)=>{cv(e.proposal.packages,n,e.rootPackageName);let r={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,url:e.proposal.url};e.proposal.tag_format_candidate!==null&&(r.tag_format=e.proposal.tag_format_candidate);let i=iv(e.proposal.packages,{refDescription:t,...e.rootPackageName===void 0?{}:{rootPackageName:e.rootPackageName}});return i!==void 0&&(r.packages=i),r},by=async(e,t,n)=>{let r=await Yv(e,t),i=B(e.env);await Xv(i,r.proposal.key,r.effectiveCloneMode);let a=yy(r,n,t),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await $v(e,o);return{data:{entry:s,key:c},human:gy(c),warnings:my(r)}},xy=e=>{let t=[e.dryRun,e.proposal!==void 0,e.description!==void 0].filter(Boolean).length;if(t>1)throw y(`refs add: use only one of --dry-run, --proposal, or --description`);if(t===0)throw y(`refs add needs --dry-run, --proposal, or --description`)},Sy=e=>{if(e===void 0||e===``)throw y(`refs add requires <source> (a git url or npm:<package>)`);return e},Cy=(e,t)=>(xy(t),t.proposal===void 0?t.description===void 0?hy(e,Sy(t.source)):by(e,Sy(t.source),t.description):vy(e,t.proposal)),wy=(e,t)=>{let n={dryRun:t.dryRun===!0};return e!==void 0&&(n.source=e),t.proposal!==void 0&&(n.proposal=t.proposal),t.description!==void 0&&(n.description=t.description),n},Ty=(e,t)=>{e.command(`add`).description(`Add a git reference in two phases: propose (--dry-run), then finalize (--proposal).`).argument(`[source]`,`git url or npm:<package> (omit when finalizing with --proposal)`).option(`--dry-run`,`resolve and clone the source, writing a reviewable proposal`).option(`--proposal <file>`,`finalize from a completed proposal JSON file (- for stdin)`).option(`--description <text>`,`one-shot: dry-run then finalize immediately with this description`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let r=await Cy(t,wy(e,n));Z(t,i,r.human,r.data,r.warnings)})()})},Ey=async e=>{let t=await e.runner.run(`git`,[`--version`]);return t.exitCode===0?{detail:t.stdout.trim(),name:`git`,status:`ok`}:{detail:t.stderr.trim()||`git --version exited with code ${t.exitCode}`,name:`git`,status:`fail`}},Dy=/^v(?<major>\d+)\.(?<minor>\d+)/u,Oy=e=>{let t=Dy.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},ky=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,Ay=e=>{let{nodeVersion:t}=e;return ky(Oy(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},jy=()=>vl.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),My=async e=>{try{return{config:await H(e)}}catch(e){return{config:jy(),errorMessage:G_(e)}}},Ny=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},Py={ci:`update check is off in CI — set REFS_UPDATE_CHECK=1 to run it here anyway`,config:`update check is off ([updates].check = false in config.toml)`,env:`update check is off (REFS_UPDATE_CHECK=0)`},Fy=(e,t,n)=>{if(Ug(e,t)){let r=n?` (npm was unreachable just now; this was its last answer)`:``;return{detail:`${Wg(e,t)}${r}`,name:`cli-update`,status:`warn`}}return n?{detail:`could not reach npm to check; its last answer was ${t}, which this CLI (${e}) already has`,name:`cli-update`,status:`warn`}:{detail:`this CLI (${e}) is npm's latest published release`,name:`cli-update`,status:`ok`}},Iy=async(e,t)=>{let n=Jg({env:e.env,updates:t.updates});if(n!==`on`)return{detail:Py[n],name:`cli-update`,status:`ok`};let{latest:r,stale:i}=await Hg({fetch:e.fetcher,home:B(e.env),nowMs:Date.now()});return r===void 0?{detail:`could not reach npm to learn the latest published version — not a fault of your setup, and nothing else depends on it`,name:`cli-update`,status:`warn`}:Fy(e.cliVersion,r,i)},Ly=(e,t)=>Object.keys(t.refs).map(e=>rl.parse(e)).map(t=>({dest:V(e,t),key:t})).filter(e=>U(e.dest)),Ry=[`pre-commit`,`pre-push`],zy=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},By=async e=>{let t=await Promise.all(Ry.map(t=>zy(e,t)));return Ry.filter((e,n)=>!t[n])},Vy=async(e,t,n)=>{let r=await e.runner.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:n});return r.exitCode===0&&r.stdout.trim()===t.hooksDir},Hy=e=>e.missingHooks.length>0?{detail:`${e.missingHooks.map(e=>`hooks/${e}`).join(`, `)} missing or not executable — run: refs init`,name:`hooks-guard`,status:`fail`}:e.badKeys.length>0?{detail:`core.hooksPath not set for: ${e.badKeys.join(`, `)} — run: refs init`,name:`hooks-guard`,status:`fail`}:{detail:`${Ry.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},Uy=async(e,t,n)=>{let r=Ly(t,n),[i,a]=await Promise.all([By(t),Promise.all(r.map(n=>Vy(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return Hy({badKeys:o,checkoutCount:r.length,missingHooks:i})},Wy=async(e,t)=>{let n=await e.runner.run(`git`,[`status`,`--porcelain`],{cwd:t.dest});return n.exitCode===0?{broken:!1,detail:``,dirty:n.stdout.trim()!==``,key:t.key}:{broken:!0,detail:n.stderr.trim(),dirty:!1,key:t.key}},Gy=e=>{let t=e.filter(e=>e.broken);if(t.length>0)return{detail:t.map(e=>`${e.key}: git status failed — ${e.detail}`).join(`; `),name:`dirty-checkouts`,status:`fail`};let n=e.filter(e=>e.dirty).map(e=>e.key);return n.length===0?{detail:`no local changes in any checkout`,name:`dirty-checkouts`,status:`ok`}:{detail:`local changes will be discarded on next sync: ${n.join(`, `)}`,name:`dirty-checkouts`,status:`warn`}},Ky=async(e,t,n)=>{let r=Ly(t,n),i=await Promise.all(r.map(t=>Wy(e,t)));return Gy(i)},qy=async e=>{try{return await Ag(e)}catch{return Eg.parse({})}},Jy=async e=>{try{return(await c(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(z(e))return[];throw e}},Yy=async(e,t)=>{if(U(e))return[[...t]];let n=await Jy(e);return(await Promise.all(n.map(n=>Yy(m(e,n),[...t,n])))).flat()},Xy=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},Zy=(e,t,n)=>Xy(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: ${X_(e.dest)}`,Qy=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),$y=async(e,t,n)=>{let r=(await Yy(e.sourcesDir,[])).map(t=>Qy(e,t)).filter(e=>!Object.hasOwn(t.refs,e.key));if(r.length===0)return{detail:`no orphaned checkouts under sources/`,name:`orphans`,status:`ok`};let i=Date.now();return{detail:r.map(e=>Zy(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},eb=e=>e!==`unmaterialized`&&e!==`verified`,tb=new Set([`ambiguous`,`missing`,`relocated`,`unregistered`]),nb=(e,t)=>{let[n]=e;if(n===void 0)return t===void 0?{status:`ok`}:{discovery_incomplete:t,status:`unknown`};let r={packages:[...e],status:e.some(e=>tb.has(e.status))?`drift`:`unknown`};return t!==void 0&&(r.discovery_incomplete=t),r},rb=`(unknown)`,ib=e=>Gc(e.name)&&ll.safeParse(e.path).success,ab=(e,t)=>{let n=`${e.name}: declared in this checkout but not registered — it cannot be resolved by name until it is`;return e.path===void 0?`${n}. Declared at several paths (${(e.candidates??[]).join(`, `)}) — pick one`:ib(e)?`${n}. To register it: ${Y_([`--package=${J_(e.name)}`,`--create`,`--path=${J_(e.path)}`,`--description="<what it is>"`],[t])}`:`${n}. Its name or path is one the configuration cannot hold, so there is no command for it — report it and leave it unregistered`},ob=(e,t,n)=>{let r=`${e.name}: moved to ${e.path??rb} — update the entry's path (${n})`,i=Y_([`--package=${J_(e.name)}`],[t,`path`,e.path??``]);return ll.safeParse(e.path).success?`${r}. To fix it: ${i}`:r},sb=(e,t)=>{let n=`configured: ${e.configured_path??rb}`;if(e.status===`relocated`)return ob(e,t,n);if(e.status===`missing`){let r=Y_([`--package=${J_(e.name)}`,`--remove`],[t]);return`${e.name}: gone from this repo's workspaces (${n}) — repoint the entry if it moved out of them, or unregister it: ${r}`}if(e.status===`ambiguous`){let t=(e.candidates??[]).join(`, `);return`${e.name}: declared at several paths (${t}) — point the entry at one (${n})`}return`${e.name}: could not be checked — ${e.reason??`(no reason given)`} (${n})`},cb=(e,t)=>e.status===`unregistered`?ab(e,t):sb(e,t),lb=e=>`could not check for unregistered packages — ${e}`,ub=(e,t)=>{if(e.reason!==void 0)return[`could not be checked — ${e.reason}`];let n=(e.packages??[]).map(e=>cb(e,t));return e.discovery_incomplete===void 0?n:[...n,lb(e.discovery_incomplete)]},db=e=>{let t;return()=>(t??=C_(e),t)},fb=async(e,t,n)=>{let r=await c_(e);if(r===void 0||t.some(e=>e.packageName===r.name))return{issues:[]};let i=await n();if(!Hh(i))return{incomplete:Av(i),issues:[]};let a=Qh(i.packages,r.name);return a.kind===`ambiguous`?{issues:[{candidates:a.paths,name:r.name,status:`unregistered`}]}:{issues:a.kind===`found`?[{name:r.name,path:a.path,status:`unregistered`}]:[]}},pb=e=>{let t=new Map;for(let n of e)t.set(n.name,[...t.get(n.name)??[],n.path]);return t},mb=(e,t)=>{let n=new Set(e.changedDirs),r=t.filter(e=>!n.has(e.path)).map(e=>e.name);return new Set([...e.namesBefore,...r])},hb=(e,t)=>t.length===1&&t[0]!==void 0?{name:e,path:t[0],status:`unregistered`}:{candidates:[...t],name:e,status:`unregistered`},gb=async(e,t,n)=>{if(t.kind===`arrivals`&&t.changedDirs.length===0)return{issues:[]};let r=await n();if(!Hh(r))return{incomplete:Av(r),issues:[]};let i=new Set(e.map(e=>e.packageName)),a=r.packages.filter(e=>e.path!==`.`),o=t.kind===`all`?void 0:mb(t,a);return{issues:[...pb(a)].filter(([e])=>!i.has(e)).filter(([e])=>o===void 0||!o.has(e)).map(([e,t])=>hb(e,t)).toSorted((e,t)=>e.name.localeCompare(t.name))}},_b=(e,t)=>({path:e.configuredPath,reason:t,status:`unverifiable`}),vb=(e,t)=>Uh(t)?{configuredPath:e.configuredPath,path:null,status:`missing`}:_b(e,`this repo declares no workspaces, so there was nowhere to search`),yb=(e,t)=>t===e.configuredPath,bb=e=>e.packages.filter(e=>e.path!==`.`),xb=(e,t)=>{let n=Qh(bb(t),e.packageName);return n.kind===`ambiguous`?{candidates:n.paths,configuredPath:e.configuredPath,path:null,status:`ambiguous`}:Hh(t)?n.kind===`absent`?vb(e,t):yb(e,n.path)?_b(e,`the checkout changed while it was being inspected`):{configuredPath:e.configuredPath,path:n.path,status:`relocated`}:_b(e,n.kind===`found`?`workspace detection was incomplete, so the new location is not confirmed unique`:`workspace detection was incomplete`)},Sb=e=>{let t=new Map(Object.entries(e??{}));return[...t.keys()].toSorted().flatMap(e=>{let n=t.get(e);return n===void 0?[]:[{configuredPath:n.path,packageName:e}]})},Cb=async(e,t)=>{let n=await Yh(e,t.configuredPath,t.packageName);if(n.kind===`match`)return{path:t.configuredPath,status:`verified`};if(n.kind===`unreadable`)return{path:t.configuredPath,reason:n.reason,status:`unverifiable`}},wb=e=>e.flatMap(e=>e.settled===void 0?[]:[{outcome:e.settled,query:e.query}]),Tb=async(e,t,n)=>{let r=await Promise.all(t.map(async t=>({query:t,settled:await Cb(e,t)})));if(r.every(e=>e.settled!==void 0))return wb(r);let i=await n();return r.map(e=>({outcome:e.settled??xb(e.query,i),query:e.query}))},Eb=e=>{let{outcome:t,query:n}=e;return eb(t.status)?[{...t.candidates===void 0?{}:{candidates:t.candidates},configured_path:n.configuredPath,name:n.packageName,...t.status===`relocated`&&t.path!==null?{path:t.path}:{},...t.reason===void 0?{}:{reason:t.reason},status:t.status}]:[]},Db=(e,t)=>{let n=new Set(e.map(e=>e.name));return[...e,...t.filter(e=>!n.has(e.name))]},Ob=async(e,t,n)=>{let r=Sb(t),[i]=r;if(i===void 0)return{status:`ok`};let a=db(e);try{let[t,i,o]=await Promise.all([Tb(e,r,a),fb(e,r,a),gb(r,n,a)]);return nb([...t.flatMap(e=>Eb(e)),...Db(i.issues,o.issues)],o.incomplete??i.incomplete)}catch(e){return{reason:G_(e),status:`unknown`}}},kb=async(e,t,n)=>{try{return await G(e,hv(n.key),()=>Ob(n.dest,t.refs[n.key]?.packages,{kind:`all`}),{timeoutMs:100})}catch(e){if(e instanceof _&&e.code===`conflict`)return{reason:`another refs process is holding this ref`,status:`unknown`};throw e}},Ab=`config-drift`,jb=(e,t)=>{let[n]=e;return n===void 0?{detail:`every configured package path resolves in ${t} checkout(s)`,name:Ab,status:`ok`}:{detail:e.join(`; `),name:Ab,status:`warn`}},Mb=async(e,t,n)=>{let[r,...i]=n;if(r===void 0)return[];let a=await kb(e,t,r),o=await Mb(e,t,i);return[...ub(a,r.key).map(e=>`${r.key}: ${e}`),...o]},Nb=async(e,t)=>{let n=Ly(e,t);return jb(await Mb(e,t,n),n.length)},Pb=e=>{let{diagnosis:t}=e;return e.kind===`claim`||!e.isDirectory||t.pidState===`definitely-dead`||t.stale||t.meta===`malformed`||t.meta===`unreadable`||t.policy===`unknown`?!1:t.ageMs===void 0||t.ageMs>=0},Fb=e=>{let{ageMs:t,budgetMs:n,policy:r}=e;return r===`unknown`?`, state could not be read`:t===void 0||n===void 0?``:t<0?`, recorded time is in the future — check the system clock`:`, ${xp(t)} into a ${xp(n)} window`},Ib=e=>e.pid===void 0?`owner unknown (metadata ${e.meta})`:e.pidState===`definitely-dead`?`recorded pid ${e.pid} is not running`:`recorded pid ${e.pid} present`,Lb=(e,t)=>{let n=m(e.locksDir,ap,t.name),r=t.diagnosis.ageMs===void 0?``:` for ${xp(t.diagnosis.ageMs)}`;return`steal claim on ${t.name}: present${r}. Stealing this lock is blocked while it is here. A reclaim in progress clears it within a moment; if it stays, ${Rb}: ${Z_(n)}`},Rb=`stop every refs process using this home — including suspended ones — and then run`,zb=(e,t)=>{let{diagnosis:n}=t;if($f(n))return`, reclaimable now`;if(!n.stale&&t.isDirectory)return``;let r=m(e.locksDir,t.name);return`, not automatically reclaimable — if it is genuinely abandoned, ${Rb}: ${X_(r)}`},Bb=(e,t)=>{let{diagnosis:n}=t,r=t.isDirectory?``:`not a directory, `,i=zb(e,t);return`${t.name}: ${r}${Ib(n)}${Fb(n)}${i}`},Vb=async e=>{let t=await bp(e),[n]=t;return n===void 0?{detail:`no locks held`,name:`locks`,status:`ok`}:{detail:t.map(t=>t.kind===`claim`?Lb(e,t):Bb(e,t)).join(`; `),name:`locks`,status:t.every(e=>Pb(e))?`ok`:`warn`}},Hb=[`.agents`,`skills`,`refs`,`SKILL.md`],Ub=[`skills`,`refs`,`SKILL.md`],Wb=[`.claude`,`skills`,`refs`,`SKILL.md`],Gb=`npx skills add kaisers-io/refs`,Kb=`npm i -g @kaisers-io/refs@latest`,qb=(e,t)=>e===void 0?void 0:{display:t,path:e},Jb=e=>{let{dirName:t,env:n,home:r,overrideName:i}=e,a=n[i]?.trim();return a!==void 0&&a.length>0?{display:a,path:a}:qb(r===void 0?void 0:m(r,t),`~/${t}`)},Yb=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:qb(t,`~/.agents`),segments:Hb},{label:`Claude Code`,root:Jb({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:Ub},{label:`Codex`,root:Jb({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:Ub},{label:`project ./.agents`,root:qb(e.cwd,`./.agents`),segments:Hb},{label:`project ./.claude`,root:qb(e.cwd,`./.claude`),segments:Wb}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:m(t.path,...n)}])},Xb=async(e,t)=>{try{let n=await l(e);return{label:t,realPath:n,source:await s(n,`utf8`)}}catch{return}},Zb=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},Qb=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,$b=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,ex=e=>{let t=Qb.exec(e)?.groups?.body;if(t!==void 0)return $b.exec(t)?.groups?.version},tx=(e,t)=>{if(e===t)return`match`;let n=Fg(e,t);return n===void 0?`unknown`:n===0?`match`:n>0?`cli-older`:`skill-older`},nx={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${Kb}`,match:(e,t)=>`the refs skill is installed and matches this CLI (${t})`,"skill-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the skill: ${Gb}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${Kb} and ${Gb}`},rx=e=>{let{cliVersion:t,label:n,skillVersion:r}=e;if(r===void 0)return{detail:`the refs skill (${n}) predates the version gate — update it: ${Gb}`,name:`skill`,status:`warn`};let i=tx(r,t);return{detail:`${n}: ${nx[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},ix=e=>({detail:`refs skill not found in the locations this check knows about (${e.map(e=>e.display).join(`, `)}) — an install anywhere else is invisible here and still works; if it really is missing: ${Gb}`,name:`skill`,status:`warn`}),ax=async e=>{let t=Yb(e),n=await Promise.all(t.map(e=>Xb(e.path,e.label))),r=Zb(n.filter(e=>e!==void 0)).map(t=>rx({cliVersion:e.cliVersion,label:t.label,skillVersion:ex(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??ix(t)},ox=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,sx=e=>e===``?{}:{user:e},cx=e=>e===``?{}:{port:e},lx=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...sx(t.username),...cx(t.port)}:void 0}catch{return}},ux=e=>{let t=ox.exec(e),n=t?.groups?.host;return n===void 0?lx(e):{host:n,user:t?.groups?.user??`git`}},dx=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,fx=e=>e.user===void 0?dx(e):`${e.user}@${dx(e)}`,px=e=>{let t=Object.values(e.refs).map(e=>ux(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(fx(e),e);return[...n.values()].toSorted((e,t)=>fx(e).localeCompare(fx(t)))},mx=/Permission denied/u,hx=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],gx=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,_x=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=gx(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},vx=async(e,t,n)=>{let r=fx(t),i=await e.runner.run(`ssh`,_x(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:mx.test(i.stderr)?{host:r,outcome:`denied`}:hx.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},yx=(e,t)=>{let n=e.filter(e=>e.outcome===`timeout`).map(e=>e.host);if(n.length!==0)return{detail:`ssh probe timed out after ${t/1e3}s: ${n.join(`, `)}`,name:`ssh-auth`,status:`fail`}},bx=e=>{let t=e.filter(e=>e.outcome===`denied`).map(e=>e.host);if(t.length!==0)return{detail:`ssh permission denied for: ${t.join(`, `)}`,name:`ssh-auth`,status:`fail`}},xx=e=>{let t=e.filter(e=>e.outcome===`connection-warn`);if(t.length!==0)return{detail:`ssh connection issue, treated as warn: ${t.map(e=>`${e.host} (${e.detail??``})`).join(`; `)}`,name:`ssh-auth`,status:`warn`}},Sx=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),Cx=(e,t)=>yx(e,t)??bx(e)??xx(e)??Sx(e),wx=async(e,t,n)=>{let r=px(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>vx(e,t,i)));return Cx(a,i)},Tx=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${G_(t)}`,name:e.name,status:`fail`}}},Ex=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await Tx(t),i=await Ex(n);return r===void 0?i:[r,...i]},Dx=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Ey(n)},{name:`node`,run:()=>Promise.resolve(Ay(n))},{name:`config`,run:()=>Promise.resolve(Ny(t.errorMessage))},{name:`hooks-guard`,run:()=>Uy(n,r,t.config)},{name:`dirty-checkouts`,run:()=>Ky(n,r,t.config)},{name:`config-drift`,run:()=>Nb(r,t.config)},{name:`orphans`,run:()=>$y(r,t.config,i)},{name:`locks`,run:()=>Vb(r)},{name:`skill`,run:()=>ax(n)},{name:`cli-update`,run:()=>Iy(n,t.config)},{name:`ssh-auth`,run:()=>wx(n,t.config)}]},Ox=async e=>{let t=B(e.env),n=await My(t),r=await qy(t);return Ex(Dx({configLoad:n,ctx:e,home:t,state:r}))},kx={fail:`FAIL`,ok:`OK`,warn:`WARN`},Ax=e=>e.map(e=>`[${kx[e.status]}] ${e.name}: ${e.detail}`),jx=e=>e.some(e=>e.status===`fail`),Mx=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, drift, locks, ssh).`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let e=await Ox(t);Z(t,r,Ax(e),{checks:e}),jx(e)&&(process.exitCode=g.UNEXPECTED)})()})},Nx=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},Px=(e,t)=>{if(!U(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},Fx=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},Ix=`never`,Lx=(e,t,n)=>e===void 0||n-Date.parse(e)>t,Rx=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,zx=(e,t)=>{if(e===void 0)return Ix;let n=t-Date.parse(e);if(Number.isNaN(n))return Ix;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return Rx(i,`minute`);let a=Math.floor(i/60);if(a<24)return Rx(a,`hour`);let o=Math.floor(a/24);return o<365?Rx(o,`day`):Rx(Math.floor(o/365),`year`)},Bx=e=>{let t=zx(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==Ix&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},Vx=(e,t,n)=>{let r=e.state.refs[t],i=al(Dg(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:Dg(`clone_mode`,n,e.settings),description:n.description,key:t,...r?.last_fetched_at===void 0?{}:{last_fetched_at:r.last_fetched_at},missing:!U(V(e.home,rl.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:Lx(r?.last_fetched_at,i,e.now)}},Hx=e=>{let t={home:e.home,includePackages:e.includePackages,now:e.now,settings:e.config.settings,state:e.state};return Object.entries(e.config.refs).map(([e,n])=>Vx(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},Ux=async(e,t,n)=>{let r=B(e.env),i=await H(r),a=await Ag(r);return Hx({config:i,home:r,includePackages:t,now:n,state:a})},Wx=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...Bx({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],Gx=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...Wx(n,t)),e),[]),Kx=e=>e.split(`/`),qx=(e,t)=>{let n=Kx(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},Jx=(e,t)=>{if(Object.hasOwn(e.refs,t))return rl.parse(t);let n=Kx(t),r=Object.keys(e.refs).filter(e=>qx(e,n)).toSorted(),[i]=r;if(i===void 0)throw v(`no ref matches '${t}'`);if(r.length>1)throw y(`'${t}' matches more than one ref: ${r.join(`, `)}`);return rl.parse(i)},Yx=(e,t)=>{e.command(`list`).description(`List configured refs with their staleness/missing checkout status.`).option(`--packages`,`include each ref's package names in --json output (off by default)`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let n=Date.now(),i=await Ux(t,e.packages===!0,n);Z(t,r,Gx(i,n),i)})()})},Xx=e=>e===void 0?null:e,Zx=`packages`,Qx=()=>Object.keys(pl.shape).toSorted().join(`, `),$x=e=>`unknown package field '${e}' — valid fields: ${Qx()}`,eS=e=>Object.hasOwn(pl.shape,e),tS=(e,t,n)=>{if(!eS(t))throw y($x(t));let r=e[t],i=pl.safeParse({...e,[t]:n});if(!i.success)throw b(E(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},nS=async e=>{let t=Fx(e.entry,e.key,e.packageName),n=tS(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await uu(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:Xx(n.newValue),old:Xx(n.oldValue)}},rS=(e,t)=>`package '${e}' is already registered on ref '${t}' — edit its fields instead`,iS=(e,t)=>{let n=B(e.env);return G(n,`home`,async()=>{let e=await H(n),r=Jx(e,t.query),i=Nx(e,r);if(Object.hasOwn(i.packages??{},t.packageName))throw b(rS(t.packageName,r));let a=ml.safeParse({...i,packages:{...i.packages,[t.packageName]:{description:t.description,path:t.path}}});if(!a.success)throw b(E(a.error));return await uu(n,{...e,refs:{...e.refs,[r]:a.data}}),{created:!0,field:Zx,key:r,new:{description:t.description,name:t.packageName,path:t.path},old:null}})},aS=(e,t)=>`package '${e}' is not registered on ref '${t}' — nothing to remove`,oS=(e,t)=>{let n=B(e.env);return G(n,`home`,async()=>{let e=await H(n),r=Jx(e,t.query),i=Nx(e,r),a=i.packages??{};if(!Object.hasOwn(a,t.packageName))throw b(aS(t.packageName,r));let{[t.packageName]:o,...s}=a,c=Object.keys(s).length===0?sS(i):{...i,packages:s};return await uu(n,{...e,refs:{...e.refs,[r]:c}}),{field:Zx,key:r,new:null,old:{description:o?.description??``,name:t.packageName,path:o?.path??``},removed:!0}})},sS=e=>{let{packages:t,...n}=e;return n},cS=`packages`,lS=()=>Object.keys(ml.shape).filter(e=>e!==cS).toSorted().join(`, `),uS=e=>`unknown ref field '${e}' — valid fields: ${lS()}`,dS=e=>Object.hasOwn(ml.shape,e),fS=(e,t,n)=>`failed to rewrite git remote at ${e} to '${W(t)}': ${n.trim()}`,pS=async(e,t)=>{if(nu(t.home,t.dest),!U(t.dest))return;let n=await e.runner.run(`git`,[`remote`,`set-url`,`--`,`origin`,t.cloneUrl],{cwd:t.dest});if(n.exitCode!==0)throw b(fS(t.dest,t.cloneUrl,n.stderr))},mS=async(e,t)=>{let n=hf(t.value,{allowFileUrls:gv(e.env)});if(n.key!==t.key)throw b(`new url derives a different key — remove and re-add instead`);let r=V(t.home,t.key);return await pS(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},hS=(e,t,n)=>{let r={...e,[t]:n},i=ml.safeParse(r);if(!i.success)throw b(E(i.error));return i.data},gS=(e,t)=>t.field===`url`?mS(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(hS(t.entry,t.field,t.value)),_S=async(e,t)=>{let{field:n}=t;if(n===cS)throw y(`use --package <name> <field> <value>`);if(!dS(n))throw y(uS(n));let r=t.entry[n],i=await gS(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},vS=(e,t)=>{let n=B(e.env),{field:r,opts:i,query:a,value:o}=t;return G(n,`home`,async()=>{let t=await H(n),s=Jx(t,a),c=Nx(t,s);if(i.packageName!==void 0)return nS({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await _S(e,{entry:c,field:r,home:n,key:s,value:o});return await uu(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:Xx(l.new),old:Xx(l.old)}})},yS=`settings`,bS=[],xS=()=>Object.keys(dl.shape).toSorted().join(`, `),SS=e=>`unknown setting '${e}' — valid settings: ${xS()}`,CS=e=>Object.hasOwn(dl.shape,e),wS=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,TS=e=>{try{let t=Jx(e,yS);return[wS(`ref '${t}'`)]}catch(e){if(e instanceof _&&e.code===`usage`)return[wS("one of several matching refs — see `refs list`")];if(e instanceof _&&e.code===`not_found`)return bS;throw e}},ES=e=>({data:{field:e.key,key:yS,new:Xx(e.parsed[e.key]),old:Xx(e.old)},warnings:TS(e.config)}),DS=(e,t)=>{let n=B(e.env);return G(n,`home`,async()=>{let e=await H(n);if(!CS(t.key))throw y(SS(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=dl.safeParse(i);if(!a.success)throw b(E(a.error));return await uu(n,{...e,settings:a.data}),ES({config:e,key:t.key,old:r,parsed:a.data})})},OS=[],kS=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},AS=e=>{let{description:t,path:n}=e.create,{packageName:r}=e.opts;if(r===void 0||t===void 0||n===void 0||e.second!==void 0||e.value!==void 0)throw y(`--create registers a new package: it needs --package <name>, --path <path> and --description <text>, and takes no <field> <value> arguments`);return{description:t,packageName:r,path:n}},jS=e=>{if(e.second===void 0||e.value===void 0)throw y(`missing <field> and <value> — see 'refs edit --help'`);return{field:e.second,value:e.value}},MS=e=>{let{packageName:t}=e.opts;if(t===void 0||e.second!==void 0||e.value!==void 0||e.create.path!==void 0||e.create.description!==void 0)throw y(`--remove unregisters a package: it needs --package <name>, and takes no <field> <value> arguments, no --path and no --description`);return{packageName:t}},NS=async(e,t)=>{let{packageName:n}=MS(t);return{data:await oS(e,{packageName:n,query:t.first}),warnings:OS}},PS=async(e,t)=>{let{description:n,packageName:r,path:i}=AS(t);return{data:await iS(e,{description:n,packageName:r,path:i,query:t.first}),warnings:OS}},FS=(e,t,n)=>{if(t.opts.packageName!==void 0)throw y(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return DS(e,n)},IS=e=>{if(e.create===!0&&e.remove===!0)throw y(`use either --create or --remove, not both: one registers a package and the other unregisters it`);return e.create===!0?`create`:e.remove===!0?`remove`:void 0},LS=async(e,t)=>{if(t.create.description!==void 0||t.create.path!==void 0)throw y(`--path and --description only apply to --create — to change one field of a registered package use: refs edit <ref> <field> <value> --package <name>`);let{field:n,value:r}=jS(t);return t.first===`settings`?FS(e,t,{key:n,value:r}):{data:await vS(e,{field:n,opts:t.opts,query:t.first,value:r}),warnings:OS}},RS=(e,t)=>{let n=IS(t.create);return n===`create`?PS(e,t):n===`remove`?NS(e,t):LS(e,t)},zS=e=>e==null?`(unset)`:String(e),BS=e=>{if(e.created===!0){let t=e.new;return[`${e.key}: registered '${t.name}' at ${t.path}`]}if(e.removed===!0){let t=e.old;return[`${e.key}: unregistered '${t.name}' (was at ${t.path})`]}return[`${e.key}: ${e.field} '${zS(e.old)}' -> '${zS(e.new)}'`]},VS=(e,t)=>{e.command(`edit`).description(`Edit one field: 'refs edit settings <key> <value>' for a global setting, or 'refs edit <ref> <field> <value> [--package <name>]' for a ref or package field. With --create, registers a package the config does not have yet; with --remove, unregisters one it has.`).argument(`<ref-or-settings>`,`a ref key/unique suffix, or the literal 'settings'`).argument(`[field-or-key]`,`field to edit (or, in settings mode, the setting key)`).argument(`[value]`,`the new value`).option(`--package <name>`,`edit this package's field instead of a top-level ref field`).option(`--create`,`register --package as a new package on this ref`).option(`--remove`,`unregister --package from this ref, leaving the checkout alone`).option(`--path <path>`,`with --create: the package path, relative to the checkout root`).option(`--description <text>`,`with --create: what the package is`).action((e,n,r,i,a)=>{let o=X(a);return Q(t,o,async()=>{let{data:a,warnings:s}=await RS(t,{create:i,first:e,opts:kS(i),second:n,value:r});Z(t,o,BS(a),a,s)})()})},HS=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,US={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},WS=async e=>{await a(e.root,{recursive:!0}),await a(e.sourcesDir,{recursive:!0}),await a(e.locksDir,{recursive:!0}),await a(e.hooksDir,{recursive:!0})},GS=async e=>{let t=B(e.env);return await WS(t),{config:await G(t,`home`,async()=>{let e=await bu(t,w_);return await Md(t),e}),home:t.root,skill_hint:HS}},KS=(e,t)=>{e.command(`init`).description(`Seed or migrate the refs home directory, its config, and the git hooks guard.`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let e=await GS(t);Z(t,r,[`home: ${e.home}`,`config: ${US[e.config]}`,``,HS],e)})()})},qS=async e=>{let t=B(e.env),n=await G(t,`home`,()=>bu(t,w_));return n===`migrated`?{backup:Ql(t),result:n}:{backup:null,result:n}},JS=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${re(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,YS=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let e=await qS(t);Z(t,r,JS(e),e)})()})},XS=async e=>{try{return await i(e),!0}catch(e){if(z(e))return!1;throw e}},ZS=async e=>{try{return await c(e)}catch(e){if(z(e))return;throw e}},QS=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(z(e))return;throw e}},$S=async e=>{let t=await ZS(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await f(e)}catch(e){if(!z(e))throw e}return!0},eC=async e=>{let t=await QS(e);return t===void 0?!0:t?$S(e):!1},tC=async(e,t)=>{t!==e.sourcesDir&&await eC(t)&&await tC(e,ie(t))},nC=async(e,t)=>await XS(t)?(nu(e,t),await d(t,{force:!0,recursive:!0}),await tC(e,ie(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},rC=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),iC=async(e,t)=>{let n=await H(e),r={...n,refs:rC(n.refs,t)};await uu(e,r);let i=await Ag(e),a={...i,refs:rC(i.refs,t)};await jg(e,a)},aC=async(e,t)=>{let n=B(e.env),r=await H(n),i=Jx(r,t),a=V(n,i),{removedCheckout:o,warning:s}=await G(n,hv(i),()=>nC(n,a));return await G(n,`home`,()=>iC(n,i)),{data:{key:i,removed_checkout:o},warnings:W_(s)}},oC=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],sC=(e,t)=>{e.command(`remove`).description(`Remove a configured ref: its config/state entry AND its checkout directory.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let{data:n,warnings:r}=await aC(t,e);Z(t,i,oC(n),n,r)})()})},cC=async e=>{let t=await Yh(e.checkoutDir,e.configuredPath,e.packageName);return t.kind===`match`?{path:e.configuredPath,status:`verified`}:t.kind===`unreadable`?{path:e.configuredPath,reason:t.reason,status:`unverifiable`}:lC(e)},lC=async e=>xb(e,await C_(e.checkoutDir)),uC=async e=>{try{return await G(e.home,hv(e.key),()=>cC(e),e.lockTimeoutMs===void 0?void 0:{timeoutMs:e.lockTimeoutMs})}catch(t){if(t instanceof _&&t.code===`conflict`)return{path:e.configuredPath,reason:`could not acquire the ref lock in time`,status:`unverifiable`};throw t}},dC=async e=>{if(!U(e.checkoutDir))return{path:e.configuredPath,status:`unmaterialized`};let t=await Yh(e.checkoutDir,e.configuredPath,e.packageName);return t.kind===`match`?{path:e.configuredPath,status:`verified`}:t.kind===`unreadable`?{path:e.configuredPath,reason:t.reason,status:`unverifiable`}:(e.onProbed?.(),uC(e))},fC=(e,t)=>({local_path:null,name:e,path:null,reason:t,status:`unverifiable`}),pC=async e=>{if(!e.checkoutManaged)return fC(e.packageName,e.checkoutReason);let t=await dC(e);return{...t.candidates===void 0?{}:{candidates:t.candidates},...t.configuredPath===void 0?{}:{configured_path:t.configuredPath},local_path:t.path===null?null:m(e.checkoutDir,t.path),name:e.packageName,path:t.path,...t.reason===void 0?{}:{reason:t.reason},status:t.status}},mC=e=>[`package: ${e.name}`,`package path: ${e.local_path??`(unknown)`}`,...e.status===`verified`?[]:[`package status: ${e.status}`],...e.configured_path===void 0?[]:[`configured path: ${e.configured_path}`],...e.candidates===void 0?[]:[`candidates: ${e.candidates.join(`, `)}`],...e.reason===void 0?[]:[`reason: ${e.reason}`]],hC=`node_modules`,gC=[`.pnp.cjs`,`.pnp.js`],_C=new Set([``,`.`,`..`]),vC=e=>!ae(e)&&!e.includes(`\\`)&&e.split(`/`).every(e=>!_C.has(e)),yC=function*(e){let t=ce(e);for(;;){re(t)!==hC&&(yield m(t,hC));let e=ie(t);if(e===t)return;t=e}},bC=async e=>{if(await CC(e)!==`absent`)try{let t=JSON.parse(await s(e,`utf8`)),{name:n,version:r}=typeof t==`object`&&t?t:{};return typeof r!=`string`||r===``?{package_json:e,reason:`manifest_has_no_version`,status:`unverifiable`}:{...typeof n==`string`?{name:n}:{},package_json:e,status:`found`,version:r}}catch{return{package_json:e,reason:`manifest_unreadable`,status:`unverifiable`}}},xC=new Set([`ENOENT`,`ENOTDIR`]),SC=async e=>{try{return(await c(e)).length===0}catch{return!1}},CC=async e=>{try{return await p(e),`present`}catch(e){let t=typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0;return t!==void 0&&xC.has(t)?`absent`:`unreadable`}},wC=async e=>{for(let t of yC(e)){let e=ie(t);if((await Promise.all(gC.map(t=>CC(m(e,t))))).includes(`present`))return!0}return!1},TC=async e=>{try{if(!(await p(e)).isDirectory())throw y(`--project must be a directory: ${e}`)}catch(t){throw t instanceof Error&&t.message.startsWith(`--project`)?t:y(`--project path does not exist: ${e}`)}},EC=async e=>{let t=await CC(e);if(t===`unreadable`)return{reason:`slot_unreadable`,status:`unverifiable`};if(t===`absent`)return;let n=await bC(m(e,`package.json`));return n===void 0?await SC(e)?void 0:{reason:`installed_without_manifest`,status:`unverifiable`}:n},DC=async(e,t)=>{if(!vC(t))return{reason:`unsupported_package_name`,status:`unverifiable`};for(let n of yC(e)){let e=await EC(m(n,...t.split(`/`)));if(e!==void 0)return e}return await wC(e)?{reason:`yarn_pnp`,status:`unsupported_layout`}:{status:`not_materialized`}},OC={'"':`"`,"\\":`\\`,b:`\b`,n:`
351
- `,t:` `},kC={'"':`"`,"\\":`\\`},AC=new Set([` `,` `]),$=Symbol(`malformed git config`),jC=e=>e!==void 0&&!e.quoted&&AC.has(e.char),MC=e=>{let t=0,n=e.length;for(;t<n&&jC(e[t]);)t+=1;for(;n>t&&jC(e[n-1]);)--n;return e.slice(t,n).map(e=>e.char).join(``)},NC=e=>{let t=[],n=!1;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`\\`){r+=1;let n=OC[e[r]??``];if(n===void 0)return $;t.push({char:n,quoted:!0})}else if(i===`"`)n=!n;else if(!n&&(i===`#`||i===`;`))return MC(t);else t.push({char:i??``,quoted:n})}return n?$:MC(t)},PC=e=>{let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`\\`){n+=1;let r=kC[e[n]??``];if(r===void 0)return $;t+=r}else t+=r??``}return t},FC=/^[ \t]+|[ \t]+$/gu,IC=e=>e.replace(FC,``),LC=/^\[[ \t]*(?<section>[A-Za-z0-9.-]+)[ \t]*(?:"(?<subsection>(?:[^"\\]|\\.)*)")?[ \t]*\]/u,RC=/^(?<name>[A-Za-z][A-Za-z0-9-]*)[ \t]*(?:=[ \t]*(?<value>.*))?$/u,zC=function*(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`
349
+ packages to describe: ${Object.keys(e).toSorted().join(`, `)}`)},Pv=e=>{if(Object.keys(e).length!==0)return e},Fv=e=>{let t={default_branch:e.default_branch,description:e.description,url:e.url};return e.packages!==void 0&&(t.packages=e.packages),e.tag_format!==void 0&&(t.tag_format=e.tag_format),t},Iv=`ref.`,Lv=`${Iv}_`,Rv=`${Lv}_`,zv=e=>`${Rv}${ue(`sha256`).update(e,`utf8`).digest(`hex`)}`,Bv=e=>{let t=e.includes(`_`)?`${Lv}${e.replaceAll(`_`,`_u`).replaceAll(`/`,`_s`)}`:`${Iv}${e.replaceAll(`/`,`_`)}`;return Buffer.byteLength(t,`utf8`)<=212&&Bp(t)?t:zv(e)},Vv=e=>e.REFS_ALLOW_FILE_URLS===`1`,Hv=(e,t)=>{let n=_f(t,{allowFileUrls:Vv(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},Uv=async(e,t)=>{if(t===``)throw v(`refs add npm: requires a package name, e.g. npm:left-pad`);yv(e,`resolving npm package '${t}'…`);let n=await tm(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},Wv=(e,t)=>t.startsWith(`npm:`)?Uv(e,t.slice(4)):Promise.resolve(Hv(e,t)),Gv=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=jg(`git_transport`,void 0,t);return{...e,cloneUrl:Of(e.cloneUrl,n)}},Kv=e=>`ref '${e}' already exists — use refs edit or refs remove`,qv=(e,t)=>{if(e.refs[t]!==void 0)throw Ce(Kv(t))},Jv=async e=>{try{return await c(e,{withFileTypes:!0})}catch(e){if(R(e))return;throw e}},Yv=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),Xv=async(e,t)=>{let n=await Jv(e);if(n===void 0)return{kind:`stop`};let r=Yv(n);if(r.includes(t))return{kind:`continue`,nextDir:m(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},Zv=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await Xv(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):Zv(a.nextDir,i,[...n,r])},Qv=[],$v=async(e,t)=>{let n=await Zv(e.sourcesDir,t.split(`/`),Qv);if(n!==void 0)throw Ce(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},ey=e=>{switch(e.kind){case`candidate_not_inspected`:case`manifest_missing_name`:case`manifest_unreadable`:case`workspace_dir_unreadable`:return e.path;case`workspace_declaration_unparsed`:case`workspace_file_unreadable`:return e.file;case`unsupported_pattern`:return e.pattern;case`scan_budget_exhausted`:return`${e.pattern} at ${e.path}`;case`no_workspace_declaration`:return}},ty=e=>e.diagnostics.filter(e=>!Kh({diagnostics:[e],packages:[]})).map(e=>{let t=ey(e);return t===void 0?e.kind:`${t}: ${e.kind}`}).toSorted().join(`, `),ny=(e,t,n)=>`checkout at ${e} points at '${U(t)}' — expected '${U(n)}'; remove the checkout directory or run refs remove before retrying`,ry=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,iy=(e,t)=>{try{return _f(e,{allowFileUrls:t}).key}catch{return}},ay=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=ry(n),i=iy(t.expectedUrl,t.allowFileUrls),a=iy(r,t.allowFileUrls);if(i===void 0||a!==i)throw Ce(ny(t.dest,r,t.expectedUrl))},oy=e=>`checkout at ${e} exists but is not refs-managed — remove it (${xv(e)}) and retry`,sy=async(e,t)=>{let n=await e.run(`git`,[`config`,`--local`,`core.hooksPath`],{cwd:t.dest});if(n.exitCode!==0||n.stdout.trim()!==t.hooksDir)throw Ce(oy(t.dest))},cy=async(e,t)=>{await a(ie(t.dest),{recursive:!0}),yv(e,`cloning ${U(t.cloneUrl)} into ${t.dest}…`);let n=await Cd(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},ly=async(e,t)=>(iu(t.home,t.dest),H(t.dest)?(await ay(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await sy(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):cy(e,t)),uy=(e,t)=>`checkout for '${e}' at ${t} is missing or corrupt (git rev-parse HEAD failed) — run: refs remove ${e}, then refs add <source> --dry-run again`,dy=(e,t,n)=>`checkout for '${e}' at ${t} has a HEAD sha refs cannot store yet (${n.length} hex chars, expected 40) — only SHA-1 repositories are supported for now; \`--object-format=sha256\` repositories are not yet supported`,fy=async(e,t)=>{await ay(e,t),await sy(e,{dest:t.dest,hooksDir:t.hooksDir});let n=await e.run(`git`,[`rev-parse`,`HEAD`],{cwd:t.dest});if(n.exitCode!==0)throw y(uy(t.key,t.dest));let r=n.stdout.trim();if(!kg.shape.head_sha.safeParse(r).success)throw y(dy(t.key,t.dest,r));return r},py=e=>Kh(e)?void 0:`workspace detection could not fully inspect the declared workspaces (${ty(e)}) — members may be missing from the detected packages; the repository's own workspace declaration is what settles it`,my=(e,t)=>{let n=Dv(e.packages,t.resolved.npmDirectory,t.resolved.npmPkgName),r=Av(e.packages,n),i=py(e);return{defaultBranch:t.defaultBranch,...i===void 0?{}:{detectionWarning:i},packages:n,...r===void 0?{}:{rootPackageName:r},tagFormatCandidate:t.tagFormatCandidate}},hy=e=>e.complete?Gd(e.tags):null,gy=async(e,t,n)=>{let r=await Td(e.runner,t),i=await Fd(e.runner,t),a=hy(i);yv(e,`detecting workspace packages…`);let o=await Y_(t);return my(o,{defaultBranch:r,resolved:n,tagFormatCandidate:a})},_y=(e,t)=>W(t.home,Bv(t.resolved.key),async()=>{let n=await ly(e,{allowFileUrls:Vv(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await gy(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),vy=(e,t)=>({default_branch:e.defaultBranch,description:``,key:t.key,packages:e.packages,tag_format_candidate:e.tagFormatCandidate,url:t.cloneUrl}),yy=e=>{let{effectiveMode:t,fields:n,warning:r}=e.cloneResult;return{dest:e.dest,proposal:vy(n,e.resolved),...n.detectionWarning===void 0?{}:{detectionWarning:n.detectionWarning},...n.rootPackageName===void 0?{}:{rootPackageName:n.rootPackageName},...t===void 0?{}:{effectiveCloneMode:t},...r===void 0?{}:{warning:r}}},by=async(e,t)=>{let n=z(e.env),r=await V(n),i=Gv(await Wv(e,t),r.settings);qv(r,i.key),await $v(n,i.key);let a=B(n,i.key),o=jg(`clone_mode`,void 0,r.settings),s=await _y(e,{cloneMode:o,dest:a,home:n,resolved:i});return yy({cloneResult:s,dest:a,resolved:i})},xy=(e,t,n)=>W(e,`home`,async()=>{let r=await V(e);qv(r,t);let i=await Pg(e),a=i.refs[t],o=n??a?.effective_clone_mode,s={...a,pending_proposal_at:new Date().toISOString()};o!==void 0&&(s.effective_clone_mode=o),i.refs[t]=s,await Fg(e,i)}),Sy=(e,t)=>{let n=bl.safeParse(e);if(!n.success)throw y(T(n.error));let r=Ag.safeParse(t);if(!r.success)throw y(T(r.error));return{config:n.data,state:r.data}},Cy=async(e,t)=>{let n=await V(e.home);qv(n,e.ref.key);let r=Fv(e.ref);n.refs[e.ref.key]=r;let i=await Pg(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??jg(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...Sy(n,i),entry:r}},wy=async(e,t)=>{let n=Vv(e.env),r=await W(t.home,Bv(t.ref.key),()=>(iu(t.home,t.dest),fy(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return W(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await Cy(t,r);return await Fg(t.home,i),await fu(t.home,e),{entry:n,key:t.ref.key}})},Ty=(e,t)=>t===`-`?e.readStdin():s(t,`utf8`),Ey=e=>{try{return JSON.parse(e)}catch(e){throw y(`invalid JSON in proposal: ${_v(e)}`)}},Dy=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Oy=e=>Dy(e)&&`ok`in e&&!(`key`in e),ky=e=>{if(!Oy(e))return e;if(e.ok===!1)throw y(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(Dy(e.data))return e.data;throw y(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},Ay=e=>e.code===`unrecognized_keys`,jy=e=>e.path.length===0,My=(e,t)=>{let n=t.toSorted().map(e=>`"${e}"`).join(`, `);return e===``?`✖ unrecognized key(s) in proposal: ${n}`:`✖ unrecognized key(s) in proposal at ${e}: ${n}`},Ny=e=>{let t=new Map;for(let n of e){let e=Yt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>My(e,t))},Py=e=>`✖ invalid proposal: ${e.message}`,Fy=e=>{let t=e.issues.filter(e=>Ay(e)),n=e.issues.filter(e=>!Ay(e)),r=n.filter(e=>jy(e));if(t.length===0&&r.length===0)return T(e);let i=n.filter(e=>!jy(e)),a=[...Ny(t),...r.map(e=>Py(e))];return i.length>0&&a.push(T({issues:i})),a.join(`
350
+ `)},Iy=e=>{let t=Og.safeParse(e);if(!t.success)throw y(Fy(t.error));return t.data},Ly=async(e,t)=>{let n=await Ty(e,t);return Iy(ky(Ey(n)))},Ry=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],zy=e=>[...gv(e.warning),...gv(e.detectionWarning)],By=async(e,t)=>{let n=await by(e,t),r=z(e.env);await xy(r,n.proposal.key,n.effectiveCloneMode);let i=zy(n);return{data:n.proposal,human:Ry(n.proposal.key,n.dest),warnings:i}},Vy=e=>[`refs add: '${e}' added to config`],Hy=e=>{let t={default_branch:e.default_branch,description:e.description,key:e.key,url:e.url};e.tag_format_candidate!==null&&(t.tag_format=e.tag_format_candidate);let n=Pv(e.packages);return n!==void 0&&(t.packages=n),t},Uy=async(e,t)=>{let n=await Ly(e,t),r=z(e.env),i=B(r,n.key);if(!H(i))throw _(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let a=Hy(n),{entry:o,key:s}=await wy(e,{dest:i,home:r,ref:a});return{data:{entry:o,key:s},human:Vy(s),warnings:[]}},Wy=(e,t,n)=>{Nv(e.proposal.packages,n,e.rootPackageName);let r={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,url:e.proposal.url};e.proposal.tag_format_candidate!==null&&(r.tag_format=e.proposal.tag_format_candidate);let i=kv(e.proposal.packages,{refDescription:t,...e.rootPackageName===void 0?{}:{rootPackageName:e.rootPackageName}});return i!==void 0&&(r.packages=i),r},Gy=async(e,t,n)=>{let r=await by(e,t),i=z(e.env);await xy(i,r.proposal.key,r.effectiveCloneMode);let a=Wy(r,n,t),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await wy(e,o);return{data:{entry:s,key:c},human:Vy(c),warnings:zy(r)}},Ky=e=>{let t=[e.dryRun,e.proposal!==void 0,e.description!==void 0].filter(Boolean).length;if(t>1)throw v(`refs add: use only one of --dry-run, --proposal, or --description`);if(t===0)throw v(`refs add needs --dry-run, --proposal, or --description`)},qy=e=>{if(e===void 0||e===``)throw v(`refs add requires <source> (a git url or npm:<package>)`);return e},Jy=(e,t)=>(Ky(t),t.proposal===void 0?t.description===void 0?By(e,qy(t.source)):Gy(e,qy(t.source),t.description):Uy(e,t.proposal)),Yy=(e,t)=>{let n={dryRun:t.dryRun===!0};return e!==void 0&&(n.source=e),t.proposal!==void 0&&(n.proposal=t.proposal),t.description!==void 0&&(n.description=t.description),n},Xy=(e,t)=>{e.command(`add`).description(`Add a git reference in two phases: propose (--dry-run), then finalize (--proposal).`).argument(`[source]`,`git url or npm:<package> (omit when finalizing with --proposal)`).option(`--dry-run`,`resolve and clone the source, writing a reviewable proposal`).option(`--proposal <file>`,`finalize from a completed proposal JSON file (- for stdin)`).option(`--description <text>`,`one-shot: dry-run then finalize immediately with this description`).action((e,n,r)=>{let i=Y(r);return Z(t,i,async()=>{let r=await Jy(t,Yy(e,n));X(t,i,r.human,r.data,r.warnings)})()})},Zy=async e=>{let t=await e.runner.run(`git`,[`--version`]);return t.exitCode===0?{detail:t.stdout.trim(),name:`git`,status:`ok`}:{detail:t.stderr.trim()||`git --version exited with code ${t.exitCode}`,name:`git`,status:`fail`}},Qy=/^v(?<major>\d+)\.(?<minor>\d+)/u,$y=e=>{let t=Qy.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},eb=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,tb=e=>{let{nodeVersion:t}=e;return eb($y(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},nb=()=>bl.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),rb=async e=>{try{return{config:await V(e)}}catch(e){return{config:nb(),errorMessage:_v(e)}}},ib=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},ab={ci:`update check is off in CI — set REFS_UPDATE_CHECK=1 to run it here anyway`,config:`update check is off ([updates].check = false in config.toml)`,env:`update check is off (REFS_UPDATE_CHECK=0)`},ob=(e,t,n)=>{if(qg(e,t)){let r=n?` (npm was unreachable just now; this was its last answer)`:``;return{detail:`${Jg(e,t)}${r}`,name:`cli-update`,status:`warn`}}return n?{detail:`could not reach npm to check; its last answer was ${t}, which this CLI (${e}) already has`,name:`cli-update`,status:`warn`}:{detail:`this CLI (${e}) is npm's latest published release`,name:`cli-update`,status:`ok`}},sb=async(e,t)=>{let n=Qg({env:e.env,updates:t.updates});if(n!==`on`)return{detail:ab[n],name:`cli-update`,status:`ok`};let{latest:r,stale:i}=await Kg({fetch:e.fetcher,home:z(e.env),nowMs:Date.now()});return r===void 0?{detail:`could not reach npm to learn the latest published version — not a fault of your setup, and nothing else depends on it`,name:`cli-update`,status:`warn`}:ob(e.cliVersion,r,i)},cb=(e,t)=>Object.keys(t.refs).map(e=>il.parse(e)).map(t=>({dest:B(e,t),key:t})).filter(e=>H(e.dest)),lb=[`pre-commit`,`pre-push`],ub=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},db=async e=>{let t=await Promise.all(lb.map(t=>ub(e,t)));return lb.filter((e,n)=>!t[n])},fb=async(e,t,n)=>{let r=await e.runner.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:n});return r.exitCode===0&&r.stdout.trim()===t.hooksDir},pb=e=>e.missingHooks.length>0?{detail:`${e.missingHooks.map(e=>`hooks/${e}`).join(`, `)} missing or not executable — run: refs init`,name:`hooks-guard`,status:`fail`}:e.badKeys.length>0?{detail:`core.hooksPath not set for: ${e.badKeys.join(`, `)} — run: refs init`,name:`hooks-guard`,status:`fail`}:{detail:`${lb.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},mb=async(e,t,n)=>{let r=cb(t,n),[i,a]=await Promise.all([db(t),Promise.all(r.map(n=>fb(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return pb({badKeys:o,checkoutCount:r.length,missingHooks:i})},hb=async(e,t)=>{let n=await e.runner.run(`git`,[`status`,`--porcelain`],{cwd:t.dest});return n.exitCode===0?{broken:!1,detail:``,dirty:n.stdout.trim()!==``,key:t.key}:{broken:!0,detail:n.stderr.trim(),dirty:!1,key:t.key}},gb=e=>{let t=e.filter(e=>e.broken);if(t.length>0)return{detail:t.map(e=>`${e.key}: git status failed — ${e.detail}`).join(`; `),name:`dirty-checkouts`,status:`fail`};let n=e.filter(e=>e.dirty).map(e=>e.key);return n.length===0?{detail:`no local changes in any checkout`,name:`dirty-checkouts`,status:`ok`}:{detail:`local changes will be discarded on next sync: ${n.join(`, `)}`,name:`dirty-checkouts`,status:`warn`}},_b=async(e,t,n)=>{let r=cb(t,n),i=await Promise.all(r.map(t=>hb(e,t)));return gb(i)},vb=async e=>{try{return await Pg(e)}catch{return Ag.parse({})}},yb=async e=>{try{return(await c(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(R(e))return[];throw e}},bb=async(e,t)=>{if(H(e))return[[...t]];let n=await yb(e);return(await Promise.all(n.map(n=>bb(m(e,n),[...t,n])))).flat()},xb=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},Sb=(e,t,n)=>xb(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: ${xv(e.dest)}`,Cb=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),wb=async(e,t,n)=>{let r=(await bb(e.sourcesDir,[])).map(t=>Cb(e,t)).filter(e=>!Object.hasOwn(t.refs,e.key));if(r.length===0)return{detail:`no orphaned checkouts under sources/`,name:`orphans`,status:`ok`};let i=Date.now();return{detail:r.map(e=>Sb(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},Tb=e=>e!==`unmaterialized`&&e!==`verified`,Eb=new Set([`ambiguous`,`missing`,`relocated`,`unregistered`]),Db=(e,t={})=>{let{declined:n=[],discoveryIncomplete:r}=t,i=n.length===0?{}:{declined:[...n]},[a]=e;return a===void 0?r===void 0?{...i,status:`ok`}:{...i,discovery_incomplete:r,status:`unknown`}:{...i,...r===void 0?{}:{discovery_incomplete:r},packages:[...e],status:e.some(e=>Eb.has(e.status))?`drift`:`unknown`}},Ob=`(unknown)`,kb=e=>ul.safeParse(e.path).success,Ab=(e,t)=>{let n=`${e.name}: declared in this checkout but not registered — it cannot be resolved by name until it is`;if(e.path===void 0)return`${n}. Declared at several paths (${(e.candidates??[]).join(`, `)}) — pick one`;if(!kb(e))return`${n}. Its path is one the configuration cannot hold, so there is no command for it — report it and leave it unregistered`;let r=bv([`--package=${Q(e.name)}`,`--decline`,`--path=${Q(e.path)}`],[t]);return Kc(e.name)?`${n}. To register it: ${bv([`--package=${Q(e.name)}`,`--create`,`--path=${Q(e.path)}`,`--description="<what it is>"`],[t])}. If it should not be: ${r}`:`${n}. Its name is one the packages table cannot hold, so it cannot be registered — if that is the answer, record it: ${r}`},jb=(e,t,n)=>{let r=`${e.name}: moved to ${e.path??Ob} — update the entry's path (${n})`,i=bv([`--package=${Q(e.name)}`],[t,`path`,e.path??``]);return ul.safeParse(e.path).success?`${r}. To fix it: ${i}`:r},Mb=(e,t)=>{let n=`configured: ${e.configured_path??Ob}`;if(e.status===`relocated`)return jb(e,t,n);if(e.status===`missing`){let r=bv([`--package=${Q(e.name)}`,`--remove`],[t]);return`${e.name}: gone from this repo's workspaces (${n}) — repoint the entry if it moved out of them, or unregister it: ${r}`}if(e.status===`ambiguous`){let t=(e.candidates??[]).join(`, `);return`${e.name}: declared at several paths (${t}) — point the entry at one (${n})`}return`${e.name}: could not be checked — ${e.reason??`(no reason given)`} (${n})`},Nb=(e,t)=>e.status===`unregistered`?Ab(e,t):Mb(e,t),Pb=e=>`could not check for unregistered packages — ${e}`,Fb=e=>`…and ${e} more finding(s) — act on the ones above (register, repoint or decline) and run the check again to see the rest`,Ib=e=>{let t=e.length-10;return t<=0?[...e]:[...e.slice(0,10),Fb(t)]},Lb=(e,t)=>{if(e.reason!==void 0)return[`could not be checked — ${e.reason}`];let n=Ib((e.packages??[]).map(e=>Nb(e,t)));return e.discovery_incomplete===void 0?n:[...n,Pb(e.discovery_incomplete)]},Rb=e=>{let t;return()=>(t??=Y_(e),t)},zb=async(e,t,n)=>{let r=await f_(e);if(r===void 0||t.some(e=>e.packageName===r.name))return{issues:[]};let i=await n();if(!Kh(i))return{incomplete:ty(i),issues:[]};let a=ng(i.packages,r.name);return a.kind===`ambiguous`?{issues:[{candidates:a.paths,name:r.name,status:`unregistered`}]}:{issues:a.kind===`found`?[{name:r.name,path:a.path,status:`unregistered`}]:[]}},Bb=e=>{let t=new Map;for(let n of e)t.set(n.name,[...t.get(n.name)??[],n.path]);return t},Vb=(e,t)=>{let n=new Set(e.changedDirs),r=t.filter(e=>!n.has(e.path)).map(e=>e.name);return new Set([...e.namesBefore,...r])},Hb=(e,t)=>t.length===1&&t[0]!==void 0?{name:e,path:t[0],status:`unregistered`}:{candidates:[...t],name:e,status:`unregistered`},Ub=async(e,t,n)=>{if(t.kind===`arrivals`&&t.changedDirs.length===0)return{issues:[]};let r=await n();if(!Kh(r))return{incomplete:ty(r),issues:[]};let i=new Set(e.map(e=>e.packageName)),a=r.packages.filter(e=>e.path!==`.`),o=t.kind===`all`?void 0:Vb(t,a);return{issues:[...Bb(a)].filter(([e])=>!i.has(e)).filter(([e])=>o===void 0||!o.has(e)).map(([e,t])=>Hb(e,t)).toSorted((e,t)=>e.name.localeCompare(t.name))}},Wb=(e,t)=>{if(t.length===0)return{issues:[...e],suppressed:[]};let n=(e,n)=>t.some(t=>t.name===e&&t.path===n),r=[];return{issues:e.flatMap(e=>{if(e.status!==`unregistered`)return[e];let t=e.path===void 0?e.candidates??[]:[e.path],i=t.filter(t=>!n(e.name,t)),a=t.filter(t=>n(e.name,t));return r.push(...a.map(t=>({name:e.name,path:t}))),i.length===0?[]:[Hb(e.name,i)]}),suppressed:r}},Gb=(e,t)=>({path:e.configuredPath,reason:t,status:`unverifiable`}),Kb=(e,t)=>qh(t)?{configuredPath:e.configuredPath,path:null,status:`missing`}:Gb(e,`this repo declares no workspaces, so there was nowhere to search`),qb=(e,t)=>t===e.configuredPath,Jb=e=>e.packages.filter(e=>e.path!==`.`),Yb=(e,t)=>{let n=ng(Jb(t),e.packageName);return n.kind===`ambiguous`?{candidates:n.paths,configuredPath:e.configuredPath,path:null,status:`ambiguous`}:Kh(t)?n.kind===`absent`?Kb(e,t):qb(e,n.path)?Gb(e,`the checkout changed while it was being inspected`):{configuredPath:e.configuredPath,path:n.path,status:`relocated`}:Gb(e,n.kind===`found`?`workspace detection was incomplete, so the new location is not confirmed unique`:`workspace detection was incomplete`)},Xb=e=>{let t=new Map(Object.entries(e??{}));return[...t.keys()].toSorted().flatMap(e=>{let n=t.get(e);return n===void 0?[]:[{configuredPath:n.path,packageName:e}]})},Zb=async(e,t)=>{let n=await $h(e,t.configuredPath,t.packageName);if(n.kind===`match`)return{path:t.configuredPath,status:`verified`};if(n.kind===`unreadable`)return{path:t.configuredPath,reason:n.reason,status:`unverifiable`}},Qb=e=>e.flatMap(e=>e.settled===void 0?[]:[{outcome:e.settled,query:e.query}]),$b=async(e,t,n)=>{let r=await Promise.all(t.map(async t=>({query:t,settled:await Zb(e,t)})));if(r.every(e=>e.settled!==void 0))return Qb(r);let i=await n();return r.map(e=>({outcome:e.settled??Yb(e.query,i),query:e.query}))},ex=e=>{let{outcome:t,query:n}=e;return Tb(t.status)?[{...t.candidates===void 0?{}:{candidates:t.candidates},configured_path:n.configuredPath,name:n.packageName,...t.status===`relocated`&&t.path!==null?{path:t.path}:{},...t.reason===void 0?{}:{reason:t.reason},status:t.status}]:[]},tx=(e,t)=>{let n=new Set(e.map(e=>e.name));return[...e,...t.filter(e=>!n.has(e.name))]},nx=async(e,t,n)=>{let r=Xb(t.packages),[i]=r;if(i===void 0)return{status:`ok`};let a=Rb(e);try{let[i,o,s]=await Promise.all([$b(e,r,a),zb(e,r,a),Ub(r,n,a)]),c=Wb([...i.flatMap(e=>ex(e)),...tx(o.issues,s.issues)],t.declined_packages??[]);return Db(c.issues,{declined:c.suppressed,...(s.incomplete??o.incomplete)===void 0?{}:{discoveryIncomplete:s.incomplete??o.incomplete}})}catch(e){return{reason:_v(e),status:`unknown`}}},rx=async(e,t,n)=>{try{return await W(e,Bv(n.key),()=>nx(n.dest,t.refs[n.key]??{},{kind:`all`}),{timeoutMs:100})}catch(e){if(e instanceof g&&e.code===`conflict`)return{reason:`another refs process is holding this ref`,status:`unknown`};throw e}},ix=`config-drift`,ax=e=>e===0?``:` (${e} declined package(s) not reported)`,ox=(e,t)=>{let{declined:n,findings:r,lines:i}=e,[a]=i;return a===void 0?{detail:`every configured package path resolves in ${t} checkout(s)${ax(n)}`,name:ix,status:`ok`}:{detail:`${i.join(`; `)}${ax(n)}`,findings:r,name:ix,status:`warn`}},sx=async(e,t,n)=>{let[r,...i]=n;if(r===void 0)return{declined:0,findings:[],lines:[]};let a=await rx(e,t,r),o=await sx(e,t,i),s=a.packages??[];return{declined:(a.declined??[]).length+o.declined,findings:s.length===0?o.findings:[{key:r.key,packages:s},...o.findings],lines:[...Lb(a,r.key).map(e=>`${r.key}: ${e}`),...o.lines]}},cx=async(e,t)=>{let n=cb(e,t);return ox(await sx(e,t,n),n.length)},lx=e=>{let{diagnosis:t}=e;return e.kind===`claim`||!e.isDirectory||t.pidState===`definitely-dead`||t.stale||t.meta===`malformed`||t.meta===`unreadable`||t.policy===`unknown`?!1:t.ageMs===void 0||t.ageMs>=0},ux=e=>{let{ageMs:t,budgetMs:n,policy:r}=e;return r===`unknown`?`, state could not be read`:t===void 0||n===void 0?``:t<0?`, recorded time is in the future — check the system clock`:`, ${Cp(t)} into a ${Cp(n)} window`},dx=e=>e.pid===void 0?`owner unknown (metadata ${e.meta})`:e.pidState===`definitely-dead`?`recorded pid ${e.pid} is not running`:`recorded pid ${e.pid} present`,fx=(e,t)=>{let n=m(e.locksDir,sp,t.name),r=t.diagnosis.ageMs===void 0?``:` for ${Cp(t.diagnosis.ageMs)}`;return`steal claim on ${t.name}: present${r}. Stealing this lock is blocked while it is here. A reclaim in progress clears it within a moment; if it stays, ${px}: ${Sv(n)}`},px=`stop every refs process using this home — including suspended ones — and then run`,mx=(e,t)=>{let{diagnosis:n}=t;if(tp(n))return`, reclaimable now`;if(!n.stale&&t.isDirectory)return``;let r=m(e.locksDir,t.name);return`, not automatically reclaimable — if it is genuinely abandoned, ${px}: ${xv(r)}`},hx=(e,t)=>{let{diagnosis:n}=t,r=t.isDirectory?``:`not a directory, `,i=mx(e,t);return`${t.name}: ${r}${dx(n)}${ux(n)}${i}`},gx=async e=>{let t=await Sp(e),[n]=t;return n===void 0?{detail:`no locks held`,name:`locks`,status:`ok`}:{detail:t.map(t=>t.kind===`claim`?fx(e,t):hx(e,t)).join(`; `),name:`locks`,status:t.every(e=>lx(e))?`ok`:`warn`}},_x=[`.agents`,`skills`,`refs`,`SKILL.md`],vx=[`skills`,`refs`,`SKILL.md`],yx=[`.claude`,`skills`,`refs`,`SKILL.md`],bx=`npx skills add kaisers-io/refs`,xx=`npm i -g @kaisers-io/refs@latest`,Sx=(e,t)=>e===void 0?void 0:{display:t,path:e},Cx=e=>{let{dirName:t,env:n,home:r,overrideName:i}=e,a=n[i]?.trim();return a!==void 0&&a.length>0?{display:a,path:a}:Sx(r===void 0?void 0:m(r,t),`~/${t}`)},wx=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:Sx(t,`~/.agents`),segments:_x},{label:`Claude Code`,root:Cx({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:vx},{label:`Codex`,root:Cx({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:vx},{label:`project ./.agents`,root:Sx(e.cwd,`./.agents`),segments:_x},{label:`project ./.claude`,root:Sx(e.cwd,`./.claude`),segments:yx}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:m(t.path,...n)}])},Tx=async(e,t)=>{try{let n=await l(e);return{label:t,realPath:n,source:await s(n,`utf8`)}}catch{return}},Ex=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},Dx=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,Ox=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,kx=e=>{let t=Dx.exec(e)?.groups?.body;if(t!==void 0)return Ox.exec(t)?.groups?.version},Ax=(e,t)=>{if(e===t)return`match`;let n=zg(e,t);return n===void 0?`unknown`:n===0?`match`:n>0?`cli-older`:`skill-older`},jx={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${xx}`,match:(e,t)=>`the refs skill is installed and matches this CLI (${t})`,"skill-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the skill: ${bx}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${xx} and ${bx}`},Mx=e=>{let{cliVersion:t,label:n,skillVersion:r}=e;if(r===void 0)return{detail:`the refs skill (${n}) predates the version gate — update it: ${bx}`,name:`skill`,status:`warn`};let i=Ax(r,t);return{detail:`${n}: ${jx[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},Nx=e=>({detail:`refs skill not found in the locations this check knows about (${e.map(e=>e.display).join(`, `)}) — an install anywhere else is invisible here and still works; if it really is missing: ${bx}`,name:`skill`,status:`warn`}),Px=async e=>{let t=wx(e),n=await Promise.all(t.map(e=>Tx(e.path,e.label))),r=Ex(n.filter(e=>e!==void 0)).map(t=>Mx({cliVersion:e.cliVersion,label:t.label,skillVersion:kx(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??Nx(t)},Fx=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,Ix=e=>e===``?{}:{user:e},Lx=e=>e===``?{}:{port:e},Rx=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...Ix(t.username),...Lx(t.port)}:void 0}catch{return}},zx=e=>{let t=Fx.exec(e),n=t?.groups?.host;return n===void 0?Rx(e):{host:n,user:t?.groups?.user??`git`}},Bx=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,Vx=e=>e.user===void 0?Bx(e):`${e.user}@${Bx(e)}`,Hx=e=>{let t=Object.values(e.refs).map(e=>zx(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(Vx(e),e);return[...n.values()].toSorted((e,t)=>Vx(e).localeCompare(Vx(t)))},Ux=/Permission denied/u,Wx=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],Gx=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,Kx=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=Gx(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},qx=async(e,t,n)=>{let r=Vx(t),i=await e.runner.run(`ssh`,Kx(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:Ux.test(i.stderr)?{host:r,outcome:`denied`}:Wx.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},Jx=(e,t)=>{let n=e.filter(e=>e.outcome===`timeout`).map(e=>e.host);if(n.length!==0)return{detail:`ssh probe timed out after ${t/1e3}s: ${n.join(`, `)}`,name:`ssh-auth`,status:`fail`}},Yx=e=>{let t=e.filter(e=>e.outcome===`denied`).map(e=>e.host);if(t.length!==0)return{detail:`ssh permission denied for: ${t.join(`, `)}`,name:`ssh-auth`,status:`fail`}},Xx=e=>{let t=e.filter(e=>e.outcome===`connection-warn`);if(t.length!==0)return{detail:`ssh connection issue, treated as warn: ${t.map(e=>`${e.host} (${e.detail??``})`).join(`; `)}`,name:`ssh-auth`,status:`warn`}},Zx=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),Qx=(e,t)=>Jx(e,t)??Yx(e)??Xx(e)??Zx(e),$x=async(e,t,n)=>{let r=Hx(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>qx(e,t,i)));return Qx(a,i)},eS=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${_v(t)}`,name:e.name,status:`fail`}}},tS=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await eS(t),i=await tS(n);return r===void 0?i:[r,...i]},nS=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Zy(n)},{name:`node`,run:()=>Promise.resolve(tb(n))},{name:`config`,run:()=>Promise.resolve(ib(t.errorMessage))},{name:`hooks-guard`,run:()=>mb(n,r,t.config)},{name:`dirty-checkouts`,run:()=>_b(n,r,t.config)},{name:`config-drift`,run:()=>cx(r,t.config)},{name:`orphans`,run:()=>wb(r,t.config,i)},{name:`locks`,run:()=>gx(r)},{name:`skill`,run:()=>Px(n)},{name:`cli-update`,run:()=>sb(n,t.config)},{name:`ssh-auth`,run:()=>$x(n,t.config)}]},rS=async e=>{let t=z(e.env),n=await rb(t),r=await vb(t);return tS(nS({configLoad:n,ctx:e,home:t,state:r}))},iS={fail:`FAIL`,ok:`OK`,warn:`WARN`},aS=e=>e.map(e=>`[${iS[e.status]}] ${e.name}: ${e.detail}`),oS=e=>e.some(e=>e.status===`fail`),sS=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, drift, locks, ssh).`).action((e,n)=>{let r=Y(n);return Z(t,r,async()=>{let e=await rS(t);X(t,r,aS(e),{checks:e}),oS(e)&&(process.exitCode=Se.UNEXPECTED)})()})},cS=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},lS=(e,t)=>{if(!H(e))throw _(`checkout for '${t}' is missing — run: refs sync ${t}`)},uS=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw _(`no package '${n}' registered on ref '${t}'`);return r},dS=`never`,fS=(e,t,n)=>e===void 0||n-Date.parse(e)>t,pS=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,mS=(e,t)=>{if(e===void 0)return dS;let n=t-Date.parse(e);if(Number.isNaN(n))return dS;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return pS(i,`minute`);let a=Math.floor(i/60);if(a<24)return pS(a,`hour`);let o=Math.floor(a/24);return o<365?pS(o,`day`):pS(Math.floor(o/365),`year`)},hS=e=>{let t=mS(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==dS&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},gS=(e,t,n)=>{let r=e.state.refs[t],i=ol(jg(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:jg(`clone_mode`,n,e.settings),description:n.description,key:t,...r?.last_fetched_at===void 0?{}:{last_fetched_at:r.last_fetched_at},missing:!H(B(e.home,il.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:fS(r?.last_fetched_at,i,e.now)}},_S=e=>{let t={home:e.home,includePackages:e.includePackages,now:e.now,settings:e.config.settings,state:e.state};return Object.entries(e.config.refs).map(([e,n])=>gS(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},vS=async(e,t,n)=>{let r=z(e.env),i=await V(r),a=await Pg(r);return _S({config:i,home:r,includePackages:t,now:n,state:a})},yS=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...hS({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],bS=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...yS(n,t)),e),[]),xS=e=>e.split(`/`),SS=(e,t)=>{let n=xS(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},CS=(e,t)=>{if(Object.hasOwn(e.refs,t))return il.parse(t);let n=xS(t),r=Object.keys(e.refs).filter(e=>SS(e,n)).toSorted(),[i]=r;if(i===void 0)throw _(`no ref matches '${t}'`);if(r.length>1)throw v(`'${t}' matches more than one ref: ${r.join(`, `)}`);return il.parse(i)},wS=(e,t)=>{e.command(`list`).description(`List configured refs with their staleness/missing checkout status.`).option(`--packages`,`include each ref's package names in --json output (off by default)`).action((e,n)=>{let r=Y(n);return Z(t,r,async()=>{let n=Date.now(),i=await vS(t,e.packages===!0,n);X(t,r,bS(i,n),i)})()})},TS=e=>e===void 0?null:e,ES=(e,t)=>e.name===t.name&&e.path===t.path,DS=(e,t)=>{let n=(e.declined_packages??[]).filter(e=>!ES(e,t));if(n.length===0){let{declined_packages:t,...n}=e;return n}return{...e,declined_packages:n}},OS=(e,t)=>`package '${e.name}' at '${e.path}' is already declined on ref '${t}'`,kS=(e,t)=>`package '${e.name}' at '${e.path}' is not declined on ref '${t}' — nothing to undo`,AS=(e,t)=>`package '${e}' is registered on ref '${t}' — declining applies to packages the configuration does not have; unregister it first with --remove`,jS=(e,t,n)=>{if(Object.hasOwn(e.packages??{},t.name))throw y(AS(t.name,n));let r=e.declined_packages??[];if(r.some(e=>ES(e,t)))throw y(OS(t,n));return{...e,declined_packages:[...r,t]}},MS=e=>{if(e.declined)return jS(e.entry,e.record,e.key);if(!(e.entry.declined_packages??[]).some(t=>ES(t,e.record)))throw y(kS(e.record,e.key));return DS(e.entry,e.record)},NS=(e,t)=>{let n=z(e.env);return W(n,`home`,async()=>{let e=await V(n),r=CS(e,t.query),i=cS(e,r),a={name:t.packageName,path:t.path},o=MS({declined:t.declined,entry:i,key:r,record:a});return await fu(n,{...e,refs:{...e.refs,[r]:o}}),{declined:t.declined,field:`declined_packages`,key:r,new:t.declined?a:null,old:t.declined?null:a}})},PS=`packages`,FS=()=>Object.keys(hl.shape).toSorted().join(`, `),IS=e=>`unknown package field '${e}' — valid fields: ${FS()}`,LS=e=>Object.hasOwn(hl.shape,e),RS=(e,t,n)=>{if(!LS(t))throw v(IS(t));let r=e[t],i=hl.safeParse({...e,[t]:n});if(!i.success)throw y(T(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},zS=async e=>{let t=uS(e.entry,e.key,e.packageName),n=RS(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await fu(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:TS(n.newValue),old:TS(n.oldValue)}},BS=(e,t)=>`package '${e}' is already registered on ref '${t}' — edit its fields instead`,VS=(e,t)=>{let n=z(e.env);return W(n,`home`,async()=>{let e=await V(n),r=CS(e,t.query),i=cS(e,r);if(Object.hasOwn(i.packages??{},t.packageName))throw y(BS(t.packageName,r));let a=gl.safeParse({...DS(i,{name:t.packageName,path:t.path}),packages:{...i.packages,[t.packageName]:{description:t.description,path:t.path}}});if(!a.success)throw y(T(a.error));return await fu(n,{...e,refs:{...e.refs,[r]:a.data}}),{created:!0,field:PS,key:r,new:{description:t.description,name:t.packageName,path:t.path},old:null}})},HS=(e,t)=>`package '${e}' is not registered on ref '${t}' — nothing to remove`,US=(e,t)=>{let n=z(e.env);return W(n,`home`,async()=>{let e=await V(n),r=CS(e,t.query),i=cS(e,r),a=i.packages??{};if(!Object.hasOwn(a,t.packageName))throw y(HS(t.packageName,r));let{[t.packageName]:o,...s}=a,c=Object.keys(s).length===0?WS(i):{...i,packages:s};return await fu(n,{...e,refs:{...e.refs,[r]:c}}),{field:PS,key:r,new:null,old:{description:o?.description??``,name:t.packageName,path:o?.path??``},removed:!0}})},WS=e=>{let{packages:t,...n}=e;return n},GS=e=>e.second===void 0&&e.value===void 0,KS=e=>{let{description:t,path:n}=e.create,{packageName:r}=e;if(r===void 0||t===void 0||n===void 0||!GS(e))throw v(`--create registers a new package: it needs --package <name>, --path <path> and --description <text>, and takes no <field> <value> arguments`);return{description:t,packageName:r,path:n}},qS=e=>{let{packageName:t}=e;if(t===void 0||e.create.path!==void 0||!GS(e)||e.create.description!==void 0)throw v(`--remove unregisters a package: it needs --package <name>, and takes no <field> <value> arguments, no --path and no --description`);return{packageName:t}},JS=e=>{let{packageName:t}=e,{path:n}=e.create;if(t===void 0||n===void 0||!GS(e)||e.create.description!==void 0)throw v(`--decline and --undecline record a decision about one package at one path: each needs --package <name> and --path <path>, and takes no <field> <value> arguments and no --description`);return{packageName:t,path:n}},YS=[`create`,`remove`,`decline`,`undecline`],XS=e=>{let t=YS.filter(t=>e[t]===!0);if(t.length>1)throw v(`use one of --create, --remove, --decline or --undecline: they are different answers about the same package, and running two at once would guess which one was meant`);return t[0]},ZS=(e,t,n)=>t===`create`?VS(e,{...KS(n),query:n.first}):t===`remove`?US(e,{...qS(n),query:n.first}):NS(e,{...JS(n),declined:t===`decline`,query:n.first}),QS=`packages`,$S=()=>Object.keys(gl.shape).filter(e=>e!==QS).toSorted().join(`, `),eC=e=>`unknown ref field '${e}' — valid fields: ${$S()}`,tC=e=>Object.hasOwn(gl.shape,e),nC=(e,t,n)=>`failed to rewrite git remote at ${e} to '${U(t)}': ${n.trim()}`,rC=async(e,t)=>{if(iu(t.home,t.dest),!H(t.dest))return;let n=await e.runner.run(`git`,[`remote`,`set-url`,`--`,`origin`,t.cloneUrl],{cwd:t.dest});if(n.exitCode!==0)throw y(nC(t.dest,t.cloneUrl,n.stderr))},iC=async(e,t)=>{let n=_f(t.value,{allowFileUrls:Vv(e.env)});if(n.key!==t.key)throw y(`new url derives a different key — remove and re-add instead`);let r=B(t.home,t.key);return await rC(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},aC=(e,t,n)=>{let r={...e,[t]:n},i=gl.safeParse(r);if(!i.success)throw y(T(i.error));return i.data},oC=(e,t)=>t.field===`url`?iC(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(aC(t.entry,t.field,t.value)),sC=async(e,t)=>{let{field:n}=t;if(n===QS)throw v(`use --package <name> <field> <value>`);if(!tC(n))throw v(eC(n));let r=t.entry[n],i=await oC(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},cC=(e,t)=>{let n=z(e.env),{field:r,opts:i,query:a,value:o}=t;return W(n,`home`,async()=>{let t=await V(n),s=CS(t,a),c=cS(t,s);if(i.packageName!==void 0)return zS({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await sC(e,{entry:c,field:r,home:n,key:s,value:o});return await fu(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:TS(l.new),old:TS(l.old)}})},lC=`settings`,uC=[],dC=()=>Object.keys(fl.shape).toSorted().join(`, `),fC=e=>`unknown setting '${e}' — valid settings: ${dC()}`,pC=e=>Object.hasOwn(fl.shape,e),mC=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,hC=e=>{try{let t=CS(e,lC);return[mC(`ref '${t}'`)]}catch(e){if(e instanceof g&&e.code===`usage`)return[mC("one of several matching refs — see `refs list`")];if(e instanceof g&&e.code===`not_found`)return uC;throw e}},gC=e=>({data:{field:e.key,key:lC,new:TS(e.parsed[e.key]),old:TS(e.old)},warnings:hC(e.config)}),_C=(e,t)=>{let n=z(e.env);return W(n,`home`,async()=>{let e=await V(n);if(!pC(t.key))throw v(fC(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=fl.safeParse(i);if(!a.success)throw y(T(a.error));return await fu(n,{...e,settings:a.data}),gC({config:e,key:t.key,old:r,parsed:a.data})})},vC=[],yC=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},bC=e=>{if(e.second===void 0||e.value===void 0)throw v(`missing <field> and <value> — see 'refs edit --help'`);return{field:e.second,value:e.value}},xC=(e,t,n)=>{if(t.opts.packageName!==void 0)throw v(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return _C(e,n)},SC=async(e,t)=>{if(t.create.description!==void 0||t.create.path!==void 0)throw v(`--path and --description only apply to the package modes — to change one field of a registered package use: refs edit <ref> <field> <value> --package <name>`);let{field:n,value:r}=bC(t);return t.first===`settings`?xC(e,t,{key:n,value:r}):{data:await cC(e,{field:n,opts:t.opts,query:t.first,value:r}),warnings:vC}},CC=async(e,t)=>{let n=XS(t.create);return n===void 0?SC(e,t):{data:await ZS(e,n,{create:t.create,first:t.first,packageName:t.opts.packageName,second:t.second,value:t.value}),warnings:vC}},wC=e=>e==null?`(unset)`:String(e),TC=(e,t)=>{let n=t?e.new:e.old,r=t?`declined`:`no longer declining`;return`${e.key}: ${r} '${n.name}' at ${n.path}`},EC=e=>{if(e.created===!0){let t=e.new;return`${e.key}: registered '${t.name}' at ${t.path}`}if(e.removed===!0){let t=e.old;return`${e.key}: unregistered '${t.name}' (was at ${t.path})`}return e.declined===void 0?void 0:TC(e,e.declined)},DC=e=>{let t=EC(e);return t===void 0?[`${e.key}: ${e.field} '${wC(e.old)}' -> '${wC(e.new)}'`]:[t]},OC=(e,t)=>{e.command(`edit`).description(`Edit one field: 'refs edit settings <key> <value>' for a global setting, or 'refs edit <ref> <field> <value> [--package <name>]' for a ref or package field. With --create, registers a package the config does not have yet; with --remove, unregisters one it has; with --decline, records that a package the checkout declares is deliberately not registered, so drift stops reporting it.`).argument(`<ref-or-settings>`,`a ref key/unique suffix, or the literal 'settings'`).argument(`[field-or-key]`,`field to edit (or, in settings mode, the setting key)`).argument(`[value]`,`the new value`).option(`--package <name>`,`edit this package's field instead of a top-level ref field`).option(`--create`,`register --package as a new package on this ref`).option(`--remove`,`unregister --package from this ref, leaving the checkout alone`).option(`--decline`,`record that --package at --path is deliberately not registered`).option(`--undecline`,`withdraw a decline, so the package is reported again`).option(`--path <path>`,`with --create/--decline/--undecline: the package path, relative to the checkout root`).option(`--description <text>`,`with --create: what the package is`).action((e,n,r,i,a)=>{let o=Y(a);return Z(t,o,async()=>{let{data:a,warnings:s}=await CC(t,{create:i,first:e,opts:yC(i),second:n,value:r});X(t,o,DC(a),a,s)})()})},kC=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,AC={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},jC=async e=>{await a(e.root,{recursive:!0}),await a(e.sourcesDir,{recursive:!0}),await a(e.locksDir,{recursive:!0}),await a(e.hooksDir,{recursive:!0})},MC=async e=>{let t=z(e.env);return await jC(t),{config:await W(t,`home`,async()=>{let e=await Su(t,X_);return await Pd(t),e}),home:t.root,skill_hint:kC}},NC=(e,t)=>{e.command(`init`).description(`Seed or migrate the refs home directory, its config, and the git hooks guard.`).action((e,n)=>{let r=Y(n);return Z(t,r,async()=>{let e=await MC(t);X(t,r,[`home: ${e.home}`,`config: ${AC[e.config]}`,``,kC],e)})()})},PC=async e=>{let t=z(e.env),n=await W(t,`home`,()=>Su(t,X_));return n===`migrated`?{backup:eu(t),result:n}:{backup:null,result:n}},FC=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${re(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,IC=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=Y(n);return Z(t,r,async()=>{let e=await PC(t);X(t,r,FC(e),e)})()})},LC=async e=>{try{return await i(e),!0}catch(e){if(R(e))return!1;throw e}},RC=async e=>{try{return await c(e)}catch(e){if(R(e))return;throw e}},zC=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(R(e))return;throw e}},BC=async e=>{let t=await RC(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await f(e)}catch(e){if(!R(e))throw e}return!0},VC=async e=>{let t=await zC(e);return t===void 0?!0:t?BC(e):!1},HC=async(e,t)=>{t!==e.sourcesDir&&await VC(t)&&await HC(e,ie(t))},UC=async(e,t)=>await LC(t)?(iu(e,t),await d(t,{force:!0,recursive:!0}),await HC(e,ie(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},WC=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),GC=async(e,t)=>{let n=await V(e),r={...n,refs:WC(n.refs,t)};await fu(e,r);let i=await Pg(e),a={...i,refs:WC(i.refs,t)};await Fg(e,a)},KC=async(e,t)=>{let n=z(e.env),r=await V(n),i=CS(r,t),a=B(n,i),{removedCheckout:o,warning:s}=await W(n,Bv(i),()=>UC(n,a));return await W(n,`home`,()=>GC(n,i)),{data:{key:i,removed_checkout:o},warnings:gv(s)}},qC=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],JC=(e,t)=>{e.command(`remove`).description(`Remove a configured ref: its config/state entry AND its checkout directory.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=Y(r);return Z(t,i,async()=>{let{data:n,warnings:r}=await KC(t,e);X(t,i,qC(n),n,r)})()})},YC=async e=>{let t=await $h(e.checkoutDir,e.configuredPath,e.packageName);return t.kind===`match`?{path:e.configuredPath,status:`verified`}:t.kind===`unreadable`?{path:e.configuredPath,reason:t.reason,status:`unverifiable`}:XC(e)},XC=async e=>Yb(e,await Y_(e.checkoutDir)),ZC=async e=>{try{return await W(e.home,Bv(e.key),()=>YC(e),e.lockTimeoutMs===void 0?void 0:{timeoutMs:e.lockTimeoutMs})}catch(t){if(t instanceof g&&t.code===`conflict`)return{path:e.configuredPath,reason:`could not acquire the ref lock in time`,status:`unverifiable`};throw t}},QC=async e=>{if(!H(e.checkoutDir))return{path:e.configuredPath,status:`unmaterialized`};let t=await $h(e.checkoutDir,e.configuredPath,e.packageName);return t.kind===`match`?{path:e.configuredPath,status:`verified`}:t.kind===`unreadable`?{path:e.configuredPath,reason:t.reason,status:`unverifiable`}:(e.onProbed?.(),ZC(e))},$C=(e,t)=>({local_path:null,name:e,path:null,reason:t,status:`unverifiable`}),ew=async e=>{if(!e.checkoutManaged)return $C(e.packageName,e.checkoutReason);let t=await QC(e);return{...t.candidates===void 0?{}:{candidates:t.candidates},...t.configuredPath===void 0?{}:{configured_path:t.configuredPath},local_path:t.path===null?null:m(e.checkoutDir,t.path),name:e.packageName,path:t.path,...t.reason===void 0?{}:{reason:t.reason},status:t.status}},tw=e=>[`package: ${e.name}`,`package path: ${e.local_path??`(unknown)`}`,...e.status===`verified`?[]:[`package status: ${e.status}`],...e.configured_path===void 0?[]:[`configured path: ${e.configured_path}`],...e.candidates===void 0?[]:[`candidates: ${e.candidates.join(`, `)}`],...e.reason===void 0?[]:[`reason: ${e.reason}`]],nw=`node_modules`,rw=[`.pnp.cjs`,`.pnp.js`],iw=new Set([``,`.`,`..`]),aw=e=>!ae(e)&&!e.includes(`\\`)&&e.split(`/`).every(e=>!iw.has(e)),ow=function*(e){let t=ce(e);for(;;){re(t)!==nw&&(yield m(t,nw));let e=ie(t);if(e===t)return;t=e}},sw=async e=>{if(await uw(e)!==`absent`)try{let t=JSON.parse(await s(e,`utf8`)),{name:n,version:r}=typeof t==`object`&&t?t:{};return typeof r!=`string`||r===``?{package_json:e,reason:`manifest_has_no_version`,status:`unverifiable`}:{...typeof n==`string`?{name:n}:{},package_json:e,status:`found`,version:r}}catch{return{package_json:e,reason:`manifest_unreadable`,status:`unverifiable`}}},cw=new Set([`ENOENT`,`ENOTDIR`]),lw=async e=>{try{return(await c(e)).length===0}catch{return!1}},uw=async e=>{try{return await p(e),`present`}catch(e){let t=typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0;return t!==void 0&&cw.has(t)?`absent`:`unreadable`}},dw=async e=>{for(let t of ow(e)){let e=ie(t);if((await Promise.all(rw.map(t=>uw(m(e,t))))).includes(`present`))return!0}return!1},fw=async e=>{try{if(!(await p(e)).isDirectory())throw v(`--project must be a directory: ${e}`)}catch(t){throw t instanceof Error&&t.message.startsWith(`--project`)?t:v(`--project path does not exist: ${e}`)}},pw=async e=>{let t=await uw(e);if(t===`unreadable`)return{reason:`slot_unreadable`,status:`unverifiable`};if(t===`absent`)return;let n=await sw(m(e,`package.json`));return n===void 0?await lw(e)?void 0:{reason:`installed_without_manifest`,status:`unverifiable`}:n},mw=async(e,t)=>{if(!aw(t))return{reason:`unsupported_package_name`,status:`unverifiable`};for(let n of ow(e)){let e=await pw(m(n,...t.split(`/`)));if(e!==void 0)return e}return await dw(e)?{reason:`yarn_pnp`,status:`unsupported_layout`}:{status:`not_materialized`}},hw={'"':`"`,"\\":`\\`,b:`\b`,n:`
351
+ `,t:` `},gw={'"':`"`,"\\":`\\`},_w=new Set([` `,` `]),$=Symbol(`malformed git config`),vw=e=>e!==void 0&&!e.quoted&&_w.has(e.char),yw=e=>{let t=0,n=e.length;for(;t<n&&vw(e[t]);)t+=1;for(;n>t&&vw(e[n-1]);)--n;return e.slice(t,n).map(e=>e.char).join(``)},bw=e=>{let t=[],n=!1;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`\\`){r+=1;let n=hw[e[r]??``];if(n===void 0)return $;t.push({char:n,quoted:!0})}else if(i===`"`)n=!n;else if(!n&&(i===`#`||i===`;`))return yw(t);else t.push({char:i??``,quoted:n})}return n?$:yw(t)},xw=e=>{let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`\\`){n+=1;let r=gw[e[n]??``];if(r===void 0)return $;t+=r}else t+=r??``}return t},Sw=/^[ \t]+|[ \t]+$/gu,Cw=e=>e.replace(Sw,``),ww=/^\[[ \t]*(?<section>[A-Za-z0-9.-]+)[ \t]*(?:"(?<subsection>(?:[^"\\]|\\.)*)")?[ \t]*\]/u,Tw=/^(?<name>[A-Za-z][A-Za-z0-9-]*)[ \t]*(?:=[ \t]*(?<value>.*))?$/u,Ew=function*(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`
352
352
  `)yield t,t=``,n=!1,r=!1;else if(a!==`\r`||e[i+1]!==`
353
353
  `){if(r)t+=a;else if(a===`\\`){let n=e[i+1];n===`
354
354
  `||n===`\r`&&e[i+2]===`
355
- `?i+=n===`\r`?2:1:(t+=a+(n??``),i+=1)}else a===`"`?n=!n:!n&&(a===`#`||a===`;`)&&(r=!0),t+=a}}t!==``&&(yield t)},BC=(e,t)=>e.subsection===void 0?`${e.name}.${t.toLowerCase()}`:`${e.name}.${e.subsection}.${t.toLowerCase()}`,VC=(e,t)=>{let n=e.toLowerCase();if(t===void 0)return{name:n};let r=PC(t);return r===$?$:{name:n,subsection:r}},HC=e=>{let t=LC.exec(e),n=t?.groups?.section;if(n===void 0)return;let r=IC(e.slice(t?.[0].length??0)),i=VC(n,t?.groups?.subsection);return i===$?$:{rest:r,section:i}},UC=e=>e===``||e.startsWith(`#`)||e.startsWith(`;`),WC=e=>{let t=RC.exec(e),n=t?.groups?.name;if(n===void 0)return $;let r=NC(t?.groups?.value??``);return r===$?$:{name:n,value:r}},GC=(e,t)=>{let n=WC(t.line);if(n===$)return`malformed`;let r=BC(t.section,n.name);return t.wanted.includes(r)&&e.set(r,[...e.get(r)??[],n.value]),`ok`},KC=(e,t,n)=>t.rest===``||UC(t.rest)?t.section:GC(e,{line:t.rest,section:t.section,wanted:n})===`malformed`?$:t.section,qC=(e,t)=>{let n=HC(t.line);return n===$?$:n===void 0?t.section===JC||GC(e,t)===`malformed`?$:t.section:KC(e,n,t.wanted)},JC={name:``},YC=(e,t)=>{let n=new Map,r=JC;for(let i of zC(e)){let e=IC(i),a=UC(e)?r:qC(n,{line:e,section:r,wanted:t});if(a===$)return;r=a}return n},XC=`core.hookspath`,ZC=`remote.origin.url`,QC=[XC,ZC],$C={status:`managed`},ew={status:`missing`},tw=e=>({reason:e,status:`unmanaged`}),nw=e=>({reason:e,status:`unverifiable`}),rw=new Set([`ENOENT`,`ENOTDIR`]),iw=e=>typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0,aw=async e=>{try{return await i(e),`present`}catch(e){let t=iw(e);return t!==void 0&&rw.has(t)?`absent`:`unreadable`}},ow=async e=>{try{let t=await i(m(e,`.git`));return t.isSymbolicLink()?tw(`git_is_symlink`):t.isDirectory()?void 0:tw(`git_is_file`)}catch(e){let t=iw(e);return t!==void 0&&rw.has(t)?tw(`no_git`):nw(`git_unreadable`)}},sw=(e,t)=>{let n=e.get(t);if(n===void 0||n.length!==1)return;let[r]=n;return r===void 0||r===``?void 0:r},cw=(e,t,n)=>{try{return hf(e,{allowFileUrls:n}).key===hf(t,{allowFileUrls:n}).key}catch{return!1}},lw=e=>(e.get(XC)?.length??0)>1||(e.get(ZC)?.length??0)>1,uw=(e,t)=>{let n=YC(e,QC);return n===void 0?nw(`config_malformed`):lw(n)?nw(`duplicate_config_values`):dw(n,t)},dw=(e,t)=>{if(sw(e,XC)!==t.hooksDir)return tw(`no_refs_marker`);let n=sw(e,ZC);return n===void 0?tw(`no_origin`):cw(n,t.expectedUrl,t.allowFileUrls)?$C:tw(`origin_mismatch`)},fw={missing:ew,outside:tw(`outside_sources`),unreadable:nw(`path_unreadable`)},pw=async e=>{let t=await Eu(e.sourcesDir,e.dest);if(t.kind!==`inside`)return t.kind===`unreadable`?await aw(e.sourcesDir)===`absent`?ew:fw.unreadable:fw[t.kind]},mw=async e=>{let t=await pw(e);if(t!==void 0)return t;let n=await ow(e.dest);if(n!==void 0)return n;try{return uw(await s(m(e.dest,`.git`,`config`),`utf8`),e)}catch{return nw(`config_unreadable`)}},hw=e=>`no registered package or ref matches '${e}' — this does not establish that the repository is untracked; it may be registered under a different identifier. Run: refs list --json`,gw=e=>`ref '${e}' is not in the active refs configuration — to track it: refs add <url>`,_w=e=>`--ref '${e}' matched no configured ref — pass a full ref key or a unique suffix of one. Run: refs list --json`,vw=/^[a-z][a-z0-9+.-]*:\/\//iu,yw=/^git@[^:/\s]+:[^\s]+$/u,bw=e=>vw.test(e)||yw.test(e),xw=(e,t)=>{try{return hf(e,t)}catch{if(bw(e))throw b(`query looks like a git url but is not a supported form — check the url (credentials are never accepted) or run: refs resolve <package|ref-suffix>`);return}},Sw=(e,t,n)=>{let r=xw(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v(gw(r.key),`ref_not_registered`)}},Cw=(e,t)=>{let n=[];for(let r of Object.keys(e.refs).toSorted()){let i=e.refs[r]?.packages?.[t];i!==void 0&&n.push({entry:i,key:rl.parse(r)})}return n},ww=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — pick one with: refs resolve ${e} --ref <ref>`,Tw=(e,t)=>{let n=Cw(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y(ww(t,n.map(e=>e.key)));return r}},Ew=function*(e){let t=e.split(`/`);for(let e=t.length-1;e>=1;--e)yield t.slice(0,e).join(`/`)},Dw=(e,t)=>{for(let n of Ew(t)){let t=Tw(e,n);if(t!==void 0)return{...t,name:n}}},Ow=(e,t,n)=>{try{return Jx(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v(n,`unmatched_query`):e}},kw=(e,t)=>{let n=e[t];if(n!==void 0)return{entry:n,name:t};for(let n of Ew(t)){let t=e[n];if(t!==void 0)return{entry:t,name:n}}},Aw=(e,t,n)=>{let r=Ow(e,n,_w(n)),i=kw(e.refs[r]?.packages??{},t);if(i===void 0)throw v(bw(t)?`ref '${r}' is tracked but registers no package matching that query — inspect: refs show ${r} --packages --json`:`ref '${r}' is tracked but registers no package matching '${t}' — inspect: refs show ${r} --packages --json`,`package_not_registered`);return{key:r,packageMatch:{...i,key:r}}},jw=(e,t,n)=>{let r=Sw(e,t,n);if(r!==void 0)return r;let i=Tw(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=Dw(e,t);return a===void 0?{key:Ow(e,t,hw(t))}:{key:a.key,packageMatch:a}},Mw=(e,t,n)=>n.ref===void 0?jw(e,t,n):Aw(e,t,n.ref),Nw=(e,t)=>{let n={head_sha:t.headSha,last_fetched_at:new Date().toISOString()},r=t.effectiveCloneMode??e?.effective_clone_mode;return r!==void 0&&(n.effective_clone_mode=r),n},Pw=async(e,t,n)=>{let r=await H(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await uu(e,r))},Fw=(e,t,n)=>G(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await Pw(e,t,n.branchRenamedTo);let r=await Ag(e);r.refs[t]=Nw(r.refs[t],n),await jg(e,r)}),Iw=2e3,Lw=e=>{if(e.length<=Iw)return e;let t=e.slice(0,1500),n=e.slice(e.length-500),r=e.length-Iw;return`${t}\n… ${String(r)} characters omitted …\n${n}`},Rw=async(e,t,n)=>{try{await G(e,`home`,async()=>{let r=await Ag(e);r.refs[t]={...r.refs[t],last_error:Lw(n)},await jg(e,r)})}catch{}},zw=e=>{let t=0,n=[];return{acquire:()=>{if(t<e)return t+=1,Promise.resolve();let{promise:r,resolve:i}=Promise.withResolvers();return n.push(()=>{t+=1,i()}),r},release:()=>{--t;let e=n.shift();e!==void 0&&e()}}},Bw=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},Vw=(e,t,n)=>`sync produced a HEAD sha for '${e}' at ${t} that refs cannot store yet (${n.length} hex chars) — only SHA-1 repositories are supported for now`,Hw=(e,t,n)=>{if(!Tg.shape.head_sha.safeParse(n).success)throw b(Vw(e,t,n));return n},Uw=(e,t,n)=>{let r={effectiveCloneMode:t.effectiveMode,headSha:n.headSha,status:`cloned`};return n.actualBranch!==e.ref.default_branch&&(r.branchRenamedTo=n.actualBranch),t.warning!==void 0&&(r.warning=t.warning),r},Ww=async(e,t,n)=>{await a(ie(n),{recursive:!0});let r=Dg(`clone_mode`,t.ref,t.settings),i=await xd(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Cd(e.runner,n),s=await Vv(e.runner,{allowFileUrls:gv(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return Uw(t,i,{actualBranch:o,headSha:s})},Gw=async(e,t,n)=>{await Iv(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await Pv(e.runner,{allowFileUrls:gv(e.env),dest:n,expectedUrl:t.ref.url});let r=await kd(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:Hw(t.key,n,r.newSha),previousSha:r.oldSha,status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},Kw=(e,t,n)=>(nu(t.home,n),U(n)?Gw(e,t,n):Ww(e,t,n)),qw={changedDirs:[],kind:`arrivals`,namesBefore:[]},Jw=async(e,t,n)=>{if(n.previousSha===void 0)return qw;let r=await ld(e.runner,{dir:t,from:n.previousSha,to:n.headSha});return r===void 0?qw:{...r,kind:`arrivals`}},Yw=(e,t)=>G(t.home,hv(t.key),async()=>{let n=V(t.home,t.key),r=await Kw(e,t,n),i=await Jw(e,n,r);return{...r,structure:await Ob(n,t.ref.packages,i)}}),Xw=e=>{let t=[];e.branchRenamedTo!==void 0&&t.push(`default branch renamed to ${e.branchRenamedTo}`),e.warning!==void 0&&t.push(e.warning);let[n]=t;if(n!==void 0)return t.join(` | `)},Zw=(e,t)=>{let n={key:e,status:t.status},r=Xw(t);return r!==void 0&&(n.warning=r),t.structure!==void 0&&(n.structure=t.structure),n},Qw=async(e,t)=>{try{let n=await Yw(e,t);return await Fw(t.home,t.key,n),n}catch(e){throw await Rw(t.home,t.key,G_(e)),e}},$w=async(e,t)=>{try{return Zw(t.key,await Qw(e,t))}catch(e){return{error:G_(e),key:t.key,status:`failed`}}},eT=(e,t)=>e.status===`rejected`?{error:G_(e.reason),key:t,status:`failed`}:e.value,tT=async(e,t)=>{let n=zw(4);return(await Promise.allSettled(t.map(t=>Bw(n,()=>$w(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return eT(e,r.key)})},nT=async e=>{let{packageMatch:t}=e.match;return t===void 0?null:await pC({checkoutDir:e.dest,checkoutManaged:e.checkout.status===`managed`||e.checkout.status===`missing`,checkoutReason:`checkout is ${e.checkout.status}`,configuredPath:t.entry.path,home:e.home,key:e.match.key,packageName:t.name})},rT=(e,t,n)=>Mw(t,n.query,{allowFileUrls:gv(e.env),...n.ref===void 0?{}:{ref:n.ref}}),iT=async(e,t)=>{let n=B(e.env),r=await H(n);return{config:r,home:n,match:rT(e,r,t),state:await Ag(n)}},aT=async(e,t)=>{if(t===void 0)return;let{packageMatch:n}=e;if(n===void 0)throw y(`--project needs a query that names a package; '${e.key}' resolves to the ref itself`);return await DC(t,n.name)},oT=(e,t)=>{if(e.status!==`managed`&&e.status!==`missing`)throw b(`refusing to sync ${t}: its checkout is ${e.status}${e.reason===void 0?``:` (${e.reason})`} — run: refs doctor`)},sT=async(e,t)=>(await Qw(e,{home:t.home,key:t.match.key,ref:Nx(t.config,t.match.key),settings:t.config.settings})).status,cT=async(e,t)=>{t.project!==void 0&&await TC(t.project);let n=await iT(e,t),r=await uT(e,n,t);return t.syncIfStale!==!0||!(r.stale||r.missing)?r:(oT(r.checkout,r.key),await lT(e,{key:r.key,opts:t,target:n}))},lT=async(e,t)=>{let{key:n,opts:r}=t,i=await sT(e,t.target),a=await iT(e,r);if(a.match.key!==n)throw Se(`configuration changed while resolving '${r.query}' — retry`);return{...await uT(e,a,r),sync:{status:i}}},uT=async(e,t,n)=>{let{config:r,home:i,match:a,state:o}=t,{now:s}=n,c=Nx(r,a.key),l=V(i,a.key),u=al(Dg(`sync_ttl`,c,r.settings)),d=o.refs[a.key]?.last_fetched_at,f=await mw({allowFileUrls:gv(e.env),dest:l,expectedUrl:c.url,hooksDir:i.hooksDir,sourcesDir:i.sourcesDir}),p=await aT(a,n.project);return{checkout:f,key:a.key,...d===void 0?{}:{last_fetched_at:d},...p===void 0?{}:{installed:p},local_path:l,missing:f.status===`missing`,package:await nT({checkout:f,dest:l,home:i,match:a}),stale:Lx(d,u,s)}},dT=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...Bx({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale}),...e.checkout.status===`managed`||e.checkout.status===`missing`?[]:[`checkout: ${e.checkout.status}${e.checkout.reason===void 0?``:` (${e.checkout.reason})`}`]];return e.package!==null&&n.push(...mC(e.package)),e.sync!==void 0&&n.push(`sync: ${e.sync.status}`),e.installed!==void 0&&n.push(`installed: ${e.installed.version??`(${e.installed.status})`}`,...e.installed.name===void 0?[]:[`installed name: ${e.installed.name}`],...e.installed.reason===void 0?[]:[`installed reason: ${e.installed.reason}`]),n},fT=(e,t,n)=>({now:t,...n.project===void 0?{}:{project:n.project},query:e,...n.ref===void 0?{}:{ref:n.ref},...n.syncIfStale===!0?{syncIfStale:!0}:{}}),pT=(e,t)=>{e.command(`resolve`).description(`Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package.`).argument(`<query>`,`git url, npm package name, import path, or unique ref-key suffix`).option(`--ref <ref>`,`resolve the query as a package within this ref (full key or unique suffix)`).option(`--project <dir>`,`report the version this project has installed of the query's package`).option(`--sync-if-stale`,`fetch or clone first when the ref is stale or its checkout is absent`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let r=Date.now(),a=await cT(t,fT(e,r,n));Z(t,i,dT(a,r),a)})()})},mT={},hT=async(e,t)=>{if(!U(t))return{tags:[]};try{let{tags:n}=await Nd(e.runner,t,5);return{tags:n}}catch(e){return{tags:[],warning:`could not list tags: ${G_(e)}`}}},gT=async(e,t,n,r)=>{let i=B(e.env),a=await H(i),o=Jx(a,t),s=Nx(a,o),c=await Ag(i),l=V(i,o),{packages:u,...d}=s,f=n.tags?await hT(e,l):void 0,p=c.refs[o]??mT;return{data:{...d,key:o,local_path:l,missing:!U(l),...n.packages?{packages:u??{}}:{},packages_count:Object.keys(u??{}).length,...f===void 0?{}:{sample_tags:f.tags},stale:Lx(p.last_fetched_at,al(Dg(`sync_ttl`,s,a.settings)),r),state:p},warnings:W_(f?.warning)}},_T=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...Bx({lastFetchedAt:e.state.last_fetched_at,missing:e.missing,now:t,stale:e.stale})];return e.sample_tags!==void 0&&e.sample_tags.length>0&&n.push(`tags: ${e.sample_tags.join(`, `)}`),n},vT=(e,t)=>{e.command(`show`).description(`Show a configured ref: entry, state, local path, package count; --packages/--tags add the package map and sample tags to --json.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).option(`--packages`,`include the ref's full package map in --json output (off by default)`).option(`--tags`,`include sample tags in --json output (human output always probes for them)`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let r={packages:n.packages===!0,tags:!i.json||n.tags===!0},a=Date.now(),{data:o,warnings:s}=await gT(t,e,r,a);Z(t,i,_T(o,a),o,s)})()})},yT=(e,t,n)=>({home:e,key:n,ref:Nx(t,n),settings:t.settings}),bT=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>yT(e,t,rl.parse(n))):n.map(n=>yT(e,t,Jx(t,n))),xT=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=al(Dg(`sync_ttl`,t.ref,t.settings)),a=Lx(n.refs[t.key]?.last_fetched_at,i,r),o=!U(V(e,t.key));return a||o})},ST=async(e,t,n)=>{if(!Xg({env:e.env,updates:n.updates}))return[];let{latest:r,refreshed:i}=await Hg({fetch:e.fetcher,home:t,nowMs:Date.now()});return!i||r===void 0||!Ug(e.cliVersion,r)?[]:[Wg(e.cliVersion,r)]},CT=async(e,t,n)=>{if(!n)return t;let r=await Ag(e);return xT(e,t,r)},wT=async(e,t)=>{let n=B(e.env),r=await H(n),i=bT(n,r,t.refs),a=await CT(n,i,t.staleOnly),[o,s]=await Promise.all([tT(e,a),a.length>0?ST(e,n,r):Promise.resolve([])]);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o,warnings:s}},TT=[`updated`,`fresh`,`cloned`,`restored`,`failed`],ET={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},DT=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},OT=e=>{if(e.status===`failed`)return[` ${e.key}: ${e.error??`unknown error`}`];let t=e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`;return e.structure===void 0?[t]:[t,...ub(e.structure,e.key).map(e=>` ${e}`)]},kT=e=>{let t=DT(e),n=[TT.map(e=>`${ET[e]} (${t[e].length})`).join(` / `)];for(let e of TT)for(let r of t[e])n.push(...OT(r));return n},AT=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),jT=(e,t)=>{e.command(`sync`).description(`Fetch (or re-clone, if the checkout is missing) configured refs — all by default.`).argument(`[refs...]`,`ref keys or unique suffixes to sync (default: every configured ref)`).option(`--stale-only`,`skip refs whose last sync is still within their ref's sync_ttl`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let r=await wT(t,AT(e,n));Z(t,i,kT(r.results),{results:r.results},r.warnings),r.failedCount>0&&(process.exitCode=g.UNEXPECTED)})()})},MT=(e,t,n)=>n===void 0?e.tag_format:Fx(e,t,n).tag_format??e.tag_format,NT=(e,t,n)=>{if(e!==void 0)return e;let r=n===void 0?`ref '${t}'`:`package '${n}'`,i=n===void 0?[]:[`--package=${J_(n)}`];throw b(`${r} has no tag_format configured — inspect the repository's real tags and set one with: ${Y_(i,[t,`tag_format`,`<format>`])}`)},PT=async(e,t)=>{let n=B(e.env),r=await H(n),i=Jx(r,t.query),a=Nx(r,i),o=NT(MT(a,i,t.opts.packageName),i,t.opts.packageName),s=V(n,i);Px(s,i);let c=await Gd(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},FT=e=>[`${e.key}@${e.version} -> ${e.tag}`],IT=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},LT=[KS,Ty,VS,Yx,Mx,YS,sC,pT,vT,jT,(e,t)=>{e.command(`tag`).description(`Resolve a version to its git tag, via the ref's (or a package's) tag_format.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).argument(`<version>`,`version to resolve, e.g. 4.1.0`).option(`--package <name>`,`resolve against this package's tag_format instead of the ref's`).action((e,n,r,i)=>{let a=X(i);return Q(t,a,async()=>{let i=await PT(t,{opts:IT(r),query:e,version:n});Z(t,a,FT(i),i)})()})}],RT=(e,t)=>{for(let n of LT)n(e,t)},zT=[``,`Examples:`,` $ refs list --json`,` $ refs sync --stale-only --json`,` $ refs resolve zod/mini --json`,``,`Every command accepts --json for structured output and --verbose for stack traces on error.`].join(`
356
- `),BT=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),VT=`--json`,HT=`--verbose`,UT=/\n$/u,WT=/^error: /u,GT=e=>e.replace(WT,``),KT=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},qT=e=>KT(e,VT),JT=e=>KT(e,HT),YT=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,XT=e=>{let t=new z_().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(w_).option(VT,`emit machine-readable JSON on stdout instead of human-readable text`).option(HT,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(UT,``))},writeOut:t=>{e.out(t.replace(UT,``))}});return t.addHelpText(`after`,zT),RT(t,e),t},ZT=()=>{process.exitCode=g.OK},QT=(e,t,n)=>{let r={code:`usage`,message:YT(GT(n.message),n.stack,t.verbose)};K_(e,t,r),process.exitCode=g.USAGE},$T=(e,t,n)=>{if(BT.has(n.code)){ZT();return}QT(e,t,n)},eE=(e,t,n)=>{let r=we(n,{verbose:t.verbose});K_(e,t,r),process.exitCode=r.exitCode},tE=async(e,t,n)=>{let r={json:qT(n),verbose:JT(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof O_){$T(e,r,t);return}eE(e,r,t)}},nE=(e,t)=>tE(e,XT(e),t);import.meta.main&&await nE(D_(),process.argv);export{XT as buildProgram,X as cliOptsOf,Z as emit,K_ as emitError,G_ as errorMessageOf,q_ as progress,D_ as realContext,RT as registerCommands,nE as run,tE as runProgram,W_ as warningsFor,Q as wrapAction};
355
+ `?i+=n===`\r`?2:1:(t+=a+(n??``),i+=1)}else a===`"`?n=!n:!n&&(a===`#`||a===`;`)&&(r=!0),t+=a}}t!==``&&(yield t)},Dw=(e,t)=>e.subsection===void 0?`${e.name}.${t.toLowerCase()}`:`${e.name}.${e.subsection}.${t.toLowerCase()}`,Ow=(e,t)=>{let n=e.toLowerCase();if(t===void 0)return{name:n};let r=xw(t);return r===$?$:{name:n,subsection:r}},kw=e=>{let t=ww.exec(e),n=t?.groups?.section;if(n===void 0)return;let r=Cw(e.slice(t?.[0].length??0)),i=Ow(n,t?.groups?.subsection);return i===$?$:{rest:r,section:i}},Aw=e=>e===``||e.startsWith(`#`)||e.startsWith(`;`),jw=e=>{let t=Tw.exec(e),n=t?.groups?.name;if(n===void 0)return $;let r=bw(t?.groups?.value??``);return r===$?$:{name:n,value:r}},Mw=(e,t)=>{let n=jw(t.line);if(n===$)return`malformed`;let r=Dw(t.section,n.name);return t.wanted.includes(r)&&e.set(r,[...e.get(r)??[],n.value]),`ok`},Nw=(e,t,n)=>t.rest===``||Aw(t.rest)?t.section:Mw(e,{line:t.rest,section:t.section,wanted:n})===`malformed`?$:t.section,Pw=(e,t)=>{let n=kw(t.line);return n===$?$:n===void 0?t.section===Fw||Mw(e,t)===`malformed`?$:t.section:Nw(e,n,t.wanted)},Fw={name:``},Iw=(e,t)=>{let n=new Map,r=Fw;for(let i of Ew(e)){let e=Cw(i),a=Aw(e)?r:Pw(n,{line:e,section:r,wanted:t});if(a===$)return;r=a}return n},Lw=`core.hookspath`,Rw=`remote.origin.url`,zw=[Lw,Rw],Bw={status:`managed`},Vw={status:`missing`},Hw=e=>({reason:e,status:`unmanaged`}),Uw=e=>({reason:e,status:`unverifiable`}),Ww=new Set([`ENOENT`,`ENOTDIR`]),Gw=e=>typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0,Kw=async e=>{try{return await i(e),`present`}catch(e){let t=Gw(e);return t!==void 0&&Ww.has(t)?`absent`:`unreadable`}},qw=async e=>{try{let t=await i(m(e,`.git`));return t.isSymbolicLink()?Hw(`git_is_symlink`):t.isDirectory()?void 0:Hw(`git_is_file`)}catch(e){let t=Gw(e);return t!==void 0&&Ww.has(t)?Hw(`no_git`):Uw(`git_unreadable`)}},Jw=(e,t)=>{let n=e.get(t);if(n===void 0||n.length!==1)return;let[r]=n;return r===void 0||r===``?void 0:r},Yw=(e,t,n)=>{try{return _f(e,{allowFileUrls:n}).key===_f(t,{allowFileUrls:n}).key}catch{return!1}},Xw=e=>(e.get(Lw)?.length??0)>1||(e.get(Rw)?.length??0)>1,Zw=(e,t)=>{let n=Iw(e,zw);return n===void 0?Uw(`config_malformed`):Xw(n)?Uw(`duplicate_config_values`):Qw(n,t)},Qw=(e,t)=>{if(Jw(e,Lw)!==t.hooksDir)return Hw(`no_refs_marker`);let n=Jw(e,Rw);return n===void 0?Hw(`no_origin`):Yw(n,t.expectedUrl,t.allowFileUrls)?Bw:Hw(`origin_mismatch`)},$w={missing:Vw,outside:Hw(`outside_sources`),unreadable:Uw(`path_unreadable`)},eT=async e=>{let t=await Ou(e.sourcesDir,e.dest);if(t.kind!==`inside`)return t.kind===`unreadable`?await Kw(e.sourcesDir)===`absent`?Vw:$w.unreadable:$w[t.kind]},tT=async e=>{let t=await eT(e);if(t!==void 0)return t;let n=await qw(e.dest);if(n!==void 0)return n;try{return Zw(await s(m(e.dest,`.git`,`config`),`utf8`),e)}catch{return Uw(`config_unreadable`)}},nT=e=>`no registered package or ref matches '${e}' — this does not establish that the repository is untracked; it may be registered under a different identifier. Run: refs list --json`,rT=e=>`ref '${e}' is not in the active refs configuration — to track it: refs add <url>`,iT=e=>`--ref '${e}' matched no configured ref — pass a full ref key or a unique suffix of one. Run: refs list --json`,aT=/^[a-z][a-z0-9+.-]*:\/\//iu,oT=/^git@[^:/\s]+:[^\s]+$/u,sT=e=>aT.test(e)||oT.test(e),cT=(e,t)=>{try{return _f(e,t)}catch{if(sT(e))throw y(`query looks like a git url but is not a supported form — check the url (credentials are never accepted) or run: refs resolve <package|ref-suffix>`);return}},lT=(e,t,n)=>{let r=cT(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw _(rT(r.key),`ref_not_registered`)}},uT=(e,t)=>{let n=[];for(let r of Object.keys(e.refs).toSorted()){let i=e.refs[r]?.packages?.[t];i!==void 0&&n.push({entry:i,key:il.parse(r)})}return n},dT=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — pick one with: refs resolve ${e} --ref <ref>`,fT=(e,t)=>{let n=uT(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw v(dT(t,n.map(e=>e.key)));return r}},pT=function*(e){let t=e.split(`/`);for(let e=t.length-1;e>=1;--e)yield t.slice(0,e).join(`/`)},mT=(e,t)=>{for(let n of pT(t)){let t=fT(e,n);if(t!==void 0)return{...t,name:n}}},hT=(e,t,n)=>{try{return CS(e,t)}catch(e){throw e instanceof g&&e.code===`not_found`?_(n,`unmatched_query`):e}},gT=(e,t)=>{let n=e[t];if(n!==void 0)return{entry:n,name:t};for(let n of pT(t)){let t=e[n];if(t!==void 0)return{entry:t,name:n}}},_T=(e,t,n)=>{let r=hT(e,n,iT(n)),i=gT(e.refs[r]?.packages??{},t);if(i===void 0)throw _(sT(t)?`ref '${r}' is tracked but registers no package matching that query — inspect: refs show ${r} --packages --json`:`ref '${r}' is tracked but registers no package matching '${t}' — inspect: refs show ${r} --packages --json`,`package_not_registered`);return{key:r,packageMatch:{...i,key:r}}},vT=(e,t,n)=>{let r=lT(e,t,n);if(r!==void 0)return r;let i=fT(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=mT(e,t);return a===void 0?{key:hT(e,t,nT(t))}:{key:a.key,packageMatch:a}},yT=(e,t,n)=>n.ref===void 0?vT(e,t,n):_T(e,t,n.ref),bT=(e,t)=>{let n={head_sha:t.headSha,last_fetched_at:new Date().toISOString()},r=t.effectiveCloneMode??e?.effective_clone_mode;return r!==void 0&&(n.effective_clone_mode=r),n},xT=async(e,t,n)=>{let r=await V(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await fu(e,r))},ST=(e,t,n)=>W(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await xT(e,t,n.branchRenamedTo);let r=await Pg(e);r.refs[t]=bT(r.refs[t],n),await Fg(e,r)}),CT=2e3,wT=e=>{if(e.length<=CT)return e;let t=e.slice(0,1500),n=e.slice(e.length-500),r=e.length-CT;return`${t}\n… ${String(r)} characters omitted …\n${n}`},TT=async(e,t,n)=>{try{await W(e,`home`,async()=>{let r=await Pg(e);r.refs[t]={...r.refs[t],last_error:wT(n)},await Fg(e,r)})}catch{}},ET=e=>{let t=0,n=[];return{acquire:()=>{if(t<e)return t+=1,Promise.resolve();let{promise:r,resolve:i}=Promise.withResolvers();return n.push(()=>{t+=1,i()}),r},release:()=>{--t;let e=n.shift();e!==void 0&&e()}}},DT=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},OT=(e,t,n)=>`sync produced a HEAD sha for '${e}' at ${t} that refs cannot store yet (${n.length} hex chars) — only SHA-1 repositories are supported for now`,kT=(e,t,n)=>{if(!kg.shape.head_sha.safeParse(n).success)throw y(OT(e,t,n));return n},AT=(e,t,n)=>{let r={effectiveCloneMode:t.effectiveMode,headSha:n.headSha,status:`cloned`};return n.actualBranch!==e.ref.default_branch&&(r.branchRenamedTo=n.actualBranch),t.warning!==void 0&&(r.warning=t.warning),r},jT=async(e,t,n)=>{await a(ie(n),{recursive:!0});let r=jg(`clone_mode`,t.ref,t.settings),i=await Cd(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Td(e.runner,n),s=await fy(e.runner,{allowFileUrls:Vv(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return AT(t,i,{actualBranch:o,headSha:s})},MT=async(e,t,n)=>{await sy(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await ay(e.runner,{allowFileUrls:Vv(e.env),dest:n,expectedUrl:t.ref.url});let r=await jd(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:kT(t.key,n,r.newSha),previousSha:r.oldSha,status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},NT=(e,t,n)=>(iu(t.home,n),H(n)?MT(e,t,n):jT(e,t,n)),PT={changedDirs:[],kind:`arrivals`,namesBefore:[]},FT=async(e,t,n)=>{if(n.previousSha===void 0)return PT;let r=await dd(e.runner,{dir:t,from:n.previousSha,to:n.headSha});return r===void 0?PT:{...r,kind:`arrivals`}},IT=(e,t)=>W(t.home,Bv(t.key),async()=>{let n=B(t.home,t.key),r=await NT(e,t,n),i=await FT(e,n,r);return{...r,structure:await nx(n,t.ref,i)}}),LT=e=>{let t=[];e.branchRenamedTo!==void 0&&t.push(`default branch renamed to ${e.branchRenamedTo}`),e.warning!==void 0&&t.push(e.warning);let[n]=t;if(n!==void 0)return t.join(` | `)},RT=(e,t)=>{let n={key:e,status:t.status},r=LT(t);return r!==void 0&&(n.warning=r),t.structure!==void 0&&(n.structure=t.structure),n},zT=async(e,t)=>{try{let n=await IT(e,t);return await ST(t.home,t.key,n),n}catch(e){throw await TT(t.home,t.key,_v(e)),e}},BT=async(e,t)=>{try{return RT(t.key,await zT(e,t))}catch(e){return{error:_v(e),key:t.key,status:`failed`}}},VT=(e,t)=>e.status===`rejected`?{error:_v(e.reason),key:t,status:`failed`}:e.value,HT=async(e,t)=>{let n=ET(4);return(await Promise.allSettled(t.map(t=>DT(n,()=>BT(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return VT(e,r.key)})},UT=async e=>{let{packageMatch:t}=e.match;return t===void 0?null:await ew({checkoutDir:e.dest,checkoutManaged:e.checkout.status===`managed`||e.checkout.status===`missing`,checkoutReason:`checkout is ${e.checkout.status}`,configuredPath:t.entry.path,home:e.home,key:e.match.key,packageName:t.name})},WT=(e,t,n)=>yT(t,n.query,{allowFileUrls:Vv(e.env),...n.ref===void 0?{}:{ref:n.ref}}),GT=async(e,t)=>{let n=z(e.env),r=await V(n);return{config:r,home:n,match:WT(e,r,t),state:await Pg(n)}},KT=async(e,t)=>{if(t===void 0)return;let{packageMatch:n}=e;if(n===void 0)throw v(`--project needs a query that names a package; '${e.key}' resolves to the ref itself`);return await mw(t,n.name)},qT=(e,t)=>{if(e.status!==`managed`&&e.status!==`missing`)throw y(`refusing to sync ${t}: its checkout is ${e.status}${e.reason===void 0?``:` (${e.reason})`} — run: refs doctor`)},JT=async(e,t)=>(await zT(e,{home:t.home,key:t.match.key,ref:cS(t.config,t.match.key),settings:t.config.settings})).status,YT=async(e,t)=>{t.project!==void 0&&await fw(t.project);let n=await GT(e,t),r=await ZT(e,n,t);return t.syncIfStale!==!0||!(r.stale||r.missing)?r:(qT(r.checkout,r.key),await XT(e,{key:r.key,opts:t,target:n}))},XT=async(e,t)=>{let{key:n,opts:r}=t,i=await JT(e,t.target),a=await GT(e,r);if(a.match.key!==n)throw Ce(`configuration changed while resolving '${r.query}' — retry`);return{...await ZT(e,a,r),sync:{status:i}}},ZT=async(e,t,n)=>{let{config:r,home:i,match:a,state:o}=t,{now:s}=n,c=cS(r,a.key),l=B(i,a.key),u=ol(jg(`sync_ttl`,c,r.settings)),d=o.refs[a.key]?.last_fetched_at,f=await tT({allowFileUrls:Vv(e.env),dest:l,expectedUrl:c.url,hooksDir:i.hooksDir,sourcesDir:i.sourcesDir}),p=await KT(a,n.project);return{checkout:f,key:a.key,...d===void 0?{}:{last_fetched_at:d},...p===void 0?{}:{installed:p},local_path:l,missing:f.status===`missing`,package:await UT({checkout:f,dest:l,home:i,match:a}),stale:fS(d,u,s)}},QT=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...hS({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale}),...e.checkout.status===`managed`||e.checkout.status===`missing`?[]:[`checkout: ${e.checkout.status}${e.checkout.reason===void 0?``:` (${e.checkout.reason})`}`]];return e.package!==null&&n.push(...tw(e.package)),e.sync!==void 0&&n.push(`sync: ${e.sync.status}`),e.installed!==void 0&&n.push(`installed: ${e.installed.version??`(${e.installed.status})`}`,...e.installed.name===void 0?[]:[`installed name: ${e.installed.name}`],...e.installed.reason===void 0?[]:[`installed reason: ${e.installed.reason}`]),n},$T=(e,t,n)=>({now:t,...n.project===void 0?{}:{project:n.project},query:e,...n.ref===void 0?{}:{ref:n.ref},...n.syncIfStale===!0?{syncIfStale:!0}:{}}),eE=(e,t)=>{e.command(`resolve`).description(`Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package.`).argument(`<query>`,`git url, npm package name, import path, or unique ref-key suffix`).option(`--ref <ref>`,`resolve the query as a package within this ref (full key or unique suffix)`).option(`--project <dir>`,`report the version this project has installed of the query's package`).option(`--sync-if-stale`,`fetch or clone first when the ref is stale or its checkout is absent`).action((e,n,r)=>{let i=Y(r);return Z(t,i,async()=>{let r=Date.now(),a=await YT(t,$T(e,r,n));X(t,i,QT(a,r),a)})()})},tE={},nE=async(e,t)=>{if(!H(t))return{tags:[]};try{let{tags:n}=await Fd(e.runner,t,5);return{tags:n}}catch(e){return{tags:[],warning:`could not list tags: ${_v(e)}`}}},rE=async(e,t,n,r)=>{let i=z(e.env),a=await V(i),o=CS(a,t),s=cS(a,o),c=await Pg(i),l=B(i,o),{packages:u,...d}=s,f=n.tags?await nE(e,l):void 0,p=c.refs[o]??tE;return{data:{...d,key:o,local_path:l,missing:!H(l),...n.packages?{packages:u??{}}:{},packages_count:Object.keys(u??{}).length,...f===void 0?{}:{sample_tags:f.tags},stale:fS(p.last_fetched_at,ol(jg(`sync_ttl`,s,a.settings)),r),state:p},warnings:gv(f?.warning)}},iE=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...hS({lastFetchedAt:e.state.last_fetched_at,missing:e.missing,now:t,stale:e.stale})];return e.sample_tags!==void 0&&e.sample_tags.length>0&&n.push(`tags: ${e.sample_tags.join(`, `)}`),n},aE=(e,t)=>{e.command(`show`).description(`Show a configured ref: entry, state, local path, package count; --packages/--tags add the package map and sample tags to --json.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).option(`--packages`,`include the ref's full package map in --json output (off by default)`).option(`--tags`,`include sample tags in --json output (human output always probes for them)`).action((e,n,r)=>{let i=Y(r);return Z(t,i,async()=>{let r={packages:n.packages===!0,tags:!i.json||n.tags===!0},a=Date.now(),{data:o,warnings:s}=await rE(t,e,r,a);X(t,i,iE(o,a),o,s)})()})},oE=(e,t,n)=>({home:e,key:n,ref:cS(t,n),settings:t.settings}),sE=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>oE(e,t,il.parse(n))):n.map(n=>oE(e,t,CS(t,n))),cE=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=ol(jg(`sync_ttl`,t.ref,t.settings)),a=fS(n.refs[t.key]?.last_fetched_at,i,r),o=!H(B(e,t.key));return a||o})},lE=async(e,t,n)=>{if(!e_({env:e.env,updates:n.updates}))return[];let{latest:r,refreshed:i}=await Kg({fetch:e.fetcher,home:t,nowMs:Date.now()});return!i||r===void 0||!qg(e.cliVersion,r)?[]:[Jg(e.cliVersion,r)]},uE=async(e,t,n)=>{if(!n)return t;let r=await Pg(e);return cE(e,t,r)},dE=async(e,t)=>{let n=z(e.env),r=await V(n),i=sE(n,r,t.refs),a=await uE(n,i,t.staleOnly),[o,s]=await Promise.all([HT(e,a),a.length>0?lE(e,n,r):Promise.resolve([])]);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o,warnings:s}},fE=[`updated`,`fresh`,`cloned`,`restored`,`failed`],pE={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},mE=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},hE=e=>{if(e.status===`failed`)return[` ${e.key}: ${e.error??`unknown error`}`];let t=e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`;return e.structure===void 0?[t]:[t,...Lb(e.structure,e.key).map(e=>` ${e}`)]},gE=e=>{let t=mE(e),n=[fE.map(e=>`${pE[e]} (${t[e].length})`).join(` / `)];for(let e of fE)for(let r of t[e])n.push(...hE(r));return n},_E=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),vE=(e,t)=>{e.command(`sync`).description(`Fetch (or re-clone, if the checkout is missing) configured refs — all by default.`).argument(`[refs...]`,`ref keys or unique suffixes to sync (default: every configured ref)`).option(`--stale-only`,`skip refs whose last sync is still within their ref's sync_ttl`).action((e,n,r)=>{let i=Y(r);return Z(t,i,async()=>{let r=await dE(t,_E(e,n));X(t,i,gE(r.results),{results:r.results},r.warnings),r.failedCount>0&&(process.exitCode=Se.UNEXPECTED)})()})},yE=(e,t,n)=>n===void 0?e.tag_format:uS(e,t,n).tag_format??e.tag_format,bE=(e,t,n)=>{if(e!==void 0)return e;let r=n===void 0?`ref '${t}'`:`package '${n}'`,i=n===void 0?[]:[`--package=${Q(n)}`];throw y(`${r} has no tag_format configured — inspect the repository's real tags and set one with: ${bv(i,[t,`tag_format`,`<format>`])}`)},xE=async(e,t)=>{let n=z(e.env),r=await V(n),i=CS(r,t.query),a=cS(r,i),o=bE(yE(a,i,t.opts.packageName),i,t.opts.packageName),s=B(n,i);lS(s,i);let c=await qd(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},SE=e=>[`${e.key}@${e.version} -> ${e.tag}`],CE=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},wE=[NC,Xy,OC,wS,sS,IC,JC,eE,aE,vE,(e,t)=>{e.command(`tag`).description(`Resolve a version to its git tag, via the ref's (or a package's) tag_format.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).argument(`<version>`,`version to resolve, e.g. 4.1.0`).option(`--package <name>`,`resolve against this package's tag_format instead of the ref's`).action((e,n,r,i)=>{let a=Y(i);return Z(t,a,async()=>{let i=await xE(t,{opts:CE(r),query:e,version:n});X(t,a,SE(i),i)})()})}],TE=(e,t)=>{for(let n of wE)n(e,t)},EE=[``,`Examples:`,` $ refs list --json`,` $ refs sync --stale-only --json`,` $ refs resolve zod/mini --json`,``,`Every command accepts --json for structured output and --verbose for stack traces on error.`].join(`
356
+ `),DE=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),OE=`--json`,kE=`--verbose`,AE=/\n$/u,jE=/^error: /u,ME=e=>e.replace(jE,``),NE=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},PE=e=>NE(e,OE),FE=e=>NE(e,kE),IE=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,LE=e=>{let t=new dv().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(X_).option(OE,`emit machine-readable JSON on stdout instead of human-readable text`).option(kE,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(AE,``))},writeOut:t=>{e.out(t.replace(AE,``))}});return t.addHelpText(`after`,EE),TE(t,e),t},RE=()=>{process.exitCode=Se.OK},zE=(e,t,n)=>{let r={code:`usage`,message:IE(ME(n.message),n.stack,t.verbose)};vv(e,t,r),process.exitCode=Se.USAGE},BE=(e,t,n)=>{if(DE.has(n.code)){RE();return}zE(e,t,n)},VE=(e,t,n)=>{let r=Te(n,{verbose:t.verbose});vv(e,t,r),process.exitCode=r.exitCode},HE=async(e,t,n)=>{let r={json:PE(n),verbose:FE(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof ev){BE(e,r,t);return}VE(e,r,t)}},UE=(e,t)=>HE(e,LE(e),t);import.meta.main&&await UE($_(),process.argv);export{LE as buildProgram,Y as cliOptsOf,X as emit,vv as emitError,_v as errorMessageOf,yv as progress,$_ as realContext,TE as registerCommands,UE as run,HE as runProgram,gv as warningsFor,Z as wrapAction};