@kaisers-io/refs 0.10.0 → 0.12.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.
Files changed (3) hide show
  1. package/CHANGELOG.md +398 -1
  2. package/dist/refs.mjs +46 -40
  3. package/package.json +1 -1
package/dist/refs.mjs CHANGED
@@ -1,13 +1,13 @@
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,readFile as o,readdir as s,realpath as c,rename as l,rm as u,rmdir as d,stat as f,writeFile as p}from"node:fs/promises";import m,{basename as ee,dirname as te,isAbsolute as ne,join as h,posix as re,relative as ie,resolve as ae,sep as oe}from"node:path";import{randomUUID as se}from"node:crypto";import ce,{existsSync as le,realpathSync as ue}from"node:fs";import{homedir as de}from"node:os";import{setTimeout as fe}from"node:timers/promises";import{EventEmitter as pe,once as me}from"node:events";import he,{spawn as ge}from"node:child_process";import g from"node:process";import{stripVTControlCharacters as _e}from"node:util";const _={CONFLICT:5,NOT_FOUND:4,OK:0,UNEXPECTED:1,USAGE:2,VALIDATION:3};var v=class extends Error{code;exitCode;constructor(e,t,n,r){super(n,r),this.code=t,this.exitCode=e,this.name=`RefsError`}};const ve=e=>new v(_.CONFLICT,`conflict`,e),y=e=>new v(_.NOT_FOUND,`not_found`,e),b=e=>new v(_.USAGE,`usage`,e),x=e=>new v(_.VALIDATION,`validation`,e),ye=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,be=(e,t)=>e instanceof v?{code:e.code,exitCode:e.exitCode,message:ye(e.message,e.stack,t.verbose)}:e instanceof Error?{code:`unexpected`,exitCode:_.UNEXPECTED,message:ye(e.message,e.stack,t.verbose)}:{code:`unexpected`,exitCode:_.UNEXPECTED,message:String(e)};function xe(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 Se(e,t=`|`){return e.map(e=>ze(e)).join(t)}function Ce(e,t){return typeof t==`bigint`?t.toString():t}function we(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Te(e){return e==null}function Ee(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function De(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 S(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oe(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function ke(e){return JSON.stringify(e)}function Ae(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const je=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Me(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ne=we(()=>{if(E.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Pe(e){if(Me(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Me(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Fe(e){return Pe(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Ie=new Set([`string`,`number`,`symbol`]);function Le(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Re(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function C(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 Be(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const Ve={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function He(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`);return Re(e,Oe(e._zod.def,{get shape(){let e={};for(let r of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,r))throw Error(`Unrecognized key: "${String(r)}"`);t[r]&&S(e,r,n.shape[r])}return S(this,`shape`,e),e},checks:[]}))}function Ue(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`);return Re(e,Oe(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,e))throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&delete r[e]}return S(this,`shape`,r),r},checks:[]}))}function We(e,t){if(!Pe(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;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 Re(e,Oe(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return S(this,`shape`,n),n}}))}function Ge(e,t){if(!Pe(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Re(e,Oe(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return S(this,`shape`,n),n}}))}function Ke(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.`);return Re(e,Oe(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return S(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function qe(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`);return Re(t,Oe(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(r,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t of Reflect.ownKeys(r))i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return S(this,`shape`,i),i},checks:[]}))}function Je(e,t,n){return Re(t,Oe(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(i,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t of Reflect.ownKeys(r))i[t]=new e({type:`nonoptional`,innerType:r[t]});return S(this,`shape`,i),i}}))}function Ye(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 Xe(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 Ze(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Qe(e){return typeof e==`string`?e:e?.message}function $e(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function et(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:Qe(e.inst?._zod.def?.error?.(e))??Qe(a?.(e))??Qe(t?.error?.(e))??Qe(n.customError?.(e))??Qe(n.localeError?.(e))??`Invalid input`,{inst:s,schema:c,continue:l,input:u,...d}=e;return d.path??=[],d.message=o,t?.reportInput&&(d.input=u),d}const tt=/[\uD800-\uDBFF]/;function nt(e){let t=e.length;if(!tt.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 rt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function it(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 at(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function ot(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):lt(e,n,r.value)}}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 lt(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 ut(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let dt,ft=!1;const pt={configurable:!0,get(){ft=!0}};function w(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,pt);let e=ft;ft=!1;try{let r=n(this);return ft?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),ft||=e,r}catch(n){throw delete this[t],ft||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function mt(e,t,n,r){let i=ut(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 ht(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var gt;const _t={value:void 0,enumerable:!1};let vt=`captureStackTrace`in Error?Error:null;function yt(e){let t=vt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return vt=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function T(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){_t.value=new a(r);try{Object.defineProperty(n,"_zod",_t)}finally{_t.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),ot(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?yt(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 bt=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},xt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(gt=globalThis).__zod_globalConfig??(gt.__zod_globalConfig={});const E=globalThis.__zod_globalConfig;function D(e){return e&&Object.assign(E,e),E}function St(){let e=this._zod;return e.message??=JSON.stringify(e.def,Ce,2),e.message}function Ct(e){this._zod.message=e}const wt={get:St,set:Ct,enumerable:!0,configurable:!0},Tt={value:void 0,enumerable:!1},Et={value:void 0,enumerable:!1},Dt=new WeakSet([Object.prototype,Error.prototype]),Ot=(e,t)=>{e.name=`$ZodError`,Tt.value=e._zod,Object.defineProperty(e,"_zod",Tt),Et.value=t,Object.defineProperty(e,"issues",Et),Tt.value=void 0,Et.value=void 0,Object.defineProperty(e,"message",wt);let n=Object.getPrototypeOf(e);Dt.has(n)||(Dt.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})}}))},kt=T(`$ZodError`,Ot),At=T(`$ZodError`,Ot,void 0,{Parent:Error});function jt(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 Mt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?jt(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Nt(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 Pt(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 O(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 ${Pt(e.path)}`);return t.join(`
3
- `)}function Ft(e,t){return{callee:t?.callee??e,Err:t?.Err}}const It=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 bt;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>et(e,o,D())));throw je(n,a?.callee??t),n}return s.value};return t},Lt=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=>et(e,o,D())));throw je(n,a?.callee??t),n}return s.value};return t},Rt=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 bt;return a.issues.length?{success:!1,error:new(e??kt)(a.issues.map(e=>et(e,i,D())))}:{success:!0,data:a.value}},zt=Rt(At),Bt=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?{success:!1,error:new e(a.issues.map(e=>et(e,i,D())))}:{success:!0,data:a.value}},Vt=Bt(At),Ht=e=>{let t=It(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Ft(n,a))};return n},Ut=e=>{let t=It(e),n=(e,r,i,a)=>t(e,r,i,Ft(n,a));return n},Wt=e=>{let t=Lt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Ft(n,a))};return n},Gt=e=>{let t=Lt(e),n=async(e,r,i,a)=>await t(e,r,i,Ft(n,a));return n},Kt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Rt(e)(t,n,i)},qt=e=>(t,n,r)=>Rt(e)(t,n,r),Jt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Bt(e)(t,n,i)},Yt=e=>async(t,n,r)=>Bt(e)(t,n,r),Xt=/^[cC][0-9a-z]{6,}$/,Zt=/^[0-9a-z]+$/,Qt=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,$t=/^[0-9a-vA-V]{20}$/,en=/^[A-Za-z0-9]{27}$/,tn=/^[a-zA-Z0-9_-]{21}$/;function nn(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const rn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,an=/^([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})$/,on=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)$/,sn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function cn(){return RegExp(`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const ln=/^(?:(?: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])$/,un=/^(([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}|:))$/,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])\/([0-9]|[1-2][0-9]|3[0-2])$/,fn=/^(([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])$/,pn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mn=/^[A-Za-z0-9_-]*$/,hn=/^https?$/,gn=/^\+[1-9]\d{6,14}$/,_n=`(?:(?:\\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 vn(e){return RegExp(`^${e}$`)}const yn=vn(_n);function bn(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 xn(e){return RegExp(`^${bn(e)}$`)}function Sn(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${bn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${bn({precision:e.precision})}`:n;return RegExp(`^${_n}T(?:${r})$`)}const Cn=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},wn=/^-?\d+$/,Tn=/^-?\d+(?:\.\d+)?$/,En=/^(?:true|false)$/i,Dn=/^[^A-Z]*$/,On=/^[^a-z]*$/,k=T(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),kn=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},An={number:`number`,bigint:`bigint`,object:`date`},jn=T(`$ZodCheckLessThan`,(e,t)=>{k.init(e,t);let n=An[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:An[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})}}),Mn=T(`$ZodCheckGreaterThan`,(e,t)=>{k.init(e,t);let n=An[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:An[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})}}),Nn=T(`$ZodCheckMultipleOf`,(e,t)=>{k.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),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):De(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})}}),Pn=T(`$ZodCheckNumberFormat`,(e,t)=>{k.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ve[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=wn)}),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})}}),Fn=T(`$ZodCheckMaxLength`,(e,t)=>{var n;k.init(e,t),(n=e._zod.def).when??(n.when=kn),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?nt(r):i)<=t.maximum)return;let a=rt(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),In=T(`$ZodCheckMinLength`,(e,t)=>{var n;k.init(e,t),(n=e._zod.def).when??(n.when=kn),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?nt(r):i)>=t.minimum)return;let a=rt(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ln=T(`$ZodCheckLengthEquals`,(e,t)=>{var n;k.init(e,t),(n=e._zod.def).when??(n.when=kn),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?nt(r):i;if(a===t.length)return;let o=rt(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})}}),Rn=T(`$ZodCheckStringFormat`,(e,t)=>{var n,r;k.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),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=()=>{})}),zn=T(`$ZodCheckRegex`,(e,t)=>{Rn.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})}}),Bn=T(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Dn,Rn.init(e,t)}),Vn=T(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=On,Rn.init(e,t)}),Hn=T(`$ZodCheckIncludes`,(e,t)=>{k.init(e,t);let n=Le(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),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})}}),Un=T(`$ZodCheckStartsWith`,(e,t)=>{k.init(e,t);let n=RegExp(`^${Le(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(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})}}),Wn=T(`$ZodCheckEndsWith`,(e,t)=>{k.init(e,t);let n=RegExp(`.*${Le(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(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})}}),Gn=T(`$ZodCheckOverwrite`,(e,t)=>{k.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Kn=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1,e(this),--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 m,{basename as ne,dirname as re,isAbsolute as ie,join as h,posix as ae,relative as oe,resolve as se,sep as ce}from"node:path";import{createHash as le,randomUUID as ue}from"node:crypto";import de,{existsSync as fe,realpathSync as pe}from"node:fs";import{homedir as me}from"node:os";import{setTimeout as he}from"node:timers/promises";import{EventEmitter as ge,once as _e}from"node:events";import ve,{spawn as ye}from"node:child_process";import g from"node:process";import{stripVTControlCharacters as be}from"node:util";const xe={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 _(xe.CONFLICT,`conflict`,e),v=(e,t)=>new _(xe.NOT_FOUND,`not_found`,e,t===void 0?void 0:{reason:t}),y=e=>new _(xe.USAGE,`usage`,e),b=e=>new _(xe.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:xe.UNEXPECTED,message:Ce(e.message,e.stack,t.verbose)}:{code:`unexpected`,exitCode:xe.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=>Ue(e)).join(t)}function De(e,t){return typeof t==`bigint`?t.toString():t}function Oe(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ke(e){return e==null}function Ae(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function je(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 x(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Me(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Ne(e){return JSON.stringify(e)}function Pe(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Fe=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Le=Oe(()=>{if(T.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Re(e){if(Ie(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Ie(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ze(e){return Re(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Be=new Set([`string`,`number`,`symbol`]);function Ve(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function He(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 Ue(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function We(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const Ge={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ke(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`);return He(e,Me(e._zod.def,{get shape(){let e={};for(let r of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,r))throw Error(`Unrecognized key: "${String(r)}"`);t[r]&&x(e,r,n.shape[r])}return x(this,`shape`,e),e},checks:[]}))}function qe(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`);return He(e,Me(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,e))throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&delete r[e]}return x(this,`shape`,r),r},checks:[]}))}function Je(e,t){if(!Re(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;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 He(e,Me(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return x(this,`shape`,n),n}}))}function Ye(e,t){if(!Re(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return He(e,Me(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return x(this,`shape`,n),n}}))}function Xe(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.`);return He(e,Me(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return x(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Ze(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`);return He(t,Me(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(r,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t of Reflect.ownKeys(r))i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return x(this,`shape`,i),i},checks:[]}))}function Qe(e,t,n){return He(t,Me(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(i,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t of Reflect.ownKeys(r))i[t]=new e({type:`nonoptional`,innerType:r[t]});return x(this,`shape`,i),i}}))}function $e(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 et(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 tt(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function nt(e){return typeof e==`string`?e:e?.message}function rt(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function it(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:nt(e.inst?._zod.def?.error?.(e))??nt(a?.(e))??nt(t?.error?.(e))??nt(n.customError?.(e))??nt(n.localeError?.(e))??`Invalid input`,{inst:s,schema:c,continue:l,input:u,...d}=e;return d.path??=[],d.message=o,t?.reportInput&&(d.input=u),d}const at=/[\uD800-\uDBFF]/;function ot(e){let t=e.length;if(!at.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 st(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ct(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 lt(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function ut(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):pt(e,n,r.value)}}function dt(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function ft(e,t,n){return dt(e,t,n,!1)}function pt(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:dt(this,t,n.bind(this))},set(e){dt(this,t,e)}})}function mt(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let ht,gt=!1;const _t={configurable:!0,get(){gt=!0}};function C(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&ht!==e._zod){ht=void 0;return}ht=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,_t);let e=gt;gt=!1;try{let r=n(this);return gt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),gt||=e,r}catch(n){throw delete this[t],gt||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function vt(e,t,n,r){let i=mt(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 yt(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var bt;const xt={value:void 0,enumerable:!1};let St=`captureStackTrace`in Error?Error:null;function Ct(e){let t=St;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return St=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){xt.value=new a(r);try{Object.defineProperty(n,"_zod",xt)}finally{xt.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),ut(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?Ct(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 wt=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Tt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(bt=globalThis).__zod_globalConfig??(bt.__zod_globalConfig={});const T=globalThis.__zod_globalConfig;function E(e){return e&&Object.assign(T,e),T}function Et(){let e=this._zod;return e.message??=JSON.stringify(e.def,De,2),e.message}function Dt(e){this._zod.message=e}const Ot={get:Et,set:Dt,enumerable:!0,configurable:!0},kt={value:void 0,enumerable:!1},At={value:void 0,enumerable:!1},jt=new WeakSet([Object.prototype,Error.prototype]),Mt=(e,t)=>{e.name=`$ZodError`,kt.value=e._zod,Object.defineProperty(e,"_zod",kt),At.value=t,Object.defineProperty(e,"issues",At),kt.value=void 0,At.value=void 0,Object.defineProperty(e,"message",Ot);let n=Object.getPrototypeOf(e);jt.has(n)||(jt.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})}}))},Nt=w(`$ZodError`,Mt),Pt=w(`$ZodError`,Mt,void 0,{Parent:Error});function Ft(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 It(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Ft(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Lt(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 Rt(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 D(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 ${Rt(e.path)}`);return t.join(`
3
+ `)}function zt(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Bt=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 wt;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>it(e,o,E())));throw Fe(n,a?.callee??t),n}return s.value};return t},Vt=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=>it(e,o,E())));throw Fe(n,a?.callee??t),n}return s.value};return t},Ht=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 wt;return a.issues.length?{success:!1,error:new(e??Nt)(a.issues.map(e=>it(e,i,E())))}:{success:!0,data:a.value}},Ut=Ht(Pt),Wt=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?{success:!1,error:new e(a.issues.map(e=>it(e,i,E())))}:{success:!0,data:a.value}},Gt=Wt(Pt),Kt=e=>{let t=Bt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,zt(n,a))};return n},qt=e=>{let t=Bt(e),n=(e,r,i,a)=>t(e,r,i,zt(n,a));return n},Jt=e=>{let t=Vt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,zt(n,a))};return n},Yt=e=>{let t=Vt(e),n=async(e,r,i,a)=>await t(e,r,i,zt(n,a));return n},Xt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ht(e)(t,n,i)},Zt=e=>(t,n,r)=>Ht(e)(t,n,r),Qt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Wt(e)(t,n,i)},$t=e=>async(t,n,r)=>Wt(e)(t,n,r),en=/^[cC][0-9a-z]{6,}$/,tn=/^[0-9a-z]+$/,nn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,rn=/^[0-9a-vA-V]{20}$/,an=/^[A-Za-z0-9]{27}$/,on=/^[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)?)?)$/,ln=/^([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})$/,un=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)$/,dn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function fn(){return RegExp(`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const pn=/^(?:(?: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])$/,mn=/^(([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}|:))$/,hn=/^((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])$/,gn=/^(([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])$/,_n=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,vn=/^[A-Za-z0-9_-]*$/,yn=/^https?$/,bn=/^\+[1-9]\d{6,14}$/,xn=`(?:(?:\\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 Sn(e){return RegExp(`^${e}$`)}const Cn=Sn(xn);function wn(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 Tn(e){return RegExp(`^${wn(e)}$`)}function En(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${wn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${wn({precision:e.precision})}`:n;return RegExp(`^${xn}T(?:${r})$`)}const Dn=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},On=/^-?\d+$/,kn=/^-?\d+(?:\.\d+)?$/,An=/^(?:true|false)$/i,jn=/^[^A-Z]*$/,Mn=/^[^a-z]*$/,O=w(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Nn=e=>{let t=e.value;return!ke(t)&&t.length!==void 0},Pn={number:`number`,bigint:`bigint`,object:`date`},Fn=w(`$ZodCheckLessThan`,(e,t)=>{O.init(e,t);let n=Pn[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Pn[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})}}),In=w(`$ZodCheckGreaterThan`,(e,t)=>{O.init(e,t);let n=Pn[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Pn[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})}}),Ln=w(`$ZodCheckMultipleOf`,(e,t)=>{O.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),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):je(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})}}),Rn=w(`$ZodCheckNumberFormat`,(e,t)=>{O.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ge[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=On)}),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})}}),zn=w(`$ZodCheckMaxLength`,(e,t)=>{var n;O.init(e,t),(n=e._zod.def).when??(n.when=Nn),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?ot(r):i)<=t.maximum)return;let a=st(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Bn=w(`$ZodCheckMinLength`,(e,t)=>{var n;O.init(e,t),(n=e._zod.def).when??(n.when=Nn),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?ot(r):i)>=t.minimum)return;let a=st(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Vn=w(`$ZodCheckLengthEquals`,(e,t)=>{var n;O.init(e,t),(n=e._zod.def).when??(n.when=Nn),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?ot(r):i;if(a===t.length)return;let o=st(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})}}),Hn=w(`$ZodCheckStringFormat`,(e,t)=>{var n,r;O.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),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=()=>{})}),Un=w(`$ZodCheckRegex`,(e,t)=>{Hn.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})}}),Wn=w(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=jn,Hn.init(e,t)}),Gn=w(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Mn,Hn.init(e,t)}),Kn=w(`$ZodCheckIncludes`,(e,t)=>{O.init(e,t);let n=Ve(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),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})}}),qn=w(`$ZodCheckStartsWith`,(e,t)=>{O.init(e,t);let n=RegExp(`^${Ve(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(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})}}),Jn=w(`$ZodCheckEndsWith`,(e,t)=>{O.init(e,t);let n=RegExp(`.*${Ve(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(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})}}),Yn=w(`$ZodCheckOverwrite`,(e,t)=>{O.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Xn=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1,e(this),--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 qn={major:4,minor:5,patch:2},A=T(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=qn;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=Ye(t),a;for(let o of n){if(o._zod.def.when){if(Xe(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 bt;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&($e(t.issues,n,e),i||=Ye(t,n))});else{if(t.issues.length===n)continue;$e(t.issues,n,e),i||=Ye(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(Ye(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new bt;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 bt;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return ct(this,`~standard`,Yn(this))},set"~standard"(e){st(this,`~standard`,e)}}),Jn=e=>e.success?{value:e.data}:{issues:e.error?.issues};function Yn(e){return{validate:t=>{try{return Jn(zt(e,t))}catch{return Vt(e,t).then(Jn)}},vendor:`zod`,version:1}}const Xn=T(`$ZodString`,(e,t)=>{A.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Cn(e._zod.bag),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}}),j=T(`$ZodStringFormat`,(e,t)=>{Rn.init(e,t),Xn.init(e,t)}),Zn=T(`$ZodGUID`,(e,t)=>{t.pattern??=an,j.init(e,t)}),Qn=T(`$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??=on(e)}else t.pattern??=on();j.init(e,t)}),$n=T(`$ZodEmail`,(e,t)=>{t.pattern??=sn,j.init(e,t)});function er(e,t){if(!t.normalize&&t.protocol?.source===hn.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}const tr=/[\t\n\r]/g;function nr(e){return e.replace(tr,``)}function rr(e,t){return t.lastIndex=0,t.test(e.hostname)}function ir(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const ar=T(`$ZodURL`,(e,t)=>{j.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=er(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&&!rr(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&&!ir(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:nr(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),or=T(`$ZodEmoji`,(e,t)=>{t.pattern??=cn(),j.init(e,t)}),sr=T(`$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?tn:nn(t.length),j.init(e,t)}),cr=T(`$ZodCUID`,(e,t)=>{t.pattern??=Xt,j.init(e,t)}),lr=T(`$ZodCUID2`,(e,t)=>{t.pattern??=Zt,j.init(e,t)}),ur=T(`$ZodULID`,(e,t)=>{t.pattern??=Qt,j.init(e,t)}),dr=T(`$ZodXID`,(e,t)=>{t.pattern??=$t,j.init(e,t)}),fr=T(`$ZodKSUID`,(e,t)=>{t.pattern??=en,j.init(e,t)}),pr=T(`$ZodISODateTime`,(e,t)=>{t.pattern??=Sn(t),j.init(e,t),(t.local||t.precision===-1)&&(e._zod.bag.laxFormat=!0,e._zod.onattach.push(e=>{e._zod.bag.laxFormat=!0}))}),mr=T(`$ZodISODate`,(e,t)=>{t.pattern??=yn,j.init(e,t)}),hr=T(`$ZodISOTime`,(e,t)=>{t.pattern??=xn(t),j.init(e,t)}),gr=T(`$ZodISODuration`,(e,t)=>{t.pattern??=rn,j.init(e,t)}),_r=T(`$ZodIPv4`,(e,t)=>{t.pattern??=ln,j.init(e,t),e._zod.bag.format=`ipv4`}),vr=/^[0-9a-fA-F:.]+$/;function yr(e){if(!vr.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}const br=T(`$ZodIPv6`,(e,t)=>{t.pattern??=un,j.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{yr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),xr=T(`$ZodCIDRv4`,(e,t)=>{t.pattern??=dn,j.init(e,t)});function Sr(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:yr(n)}const Cr=T(`$ZodCIDRv6`,(e,t)=>{t.pattern??=fn,j.init(e,t),e._zod.check=n=>{Sr(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 Tr=T(`$ZodBase64`,(e,t)=>{t.pattern??=pn,j.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{wr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Er(e){if(!mn.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return wr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Dr=T(`$ZodBase64URL`,(e,t)=>{t.pattern??=mn,j.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Er(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Or=T(`$ZodE164`,(e,t)=>{t.pattern??=gn,j.init(e,t)});function kr(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 Ar=T(`$ZodJWT`,(e,t)=>{j.init(e,t),e._zod.check=n=>{kr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),jr=T(`$ZodNumber`,(e,t)=>{A.init(e,t),e._zod.pattern=e._zod.bag.pattern??Tn,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}}),Mr=T(`$ZodNumberFormat`,(e,t)=>{Pn.init(e,t),jr.init(e,t)}),Nr=T(`$ZodBoolean`,(e,t)=>{A.init(e,t),e._zod.pattern=En,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}}),Pr=T(`$ZodUnknown`,(e,t)=>{A.init(e,t),e._zod.parse=e=>e}),Fr=T(`$ZodNever`,(e,t)=>{A.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Ir(e,t,n){e.issues.length&&t.issues.push(...Ze(n,e.issues)),t.value[n]=e.value}const Lr=T(`$ZodArray`,(e,t)=>{A.init(e,t);let n=E.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=[];for(let e=0;e<a.length;e++){let n=a[e],s=t.element._zod.run({value:n,issues:[]},i);s instanceof Promise?o.push(s.then(t=>Ir(t,r,e))):Ir(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function Rr(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(...Ze(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&&(t.value[n]=void 0):t.value[n]=e.value}}const zr=[];function Br(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:zr,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=Be(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function Vr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(let i in t){if(s.has(i))continue;if(i===`__proto__`){l===`never`&&o.push(i);continue}if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Rr(e,n,i,t,u,d))):Rr(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Hr=new WeakMap,Ur=T(`$ZodObject`,(e,t)=>{if(A.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Hr.set(t,e),Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),Hr.set(t,n),n}})}let n=we(()=>Br(t));w(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)||S(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 r=Me,i=t.catchall,a,o=E.memoizer;o?.attach(e),e._zod.parse=(t,s)=>{a??=n.value;let c=t.value;if(!r(c))return t.issues.push({expected:`object`,code:`invalid_type`,input:c,inst:e}),t;t.value=o?o.alloc(e,t,{},s):{};let l=[],u=a.shape;for(let e of a.allKeys){if(e===`__proto__`)continue;let n=u[e],r=n._zod.optin,i=n._zod.optout,a=n._zod.run({value:c[e],issues:[]},s);a instanceof Promise?l.push(a.then(n=>Rr(n,t,e,c,r,i))):Rr(a,t,e,c,r,i)}return i?Vr(l,c,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),Wr=T(`$ZodObjectJIT`,(e,t)=>{Ur.init(e,t);let n=e._zod.parse,r=we(()=>Br(t)),i=E.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Kn([`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 Zn={major:4,minor:5,patch:2},k=w(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Zn;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=$e(t),a;for(let o of n){if(o._zod.def.when){if(et(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 wt;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(rt(t.issues,n,e),i||=$e(t,n))});else{if(t.issues.length===n)continue;rt(t.issues,n,e),i||=$e(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if($e(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new wt;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 wt;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return ft(this,`~standard`,$n(this))},set"~standard"(e){dt(this,`~standard`,e)}}),Qn=e=>e.success?{value:e.data}:{issues:e.error?.issues};function $n(e){return{validate:t=>{try{return Qn(Ut(e,t))}catch{return Gt(e,t).then(Qn)}},vendor:`zod`,version:1}}const er=w(`$ZodString`,(e,t)=>{k.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Dn(e._zod.bag),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}}),A=w(`$ZodStringFormat`,(e,t)=>{Hn.init(e,t),er.init(e,t)}),tr=w(`$ZodGUID`,(e,t)=>{t.pattern??=ln,A.init(e,t)}),nr=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??=un(e)}else t.pattern??=un();A.init(e,t)}),rr=w(`$ZodEmail`,(e,t)=>{t.pattern??=dn,A.init(e,t)});function ir(e,t){if(!t.normalize&&t.protocol?.source===yn.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}const ar=/[\t\n\r]/g;function or(e){return e.replace(ar,``)}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 lr=w(`$ZodURL`,(e,t)=>{A.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=ir(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:or(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),ur=w(`$ZodEmoji`,(e,t)=>{t.pattern??=fn(),A.init(e,t)}),dr=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?on:sn(t.length),A.init(e,t)}),fr=w(`$ZodCUID`,(e,t)=>{t.pattern??=en,A.init(e,t)}),pr=w(`$ZodCUID2`,(e,t)=>{t.pattern??=tn,A.init(e,t)}),mr=w(`$ZodULID`,(e,t)=>{t.pattern??=nn,A.init(e,t)}),hr=w(`$ZodXID`,(e,t)=>{t.pattern??=rn,A.init(e,t)}),gr=w(`$ZodKSUID`,(e,t)=>{t.pattern??=an,A.init(e,t)}),_r=w(`$ZodISODateTime`,(e,t)=>{t.pattern??=En(t),A.init(e,t),(t.local||t.precision===-1)&&(e._zod.bag.laxFormat=!0,e._zod.onattach.push(e=>{e._zod.bag.laxFormat=!0}))}),vr=w(`$ZodISODate`,(e,t)=>{t.pattern??=Cn,A.init(e,t)}),yr=w(`$ZodISOTime`,(e,t)=>{t.pattern??=Tn(t),A.init(e,t)}),br=w(`$ZodISODuration`,(e,t)=>{t.pattern??=cn,A.init(e,t)}),xr=w(`$ZodIPv4`,(e,t)=>{t.pattern??=pn,A.init(e,t),e._zod.bag.format=`ipv4`}),Sr=/^[0-9a-fA-F:.]+$/;function Cr(e){if(!Sr.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}const wr=w(`$ZodIPv6`,(e,t)=>{t.pattern??=mn,A.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{Cr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Tr=w(`$ZodCIDRv4`,(e,t)=>{t.pattern??=hn,A.init(e,t)});function Er(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:Cr(n)}const Dr=w(`$ZodCIDRv6`,(e,t)=>{t.pattern??=gn,A.init(e,t),e._zod.check=n=>{Er(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Or(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const kr=w(`$ZodBase64`,(e,t)=>{t.pattern??=_n,A.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Or(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Ar(e){if(!vn.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Or(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const jr=w(`$ZodBase64URL`,(e,t)=>{t.pattern??=vn,A.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Ar(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Mr=w(`$ZodE164`,(e,t)=>{t.pattern??=bn,A.init(e,t)});function Nr(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 Pr=w(`$ZodJWT`,(e,t)=>{A.init(e,t),e._zod.check=n=>{Nr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Fr=w(`$ZodNumber`,(e,t)=>{k.init(e,t),e._zod.pattern=e._zod.bag.pattern??kn,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}}),Ir=w(`$ZodNumberFormat`,(e,t)=>{Rn.init(e,t),Fr.init(e,t)}),Lr=w(`$ZodBoolean`,(e,t)=>{k.init(e,t),e._zod.pattern=An,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}}),Rr=w(`$ZodUnknown`,(e,t)=>{k.init(e,t),e._zod.parse=e=>e}),zr=w(`$ZodNever`,(e,t)=>{k.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Br(e,t,n){e.issues.length&&t.issues.push(...tt(n,e.issues)),t.value[n]=e.value}const Vr=w(`$ZodArray`,(e,t)=>{k.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=[];for(let e=0;e<a.length;e++){let n=a[e],s=t.element._zod.run({value:n,issues:[]},i);s instanceof Promise?o.push(s.then(t=>Br(t,r,e))):Br(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function Hr(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(...tt(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&&(t.value[n]=void 0):t.value[n]=e.value}}const Ur=[];function Wr(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Ur,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=We(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function Gr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(let i in t){if(s.has(i))continue;if(i===`__proto__`){l===`never`&&o.push(i);continue}if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Hr(e,n,i,t,u,d))):Hr(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Kr=new WeakMap,qr=w(`$ZodObject`,(e,t)=>{if(k.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Kr.set(t,e),Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),Kr.set(t,n),n}})}let n=Oe(()=>Wr(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)||x(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 r=Ie,i=t.catchall,a,o=T.memoizer;o?.attach(e),e._zod.parse=(t,s)=>{a??=n.value;let c=t.value;if(!r(c))return t.issues.push({expected:`object`,code:`invalid_type`,input:c,inst:e}),t;t.value=o?o.alloc(e,t,{},s):{};let l=[],u=a.shape;for(let e of a.allKeys){if(e===`__proto__`)continue;let n=u[e],r=n._zod.optin,i=n._zod.optout,a=n._zod.run({value:c[e],issues:[]},s);a instanceof Promise?l.push(a.then(n=>Hr(n,t,e,c,r,i))):Hr(a,t,e,c,r,i)}return i?Gr(l,c,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),Jr=w(`$ZodObjectJIT`,(e,t)=>{qr.init(e,t);let n=e._zod.parse,r=Oe(()=>Wr(t)),i=T.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Xn([`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
  for (let i = 0; i < ${e}.issues.length; i++) {
7
7
  const iss = ${e}.issues[i];
8
8
  iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
9
9
  payload.issues.push(iss);
10
- }`;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)}]`:ke(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(`
10
+ }`;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)}]`:Ne(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(`
11
11
  const ${n}_present = ${i};
12
12
  if (!${n}.issues.length || ${n}_present) {
13
13
  if (${n}.issues.length) {${c(n,r)}
@@ -47,9 +47,9 @@ import{access as e,chmod as t,constants as n,copyFile as r,lstat as i,mkdir as a
47
47
  newResult[${r}] = ${n}.value;
48
48
  }
49
49
 
50
- `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Me,c=!E.jitless,l=c&&Ne.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?Vr([],p,i,f,d,e):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Gr(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=>!Ye(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=>et(e,r,D())))}),t)}const Kr=T(`$ZodUnion`,(e,t)=>{A.init(e,t),w(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),w(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),w(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)))}),w(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=>Ee(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=>Gr(t,r,e,i)):Gr(o,r,e,i)}}),qr=T(`$ZodIntersection`,(e,t)=>{A.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])=>Yr(e,t,n)):Yr(e,i,a)}});function Jr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Pe(e)&&Pe(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=Jr(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=Jr(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 Yr(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=Jr(t.value,n.value);if(!c.valid){if(Ye(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const Xr=T(`$ZodRecord`,(e,t)=>{A.init(e,t);let n=E.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Pe(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=>et(e,i,D())),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(...Ze(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Ze(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`&&Tn.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=>et(e,i,D())),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(...Ze(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Ze(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}}),Zr=T(`$ZodEnum`,(e,t)=>{A.init(e,t);let n=xe(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>Ie.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>Le(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}}),Qr=T(`$ZodTransform`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,E.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new xt(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 bt;return n.value=i,n}});function $r(e,t){return e.value=t.issues.length?void 0:t.value,e}const ei=T(`$ZodOptional`,(e,t)=>{A.init(e,t),w(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,w(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),w(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(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=>$r(e,t)):$r(e,r)}return t.innerType._zod.run(e,n)}}),ti=T(`$ZodExactOptional`,(e,t)=>{ei.init(e,t),w(e,`values`,e=>e.def.innerType._zod.values),w(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ni=T(`$ZodNullable`,(e,t)=>{A.init(e,t),w(e,`optin`,e=>e.def.innerType._zod.optin),w(e,`optout`,e=>e.def.innerType._zod.optout),w(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(t.source)}|null)$`):void 0}),w(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)}),ri=T(`$ZodDefault`,(e,t)=>{A.init(e,t),e._zod.optin=`defaulted`,w(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=>ii(e,t)):ii(r,t)}});function ii(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const ai=T(`$ZodPrefault`,(e,t)=>{A.init(e,t),e._zod.optin=`defaulted`,w(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))}),oi=T(`$ZodNonOptional`,(e,t)=>{A.init(e,t),w(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=>si(t,e)):si(i,e)}});function si(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 ci(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>et(e,r,D()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const li=T(`$ZodCatch`,(e,t)=>{A.init(e,t),w(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),w(e,`optout`,e=>e.def.innerType._zod.optout),w(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=>ci(e,r,t,n)):ci(e,r,t,n)}}),ui=T(`$ZodPipe`,(e,t)=>{A.init(e,t),w(e,`values`,e=>e.def.in._zod.values),w(e,`optin`,e=>e.def.in._zod.optin),w(e,`optout`,e=>e.def.out._zod.optout),w(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=>di(e,t.in,n)):di(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>di(e,t.out,n)):di(r,t.out,n)}});function di(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 fi=T(`$ZodPreprocess`,(e,t)=>{ui.init(e,t)}),pi=T(`$ZodReadonly`,(e,t)=>{A.init(e,t),w(e,`propValues`,e=>e.def.innerType._zod.propValues),w(e,`values`,e=>e.def.innerType._zod.values),w(e,`optin`,e=>e.def.innerType?._zod?.optin),w(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(mi):mi(r)}});function mi(e){return e.memo||(e.value=Object.freeze(e.value)),e}const hi=T(`$ZodCustom`,(e,t)=>{k.init(e,t),A.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=>gi(t,n,r,e));gi(i,n,r,e)}});function gi(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(at(e))}}var _i=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const vi=`~memo`,yi=[];function bi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const xi=new WeakMap;function Si(e,t){let n=xi.get(e);if(n!==void 0)return n;if(t.has(e))return!0;t.add(e);let r=!1,i=e=>{!r&&e?._zod&&Si(e,t)&&(r=!0)},a=e._zod.def;if(a.type===`lazy`)i(e._zod.innerType);else{let e=a.shape;if(e)for(let t of Reflect.ownKeys(e))i(e[t]);for(let e in a){let t=a[e];if(!(!t||typeof t!=`object`)){if(t._zod)i(t);else if(Array.isArray(t))for(let e of t)i(e)}}}return t.delete(e),xi.set(e,r),r}function Ci(e,t){let n=e.buckets.get(t);return n||(n=new Map,e.buckets.set(t,n)),n}let wi;const Ti=[],Ei={alloc(e,t,n){let r=wi;if(!r)return n;wi=void 0;let i={value:n,issues:null};return r.set(t.value,i),Ti.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`&&Oi(n,e.value))throw new _i;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,a=(o,s)=>{if(n===void 0&&(n=Si(e,new Set),!n))return e._zod.parse=t,e._zod.run===a&&(e._zod.run=t),t(o,s);let c=o.value;if(typeof c!=`object`||!c)return t(o,s);let l=s[vi];l||(l={buckets:new Map,backEdges:void 0},s[vi]=l);let u;r===s?u=i:(u=Ci(l,e),r=s,i=u);let d=u.get(c);if(d)return o.value=d.value,d.issues?d.issues.length&&o.issues.push(...bi(d.issues)):(o.memo=!0,l.backEdges??(l.backEdges=new Set),l.backEdges.add(d.value)),o;wi=u;let f=Ti.length,p=t(o,s);wi=void 0;let m=Ti.length>f?Ti.pop():void 0;return p instanceof Promise?p.then(e=>(m&&(m.issues=e.issues.length?bi(e.issues):yi),e)):(m&&(m.issues=p.issues.length?bi(p.issues):yi),p)};e._zod.parse=a,e._zod.run===t&&(e._zod.run=a)})}};function Di(){return Ei}function Oi(e,t){let n=e[vi]?.backEdges;return n!==void 0&&typeof t==`object`&&!!t&&n.has(t)}const ki=()=>{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`,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(it(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${ze(e.values[0])}`:`Invalid option: expected one of ${Se(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`:``}: ${Se(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 Ai(){return{localeError:ki()}}var ji,Mi=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 Ni(){return new Mi}(ji=globalThis).__zod_globalRegistry??(ji.__zod_globalRegistry=Ni());const Pi=globalThis.__zod_globalRegistry;function Fi(e,t){return new e({type:`string`,...C(t)})}function Ii(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...C(t)})}function Li(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...C(t)})}function Ri(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...C(t)})}function zi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...C(t)})}function Bi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...C(t)})}function Vi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...C(t)})}function Hi(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...C(t)})}function Ui(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...C(t)})}function Wi(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...C(t)})}function Gi(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...C(t)})}function Ki(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...C(t)})}function qi(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...C(t)})}function Ji(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...C(t)})}function Yi(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...C(t)})}function Xi(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...C(t)})}function Zi(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...C(t)})}function Qi(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...C(t)})}function $i(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...C(t)})}function ea(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...C(t)})}function ta(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...C(t)})}function na(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...C(t)})}function ra(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...C(t)})}function ia(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...C(t)})}function aa(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...C(t)})}function oa(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...C(t)})}function sa(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...C(t)})}function ca(e,t){return new e({type:`number`,checks:[],...C(t)})}function la(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...C(t)})}function ua(e,t){return new e({type:`boolean`,...C(t)})}function da(e){return new e({type:`unknown`})}function fa(e,t){return new e({type:`never`,...C(t)})}function pa(e,t){return new jn({check:`less_than`,...C(t),value:e,inclusive:!1})}function ma(e,t){return new jn({check:`less_than`,...C(t),value:e,inclusive:!0})}function ha(e,t){return new Mn({check:`greater_than`,...C(t),value:e,inclusive:!1})}function ga(e,t){return new Mn({check:`greater_than`,...C(t),value:e,inclusive:!0})}function _a(e,t){return new Nn({check:`multiple_of`,...C(t),value:e})}function va(e,t){return new Fn({check:`max_length`,...C(t),maximum:e})}function ya(e,t){return new In({check:`min_length`,...C(t),minimum:e})}function ba(e,t){return new Ln({check:`length_equals`,...C(t),length:e})}function xa(e,t){return new zn({check:`string_format`,format:`regex`,...C(t),pattern:e})}function Sa(e){return new Bn({check:`string_format`,format:`lowercase`,...C(e)})}function Ca(e){return new Vn({check:`string_format`,format:`uppercase`,...C(e)})}function wa(e,t){return new Hn({check:`string_format`,format:`includes`,...C(t),includes:e})}function Ta(e,t){return new Un({check:`string_format`,format:`starts_with`,...C(t),prefix:e})}function Ea(e,t){return new Wn({check:`string_format`,format:`ends_with`,...C(t),suffix:e})}function Da(e){return new Gn({check:`overwrite`,tx:e})}function Oa(e){return Da(t=>t.normalize(e))}function ka(){return Da(e=>e.trim())}function Aa(){return Da(e=>e.toLowerCase())}function ja(){return Da(e=>e.toUpperCase())}function Ma(){return Da(e=>Ae(e))}function Na(e,t,n){return new e({type:`array`,element:t,...C(n)})}function Pa(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...C(n)})}function Fa(e,t){let n=Ia(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(at(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(at(r))}},e(t.value,t)),t);return n}function Ia(e,t){let n=new k({check:`custom`,...C(t)});return n._zod.check=e,n}function La(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&S(e,t,n[t]);return e}function Ra(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??Pi,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:[],external:e?.external??void 0}}function za(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 M(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,M(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&La(o.schema,c),t.io===`input`&&N(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 Ba(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Va(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}/${Ba(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+Ba(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>
50
+ `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Ie,c=!T.jitless,l=c&&Le.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?Gr([],p,i,f,d,e):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Yr(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=>!$e(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=>it(e,r,E())))}),t)}const Xr=w(`$ZodUnion`,(e,t)=>{k.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=>Ae(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=>Yr(t,r,e,i)):Yr(o,r,e,i)}}),Zr=w(`$ZodIntersection`,(e,t)=>{k.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])=>$r(e,t,n)):$r(e,i,a)}});function Qr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Re(e)&&Re(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=Qr(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=Qr(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 $r(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=Qr(t.value,n.value);if(!c.valid){if($e(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const ei=w(`$ZodRecord`,(e,t)=>{k.init(e,t);let n=T.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Re(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=>it(e,i,E())),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(...tt(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...tt(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`&&kn.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=>it(e,i,E())),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(...tt(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...tt(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}}),ti=w(`$ZodEnum`,(e,t)=>{k.init(e,t);let n=Te(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>Be.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>Ve(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}}),ni=w(`$ZodTransform`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,T.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Tt(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 wt;return n.value=i,n}});function ri(e,t){return e.value=t.issues.length?void 0:t.value,e}const ii=w(`$ZodOptional`,(e,t)=>{k.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(`^(${Ae(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=>ri(e,t)):ri(e,r)}return t.innerType._zod.run(e,n)}}),ai=w(`$ZodExactOptional`,(e,t)=>{ii.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)}),oi=w(`$ZodNullable`,(e,t)=>{k.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(`^(${Ae(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)}),si=w(`$ZodDefault`,(e,t)=>{k.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=>ci(e,t)):ci(r,t)}});function ci(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const li=w(`$ZodPrefault`,(e,t)=>{k.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))}),ui=w(`$ZodNonOptional`,(e,t)=>{k.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 fi(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>it(e,r,E()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const pi=w(`$ZodCatch`,(e,t)=>{k.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=>fi(e,r,t,n)):fi(e,r,t,n)}}),mi=w(`$ZodPipe`,(e,t)=>{k.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=>hi(e,t.in,n)):hi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>hi(e,t.out,n)):hi(r,t.out,n)}});function hi(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 gi=w(`$ZodPreprocess`,(e,t)=>{mi.init(e,t)}),_i=w(`$ZodReadonly`,(e,t)=>{k.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(vi):vi(r)}});function vi(e){return e.memo||(e.value=Object.freeze(e.value)),e}const yi=w(`$ZodCustom`,(e,t)=>{O.init(e,t),k.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=>bi(t,n,r,e));bi(i,n,r,e)}});function bi(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(lt(e))}}var xi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Si=`~memo`,Ci=[];function wi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const Ti=new WeakMap;function Ei(e,t){let n=Ti.get(e);if(n!==void 0)return n;if(t.has(e))return!0;t.add(e);let r=!1,i=e=>{!r&&e?._zod&&Ei(e,t)&&(r=!0)},a=e._zod.def;if(a.type===`lazy`)i(e._zod.innerType);else{let e=a.shape;if(e)for(let t of Reflect.ownKeys(e))i(e[t]);for(let e in a){let t=a[e];if(!(!t||typeof t!=`object`)){if(t._zod)i(t);else if(Array.isArray(t))for(let e of t)i(e)}}}return t.delete(e),Ti.set(e,r),r}function Di(e,t){let n=e.buckets.get(t);return n||(n=new Map,e.buckets.set(t,n)),n}let Oi;const ki=[],Ai={alloc(e,t,n){let r=Oi;if(!r)return n;Oi=void 0;let i={value:n,issues:null};return r.set(t.value,i),ki.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`&&Mi(n,e.value))throw new xi;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,a=(o,s)=>{if(n===void 0&&(n=Ei(e,new Set),!n))return e._zod.parse=t,e._zod.run===a&&(e._zod.run=t),t(o,s);let c=o.value;if(typeof c!=`object`||!c)return t(o,s);let l=s[Si];l||(l={buckets:new Map,backEdges:void 0},s[Si]=l);let u;r===s?u=i:(u=Di(l,e),r=s,i=u);let d=u.get(c);if(d)return o.value=d.value,d.issues?d.issues.length&&o.issues.push(...wi(d.issues)):(o.memo=!0,l.backEdges??(l.backEdges=new Set),l.backEdges.add(d.value)),o;Oi=u;let f=ki.length,p=t(o,s);Oi=void 0;let ee=ki.length>f?ki.pop():void 0;return p instanceof Promise?p.then(e=>(ee&&(ee.issues=e.issues.length?wi(e.issues):Ci),e)):(ee&&(ee.issues=p.issues.length?wi(p.issues):Ci),p)};e._zod.parse=a,e._zod.run===t&&(e._zod.run=a)})}};function ji(){return Ai}function Mi(e,t){let n=e[Si]?.backEdges;return n!==void 0&&typeof t==`object`&&!!t&&n.has(t)}const Ni=()=>{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`,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(ct(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Ue(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 Pi(){return{localeError:Ni()}}var Fi,Ii=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 Li(){return new Ii}(Fi=globalThis).__zod_globalRegistry??(Fi.__zod_globalRegistry=Li());const Ri=globalThis.__zod_globalRegistry;function zi(e,t){return new e({type:`string`,...S(t)})}function Bi(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...S(t)})}function Vi(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...S(t)})}function Hi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...S(t)})}function Ui(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...S(t)})}function Wi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...S(t)})}function Gi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...S(t)})}function Ki(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...S(t)})}function qi(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...S(t)})}function Ji(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...S(t)})}function Yi(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...S(t)})}function Xi(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...S(t)})}function Zi(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...S(t)})}function Qi(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...S(t)})}function $i(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...S(t)})}function ea(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...S(t)})}function ta(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...S(t)})}function na(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...S(t)})}function ra(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...S(t)})}function ia(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...S(t)})}function aa(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...S(t)})}function oa(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...S(t)})}function sa(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...S(t)})}function ca(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...S(t)})}function la(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...S(t)})}function ua(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...S(t)})}function da(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...S(t)})}function fa(e,t){return new e({type:`number`,checks:[],...S(t)})}function pa(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 ha(e){return new e({type:`unknown`})}function ga(e,t){return new e({type:`never`,...S(t)})}function _a(e,t){return new Fn({check:`less_than`,...S(t),value:e,inclusive:!1})}function va(e,t){return new Fn({check:`less_than`,...S(t),value:e,inclusive:!0})}function ya(e,t){return new In({check:`greater_than`,...S(t),value:e,inclusive:!1})}function ba(e,t){return new In({check:`greater_than`,...S(t),value:e,inclusive:!0})}function xa(e,t){return new Ln({check:`multiple_of`,...S(t),value:e})}function Sa(e,t){return new zn({check:`max_length`,...S(t),maximum:e})}function Ca(e,t){return new Bn({check:`min_length`,...S(t),minimum:e})}function wa(e,t){return new Vn({check:`length_equals`,...S(t),length:e})}function Ta(e,t){return new Un({check:`string_format`,format:`regex`,...S(t),pattern:e})}function Ea(e){return new Wn({check:`string_format`,format:`lowercase`,...S(e)})}function Da(e){return new Gn({check:`string_format`,format:`uppercase`,...S(e)})}function Oa(e,t){return new Kn({check:`string_format`,format:`includes`,...S(t),includes:e})}function ka(e,t){return new qn({check:`string_format`,format:`starts_with`,...S(t),prefix:e})}function Aa(e,t){return new Jn({check:`string_format`,format:`ends_with`,...S(t),suffix:e})}function ja(e){return new Yn({check:`overwrite`,tx:e})}function Ma(e){return ja(t=>t.normalize(e))}function Na(){return ja(e=>e.trim())}function Pa(){return ja(e=>e.toLowerCase())}function Fa(){return ja(e=>e.toUpperCase())}function Ia(){return ja(e=>Pe(e))}function La(e,t,n){return new e({type:`array`,element:t,...S(n)})}function Ra(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...S(n)})}function za(e,t){let n=Ba(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(lt(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(lt(r))}},e(t.value,t)),t);return n}function Ba(e,t){let n=new O({check:`custom`,...S(t)});return n._zod.check=e,n}function Va(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&x(e,t,n[t]);return e}function Ha(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??Ri,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:[],external:e?.external??void 0}}function Ua(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 j(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,j(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Va(o.schema,c),t.io===`input`&&M(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 Wa(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Ga(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}/${Wa(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+Wa(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>
51
51
 
52
- 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}if(r.count>1&&e.reused===`ref`){a(n);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function Ha(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;Ha(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 Ua=new Set([`type`,`properties`,`required`,`additionalProperties`]),Wa=[`oneOf`,`anyOf`];function Ga(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Ka(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Ua.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]??Ga(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}S(n,r,e.length===1?e[0]:Ka(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=Ga(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 qa(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Ua)if(t in e)return;let n=t.filter(e=>Wa.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Ka(t);else{let e=n[0],i=Wa.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=>Ka([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,La(e,r))}function Ja(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)):La(i,s),La(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())Ha(t[1].def??t[1].schema);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)??[])qa(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)}La(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,S(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:Xa(t,`input`,e.processors),output:Xa(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function N(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 N(r.element,n);if(r.type===`set`)return N(r.valueType,n);if(r.type===`lazy`)return N(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 N(r.innerType,n);if(r.type===`intersection`)return N(r.left,n)||N(r.right,n);if(r.type===`record`||r.type===`map`)return N(r.keyType,n)||N(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:N(r.in,n)||N(r.out,n);if(r.type===`object`){for(let e in r.shape)if(N(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(N(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(N(e,n))return!0;return!!(r.rest&&N(r.rest,n))}return!1}const Ya=(e,t={})=>n=>{let r=Ra({...n,processors:t});return M(e,r),Va(r,e),Ja(r,e)},Xa=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Ra({...i??{},target:a,io:t,processors:n});return M(e,o),Va(o,e),Ja(o,e)},Za={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Qa=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Za[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];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}))])}},$a=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(Number.isFinite(c)&&c!==0?i.multipleOf=Math.abs(c):za(e,t,i,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))},eo=(e,t,n,r)=>{n.type=`boolean`},to=(e,t,n,r)=>{n.not={}},no=(e,t,n,r)=>{let i=e._zod.def,a=xe(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},ro=(e,t,n,r)=>{za(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},io=(e,t,n,r)=>{za(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ao=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=M(a.element,t,{...r,path:[...r.path,`items`]})};function oo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?oo(t.out):t.type===`catch`?oo(t.innerType):e._zod.optin}const so=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&za(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)S(i.properties,e,M(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`?oo(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=M(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},co=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>M(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},lo=(e,t,n,r)=>{let i=e._zod.def,a=M(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=M(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)},uo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=M(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)S(i.patternProperties,t.source,e)}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=M(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=M(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values,l=t.io===`input`&&oo(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)}},fo=(e,t,n,r)=>{let i=e._zod.def,a=M(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`}]},po=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},mo=Symbol();function ho(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(za(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),mo):JSON.parse(o)}const go=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=ho(i.defaultValue,e,t,n,r);o!==mo&&(n.default=o)},_o=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=ho(i.defaultValue,e,t,n,r);o!==mo&&(n._prefault=o)},vo=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{za(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},yo=(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;M(o,t,r);let s=t.seen.get(e);s.ref=o},bo=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},xo=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},So=new WeakSet([Object.prototype,Error.prototype]);function Co(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 P=T(`ZodError`,(e,t)=>{kt.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);So.has(n)||(So.add(n),Co(n,`format`,e=>t=>Nt(e,t)),Co(n,`flatten`,e=>t=>Mt(e,t)),Co(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ce,2)}),Co(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ce,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),wo=It(P),To=Lt(P),Eo=Rt(P),Do=Bt(P),Oo=Ht(P),ko=Ut(P),Ao=Wt(P),jo=Gt(P),Mo=Kt(P),No=qt(P),Po=Jt(P),Fo=Yt(P);function Io(){E.localeError||D(Ai())}function Lo(){E.memoizer||D({memoizer:Di()})}const F=T(`ZodType`,(e,t)=>(Io(),A.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Oe(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 Re(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check($s(e,t))},superRefine(e,t){return this.check(ec(e,t))},overwrite(e){return this.check(Da(e))},optional(){return Ps(this)},exactOptional(){return Is(this)},nullable(){return Rs(this)},nullish(){return Ps(Rs(this))},nonoptional(e){return Ws(this,e)},array(){return bs(this)},or(e){return ws([this,e])},and(e){return Es(this,e)},transform(e){return Js(this,Ms(e))},default(e){return Bs(this,e)},prefault(e){return Hs(this,e)},catch(e){return Ks(this,e)},pipe(e){return Js(this,e)},readonly(){return Zs(this)},describe(e){let t=this.clone();return Pi.add(t,{description:e}),t},meta(...e){if(e.length===0)return Pi.get(this);let t=this.clone();return Pi.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`,{...Yn(this),jsonSchema:{input:Xa(this,`input`),output:Xa(this,`output`)}})},set"~standard"(e){st(this,`~standard`,e)},parse:function e(t,n){return wo(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await To(this,t,n,{callee:e})},safeParse(e,t){return Eo(this,e,t)},async safeParseAsync(e,t){return Do(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){st(this,`spa`,e)},encode:function e(t,n){return Oo(this,t,n,{callee:e})},decode:function e(t,n){return ko(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Ao(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await jo(this,t,n,{callee:e})},safeEncode(e,t){return Mo(this,e,t)},safeDecode(e,t){return No(this,e,t)},async safeEncodeAsync(e,t){return Po(this,e,t)},async safeDecodeAsync(e,t){return Fo(this,e,t)},toJSONSchema(e){return Ya(this,{})(e)},get description(){return Pi.get(this)?.description},get _def(){return this._zod.def}}),Ro=T(`_ZodString`,(e,t)=>{Xn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qa(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null},{regex(...e){return this.check(xa(...e))},includes(...e){return this.check(wa(...e))},startsWith(...e){return this.check(Ta(...e))},endsWith(...e){return this.check(Ea(...e))},min(...e){return this.check(ya(...e))},max(...e){return this.check(va(...e))},length(...e){return this.check(ba(...e))},nonempty(...e){return this.check(ya(1,...e))},lowercase(e){return this.check(Sa(e))},uppercase(e){return this.check(Ca(e))},trim(){return this.check(ka())},normalize(...e){return this.check(Oa(...e))},toLowerCase(){return this.check(Aa())},toUpperCase(){return this.check(ja())},slugify(){return this.check(Ma())}}),zo=T(`ZodString`,(e,t)=>{Xn.init(e,t),Ro.init(e,t)},{email(e){return this.check(Ii(Wo,e))},url(e){return this.check(Hi(qo,e))},jwt(e){return this.check(ra(cs,e))},emoji(e){return this.check(Ui(Jo,e))},guid(e){return this.check(Li(Go,e))},uuid(e){return this.check(Ri(Ko,e))},uuidv4(e){return this.check(zi(Ko,e))},uuidv6(e){return this.check(Bi(Ko,e))},uuidv7(e){return this.check(Vi(Ko,e))},nanoid(e){return this.check(Wi(Yo,e))},cuid(e){return this.check(Gi(Xo,e))},cuid2(e){return this.check(Ki(Zo,e))},ulid(e){return this.check(qi(Qo,e))},base64(e){return this.check(ea(as,e))},base64url(e){return this.check(ta(os,e))},xid(e){return this.check(Ji($o,e))},ksuid(e){return this.check(Yi(es,e))},ipv4(e){return this.check(Xi(ts,e))},ipv6(e){return this.check(Zi(ns,e))},cidrv4(e){return this.check(Qi(rs,e))},cidrv6(e){return this.check($i(is,e))},e164(e){return this.check(na(ss,e))},datetime(e){return this.check(ia(Bo,e))},date(e){return this.check(aa(Vo,e))},time(e){return this.check(oa(Ho,e))},duration(e){return this.check(sa(Uo,e))}});function I(e){return Fi(zo,e)}const L=T(`ZodStringFormat`,(e,t)=>{j.init(e,t),Ro.init(e,t)}),Bo=T(`ZodISODateTime`,(e,t)=>{pr.init(e,t),L.init(e,t)}),Vo=T(`ZodISODate`,(e,t)=>{mr.init(e,t),L.init(e,t)}),Ho=T(`ZodISOTime`,(e,t)=>{hr.init(e,t),L.init(e,t)}),Uo=T(`ZodISODuration`,(e,t)=>{gr.init(e,t),L.init(e,t)}),Wo=T(`ZodEmail`,(e,t)=>{$n.init(e,t),L.init(e,t)}),Go=T(`ZodGUID`,(e,t)=>{Zn.init(e,t),L.init(e,t)}),Ko=T(`ZodUUID`,(e,t)=>{Qn.init(e,t),L.init(e,t)}),qo=T(`ZodURL`,(e,t)=>{ar.init(e,t),L.init(e,t)}),Jo=T(`ZodEmoji`,(e,t)=>{or.init(e,t),L.init(e,t)}),Yo=T(`ZodNanoID`,(e,t)=>{sr.init(e,t),L.init(e,t)}),Xo=T(`ZodCUID`,(e,t)=>{cr.init(e,t),L.init(e,t)}),Zo=T(`ZodCUID2`,(e,t)=>{lr.init(e,t),L.init(e,t)}),Qo=T(`ZodULID`,(e,t)=>{ur.init(e,t),L.init(e,t)}),$o=T(`ZodXID`,(e,t)=>{dr.init(e,t),L.init(e,t)}),es=T(`ZodKSUID`,(e,t)=>{fr.init(e,t),L.init(e,t)}),ts=T(`ZodIPv4`,(e,t)=>{_r.init(e,t),L.init(e,t)}),ns=T(`ZodIPv6`,(e,t)=>{br.init(e,t),L.init(e,t)}),rs=T(`ZodCIDRv4`,(e,t)=>{xr.init(e,t),L.init(e,t)}),is=T(`ZodCIDRv6`,(e,t)=>{Cr.init(e,t),L.init(e,t)}),as=T(`ZodBase64`,(e,t)=>{Tr.init(e,t),L.init(e,t)}),os=T(`ZodBase64URL`,(e,t)=>{Dr.init(e,t),L.init(e,t)}),ss=T(`ZodE164`,(e,t)=>{Or.init(e,t),L.init(e,t)}),cs=T(`ZodJWT`,(e,t)=>{Ar.init(e,t),L.init(e,t)}),ls=T(`ZodNumber`,(e,t)=>{jr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$a(e,t,n,r);let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null},{gt(e,t){return this.check(ha(e,t))},gte(e,t){return this.check(ga(e,t))},min(e,t){return this.check(ga(e,t))},lt(e,t){return this.check(pa(e,t))},lte(e,t){return this.check(ma(e,t))},max(e,t){return this.check(ma(e,t))},int(e){return this.check(fs(e))},safe(e){return this.check(fs(e))},positive(e){return this.check(ha(0,e))},nonnegative(e){return this.check(ga(0,e))},negative(e){return this.check(pa(0,e))},nonpositive(e){return this.check(ma(0,e))},multipleOf(e,t){return this.check(_a(e,t))},step(e,t){return this.check(_a(e,t))},finite(){return this}});function us(e){return ca(ls,e)}const ds=T(`ZodNumberFormat`,(e,t)=>{Mr.init(e,t),ls.init(e,t)});function fs(e){return la(ds,e)}const ps=T(`ZodBoolean`,(e,t)=>{Nr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eo(e,t,n,r)});function ms(e){return ua(ps,e)}const hs=T(`ZodUnknown`,(e,t)=>{Pr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function gs(){return da(hs)}const _s=T(`ZodNever`,(e,t)=>{Fr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>to(e,t,n,r)});function vs(e){return fa(_s,e)}const ys=T(`ZodArray`,(e,t)=>{Lo(),Lr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ao(e,t,n,r),e.element=t.element},{min(e,t){return this.check(ya(e,t))},nonempty(e){return this.check(ya(1,e))},max(e,t){return this.check(va(e,t))},length(e,t){return this.check(ba(e,t))},unwrap(){return this.element}});function bs(e,t){return Na(ys,e,t)}const xs=T(`ZodObject`,(e,t)=>{Lo(),Wr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>so(e,t,n,r),mt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return As(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:gs()})},loose(){return this.clone({...this._zod.def,catchall:gs()})},strict(){return this.clone({...this._zod.def,catchall:vs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return We(this,e)},safeExtend(e){return Ge(this,e)},merge(e){return Ke(this,e)},pick(e){return He(this,e)},omit(e){return Ue(this,e)},partial(...e){return qe(Ns,this,e[0])},exactPartial(...e){return qe(Fs,this,e[0],`exactPartial`)},required(...e){return Je(Us,this,e[0])}});function R(e,t){return new xs({type:`object`,shape:e,catchall:vs(),...C(t)})}function Ss(e,t){return new xs({type:`object`,shape:e,catchall:gs(),...C(t)})}const Cs=T(`ZodUnion`,(e,t)=>{Kr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>co(e,t,n,r),e.options=t.options});function ws(e,t){return new Cs({type:`union`,options:e,...C(t)})}const Ts=T(`ZodIntersection`,(e,t)=>{qr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lo(e,t,n,r)});function Es(e,t){return new Ts({type:`intersection`,left:e,right:t})}const Ds=T(`ZodRecord`,(e,t)=>{Lo(),Xr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Os(e,t,n){return!t||!t._zod?new Ds({type:`record`,keyType:I(),valueType:e,...C(t)}):new Ds({type:`record`,keyType:e,valueType:t,...C(n)})}const ks=T(`ZodEnum`,(e,t)=>{Zr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>no(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);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 ks({...t,checks:[],...C(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 ks({...t,checks:[],...C(r),entries:i})}});function As(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ks({type:`enum`,entries:n,...C(t)})}const js=T(`ZodTransform`,(e,t)=>{Lo(),Qr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>io(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new xt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(at(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(at(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Ms(e){return new js({type:`transform`,transform:e})}const Ns=T(`ZodOptional`,(e,t)=>{ei.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ps(e){return new Ns({type:`optional`,innerType:e})}const Fs=T(`ZodExactOptional`,(e,t)=>{ti.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Is(e){return new Fs({type:`optional`,innerType:e})}const Ls=T(`ZodNullable`,(e,t)=>{ni.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rs(e){return new Ls({type:`nullable`,innerType:e})}const zs=T(`ZodDefault`,(e,t)=>{ri.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>go(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bs(e,t){return new zs({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Fe(t)}})}const Vs=T(`ZodPrefault`,(e,t)=>{ai.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_o(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hs(e,t){return new Vs({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Fe(t)}})}const Us=T(`ZodNonOptional`,(e,t)=>{oi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>po(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ws(e,t){return new Us({type:`nonoptional`,innerType:e,...C(t)})}const Gs=T(`ZodCatch`,(e,t)=>{li.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ks(e,t){return new Gs({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:ht(t)})}const qs=T(`ZodPipe`,(e,t)=>{ui.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yo(e,t,n,r),e.in=t.in,e.out=t.out});function Js(e,t){return new qs({type:`pipe`,in:e,out:t})}const Ys=T(`ZodPreprocess`,(e,t)=>{qs.init(e,t),fi.init(e,t)}),Xs=T(`ZodReadonly`,(e,t)=>{pi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Zs(e){return new Xs({type:`readonly`,innerType:e})}const Qs=T(`ZodCustom`,(e,t)=>{hi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ro(e,t,n,r)});function $s(e,t={}){return Pa(Qs,e,t)}function ec(e,t){return Fa(e,t)}function tc(e,t){return new Ys({type:`pipe`,in:Ms(e),out:t})}function nc(e){return ia(Bo,e)}const rc=new Set([`__proto__`,`constructor`,`prototype`]),ic=(e,t,n)=>tc((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),ac=e=>e.length>0&&!rc.has(e),oc=e=>ic(ac,()=>`package key must be non-empty and not "__proto__", "constructor", or "prototype"`,Os(I().min(1),e)),sc=[`blobless`,`full`],cc=[`ssh`,`https`],lc=/^(?!\.{1,2}$)[^/\\%:]+$/u,uc=/^[a-z0-9][a-z0-9.-]*(?:_[1-9]\d{0,4})?$/u,dc=/^(?<amount>[1-9]\d{0,3})(?<unit>[mhd])$/u,fc={d:864e5,h:36e5,m:6e4},pc=e=>e!==``&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e),mc=e=>{if(e===void 0)return!0;let t=Number(e);return t>=1&&t<=65535},hc=e=>{let[t=``,n]=e.split(`_`);return mc(n)?t.split(`.`).every(e=>pc(e)):!1},z=I().refine(e=>{let[t,...n]=e.split(`/`);return t===void 0||n.length<2||!uc.test(t)||!hc(t)?!1:n.every(e=>lc.test(e))},`ref key must be host/path…/repo with safe, non-empty segments`).brand(),gc=I().regex(dc,`duration must be <n>m, <n>h, or <n>d`).brand(),_c=e=>{let t=dc.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)*fc[r]},vc=As(sc),yc=As(cc),bc=I().refine(e=>e.includes(`{version}`),`tag format must contain {version}`),xc=I().refine(e=>{if(e===`.`)return!0;let t=e.split(`/`);return t.length>0&&t.every(e=>lc.test(e)&&e!==`.`)},`package path must be "." or a normalized relative path without traversal`),Sc={clone_mode:`blobless`,git_transport:`https`,sync_ttl:`1h`},Cc=R({clone_mode:vc.default(Sc.clone_mode),git_transport:yc.default(Sc.git_transport),sync_ttl:gc.default(gc.parse(Sc.sync_ttl))}),wc=R((e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.removeDefault().optional()])))(Cc.shape)),Tc=R({description:I().min(1),path:xc,tag_format:bc.optional()}),Ec=R({default_branch:I().min(1),description:I().min(1),packages:oc(Tc).optional(),tag_format:bc.optional(),url:I().min(1),...wc.shape}),Dc=Ss({cli_version:I().min(1),schema_version:us().int().positive()}),Oc=ic(e=>z.safeParse(e).success,()=>`ref key must be host/path…/repo with safe, non-empty segments`,Os(I(),Ec)),kc=R({check:ms().default(!0),notify:ms().default(!0)}),Ac=R({meta:Dc,refs:Oc.default({}),settings:Cc,updates:kc.optional()});
52
+ 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}if(r.count>1&&e.reused===`ref`){a(n);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function Ka(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;Ka(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 qa=new Set([`type`,`properties`,`required`,`additionalProperties`]),Ja=[`oneOf`,`anyOf`];function Ya(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Xa(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!qa.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]??Ya(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}x(n,r,e.length===1?e[0]:Xa(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=Ya(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 Za(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of qa)if(t in e)return;let n=t.filter(e=>Ja.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Xa(t);else{let e=n[0],i=Ja.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=>Xa([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Va(e,r))}function Qa(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)):Va(i,s),Va(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())Ka(t[1].def??t[1].schema);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)??[])Za(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)}Va(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,x(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:eo(t,`input`,e.processors),output:eo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function M(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 M(r.element,n);if(r.type===`set`)return M(r.valueType,n);if(r.type===`lazy`)return M(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 M(r.innerType,n);if(r.type===`intersection`)return M(r.left,n)||M(r.right,n);if(r.type===`record`||r.type===`map`)return M(r.keyType,n)||M(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:M(r.in,n)||M(r.out,n);if(r.type===`object`){for(let e in r.shape)if(M(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(M(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(M(e,n))return!0;return!!(r.rest&&M(r.rest,n))}return!1}const $a=(e,t={})=>n=>{let r=Ha({...n,processors:t});return j(e,r),Ga(r,e),Qa(r,e)},eo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Ha({...i??{},target:a,io:t,processors:n});return j(e,o),Ga(o,e),Qa(o,e)},to={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},no=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=to[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];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}))])}},ro=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(Number.isFinite(c)&&c!==0?i.multipleOf=Math.abs(c):Ua(e,t,i,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))},io=(e,t,n,r)=>{n.type=`boolean`},ao=(e,t,n,r)=>{n.not={}},oo=(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},so=(e,t,n,r)=>{Ua(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},co=(e,t,n,r)=>{Ua(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},lo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=j(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 fo=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Ua(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)x(i.properties,e,j(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=j(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},po=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>j(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},mo=(e,t,n,r)=>{let i=e._zod.def,a=j(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=j(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)},ho=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=j(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)x(i.patternProperties,t.source,e)}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=j(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=j(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)}},go=(e,t,n,r)=>{let i=e._zod.def,a=j(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`}]},_o=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},vo=Symbol();function yo(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Ua(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),vo):JSON.parse(o)}const bo=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=yo(i.defaultValue,e,t,n,r);o!==vo&&(n.default=o)},xo=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=yo(i.defaultValue,e,t,n,r);o!==vo&&(n._prefault=o)},So=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Ua(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Co=(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;j(o,t,r);let s=t.seen.get(e);s.ref=o},wo=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},To=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Eo=new WeakSet([Object.prototype,Error.prototype]);function Do(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)=>{Nt.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Eo.has(n)||(Eo.add(n),Do(n,`format`,e=>t=>Lt(e,t)),Do(n,`flatten`,e=>t=>It(e,t)),Do(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,De,2)}),Do(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}),Oo=Bt(N),ko=Vt(N),Ao=Ht(N),jo=Wt(N),Mo=Kt(N),No=qt(N),Po=Jt(N),Fo=Yt(N),Io=Xt(N),Lo=Zt(N),Ro=Qt(N),zo=$t(N);function Bo(){T.localeError||E(Pi())}function Vo(){T.memoizer||E({memoizer:ji()})}const P=w(`ZodType`,(e,t)=>(Bo(),k.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Me(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 He(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(ic(e,t))},superRefine(e,t){return this.check(ac(e,t))},overwrite(e){return this.check(ja(e))},optional(){return zs(this)},exactOptional(){return Vs(this)},nullable(){return Us(this)},nullish(){return zs(Us(this))},nonoptional(e){return Ys(this,e)},array(){return ws(this)},or(e){return ks([this,e])},and(e){return js(this,e)},transform(e){return $s(this,Ls(e))},default(e){return Gs(this,e)},prefault(e){return qs(this,e)},catch(e){return Zs(this,e)},pipe(e){return $s(this,e)},readonly(){return nc(this)},describe(e){let t=this.clone();return Ri.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ri.get(this);let t=this.clone();return Ri.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 ft(this,`~standard`,{...$n(this),jsonSchema:{input:eo(this,`input`),output:eo(this,`output`)}})},set"~standard"(e){dt(this,`~standard`,e)},parse:function e(t,n){return Oo(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ko(this,t,n,{callee:e})},safeParse(e,t){return Ao(this,e,t)},async safeParseAsync(e,t){return jo(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){dt(this,`spa`,e)},encode:function e(t,n){return Mo(this,t,n,{callee:e})},decode:function e(t,n){return No(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Po(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Fo(this,t,n,{callee:e})},safeEncode(e,t){return Io(this,e,t)},safeDecode(e,t){return Lo(this,e,t)},async safeEncodeAsync(e,t){return Ro(this,e,t)},async safeDecodeAsync(e,t){return zo(this,e,t)},toJSONSchema(e){return $a(this,{})(e)},get description(){return Ri.get(this)?.description},get _def(){return this._zod.def}}),Ho=w(`_ZodString`,(e,t)=>{er.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>no(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null},{regex(...e){return this.check(Ta(...e))},includes(...e){return this.check(Oa(...e))},startsWith(...e){return this.check(ka(...e))},endsWith(...e){return this.check(Aa(...e))},min(...e){return this.check(Ca(...e))},max(...e){return this.check(Sa(...e))},length(...e){return this.check(wa(...e))},nonempty(...e){return this.check(Ca(1,...e))},lowercase(e){return this.check(Ea(e))},uppercase(e){return this.check(Da(e))},trim(){return this.check(Na())},normalize(...e){return this.check(Ma(...e))},toLowerCase(){return this.check(Pa())},toUpperCase(){return this.check(Fa())},slugify(){return this.check(Ia())}}),Uo=w(`ZodString`,(e,t)=>{er.init(e,t),Ho.init(e,t)},{email(e){return this.check(Bi(Jo,e))},url(e){return this.check(Ki(Zo,e))},jwt(e){return this.check(sa(fs,e))},emoji(e){return this.check(qi(Qo,e))},guid(e){return this.check(Vi(Yo,e))},uuid(e){return this.check(Hi(Xo,e))},uuidv4(e){return this.check(Ui(Xo,e))},uuidv6(e){return this.check(Wi(Xo,e))},uuidv7(e){return this.check(Gi(Xo,e))},nanoid(e){return this.check(Ji($o,e))},cuid(e){return this.check(Yi(es,e))},cuid2(e){return this.check(Xi(ts,e))},ulid(e){return this.check(Zi(ns,e))},base64(e){return this.check(ia(ls,e))},base64url(e){return this.check(aa(us,e))},xid(e){return this.check(Qi(rs,e))},ksuid(e){return this.check($i(is,e))},ipv4(e){return this.check(ea(as,e))},ipv6(e){return this.check(ta(os,e))},cidrv4(e){return this.check(na(ss,e))},cidrv6(e){return this.check(ra(cs,e))},e164(e){return this.check(oa(ds,e))},datetime(e){return this.check(ca(Wo,e))},date(e){return this.check(la(Go,e))},time(e){return this.check(ua(Ko,e))},duration(e){return this.check(da(qo,e))}});function F(e){return zi(Uo,e)}const I=w(`ZodStringFormat`,(e,t)=>{A.init(e,t),Ho.init(e,t)}),Wo=w(`ZodISODateTime`,(e,t)=>{_r.init(e,t),I.init(e,t)}),Go=w(`ZodISODate`,(e,t)=>{vr.init(e,t),I.init(e,t)}),Ko=w(`ZodISOTime`,(e,t)=>{yr.init(e,t),I.init(e,t)}),qo=w(`ZodISODuration`,(e,t)=>{br.init(e,t),I.init(e,t)}),Jo=w(`ZodEmail`,(e,t)=>{rr.init(e,t),I.init(e,t)}),Yo=w(`ZodGUID`,(e,t)=>{tr.init(e,t),I.init(e,t)}),Xo=w(`ZodUUID`,(e,t)=>{nr.init(e,t),I.init(e,t)}),Zo=w(`ZodURL`,(e,t)=>{lr.init(e,t),I.init(e,t)}),Qo=w(`ZodEmoji`,(e,t)=>{ur.init(e,t),I.init(e,t)}),$o=w(`ZodNanoID`,(e,t)=>{dr.init(e,t),I.init(e,t)}),es=w(`ZodCUID`,(e,t)=>{fr.init(e,t),I.init(e,t)}),ts=w(`ZodCUID2`,(e,t)=>{pr.init(e,t),I.init(e,t)}),ns=w(`ZodULID`,(e,t)=>{mr.init(e,t),I.init(e,t)}),rs=w(`ZodXID`,(e,t)=>{hr.init(e,t),I.init(e,t)}),is=w(`ZodKSUID`,(e,t)=>{gr.init(e,t),I.init(e,t)}),as=w(`ZodIPv4`,(e,t)=>{xr.init(e,t),I.init(e,t)}),os=w(`ZodIPv6`,(e,t)=>{wr.init(e,t),I.init(e,t)}),ss=w(`ZodCIDRv4`,(e,t)=>{Tr.init(e,t),I.init(e,t)}),cs=w(`ZodCIDRv6`,(e,t)=>{Dr.init(e,t),I.init(e,t)}),ls=w(`ZodBase64`,(e,t)=>{kr.init(e,t),I.init(e,t)}),us=w(`ZodBase64URL`,(e,t)=>{jr.init(e,t),I.init(e,t)}),ds=w(`ZodE164`,(e,t)=>{Mr.init(e,t),I.init(e,t)}),fs=w(`ZodJWT`,(e,t)=>{Pr.init(e,t),I.init(e,t)}),ps=w(`ZodNumber`,(e,t)=>{Fr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ro(e,t,n,r);let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null},{gt(e,t){return this.check(ya(e,t))},gte(e,t){return this.check(ba(e,t))},min(e,t){return this.check(ba(e,t))},lt(e,t){return this.check(_a(e,t))},lte(e,t){return this.check(va(e,t))},max(e,t){return this.check(va(e,t))},int(e){return this.check(gs(e))},safe(e){return this.check(gs(e))},positive(e){return this.check(ya(0,e))},nonnegative(e){return this.check(ba(0,e))},negative(e){return this.check(_a(0,e))},nonpositive(e){return this.check(va(0,e))},multipleOf(e,t){return this.check(xa(e,t))},step(e,t){return this.check(xa(e,t))},finite(){return this}});function ms(e){return fa(ps,e)}const hs=w(`ZodNumberFormat`,(e,t)=>{Ir.init(e,t),ps.init(e,t)});function gs(e){return pa(hs,e)}const _s=w(`ZodBoolean`,(e,t)=>{Lr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>io(e,t,n,r)});function vs(e){return ma(_s,e)}const ys=w(`ZodUnknown`,(e,t)=>{Rr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function bs(){return ha(ys)}const xs=w(`ZodNever`,(e,t)=>{zr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ao(e,t,n,r)});function Ss(e){return ga(xs,e)}const Cs=w(`ZodArray`,(e,t)=>{Vo(),Vr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Ca(e,t))},nonempty(e){return this.check(Ca(1,e))},max(e,t){return this.check(Sa(e,t))},length(e,t){return this.check(wa(e,t))},unwrap(){return this.element}});function ws(e,t){return La(Cs,e,t)}const Ts=w(`ZodObject`,(e,t)=>{Vo(),Jr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fo(e,t,n,r),vt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return Fs(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:bs()})},loose(){return this.clone({...this._zod.def,catchall:bs()})},strict(){return this.clone({...this._zod.def,catchall:Ss()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Je(this,e)},safeExtend(e){return Ye(this,e)},merge(e){return Xe(this,e)},pick(e){return Ke(this,e)},omit(e){return qe(this,e)},partial(...e){return Ze(Rs,this,e[0])},exactPartial(...e){return Ze(Bs,this,e[0],`exactPartial`)},required(...e){return Qe(Js,this,e[0])}});function Es(e,t){return new Ts({type:`object`,shape:e,catchall:Ss(),...S(t)})}function Ds(e,t){return new Ts({type:`object`,shape:e,catchall:bs(),...S(t)})}const Os=w(`ZodUnion`,(e,t)=>{Xr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>po(e,t,n,r),e.options=t.options});function ks(e,t){return new Os({type:`union`,options:e,...S(t)})}const As=w(`ZodIntersection`,(e,t)=>{Zr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mo(e,t,n,r)});function js(e,t){return new As({type:`intersection`,left:e,right:t})}const Ms=w(`ZodRecord`,(e,t)=>{Vo(),ei.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ho(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ns(e,t,n){return!t||!t._zod?new Ms({type:`record`,keyType:F(),valueType:e,...S(t)}):new Ms({type:`record`,keyType:e,valueType:t,...S(n)})}const Ps=w(`ZodEnum`,(e,t)=>{ti.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oo(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);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 Ps({...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 Ps({...t,checks:[],...S(r),entries:i})}});function Fs(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ps({type:`enum`,entries:n,...S(t)})}const Is=w(`ZodTransform`,(e,t)=>{Vo(),ni.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>co(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Tt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(lt(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(lt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Ls(e){return new Is({type:`transform`,transform:e})}const Rs=w(`ZodOptional`,(e,t)=>{ii.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>To(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function zs(e){return new Rs({type:`optional`,innerType:e})}const Bs=w(`ZodExactOptional`,(e,t)=>{ai.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>To(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Vs(e){return new Bs({type:`optional`,innerType:e})}const Hs=w(`ZodNullable`,(e,t)=>{oi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>go(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Us(e){return new Hs({type:`nullable`,innerType:e})}const Ws=w(`ZodDefault`,(e,t)=>{si.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Gs(e,t){return new Ws({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}const Ks=w(`ZodPrefault`,(e,t)=>{li.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 qs(e,t){return new Ks({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}const Js=w(`ZodNonOptional`,(e,t)=>{ui.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_o(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ys(e,t){return new Js({type:`nonoptional`,innerType:e,...S(t)})}const Xs=w(`ZodCatch`,(e,t)=>{pi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>So(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Zs(e,t){return new Xs({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:yt(t)})}const Qs=w(`ZodPipe`,(e,t)=>{mi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Co(e,t,n,r),e.in=t.in,e.out=t.out});function $s(e,t){return new Qs({type:`pipe`,in:e,out:t})}const ec=w(`ZodPreprocess`,(e,t)=>{Qs.init(e,t),gi.init(e,t)}),tc=w(`ZodReadonly`,(e,t)=>{_i.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nc(e){return new tc({type:`readonly`,innerType:e})}const rc=w(`ZodCustom`,(e,t)=>{yi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>so(e,t,n,r)});function ic(e,t={}){return Ra(rc,e,t)}function ac(e,t){return za(e,t)}function oc(e,t){return new ec({type:`pipe`,in:Ls(e),out:t})}function sc(e){return ca(Wo,e)}const cc=new Set([`__proto__`,`constructor`,`prototype`]),lc=(e,t,n)=>oc((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&&!cc.has(e),dc=e=>lc(uc,()=>`package key must be non-empty and not "__proto__", "constructor", or "prototype"`,Ns(F().min(1),e)),fc=e=>uc(e),pc=[`blobless`,`full`],mc=[`ssh`,`https`],hc=/^(?!\.{1,2}$)[^/\\%:]+$/u,gc=/^[a-z0-9][a-z0-9.-]*(?:_[1-9]\d{0,4})?$/u,_c=/^(?<amount>[1-9]\d{0,3})(?<unit>[mhd])$/u,vc={d:864e5,h:36e5,m:6e4},yc=e=>e!==``&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e),bc=e=>{if(e===void 0)return!0;let t=Number(e);return t>=1&&t<=65535},xc=e=>{let[t=``,n]=e.split(`_`);return bc(n)?t.split(`.`).every(e=>yc(e)):!1},Sc=F().refine(e=>{let[t,...n]=e.split(`/`);return t===void 0||n.length<2||!gc.test(t)||!xc(t)?!1:n.every(e=>hc.test(e))},`ref key must be host/path…/repo with safe, non-empty segments`).brand(),Cc=F().regex(_c,`duration must be <n>m, <n>h, or <n>d`).brand(),wc=e=>{let t=_c.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)*vc[r]},Tc=Fs(pc),Ec=Fs(mc),Dc=F().refine(e=>e.includes(`{version}`),`tag format must contain {version}`),Oc=F().refine(e=>{if(e===`.`)return!0;let t=e.split(`/`);return t.length>0&&t.every(e=>hc.test(e)&&e!==`.`)},`package path must be "." or a normalized relative path without traversal`),kc={clone_mode:`blobless`,git_transport:`https`,sync_ttl:`1h`},Ac=Es({clone_mode:Tc.default(kc.clone_mode),git_transport:Ec.default(kc.git_transport),sync_ttl:Cc.default(Cc.parse(kc.sync_ttl))}),jc=Es((e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.removeDefault().optional()])))(Ac.shape)),Mc=Es({description:F().min(1),path:Oc,tag_format:Dc.optional()}),Nc=Es({default_branch:F().min(1),description:F().min(1),packages:dc(Mc).optional(),tag_format:Dc.optional(),url:F().min(1),...jc.shape}),Pc=Ds({cli_version:F().min(1),schema_version:ms().int().positive()}),Fc=lc(e=>Sc.safeParse(e).success,()=>`ref key must be host/path…/repo with safe, non-empty segments`,Ns(F(),Nc)),Ic=Es({check:vs().default(!0),notify:vs().default(!0)}),Lc=Es({meta:Pc,refs:Fc.default({}),settings:Ac,updates:Ic.optional()});
53
53
  /*!
54
54
  * Copyright (c) Squirrel Chat et al., All rights reserved.
55
55
  * SPDX-License-Identifier: BSD-3-Clause
@@ -77,7 +77,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
77
77
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
78
78
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
79
79
  */
80
- let jc=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var Mc=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(jc);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}};
80
+ let Rc=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var zc=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(Rc);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}};
81
81
  /*!
82
82
  * Copyright (c) Squirrel Chat et al., All rights reserved.
83
83
  * SPDX-License-Identifier: BSD-3-Clause
@@ -105,9 +105,9 @@ let jc=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]
105
105
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
106
106
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
107
107
  */
108
- function Nc(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Pc(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+=`
108
+ function Bc(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Vc(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+=`
109
109
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
110
- `))}return i}var B=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Nc(t.toml,t.ptr),i=Pc(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
110
+ `))}return i}var L=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Bc(t.toml,t.ptr),i=Vc(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
111
111
  /*!
112
112
  * Copyright (c) Squirrel Chat et al., All rights reserved.
113
113
  * SPDX-License-Identifier: BSD-3-Clause
@@ -135,8 +135,8 @@ function Nc(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop()
135
135
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
136
136
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
137
137
  */
138
- function Fc(e,t=0){let n=e.indexOf(`
139
- `,t);return e.charCodeAt(n-1)===13&&n--,n}function Ic(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 B(`control characters are not allowed in comments`,{toml:e.s,ptr:e.p})}}function Lc(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;Ic(e)}}function Rc(e,t,n){let r=e.p;if(!n){r=Fc(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)Ic(e);else if(r===n||r===t)return}throw new B(`cannot find end of structure`,{toml:e.s,ptr:r})}
138
+ function Hc(e,t=0){let n=e.indexOf(`
139
+ `,t);return e.charCodeAt(n-1)===13&&n--,n}function Uc(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 Wc(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;Uc(e)}}function Gc(e,t,n){let r=e.p;if(!n){r=Hc(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)Uc(e);else if(r===n||r===t)return}throw new L(`cannot find end of structure`,{toml:e.s,ptr:r})}
140
140
  /*!
141
141
  * Copyright (c) Squirrel Chat et al., All rights reserved.
142
142
  * SPDX-License-Identifier: BSD-3-Clause
@@ -164,8 +164,8 @@ function Fc(e,t=0){let n=e.indexOf(`
164
164
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
165
165
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
166
166
  */
167
- let zc=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Bc=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Vc=/^[+-]?0[0-9_]/;function Hc(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 B(`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 B(`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 B(`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+=`
168
- `;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 B(`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 B(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new B(`unfinished string`,{toml:e.s,ptr:t})}function Uc(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(Ic({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Wc(e,t,n){let r=e.p,i={toml:e.s,ptr:r};Rc(e,44,n);let a=Uc(e,r,e.p);if(!a)throw new B(`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=zc.test(a);if(o||Bc.test(a)){if(Vc.test(a))throw new B(`leading zeroes are not allowed`,i);a=a.replace(/_/g,``);let e=+a;if(isNaN(e))throw new B(`invalid number`,i);if(o){if((o=!Number.isSafeInteger(e))&&!t)throw new B(`integer value cannot be represented losslessly`,i);(o||t===!0)&&(e=BigInt(a))}return e}let s=new Mc(a);if(!s.isValid())throw new B(`invalid value`,i);return s}
167
+ let Kc=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,qc=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Jc=/^[+-]?0[0-9_]/;function Yc(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+=`
168
+ `;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 Xc(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(Uc({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Zc(e,t,n){let r=e.p,i={toml:e.s,ptr:r};Gc(e,44,n);let a=Xc(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=Kc.test(a);if(o||qc.test(a)){if(Jc.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 zc(a);if(!s.isValid())throw new L(`invalid value`,i);return s}
169
169
  /*!
170
170
  * Copyright (c) Squirrel Chat et al., All rights reserved.
171
171
  * SPDX-License-Identifier: BSD-3-Clause
@@ -193,7 +193,7 @@ let zc=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Bc=/^[+-]?
193
193
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
194
194
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
195
195
  */
196
- function Gc(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)throw new B(`document contains excessively nested structures. aborting.`,{toml:e.s,ptr:r});let t=i===91?Yc(e,n):Jc(e,n);return e.d++,t}if(i===34||i===39)return Hc(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 B(`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 B(`invalid value`,{toml:e.s,ptr:r});return e.p++,!1}return Wc(e,n,t)}
196
+ function Qc(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?nl(e,n):tl(e,n);return e.d++,t}if(i===34||i===39)return Yc(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 Zc(e,n,t)}
197
197
  /*!
198
198
  * Copyright (c) Squirrel Chat et al., All rights reserved.
199
199
  * SPDX-License-Identifier: BSD-3-Clause
@@ -221,7 +221,7 @@ function Gc(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)t
221
221
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
222
222
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
223
223
  */
224
- let Kc=/^[a-zA-Z0-9-_]+[ \t]*$/;function qc(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.indexOf(t,n);if(a<0)throw new B(`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 B(`multiline strings are not allowed in keys`,{toml:e.s,ptr:e.p});let s=Hc(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=Fc(c);if(l>-1)throw new B(`newlines are not allowed in keys`,{toml:e.s,ptr:l});if(c.trimStart())throw new B(`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 B(`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(!Kc.test(t))throw new B(`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,Lc(e,!0,!0),i}function Jc(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Lc(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=qc(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 B(`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 B(`trying to redefine an already defined value`,{toml:e.s,ptr:e.p});let u=Gc(e,125,t);if(r.add(o[a]=u),Lc(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)throw new B(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new B(`unfinished table encountered`,{toml:e.s,ptr:e.p})}function Yc(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Lc(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Gc(e,93,t)),Lc(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)throw new B(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new B(`unfinished array encountered`,{toml:e.s,ptr:e.p})}
224
+ let $c=/^[a-zA-Z0-9-_]+[ \t]*$/;function el(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=Yc(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=Hc(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(!$c.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,Wc(e,!0,!0),i}function tl(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Wc(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=el(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=Qc(e,125,t);if(r.add(o[a]=u),Wc(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 nl(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Wc(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Qc(e,93,t)),Wc(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})}
225
225
  /*!
226
226
  * Copyright (c) Squirrel Chat et al., All rights reserved.
227
227
  * SPDX-License-Identifier: BSD-3-Clause
@@ -249,7 +249,7 @@ let Kc=/^[a-zA-Z0-9-_]+[ \t]*$/;function qc(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.
249
249
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
250
250
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
251
251
  */
252
- function Xc(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 Zc(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Lc(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=qc(r,`]`);if(t){if(e.charCodeAt(r.p-1)!==93)throw new B(`expected end of table declaration`,{toml:e,ptr:r.p-1});r.p++}let l=Xc(n,i,a,t?2:1);if(!l)throw new B(`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=Xc(qc(r),s,c,0);if(!t)throw new B(`trying to redefine an already defined table or value`,{toml:e,ptr:o});t[1][t[0]]=Gc(r,void 0,n)}if(Lc(r,!0),r.p<e.length&&(o=e.charCodeAt(r.p))!==10&&o!==13)throw new B(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:r.p});Lc(r)}return i}
252
+ 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 il(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Wc(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=el(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=rl(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=rl(el(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]]=Qc(r,void 0,n)}if(Wc(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});Wc(r)}return i}
253
253
  /*!
254
254
  * Copyright (c) Squirrel Chat et al., All rights reserved.
255
255
  * SPDX-License-Identifier: BSD-3-Clause
@@ -277,13 +277,13 @@ function Xc(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
277
277
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
278
278
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
279
279
  */
280
- let Qc=/^[a-z0-9-_]+$/i;function $c(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 el(e){for(let t=0;t<e.length;t++)if($c(e[t])!==`object`)return!1;return e.length!=0}function tl(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function nl(e){return e.toString({calendarName:`never`,timeZoneName:`never`})}function rl(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 tl(e);case`date`:if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString();case`object`:return il(e,n,r);case`array`:return al(e,n,r);case`temporal`:return nl(e)}}function il(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+=Qc.test(o)?o:tl(o),i+=` = `,i+=rl(e[o],$c(e[o]),t-1,n)}return i+` }`}function al(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+=rl(e[i],$c(e[i]),t-1,n)}return r+` ]`}function ol(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&&`
281
- `}[[${t}]]\n`,i+=sl(0,e[a],t,n,r);return i}function sl(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=$c(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=Qc.test(c)?c:tl(c);if(e===`array`&&el(t[c]))o+=(o&&`
282
- `)+ol(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
283
- `)+sl(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=rl(t[c],e,r,i),a+=`
284
- `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function cl(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if($c(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=sl(0,e,``,t,n);return r[r.length-1]===`
280
+ let al=/^[a-z0-9-_]+$/i;function ol(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 sl(e){for(let t=0;t<e.length;t++)if(ol(e[t])!==`object`)return!1;return e.length!=0}function cl(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function ll(e){return e.toString({calendarName:`never`,timeZoneName:`never`})}function ul(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 cl(e);case`date`:if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString();case`object`:return dl(e,n,r);case`array`:return fl(e,n,r);case`temporal`:return ll(e)}}function dl(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+=al.test(o)?o:cl(o),i+=` = `,i+=ul(e[o],ol(e[o]),t-1,n)}return i+` }`}function fl(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+=ul(e[i],ol(e[i]),t-1,n)}return r+` ]`}function pl(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&&`
281
+ `}[[${t}]]\n`,i+=ml(0,e[a],t,n,r);return i}function ml(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=ol(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=al.test(c)?c:cl(c);if(e===`array`&&sl(t[c]))o+=(o&&`
282
+ `)+pl(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
283
+ `)+ml(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=ul(t[c],e,r,i),a+=`
284
+ `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function hl(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(ol(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=ml(0,e,``,t,n);return r[r.length-1]===`
285
285
  `?r:r+`
286
- `}const V=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,ll=async(e,t)=>{await a(te(e),{recursive:!0});let n=`${e}.tmp-${se()}`;await p(n,t,`utf8`),await l(n,e)},H=e=>{let t=ae(e.REFS_HOME??h(de(),`.kaisers-io`,`refs`));return{cacheDir:h(t,`cache`),configPath:h(t,`config.toml`),hooksDir:h(t,`hooks`),locksDir:h(t,`locks`),root:t,sourcesDir:h(t,`sources`),statePath:h(t,`state.json`),updateCachePath:h(t,`cache`,`update-check.json`)}},U=(e,t)=>h(e.sourcesDir,...t.split(`/`)),ul=e=>`${e.configPath}.bak`,dl=e=>{let t=[],n=e;for(;!le(n);){let e=te(n);if(e===n)break;t.unshift(ee(n)),n=e}return{ancestor:n,missing:t}},fl=e=>{let{ancestor:t,missing:n}=dl(e),r=ue(t);return n.length===0?r:h(r,...n)},pl=(e,t,n)=>{let r=fl(e),i=fl(t),a=ie(r,i),o=a===`..`||a.startsWith(`..`+oe);if(!(a!==``&&!o&&!ne(a)))throw x(`path escapes ${n} (containment violation): ${t}`)},ml=(e,t)=>{pl(e.sourcesDir,t,`sources directory`)},hl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),gl=(e,t)=>hl(e)?e:t,_l=async e=>{try{return await o(e.configPath,`utf8`)}catch(e){throw V(e)?y(`no config found — run: refs init`):e}},vl=(e,t)=>{try{return Zc(e)}catch(e){throw e instanceof B?x(`invalid TOML in ${t}: ${e.message}`):e}},yl=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,bl=e=>{let{meta:t}=e;if(!hl(t))return;let n=t.schema_version;if(yl(n))return n},xl=(e,t)=>{let n=bl(e);if(n===void 0)throw x(`config schema version is missing or invalid in ${t} — run: refs migrate`);if(n>1)throw x(`config schema ${n} is newer than this CLI supports — upgrade refs`);if(n<1)throw x(`config schema ${n} is older than expected 1 — run: refs migrate`)},W=async e=>{let t=await _l(e),n=vl(t,e.configPath);xl(n,e.configPath);let r=Ac.safeParse(n);if(!r.success)throw x(O(r.error));return r.data},Sl=async(e,t)=>{let n=Ac.safeParse(t);if(!n.success)throw x(O(n.error));await ll(e.configPath,cl(n.data))},Cl=async e=>{try{return await f(e),!0}catch(e){if(V(e))return!1;throw e}},wl=async(e,t)=>await Cl(e.configPath)?`noop`:(await ll(e.configPath,`# refs configuration
286
+ `}const R=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,gl=async(e,t)=>{await a(re(e),{recursive:!0});let n=`${e}.tmp-${ue()}`;await te(n,t,`utf8`),await u(n,e)},z=e=>{let t=se(e.REFS_HOME??h(me(),`.kaisers-io`,`refs`));return{cacheDir:h(t,`cache`),configPath:h(t,`config.toml`),hooksDir:h(t,`hooks`),locksDir:h(t,`locks`),root:t,sourcesDir:h(t,`sources`),statePath:h(t,`state.json`),updateCachePath:h(t,`cache`,`update-check.json`)}},B=(e,t)=>h(e.sourcesDir,...t.split(`/`)),_l=e=>`${e.configPath}.bak`,vl=e=>{let t=[],n=e;for(;!fe(n);){let e=re(n);if(e===n)break;t.unshift(ne(n)),n=e}return{ancestor:n,missing:t}},yl=e=>{let{ancestor:t,missing:n}=vl(e),r=pe(t);return n.length===0?r:h(r,...n)},bl=(e,t,n)=>{let r=yl(e),i=yl(t),a=oe(r,i),o=a===`..`||a.startsWith(`..`+ce);if(!(a!==``&&!o&&!ie(a)))throw b(`path escapes ${n} (containment violation): ${t}`)},xl=(e,t)=>{bl(e.sourcesDir,t,`sources directory`)},Sl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Cl=(e,t)=>Sl(e)?e:t,wl=async e=>{try{return await s(e.configPath,`utf8`)}catch(e){throw R(e)?v(`no config found — run: refs init`):e}},Tl=(e,t)=>{try{return il(e)}catch(e){throw e instanceof L?b(`invalid TOML in ${t}: ${e.message}`):e}},El=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,Dl=e=>{let{meta:t}=e;if(!Sl(t))return;let n=t.schema_version;if(El(n))return n},Ol=(e,t)=>{let n=Dl(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`)},V=async e=>{let t=await wl(e),n=Tl(t,e.configPath);Ol(n,e.configPath);let r=Lc.safeParse(n);if(!r.success)throw b(D(r.error));return r.data},kl=async(e,t)=>{let n=Lc.safeParse(t);if(!n.success)throw b(D(n.error));await gl(e.configPath,hl(n.data))},Al=async e=>{try{return await p(e),!0}catch(e){if(R(e))return!1;throw e}},jl=async(e,t)=>await Al(e.configPath)?`noop`:(await gl(e.configPath,`# refs configuration
287
287
  #
288
288
  # Every global setting under [settings] can also be set per-ref: add the same
289
289
  # key directly inside a [refs."host/owner/repo"] table to override it just for
@@ -314,29 +314,35 @@ sync_ttl = "1h"
314
314
  # tag_format = "v{version}"
315
315
  # # Per-ref overrides of [settings] go in the same table, e.g.:
316
316
  # # clone_mode = "full"
317
- `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),Tl=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:hl(t)&&hl(r)&&(n[e]=Tl(t,r))}return n},El={meta:{},refs:{},settings:{}},Dl=async e=>{try{return await _l(e)}catch(e){if(e instanceof v&&e.code===`not_found`)return;throw e}},Ol=e=>{if(e!==void 0&&e>1)throw x(`config schema ${e} is newer than this CLI supports — upgrade refs`)},kl=async(e,t,n)=>{let r=gl(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await ll(e.configPath,cl(i))},Al=async(e,t,n)=>{await r(e.configPath,ul(e));let i=Tl(t,El),a=gl(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=Ac.safeParse(o);if(!s.success)throw x(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${ul(e)}): ${O(s.error)}`);await ll(e.configPath,cl(o))},jl=async(e,t,n)=>{let r=vl(t,e.configPath),i=bl(r);return Ol(i),i===1?(await kl(e,r,n),`noop`):(await Al(e,r,n),`migrated`)},Ml=async(e,t)=>{let n=await Dl(e);return n===void 0?(await wl(e,t),`seeded`):jl(e,n,t)},Nl=new Set([`ENOENT`,`ENOTDIR`]),Pl=e=>e.code??String(e),Fl=async e=>{try{return await i(e),!0}catch{return!1}},Il=(e,t)=>{let n=ie(e,t);return n===``||n!==`..`&&!n.startsWith(`..`+oe)&&!ne(n)},Ll=async e=>{try{return{real:await c(e)}}catch(e){return{code:Pl(e)}}},Rl=async(e,t)=>{let n=await Ll(e);if(`code`in n)return{code:n.code,kind:`unreadable`};let r=await Ll(t);return`code`in r?Nl.has(r.code)?await Fl(t)?{code:r.code,kind:`unreadable`}:{kind:`missing`}:{code:r.code,kind:`unreadable`}:Il(n.real,r.real)?{kind:`inside`,real:r.real}:{kind:`outside`}},zl=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
318
- `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},Bl=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,Vl=(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(` | `)},Hl=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:Bl(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=Vl(n,r);return o!==void 0&&(a.warning=o),a},Ul=(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},G=e=>le(h(e,`.git`)),Wl=e=>`refusing to sync ${e}: not a refs-managed checkout`,Gl=async(e,t)=>{if(!G(t))throw x(Wl(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw x(Wl(t))},Kl=/filtering not recognized/iu,ql=e=>e===void 0?{}:{cwd:e},K=(e,t,n)=>({action:e,args:t,cmd:`git`,...ql(n)}),Jl=async(e,t)=>{let n=await e.run(t.cmd,t.args,ql(t.cwd));if(n.exitCode===0)return n;let r=n.stderr.trim()||n.stdout.trim()||`exit code ${n.exitCode}`;throw x(`${t.action} failed: ${r}`)},Yl=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await Jl(e,K(`git clone`,n));return await Jl(e,K(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&Kl.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}},Xl=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},Zl=async(e,t)=>{let n=await Xl(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await Xl(e,t);if(r!==void 0)return r;throw x(`could not detect the default branch for checkout: ${t}`)},Ql=async(e,t)=>(await Jl(e,K(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),$l=async(e,t)=>(await Jl(e,K(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,eu=async(e,t)=>{await Jl(e,K(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await Zl(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${zl(n)}`),i},tu=e=>[K(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),K(`git clean -fd`,[`clean`,`-fd`],e)],nu=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...tu(r)),a.push(K(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),K(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await Jl(e,t)},ru=async(e,t)=>{await Gl(e,t.dir);let n=await Ql(e,t.dir),r=await eu(e,t),i=await $l(e,t.dir);await nu(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await Ql(e,t.dir);return Hl(Ul(r,i,{newSha:a,oldSha:n}))},iu=async(e,t,n=20)=>(await Jl(e,K(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
319
- `).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),au=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,ou=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference commits are blocked" >&2`,`exit 1`,``].join(`
320
- `),su=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=h(e.hooksDir,n);await ll(r,ou),await t(r,493)}))},cu=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,lu=/\d+\.\d+\.\d+/gu,uu=e=>bc.safeParse(e).success,du=e=>{let t=e.match(lu);return t!==null&&t.length>1},fu=e=>{let t=cu.exec(e);if(!t||du(e))return;let[n]=t,r=e.replace(n,`{version}`);if(uu(r))return r},pu=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},mu=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=fu(r);e&&pu(t,e,n)}return t},hu=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,gu=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])=>hu(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},_u=e=>{let t=mu(e);return gu(t)},vu=(e,t)=>e.replaceAll(`{version}`,()=>t),yu=async(e,t,n,r)=>{let i=vu(n,r);if(!await au(e,t,i))throw y(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},bu=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,q=e=>{let t=e.replace(bu,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},xu=/\.git$/u,Su=e=>e.replace(xu,``),Cu=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)},wu=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,Tu=/^git\+/u,Eu={"https:":`443`,"ssh:":`22`},Du=e=>e.split(`/`).some(e=>e===`.`||e===`..`),Ou=e=>e.includes(`\\`),ku=e=>e.includes(`%`),Au=e=>{let t=z.safeParse(e);if(!t.success)throw x(`not a supported git url: derived key '${q(e)}' is invalid`);return t.data},ju=({host:e,port:t,protocol:n})=>{let r=Eu[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},Mu=e=>{let t=Su(Cu(e.path));return Au(`${ju(e)}/${t}`)},Nu=e=>{let t=decodeURIComponent(e).split(`/`).filter(e=>e!==``);if(t.length<2)throw x(`not a supported git url: file url path must have at least 2 segments`);let n=t.at(-2)??``,r=t.at(-1)??``;return Au(`local/${n}/${r}`)},Pu=(e,t)=>{try{return new URL(e)}catch{throw x(`not a supported git url: ${q(t)}`)}},Fu=e=>{if(e.password!==``)throw x(`not a supported git url: credentials embedded in url`);if(e.protocol===`https:`&&e.username!==``)throw x(`not a supported git url: credentials embedded in https url`)},Iu=(e,t)=>{if(e.protocol===`file:`){if(!t)throw x(`not a supported git url: unsupported protocol ${e.protocol}`);return Nu(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw x(`not a supported git url: unsupported protocol ${e.protocol}`);return Fu(e),Mu({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},Lu=(e,t)=>{if(ku(e))throw x(`not a supported git url: percent-encoding not supported in ${q(t)}`);if(e.includes(`:`))throw x(`not a supported git url: ambiguous ':' in scp-style path ${q(t)}; use the ssh:// url form instead`);if(e.startsWith(`/`)||e.startsWith(`~`))throw x(`not a supported git url: ambiguous absolute/home-relative scp path in ${q(t)}; use the ssh:// url form instead`)},Ru=(e,t)=>{let n=e.groups?.path??``;return Lu(n,t),Mu({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},zu=(e,t)=>{if(Ou(e))throw x(`not a supported git url: backslash not allowed in ${q(t)}`)},Bu=(e,t)=>{if(Du(e))throw x(`not a supported git url: path traversal segment in ${q(t)}`)},Vu=(e,t,n)=>{if(e.protocol!==`file:`&&ku(t))throw x(`not a supported git url: percent-encoding not supported in ${q(n)}`)},Hu=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(Tu,``);zu(r,e),Bu(r,e);let i=wu.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:Ru(i,e)};let a=Pu(r,e);return Vu(a,r,e),{cloneUrl:r,key:Iu(a,n)}},Uu=`.git`,Wu=e=>e.endsWith(Uu)?e:`${e}${Uu}`,Gu=(e,t)=>`https://${e.toLowerCase()}/${Cu(t)}`,Ku=(e,t)=>`git@${e.toLowerCase()}:${Wu(Cu(t))}`,qu=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw x(`not a supported git url: unsupported protocol ${e}`)},Ju=(e,t,n)=>{let r=Eu[e.protocol];if(e.port!==``&&e.port!==r)throw x(`cannot apply git_transport=${t} to ${q(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},Yu=(e,t)=>t===`https`?Gu(e.hostname,e.pathname):Ku(e.hostname,e.pathname),Xu=(e,t,n)=>{let r=Hu(t).key;if(r!==n)throw x(`git_transport transform changed repo identity: '${q(e)}' → '${t}' (key '${n}' → '${r}')`);return t},Zu=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return Xu(t.cloneUrl,Gu(n,r),t.originalKey)},Qu=e=>{let t=Pu(e.cloneUrl,e.cloneUrl);return qu(t.protocol)===e.transport?e.cloneUrl:(Ju(t,e.transport,e.cloneUrl),Xu(e.cloneUrl,Yu(t,e.transport),e.originalKey))},$u=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:Hu(e).key,transport:t},r=wu.exec(e);return r?.groups===void 0?Qu(n):Zu(r,n)},ed=`meta.json`,td=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},nd=e=>{try{return process.kill(e,0),!0}catch(e){return td(e)!==`ESRCH`}},rd=e=>{try{return JSON.parse(e)}catch{return}},id=async e=>{try{return await o(e,`utf8`)}catch{return}},ad=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},od=e=>{if(typeof e!=`object`||!e)return;let t=e,{pid:n}=t,r=ad(t.acquired_at);if(typeof n==`number`&&r!==void 0)return{acquiredAtMs:r,pid:n}},sd=async e=>{let t=await id(h(e,ed));if(t!==void 0)return od(rd(t))},cd=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},ld=async e=>{let t=await id(h(e,ed));if(t!==void 0)return cd(rd(t))},ud=async e=>{try{return(await f(e)).mtimeMs}catch{return}},dd=async(e,t)=>{let n=h(e,ed),r=`${n}.tmp-${se()}`;await p(r,t,`utf8`),await l(r,n)},fd=async(e,t)=>{await dd(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},pd=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),md=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),hd=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=td(e);if(t!==void 0&&pd.has(t))return!1;throw e}},gd=async(e,t)=>{try{return await l(e,t),!0}catch(e){let t=td(e);if(t!==void 0&&md.has(t))return!1;throw e}},_d=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,vd=async e=>{let t=await sd(e);if(t===void 0){let t=await ud(e);return t!==void 0&&Date.now()-t>5e3}return Date.now()-t.acquiredAtMs>6e5||!nd(t.pid)},yd=async(e,t)=>{try{await fd(e,t)}catch(e){if(td(e)===`ENOENT`)return`retry`;throw e}return t},bd=async(e,t)=>{if(!await hd(e))return;let n=await yd(e,se());return n===`retry`?Date.now()>=t?void 0:bd(e,t):n},xd=e=>h(e.locksDir,`${e.name}.steal-claim`),Sd=e=>h(e.locksDir,`${e.name}.steal.${se()}`),Cd=async e=>{let t=await ud(e);return t!==void 0&&Date.now()-t>2e3},wd=async e=>await hd(e)?!0:await Cd(e)?(await u(e,{force:!0,recursive:!0}),hd(e)):!1,Td=async e=>{let t=Sd(e);return await gd(e.lockPath,t)?t:void 0},Ed=async e=>{if(!await vd(e.lockPath))return!1;let t=await Td(e);return t!==void 0&&(await u(t,{force:!0,recursive:!0}),!0)},Dd=async e=>{let t=xd(e);if(!await wd(t))return!1;try{return await Ed(e)}finally{await u(t,{force:!0,recursive:!0})}},Od=async(e,t)=>{if(!(await vd(e.lockPath)&&await Dd(e))){if(Date.now()>=t)throw ve(`lock ${e.name} is held — another refs process is running`);await fe(100)}},kd=async(e,t)=>{let n=await bd(e.lockPath,t);return n===void 0?(await Od(e,t),kd(e,t)):n},Ad=async(e,t)=>{await ld(e)===t&&await u(e,{force:!0,recursive:!0})},jd=e=>{if(e===`.`||e===`..`||!_d.test(e))throw x(`lock name must not contain "/" or other unsafe characters — only letters, digits, and "_.-" are allowed, and it may not be "." or "..": ${e}`)},J=async(e,t,n,r)=>{jd(t);let i={lockPath:h(e.locksDir,t),locksDir:e.locksDir,name:t};await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await kd(i,o);try{return await n()}finally{await Ad(i.lockPath,s)}},Md=Ss({directory:I().optional(),url:I().optional()}),Nd=Ss({repository:ws([I(),Md]).optional()}),Pd=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,Fd=new Set([`node_modules`,`favicon.ico`]),Id=e=>y(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),Ld=e=>{let[t,n]=e.split(`/`);return n??t??e},Rd=e=>{if(e.length>214)throw b(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!Pd.test(e))throw b(`invalid package name: '${e}' does not match npm naming rules`);let t=Ld(e);if(Fd.has(t))throw b(`invalid package name: '${e}' uses a reserved name`)},zd=e=>e.replaceAll(`/`,`%2F`),Bd=e=>typeof e==`string`?e:e?.url,Vd=e=>{if(typeof e==`object`&&e?.directory){let t=xc.safeParse(e.directory);if(t.success)return t.data}},Hd=async(e,t)=>{try{return await e.json()}catch{throw x(`invalid npm registry response for '${t}': not parseable JSON`)}},Ud=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${zd(t)}`);if(n.status===404)throw y(`npm package '${t}' not found`);if(n.status!==200)throw x(`failed to fetch npm package '${t}': status ${n.status}`);let r=await Hd(n,t),i=Nd.safeParse(r);if(!i.success)throw x(`invalid npm package response for '${t}'`);return i.data},Wd=(e,t)=>{try{return Hu(e)}catch{throw Id(t)}},Gd=async(e,t)=>{Rd(t);let n=await Ud(e,t),r=Bd(n.repository);if(r===void 0||r===``)throw Id(t);let{cloneUrl:i,key:a}=Wd(r,t),o=Vd(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},Kd=new Set([`candidate_not_inspected`,`manifest_unreadable`,`unsupported_pattern`,`workspace_declaration_unparsed`,`workspace_dir_unreadable`,`workspace_file_unreadable`]),qd=/[/\\]/u,Jd={kind:`ignore`},Yd=e=>!ne(e)&&e.split(qd).every(e=>e!==`.`&&e!==`..`),Xd=e=>Yd(e)&&!e.startsWith(`!`)&&!e.includes(`**`)&&(e.match(/\*/gu)??[]).length<=1,Zd=e=>Xd(e)?e.endsWith(`/*`)?{baseDir:e.slice(0,-2),kind:`expand-children`}:e===`*`?{baseDir:`.`,kind:`expand-children`}:e.includes(`*`)?Jd:{dir:e,kind:`probe-dir`}:Jd,Qd=(e,t,n)=>t.filter((e,t)=>n[t]===!0).map(t=>re.join(e,t)),$d=(e,t)=>t?.name?{description:t.description,name:t.name,path:e}:void 0,ef=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},tf=e=>!e.diagnostics.some(e=>Kd.has(e.kind)),nf=e=>!e.diagnostics.some(e=>e.kind===`no_workspace_declaration`),rf=(e,t)=>e<t?-1:+(e>t),af=e=>`path`in e?`${e.kind} ${e.path}`:`file`in e?`${e.kind} ${e.file}`:`pattern`in e?`${e.kind} ${e.pattern}`:e.kind,of=e=>e.toSorted((e,t)=>rf(af(e),af(t))),sf=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,cf=/^packages:\s*(?:#.*)?$/u,lf=e=>typeof e==`object`&&!!e&&!Array.isArray(e),uf=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!lf(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},df=Symbol(`end-of-section`),ff=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!cf.test(e))return df;if(!t.startsWith(`-`))return;let n=sf.exec(e)?.groups?.pattern?.trim();if(n)return n},pf=e=>{let t=[];for(let n of e){let e=ff(n);if(e===df)break;e!==void 0&&t.push(e)}return t},mf=e=>{let t=e.findIndex(e=>cf.test(e));return t===-1?[]:pf(e.slice(t+1))},hf=e=>{let{name:t}=e;if(typeof t==`string`)return t},gf=e=>{let{description:t}=e;if(typeof t==`string`)return t},_f=e=>!ne(e)&&!e.split(/[/\\]/u).includes(`..`),vf=(e,t)=>e.kind===`missing`?{kind:`absent`}:e.kind===`outside`?{kind:`unreadable`,reason:`${t} escapes the checkout`}:{kind:`unreadable`,reason:e.code},yf=async(e,t,n)=>{if(!_f(t))return{kind:`unreadable`,reason:`path escapes the checkout`};let r=await bf(e,t);if(`probe`in r)return r.probe;let i=await xf(r.real);return`reason`in i?{kind:`unreadable`,reason:i.reason}:i.found===n?{kind:`match`}:{found:i.found,kind:`mismatch`}},bf=async(e,t)=>{let n=await Rl(e,h(e,t));if(n.kind!==`inside`)return{probe:vf(n,`path`)};let r=await Rl(e,h(n.real,`package.json`));return r.kind===`inside`?{real:r.real}:{probe:vf(r,`manifest`)}},xf=async e=>{try{let t=JSON.parse(await o(e,`utf8`));return{found:hf(t)}}catch(e){return{reason:e.code??String(e)}}},Sf=(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(rf)}},Cf=new Set;let wf=!1;const Tf=()=>{for(let e of Cf)try{e.kill(`SIGKILL`)}catch{}},Ef=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],Df=e=>{let t=()=>{Tf(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},Of=()=>{wf||(wf=!0,Ef.forEach(e=>{Df(e)}),process.on(`exit`,Tf))},kf=()=>{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}}},Af=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
321
- `),jf=(e,t,n)=>{let r=e;return t.truncated&&(r=Af(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=Af(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},Mf={clear:()=>{},markedTimedOut:()=>!1},Nf=(e,t)=>{if(t===void 0)return Mf;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}},Pf=e=>e===void 0?{}:{cwd:e},Ff=(e,t)=>Af(e,`refs: command timed out after ${String(t)}ms`),If=(e,t)=>({exitCode:124,stderr:Ff(e,t),stdout:``,timedOut:!0}),Lf=(e,t,n)=>{let r=ge(e,t,{...Pf(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});Cf.add(r);let i=kf(),a=kf();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:Nf(r,n?.timeoutMs)}},Rf=(e,t,n)=>{try{return Lf(e,t,n)}catch(e){return{exitCode:127,stderr:Bf(e),stdout:``}}},zf=e=>!(`child`in e),Bf=e=>e instanceof Error?e.message:String(e),Vf=async e=>{try{let[t]=await me(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:Bf(e)}}},Hf=e=>e===null?1:e,Uf=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,Wf=e=>e.timedOut?If(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?Uf({exitCode:Hf(e.code),stderr:jf(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):Uf({exitCode:127,stderr:Af(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var Gf=class{async run(e,t,n){Of();let r=Rf(e,t,n);if(zf(r))return r;let i=await Vf(r.child);return Cf.delete(r.child),r.timeout.clear(),Wf({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Kf=Tc.partial({description:!0}),qf=R({default_branch:I().min(1),key:z,tag_format_candidate:bc.nullable(),url:I().min(1)});qf.extend({description:I().default(``),packages:oc(Kf)});const Jf=qf.extend({description:I().min(1),packages:oc(Tc)}),Yf=R({effective_clone_mode:vc.optional(),head_sha:I().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:I().optional(),last_fetched_at:nc().optional(),pending_proposal_at:nc().optional()}),Xf=R({refs:ic(e=>e.length>0&&!rc.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,Os(I(),Yf)).default({})}),Y=(e,t,n)=>t?.[e]??n[e],Zf=async e=>{try{return await o(e.statePath,`utf8`)}catch(e){if(V(e))return;throw e}},Qf=e=>{try{return JSON.parse(e)}catch{return}},X=async e=>{let t=await Zf(e);if(t===void 0)return Xf.parse({});let n=Qf(t);if(n===void 0)return Xf.parse({});let r=Xf.safeParse(n);return r.success?r.data:Xf.parse({})},$f=async(e,t)=>{let n=Xf.safeParse(t);if(!n.success)throw x(O(n.error));await ll(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},ep=/^\d+\.\d+\.\d+$/u,tp=/^0+(?=\d)/u,np=(e,t)=>{let n=e.replace(tp,``),r=t.replace(tp,``);return n.length===r.length?n===r?0:n<r?-1:1:n.length<r.length?-1:1},rp=(e,t)=>{if(!ep.test(e)||!ep.test(t))return;let n=e.split(`.`),r=t.split(`.`);return n.map((e,t)=>np(e,r[t]??``)).find(e=>e!==0)??0},ip=Ss({version:I().regex(ep)}),ap=R({checked_at:nc(),latest_version:I().regex(ep)}),op=async e=>{try{let t=ap.safeParse(JSON.parse(await o(e.updateCachePath,`utf8`)));return t.success?t.data:void 0}catch{return}},sp=async(e,t)=>{try{await f(e.root),await ll(e.updateCachePath,`${JSON.stringify(t,void 0,2)}\n`)}catch{}},cp=(e,t)=>{let n=t-Date.parse(e.checked_at);return n>=0&&n<864e5},lp=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=ip.safeParse(await t.json());return n.success?n.data.version:void 0}catch{return}},up=async e=>{let t=await op(e.home);if(t!==void 0&&cp(t,e.nowMs))return{latest:t.latest_version,refreshed:!1,stale:!1};let n=await lp(e.fetch);return n===void 0?{latest:t?.latest_version,refreshed:!1,stale:!0}:(await sp(e.home,{checked_at:new Date(e.nowMs).toISOString(),latest_version:n}),{latest:n,refreshed:!0,stale:!1})},dp=(e,t)=>{let n=rp(e,t);return n!==void 0&&n<0},fp=(e,t)=>`refs ${t} is available (this is ${e})update: npm i -g @kaisers-io/refs@latest`,pp=e=>{let t=e.REFS_UPDATE_CHECK?.trim();if(t===`0`)return!1;if(t===`1`)return!0},mp=e=>{let t=e.CI?.trim().toLowerCase();return t!==void 0&&t!==``&&t!==`false`&&t!==`0`},hp={check:!0,notify:!0},gp=e=>{let t=pp(e.env);return t===void 0?(e.updates??hp).check?mp(e.env)?`ci`:`on`:`config`:t?`on`:`env`},_p=e=>gp(e)===`on`,vp=e=>_p(e)&&(e.updates??hp).notify,yp=async(e,t)=>{let n=await Rl(e,h(t,`package.json`));if(n.kind===`inside`)try{let e=JSON.parse(await o(n.real,`utf8`));return{description:gf(e),name:hf(e)}}catch{return}},bp=async(e,t)=>{let n=await yp(e,h(e,t));if(n===void 0)return{diagnostic:{kind:`manifest_unreadable`,path:t}};let r=$d(t,n);return r===void 0?{diagnostic:{kind:`manifest_missing_name`,path:t}}:{pkg:r}},xp=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}},Sp=async(e,t)=>{let n=await Rl(e,t);if(n.kind===`missing`)return{ok:!0};if(n.kind!==`inside`)return{ok:!1};try{return{content:await o(n.real,`utf8`),ok:!0}}catch{return{ok:!1}}},Cp=async(e,t)=>{let n=await Sp(e,t);return n.ok?n.content===void 0?{ok:!0,patterns:new Set}:wp(n.content):{ok:!1,patterns:new Set}},wp=e=>{let t=new Set;try{let n=JSON.parse(e);uf(n.workspaces).forEach(e=>t.add(e))}catch{return{ok:!1,patterns:t}}return{ok:!0,patterns:t}},Tp=/^packages:/mu,Ep=async(e,t)=>{let n=new Set,r=await Sp(e,t);return r.ok?r.content===void 0?{ok:!0,patterns:n}:(mf(r.content.split(`
322
- `)).forEach(e=>n.add(e)),{ok:!0,patterns:n,unparsed:n.size===0&&Tp.test(r.content)}):{ok:!1,patterns:n}},Dp=async e=>{let[t,n]=await Promise.all([Cp(e,h(e,`package.json`)),Ep(e,h(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,patterns:new Set([...t.patterns,...n.patterns])}},Op=new Set([`ENOENT`,`ENOTDIR`]),kp=async(e,t)=>{let n=await Rl(e,h(t,`package.json`));if(n.kind===`missing`)return`none`;if(n.kind!==`inside`)return`rejected`;try{return await o(n.real,`utf8`),`manifest`}catch{return`rejected`}},Ap=async e=>{try{return{entries:await s(e,{withFileTypes:!0})}}catch(e){return{code:e.code??``}}},jp=(e,t,n)=>Promise.all(n.map(n=>kp(e,h(t,n.name)))),Mp=(e,t,n)=>e.filter((e,r)=>n(t[r])).map(e=>e.name),Np=async e=>{let{baseDir:t,dirs:n,fullPath:r,repoDir:i,symlinks:a}=e,o=e=>re.join(t===`.`?``:t,e),[s,c]=await Promise.all([jp(i,r,n),jp(i,r,a)]);return{diagnostics:[...Mp(n,s,e=>e===`rejected`).map(e=>({kind:`manifest_unreadable`,path:o(e)})),...Mp(a,c,e=>e!==`none`).map(e=>({kind:`candidate_not_inspected`,path:o(e)}))],dirs:Qd(t,n.map(e=>e.name),s.map(e=>e===`manifest`))}},Pp=async(e,t)=>{let n=h(e,t),r=await Rl(e,n);if(r.kind===`missing`)return{diagnostics:[],dirs:[]};if(r.kind!==`inside`)return{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]};let i=await Ap(n);return`code`in i?Op.has(i.code)?{diagnostics:[],dirs:[]}:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}:Np({baseDir:t,dirs:i.entries.filter(e=>e.isDirectory()),fullPath:n,repoDir:e,symlinks:i.entries.filter(e=>e.isSymbolicLink())})},Fp=(e,t)=>{let n=Zd(t);return n.kind===`expand-children`?Pp(e,n.baseDir):n.kind===`probe-dir`?Ip(e,n.dir):Promise.resolve({diagnostics:[{kind:`unsupported_pattern`,pattern:t}],dirs:[]})},Ip=async(e,t)=>{let n=await kp(e,h(e,t));return n===`manifest`?{diagnostics:[],dirs:[t]}:n===`rejected`?{diagnostics:[{kind:`manifest_unreadable`,path:t}],dirs:[]}:{diagnostics:[],dirs:[]}},Lp=async(e,t)=>{let n=await Promise.all([...t].map(t=>Fp(e,t))),r=new Set,i=[];for(let e of n)e.dirs.forEach(e=>r.add(e)),i.push(...e.diagnostics);return{diagnostics:i,dirs:[...r]}},Rp=async e=>{let t=await Dp(e);if(t.patterns.size===0)return{diagnostics:of([...t.diagnostics,{kind:`no_workspace_declaration`}]),packages:[]};let n=await Lp(e,t.patterns),r=await Promise.all(n.dirs.map(t=>bp(e,t))),i=xp(r);return{diagnostics:of([...t.diagnostics,...n.diagnostics,...i.diagnostics]),packages:ef(i.packages)}},zp=async e=>(await Rp(e)).packages;var Bp=`0.10.0`;const Vp=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},Hp=()=>{try{return de()}catch{return``}},Up=()=>({cliVersion:Bp,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:(e,t)=>fetch(e,t),homedir:Hp(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:Vp,runner:new Gf});var Wp=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}},Gp=class extends Wp{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},Kp=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 Gp(`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 qp(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var Jp=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=>qp(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(`
323
- `)}displayWidth(e){return _e(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,`
317
+ `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),Ml=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:Sl(t)&&Sl(r)&&(n[e]=Ml(t,r))}return n},Nl={meta:{},refs:{},settings:{}},Pl=async e=>{try{return await wl(e)}catch(e){if(e instanceof _&&e.code===`not_found`)return;throw e}},Fl=e=>{if(e!==void 0&&e>1)throw b(`config schema ${e} is newer than this CLI supports — upgrade refs`)},Il=async(e,t,n)=>{let r=Cl(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await gl(e.configPath,hl(i))},Ll=async(e,t,n)=>{await r(e.configPath,_l(e));let i=Ml(t,Nl),a=Cl(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=Lc.safeParse(o);if(!s.success)throw b(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${_l(e)}): ${D(s.error)}`);await gl(e.configPath,hl(o))},Rl=async(e,t,n)=>{let r=Tl(t,e.configPath),i=Dl(r);return Fl(i),i===1?(await Il(e,r,n),`noop`):(await Ll(e,r,n),`migrated`)},zl=async(e,t)=>{let n=await Pl(e);return n===void 0?(await jl(e,t),`seeded`):Rl(e,n,t)},Bl=new Set([`ENOENT`,`ENOTDIR`]),Vl=e=>e.code??String(e),Hl=async e=>{try{return await i(e),!0}catch{return!1}},Ul=(e,t)=>{let n=oe(e,t);return n===``||n!==`..`&&!n.startsWith(`..`+ce)&&!ie(n)},Wl=async e=>{try{return{real:await l(e)}}catch(e){return{code:Vl(e)}}},Gl=async(e,t)=>{let n=await Wl(e);if(`code`in n)return{code:n.code,kind:`unreadable`};let r=await Wl(t);return`code`in r?Bl.has(r.code)?await Hl(t)?{code:r.code,kind:`unreadable`}:{kind:`missing`}:{code:r.code,kind:`unreadable`}:Ul(n.real,r.real)?{kind:`inside`,real:r.real}:{kind:`outside`}},Kl=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,ql=/^packages:\s*(?:#.*)?$/u,Jl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Yl=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!Jl(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},Xl=Symbol(`end-of-section`),Zl=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!ql.test(e))return Xl;if(!t.startsWith(`-`))return;let n=Kl.exec(e)?.groups?.pattern?.trim();if(n)return n},Ql=e=>{let t=[];for(let n of e){let e=Zl(n);if(e===Xl)break;e!==void 0&&t.push(e)}return t},$l=e=>{let t=e.findIndex(e=>ql.test(e));return t===-1?[]:Ql(e.slice(t+1))},eu=e=>{let{name:t}=e;if(typeof t==`string`)return t},tu=e=>{let{description:t}=e;if(typeof t==`string`)return t},nu=async(e,t)=>{let n=await Gl(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}}},ru=async(e,t)=>{let n=await nu(e,t);return n.ok?n.content===void 0?{ok:!0,patterns:[]}:iu(n.content):{ok:!1,patterns:[]}},iu=e=>{try{let t=JSON.parse(e);return{ok:!0,patterns:Yl(t.workspaces)}}catch{return{ok:!1,patterns:[]}}},au=/^packages:/mu,ou=(e,t)=>t.length===0&&au.test(e),su=async(e,t)=>{let n=await nu(e,t);if(!n.ok)return{ok:!1,patterns:[]};if(n.content===void 0)return{ok:!0,patterns:[]};let r=$l(n.content.split(`
318
+ `));return{ok:!0,patterns:r,unparsed:ou(n.content,r)}},cu=async e=>{let[t,n]=await Promise.all([ru(e,h(e,`package.json`)),su(e,h(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}},lu=`\0unreadable`,uu=`pnpm-workspace.yaml`,du=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},fu=async(e,t)=>{let n=await du(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`}},pu=async(e,t,n)=>{let r=await fu(e,{dir:t.dir,path:`package.json`,rev:n});if(`kind`in r)return r.kind===`absent`?[]:[lu];try{let e=JSON.parse(r.contents);return Yl(e.workspaces)}catch{return[lu]}},mu=async(e,t,n)=>{let r=await fu(e,{dir:t.dir,path:uu,rev:n});if(`kind`in r)return r.kind===`absent`?[]:[lu];let{contents:i}=r,a=$l(i.split(`
319
+ `));return ou(i,a)?[lu]:a},hu=async(e,t,n)=>{let[r,i]=await Promise.all([pu(e,t,n),mu(e,t,n)]);return{npm:r,pnpm:i}},gu=(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([hu(e,t,t.from),hu(e,t,t.to)]);return!gu(n.npm,r.npm)||!gu(n.pnpm,r.pnpm)},vu=e=>ne(e)===`package.json`,yu=async(e,t,n)=>{let r=await e.run(`git`,[...n],{cwd:t});return r.exitCode===0?r.stdout:void 0},bu=e=>e.split(`\0`).filter(e=>e.length>0&&vu(e)),xu=async(e,t)=>{let n=await yu(e,t.dir,[`diff`,`--name-only`,`-z`,`--no-renames`,`${t.from}..${t.to}`,`--`,`*package.json`,uu]);return n===void 0?void 0:n.split(`\0`).filter(e=>e.length>0)},Su=async(e,t)=>{if(t.paths.length===0)return new Set;let n=await yu(e,t.dir,[`ls-tree`,`-r`,`-z`,`--name-only`,t.rev,`--`,...t.paths]);return n===void 0?void 0:new Set(bu(n))},Cu=async(e,t)=>{let n=await yu(e,t.dir,[`show`,`${t.rev}:${t.path}`]);if(n!==void 0)try{let e=JSON.parse(n);return{name:eu(e)}}catch{return}},wu=async(e,t,n)=>{let r=[];for(let i of n){let n=await Cu(e,{dir:t.dir,path:i,rev:t.rev});if(n===void 0)return;n.name!==void 0&&r.push(n.name)}return r},Tu={changedDirs:[],namesBefore:[]},Eu=(e,t,n)=>_u(e,{...t,touched:n.some(e=>e===`pnpm-workspace.yaml`||e===`package.json`)}),Du=e=>[...new Set(e.map(e=>re(e)))].filter(e=>e!==`.`).toSorted(),Ou=async(e,t,n)=>{let r=await Su(e,{dir:t.dir,paths:n,rev:t.from});if(r!==void 0)return wu(e,{dir:t.dir,rev:t.from},n.filter(e=>r.has(e)))},ku=async(e,t)=>{if(t.from===t.to)return Tu;let n=await xu(e,t);if(n===void 0||await Eu(e,t,n))return;let r=n.filter(e=>vu(e));if(r.length>200)return;let i=await Ou(e,t,r);return i===void 0?void 0:{changedDirs:Du(r),namesBefore:i}},Au=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
320
+ `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},ju=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,Mu=(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(` | `)},Nu=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:ju(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=Mu(n,r);return o!==void 0&&(a.warning=o),a},Pu=(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=>fe(h(e,`.git`)),Fu=e=>`refusing to sync ${e}: not a refs-managed checkout`,Iu=async(e,t)=>{if(!H(t))throw b(Fu(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw b(Fu(t))},Lu=/filtering not recognized/iu,Ru=e=>e===void 0?{}:{cwd:e},U=(e,t,n)=>({action:e,args:t,cmd:`git`,...Ru(n)}),zu=async(e,t)=>{let n=await e.run(t.cmd,t.args,Ru(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}`)},Bu=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await zu(e,U(`git clone`,n));return await zu(e,U(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&Lu.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}},Vu=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},Hu=async(e,t)=>{let n=await Vu(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await Vu(e,t);if(r!==void 0)return r;throw b(`could not detect the default branch for checkout: ${t}`)},Uu=async(e,t)=>(await zu(e,U(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),Wu=async(e,t)=>(await zu(e,U(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,Gu=async(e,t)=>{await zu(e,U(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await Hu(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${Au(n)}`),i},Ku=e=>[U(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),U(`git clean -fd`,[`clean`,`-fd`],e)],qu=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...Ku(r)),a.push(U(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),U(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await zu(e,t)},Ju=async(e,t)=>{await Iu(e,t.dir);let n=await Uu(e,t.dir),r=await Gu(e,t),i=await Wu(e,t.dir);await qu(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await Uu(e,t.dir);return Nu(Pu(r,i,{newSha:a,oldSha:n}))},Yu=async(e,t,n=20)=>(await zu(e,U(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
321
+ `).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),Xu=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,Zu=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only referencecommits are blocked" >&2`,`exit 1`,``].join(`
322
+ `),Qu=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=h(e.hooksDir,n);await gl(r,Zu),await t(r,493)}))},$u=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,ed=/\d+\.\d+\.\d+/gu,td=e=>Dc.safeParse(e).success,nd=e=>{let t=e.match(ed);return t!==null&&t.length>1},rd=e=>{let t=$u.exec(e);if(!t||nd(e))return;let[n]=t,r=e.replace(n,`{version}`);if(td(r))return r},id=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},ad=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=rd(r);e&&id(t,e,n)}return t},od=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,sd=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])=>od(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},cd=e=>{let t=ad(e);return sd(t)},ld=(e,t)=>e.replaceAll(`{version}`,()=>t),ud=async(e,t,n,r)=>{let i=ld(n,r);if(!await Xu(e,t,i))throw v(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},dd=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,W=e=>{let t=e.replace(dd,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},fd=/\.git$/u,pd=e=>e.replace(fd,``),md=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)},hd=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,gd=/^git\+/u,_d={"https:":`443`,"ssh:":`22`},vd=e=>e.split(`/`).some(e=>e===`.`||e===`..`),yd=e=>e.includes(`\\`),bd=e=>e.includes(`%`),xd=e=>{let t=Sc.safeParse(e);if(!t.success)throw b(`not a supported git url: derived key '${W(e)}' is invalid`);return t.data},Sd=({host:e,port:t,protocol:n})=>{let r=_d[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},Cd=e=>{let t=pd(md(e.path));return xd(`${Sd(e)}/${t}`)},wd=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 xd(`local/${n}/${r}`)},Td=(e,t)=>{try{return new URL(e)}catch{throw b(`not a supported git url: ${W(t)}`)}},Ed=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`)},Dd=(e,t)=>{if(e.protocol===`file:`){if(!t)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return wd(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return Ed(e),Cd({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},Od=(e,t)=>{if(bd(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`)},kd=(e,t)=>{let n=e.groups?.path??``;return Od(n,t),Cd({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},Ad=(e,t)=>{if(yd(e))throw b(`not a supported git url: backslash not allowed in ${W(t)}`)},jd=(e,t)=>{if(vd(e))throw b(`not a supported git url: path traversal segment in ${W(t)}`)},Md=(e,t,n)=>{if(e.protocol!==`file:`&&bd(t))throw b(`not a supported git url: percent-encoding not supported in ${W(n)}`)},Nd=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(gd,``);Ad(r,e),jd(r,e);let i=hd.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:kd(i,e)};let a=Td(r,e);return Md(a,r,e),{cloneUrl:r,key:Dd(a,n)}},Pd=`.git`,Fd=e=>e.endsWith(Pd)?e:`${e}${Pd}`,Id=(e,t)=>`https://${e.toLowerCase()}/${md(t)}`,Ld=(e,t)=>`git@${e.toLowerCase()}:${Fd(md(t))}`,Rd=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw b(`not a supported git url: unsupported protocol ${e}`)},zd=(e,t,n)=>{let r=_d[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`)},Bd=(e,t)=>t===`https`?Id(e.hostname,e.pathname):Ld(e.hostname,e.pathname),Vd=(e,t,n)=>{let r=Nd(t).key;if(r!==n)throw b(`git_transport transform changed repo identity: '${W(e)}' → '${t}' (key '${n}' → '${r}')`);return t},Hd=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return Vd(t.cloneUrl,Id(n,r),t.originalKey)},Ud=e=>{let t=Td(e.cloneUrl,e.cloneUrl);return Rd(t.protocol)===e.transport?e.cloneUrl:(zd(t,e.transport,e.cloneUrl),Vd(e.cloneUrl,Bd(t,e.transport),e.originalKey))},Wd=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:Nd(e).key,transport:t},r=hd.exec(e);return r?.groups===void 0?Ud(n):Hd(r,n)},Gd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,Kd=(e,t)=>{if(Gd.test(t))return h(e,`lease-${t}`)},qd=async(e,t)=>{let n=Kd(e,t);n!==void 0&&await(await o(n,`w`)).close()},Jd=async(e,t)=>{let n=Kd(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`},Yd=async(e,t)=>{let n=Kd(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`}}},Xd=`meta.json`,Zd=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},Qd=e=>{try{return process.kill(e,0),!0}catch(e){return Zd(e)!==`ESRCH`}},$d=e=>{try{return JSON.parse(e)}catch{return}},ef=async e=>{try{return await s(e,`utf8`)}catch{return}},tf=new Set([`ENOENT`,`ENOTDIR`]),nf=async e=>{try{return{state:`read`,text:await s(e,`utf8`)}}catch(e){let t=Zd(e);return{state:t!==void 0&&tf.has(t)?`missing`:`unreadable`}}},rf=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},af=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},of=e=>{if(!(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>2147483647))return e},sf=e=>{if(typeof e!=`object`||!e)return;let t=e,n=of(t.pid),r=rf(t.acquired_at);if(n===void 0||r===void 0)return;let i=af(e);return{acquiredAtMs:r,pid:n,...i===void 0?{}:{token:i}}},cf=async e=>{let t=await ef(h(e,Xd));if(t!==void 0)return af($d(t))},lf=async e=>{let t=await nf(h(e,Xd));if(t.state!==`read`)return{state:t.state};let n=sf($d(t.text));return n===void 0?{state:`malformed`}:{meta:n,state:`valid`}},uf=async e=>{try{return{mtimeMs:(await p(e)).mtimeMs,state:`ok`}}catch(e){return{state:Zd(e)===`ENOENT`?`gone`:`unreadable`}}},df=async(e,t)=>{let n=h(e,Xd),r=`${n}.tmp-${ue()}`;await te(r,t,`utf8`),await u(r,n)},ff=()=>ue(),pf=async(e,t)=>{await qd(e,t),await df(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},mf=5e3,hf=async(e,t,n)=>{if(t===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let r=await uf(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:mf,meta:t,observedAtMs:n,pidState:`unknown`,policy:`grace`,stale:i>mf}},gf=async(e,t,n)=>{let r=t.token===void 0?{state:`absent`}:await Yd(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`}},_f=async(e,t)=>{let n=await lf(e);if(n.state!==`valid`)return hf(e,n.state,t);let{meta:r}=n,i=await gf(e,r,t),a=!Qd(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}}},vf=e=>e.meta===`valid`&&e.pidState===`definitely-dead`&&e.token!==void 0,yf=async(e,t)=>await cf(e)===t?await Jd(e,t)===`gone`?`lost`:`renewed`:`lost`,bf=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),xf=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),Sf=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=Zd(e);if(t!==void 0&&bf.has(t))return!1;throw e}},Cf=async(e,t)=>{try{return await u(e,t),!0}catch(e){let t=Zd(e);if(t!==void 0&&xf.has(t))return!1;throw e}},wf=`.claims`,Tf=`.tombstones`,Ef=(e,t)=>({lockPath:h(e,t),locksDir:e,name:t}),Df=e=>h(e.locksDir,wf,e.name),Of=e=>h(e.locksDir,Tf,ue()),kf=async e=>{await a(h(e,wf),{recursive:!0}),await a(h(e,Tf),{recursive:!0})},Af=e=>Sf(e),jf=async e=>{try{await f(e)}catch{}},Mf=async e=>{let t=Of(e);return await Cf(e.lockPath,t)?t:void 0},Nf=async e=>{let t=await _f(e.lockPath,Date.now());if(!vf(t)||await cf(e.lockPath)!==t.token)return!1;let n=await Mf(e);return n!==void 0&&(await d(n,{force:!0,recursive:!0}),!0)},Pf=async e=>{await kf(e.locksDir);let t=Df(e);if(!await Af(t))return!1;let n=await Nf(e).then(e=>({ok:!0,stolen:e}),e=>({error:e,ok:!1}));if(await jf(t),!n.ok)throw n.error;return n.stolen},Ff=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}},If=async e=>(await Ff(e)).filter(e=>!e.name.startsWith(`.`)),Lf=async(e,t,n)=>{let r=await _f(h(e,t.name),n);if(r.policy!==`none`)return{diagnosis:r,isDirectory:t.isDir,kind:`lock`,name:t.name}},Rf=async(e,t)=>{let n=h(e,wf),r=await Ff(n);return(await Promise.all(r.map(async e=>({diagnosis:await _f(h(n,e.name),t),isDirectory:e.isDir,kind:`claim`,name:e.name})))).filter(e=>e.diagnosis.policy!==`none`)},zf=async e=>{let t=Date.now(),n=await If(e.locksDir),[r,i]=await Promise.all([Promise.all(n.map(n=>Lf(e.locksDir,n,t))),Rf(e.locksDir,t)]);return[...r.filter(e=>e!==void 0),...i]},Bf=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`},Vf=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)`,Hf={grace:`created`,lease:`lease renewed`,legacy:`acquired`,none:`observed`,unknown:`observed`},Uf={grace:`from creation, while its metadata has not been published`,lease:`from the last renewal`,legacy:`from acquisition (no renewable lease)`,none:``,unknown:``},Wf=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`:`, ${Hf[r]} ${Bf(t)} ago; its window is ${Bf(n)} ${Uf[r]}`},Gf=(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: ${Vf(t)}`;return vf(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}${Wf(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}${Wf(t)}. Retry once the other refs command finishes.`},Kf=(e,t)=>{if(t.stopped)return;let n=setTimeout(()=>{t.stopped||(t.inFlight=qf(e,t))},e.intervalMs);n.unref(),t.timer=n},qf=async(e,t)=>{try{if(await e.renew()===`lost`){t.lost=!0,t.stopped=!0;return}}catch{}Kf(e,t)},Jf=e=>{let t={inFlight:Promise.resolve(),lost:!1,stopped:!1};return Kf(e,t),{ownershipLost:()=>t.lost,stop:async()=>{t.stopped=!0,t.timer!==void 0&&clearTimeout(t.timer),await t.inFlight}}},Yf=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,Xf=async(e,t)=>{try{await pf(e,t)}catch(e){if(Zd(e)===`ENOENT`)return`retry`;throw e}return t},Zf=async(e,t)=>{if(!await Sf(e))return;let n=await Xf(e,ff());return n===`retry`?Date.now()>=t?void 0:Zf(e,t):n},Qf=async(e,t)=>{if(!await Pf(e)){if(Date.now()>=t){let t=await _f(e.lockPath,Date.now());throw Se(Gf(e.name,t))}await he(100)}},$f=async(e,t)=>{let n=await Zf(e.lockPath,t);return n===void 0?(await Qf(e,t),$f(e,t)):n},ep=async(e,t)=>await cf(e)===t&&(await d(e,{force:!0,recursive:!0}),!0),tp=async e=>{try{return{ok:!0,value:await e()}}catch(e){return{error:e,ok:!1}}},np=async(e,t,n,r)=>{await n.stop();let i=await tp(()=>ep(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=>{if(e===`.`||e===`..`||!Yf.test(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)=>{rp(t);let i=Ef(e.locksDir,t);await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await $f(i,o),c=Jf({intervalMs:3e4,renew:()=>yf(i.lockPath,s)});return np(i,s,c,await tp(n))},ip=Ds({directory:F().optional(),url:F().optional()}),ap=Ds({repository:ks([F(),ip]).optional()}),op=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,sp=new Set([`node_modules`,`favicon.ico`]),cp=e=>v(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),lp=e=>{let[t,n]=e.split(`/`);return n??t??e},up=e=>{if(e.length>214)throw y(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!op.test(e))throw y(`invalid package name: '${e}' does not match npm naming rules`);let t=lp(e);if(sp.has(t))throw y(`invalid package name: '${e}' uses a reserved name`)},dp=e=>e.replaceAll(`/`,`%2F`),fp=e=>typeof e==`string`?e:e?.url,pp=e=>{if(typeof e==`object`&&e?.directory){let t=Oc.safeParse(e.directory);if(t.success)return t.data}},mp=async(e,t)=>{try{return await e.json()}catch{throw b(`invalid npm registry response for '${t}': not parseable JSON`)}},hp=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${dp(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 mp(n,t),i=ap.safeParse(r);if(!i.success)throw b(`invalid npm package response for '${t}'`);return i.data},gp=(e,t)=>{try{return Nd(e)}catch{throw cp(t)}},_p=async(e,t)=>{up(t);let n=await hp(e,t),r=fp(n.repository);if(r===void 0||r===``)throw cp(t);let{cloneUrl:i,key:a}=gp(r,t),o=pp(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},vp=(e,t,n)=>{let r=e instanceof RegExp?yp(e,n):e,i=t instanceof RegExp?yp(t,n):t,a=r!==null&&i!=null&&bp(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)}},yp=(e,t)=>{let n=t.match(e);return n?n[0]:null},bp=(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},xp=`\0SLASH`+Math.random()+`\0`,Sp=`\0OPEN`+Math.random()+`\0`,Cp=`\0CLOSE`+Math.random()+`\0`,wp=`\0COMMA`+Math.random()+`\0`,Tp=`\0PERIOD`+Math.random()+`\0`,Ep=new RegExp(xp,`g`),Dp=new RegExp(Sp,`g`),Op=new RegExp(Cp,`g`),kp=new RegExp(wp,`g`),Ap=new RegExp(Tp,`g`),jp=/\\\\/g,Mp=/\\{/g,Np=/\\}/g,Pp=/\\,/g,Fp=/\\\./g;function Ip(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Lp(e){return e.replace(jp,xp).replace(Mp,Sp).replace(Np,Cp).replace(Pp,wp).replace(Fp,Tp)}function Rp(e){return e.replace(Ep,`\\`).replace(Dp,`{`).replace(Op,`}`).replace(kp,`,`).replace(Ap,`.`)}function zp(e){if(!e)return[``];let t=[],n=vp(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=zp(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function Bp(e,t={}){if(!e)return[];let{max:n=1e5,maxLength:r=4e6}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),qp(Lp(e),n,r,!0).map(Rp)}function Vp(e){return`{`+e+`}`}function Hp(e){return/^-?0\d/.test(e)}function Up(e,t){return e<=t}function Wp(e,t){return e>=t}function Gp(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 Kp(e,t,n,r){let i=e.split(/\.\./),a=[];if(i[0]===void 0||i[1]===void 0)return a;let o=Ip(i[0]),s=Ip(i[1]),c=Math.max(i[0].length,i[1].length),l=i.length===3&&i[2]!==void 0?Math.max(Math.abs(Ip(i[2])),1):1,u=Up;s<o&&(l*=-1,u=Wp);let d=i.some(Hp),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 qp(e,t,n,r){let i=[``],a=!1,o=!0;for(;;){let s=vp(`{`,`}`,e);if(!s)return Gp(i,e,[``],t,n,a);let c=s.pre;if(/\$$/.test(c)){if(i=Gp(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+Cp+s.post,r=!0;continue}return Gp(i,c+`{`+s.body+`}`+s.post,[``],t,n,a)}o&&=(a=r&&!d,!1);let p;if(d)p=Kp(s.body,u,t,n);else{let r=zp(s.body);if(r.length===1&&r[0]!==void 0&&(r=qp(r[0],t,n,!1).map(Vp),r.length===1)){if(i=Gp(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=qp(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=Gp(i,c,p,t,n,a&&!s.post.length),!s.post.length)break;e=s.post}return i}const Jp=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},Yp={"[: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]},Xp=e=>e.replace(/[[\]\\-]/g,`\\$&`),Zp=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Qp=e=>e.join(``),$p=(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(Yp))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(Xp(d)+`-`+Xp(t)):t===d&&r.push(Xp(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(Xp(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(Xp(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[Zp(e),!1,u-n,!1]}let f=`[`+(l?`^`:``)+Qp(r)+`]`,p=`[`+(l?``:`^`)+Qp(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},em=(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 tm=new Set([`!`,`?`,`+`,`*`,`@`]),nm=e=>tm.has(e),rm=e=>nm(e.type),im=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),am=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),om=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),sm=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),cm=`(?!\\.)`,lm=new Set([`[`,`.`]),um=new Set([`..`,`.`]),dm=new Set(`().*{}+?[]^$\\!`),fm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),pm=`[^/]+?`;let mm=0;var hm=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++mm;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&&nm(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&&nm(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,am)}#m(e,t=im){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=om){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!!sm.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=sm.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()),!rm(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&&um.has(this.#r[0]))){let n=lm,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?cm:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,em(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,em(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?cm:``)+pm;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?cm:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,em(i),this.#t=!!this.#t,this.#n]}#x(){if(rm(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+=(dm.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?pm:`[^/]*?`,t=!0;continue}if(o=!1,c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=$p(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=`[^/]`,t=!0;continue}i+=fm(c)}return[i,em(e),!!t,a]}};K=hm;const gm=(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={})=>(Jp(t),!n.nocomment&&t.charAt(0)===`#`?!1:new Hm(t,n).match(e)),_m=/^\*+([^+@!?*[(]*)$/,vm=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),ym=e=>t=>t.endsWith(e),bm=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),xm=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Sm=/^\*+\.\*+$/,Cm=e=>!e.startsWith(`.`)&&e.includes(`.`),wm=e=>e!==`.`&&e!==`..`&&e.includes(`.`),Tm=/^\.\*+$/,Em=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),Dm=/^\*+$/,Om=e=>e.length!==0&&!e.startsWith(`.`),km=e=>e.length!==0&&e!==`.`&&e!==`..`,Am=/^\?+([^+@!?*[(]*)?$/,jm=([e,t=``])=>{let n=Fm([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Mm=([e,t=``])=>{let n=Im([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Nm=([e,t=``])=>{let n=Im([e]);return t?e=>n(e)&&e.endsWith(t):n},Pm=([e,t=``])=>{let n=Fm([e]);return t?e=>n(e)&&e.endsWith(t):n},Fm=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},Im=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},Lm=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,Rm={win32:{sep:`\\`},posix:{sep:`/`}};q.sep=Lm===`win32`?Rm.win32.sep:Rm.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 zm=(e,t={})=>(Jp(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Bp(e,{max:t.braceExpandMax}));q.braceExpand=zm,q.makeRe=(e,t={})=>new Hm(e,t).makeRe(),q.match=(e,t,n={})=>{let r=new Hm(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const Bm=/[?*]|[+@!]\(.*?\)|\[|\]/,Vm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var Hm=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){Jp(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||Lm,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]===`?`||!Bm.test(e[2]))&&!Bm.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,m=e.length-u;for(let e of d)e[1]=m-(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 zm(this.pattern,this.options)}parse(e){Jp(e);let t=this.options;if(e===`**`)return J;if(e===``)return``;let n,r=null;(n=e.match(Dm))?r=t.dot?km:Om:(n=e.match(_m))?r=(t.nocase?t.dot?xm:bm:t.dot?ym:vm)(n[1]):(n=e.match(Am))?r=(t.nocase?t.dot?Mm:jm:t.dot?Nm:Pm)(n):(n=e.match(Sm))?r=t.dot?wm:Cm:(n=e.match(Tm))&&(r=Em);let i=hm.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`?Vm(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=hm,q.Minimatch=Hm,q.escape=gm,q.unescape=em;const Um=/[/\\]/u,Wm={kind:`ignore`},Gm=e=>!ie(e)&&e.split(Um).every(e=>e!==`.`&&e!==`..`),Km=/^!+/u,qm=/^\.?\/+/u,Jm=e=>{let t=Km.exec(e)?.[0]??``;return{body:e.slice(t.length).replace(qm,``),negated:t.length%2==1}},Ym=e=>Jm(e).negated,Xm=e=>Jm(e).body,Zm=/[?[\]{}()]/u,Qm=e=>Gm(e)&&!Ym(e)&&!e.includes(`**`)&&!Zm.test(e)&&(e.match(/\*/gu)??[]).length<=1,$m=(e,t)=>q(e,t),eh=e=>{let t=e.lastIndexOf(`/`);return(t===-1?e:e.slice(t+1)).includes(`*`)?{baseDir:t===-1?`.`:e.slice(0,t),kind:`expand-children`,pattern:e}:Wm},th=e=>Qm(e)?e.endsWith(`/*`)?{baseDir:e.slice(0,-2),kind:`expand-children`,pattern:e}:e===`*`?{baseDir:`.`,kind:`expand-children`,pattern:e}:e.includes(`*`)?eh(e):{dir:e,kind:`probe-dir`,pattern:e}:Wm,nh=e=>e.replaceAll(/\/+/gu,`/`).replace(/\/$/u,``),rh=new Set([`candidate_not_inspected`,`manifest_unreadable`,`unsupported_pattern`,`workspace_declaration_unparsed`,`workspace_dir_unreadable`,`workspace_file_unreadable`]),ih=(e,t,n)=>t.filter((e,t)=>n[t]===!0).map(t=>ae.join(e,t)),ah=(e,t)=>t?.name?{description:t.description,name:t.name,path:e}:void 0,oh=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},sh=e=>!e.diagnostics.some(e=>rh.has(e.kind)),ch=e=>!e.diagnostics.some(e=>e.kind===`no_workspace_declaration`),lh=(e,t)=>e<t?-1:+(e>t),uh=e=>`path`in e?`${e.kind} ${e.path}`:`file`in e?`${e.kind} ${e.file}`:`pattern`in e?`${e.kind} ${e.pattern}`:e.kind,dh=e=>e.toSorted((e,t)=>lh(uh(e),uh(t))),fh=e=>!ie(e)&&!e.split(/[/\\]/u).includes(`..`),ph=(e,t)=>e.kind===`missing`?{kind:`absent`}:e.kind===`outside`?{kind:`unreadable`,reason:`${t} escapes the checkout`}:{kind:`unreadable`,reason:e.code},mh=async(e,t,n)=>{if(!fh(t))return{kind:`unreadable`,reason:`path escapes the checkout`};let r=await hh(e,t);if(`probe`in r)return r.probe;let i=await gh(r.real);return`reason`in i?{kind:`unreadable`,reason:i.reason}:i.found===n?{kind:`match`}:{found:i.found,kind:`mismatch`}},hh=async(e,t)=>{let n=await Gl(e,h(e,t));if(n.kind!==`inside`)return{probe:ph(n,`path`)};let r=await Gl(e,h(n.real,`package.json`));return r.kind===`inside`?{real:r.real}:{probe:ph(r,`manifest`)}},gh=async e=>{try{let t=JSON.parse(await s(e,`utf8`));return{found:eu(t)}}catch(e){return{reason:e.code??String(e)}}},_h=(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(lh)}},vh=new Set;let yh=!1;const bh=()=>{for(let e of vh)try{e.kill(`SIGKILL`)}catch{}},xh=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],Sh=e=>{let t=()=>{bh(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},Ch=()=>{yh||(yh=!0,xh.forEach(e=>{Sh(e)}),process.on(`exit`,bh))},wh=()=>{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}}},Th=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
323
+ `),Eh=(e,t,n)=>{let r=e;return t.truncated&&(r=Th(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=Th(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},Dh={clear:()=>{},markedTimedOut:()=>!1},Oh=(e,t)=>{if(t===void 0)return Dh;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}},kh=e=>e===void 0?{}:{cwd:e},Ah=(e,t)=>Th(e,`refs: command timed out after ${String(t)}ms`),jh=(e,t)=>({exitCode:124,stderr:Ah(e,t),stdout:``,timedOut:!0}),Mh=(e,t,n)=>{let r=ye(e,t,{...kh(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});vh.add(r);let i=wh(),a=wh();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:Oh(r,n?.timeoutMs)}},Nh=(e,t,n)=>{try{return Mh(e,t,n)}catch(e){return{exitCode:127,stderr:Fh(e),stdout:``}}},Ph=e=>!(`child`in e),Fh=e=>e instanceof Error?e.message:String(e),Ih=async e=>{try{let[t]=await _e(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:Fh(e)}}},Lh=e=>e===null?1:e,Rh=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,zh=e=>e.timedOut?jh(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?Rh({exitCode:Lh(e.code),stderr:Eh(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):Rh({exitCode:127,stderr:Th(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var Bh=class{async run(e,t,n){Ch();let r=Nh(e,t,n);if(Ph(r))return r;let i=await Ih(r.child);return vh.delete(r.child),r.timeout.clear(),zh({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Vh=Mc.partial({description:!0}),Hh=Es({default_branch:F().min(1),key:Sc,tag_format_candidate:Dc.nullable(),url:F().min(1)});Hh.extend({description:F().default(``),packages:dc(Vh)});const Uh=Hh.extend({description:F().min(1),packages:dc(Mc)}),Wh=Es({effective_clone_mode:Tc.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:sc().optional(),pending_proposal_at:sc().optional()}),Gh=Es({refs:lc(e=>e.length>0&&!cc.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,Ns(F(),Wh)).default({})}),Kh=(e,t,n)=>t?.[e]??n[e],qh=async e=>{try{return await s(e.statePath,`utf8`)}catch(e){if(R(e))return;throw e}},Jh=e=>{try{return JSON.parse(e)}catch{return}},Yh=async e=>{let t=await qh(e);if(t===void 0)return Gh.parse({});let n=Jh(t);if(n===void 0)return Gh.parse({});let r=Gh.safeParse(n);return r.success?r.data:Gh.parse({})},Xh=async(e,t)=>{let n=Gh.safeParse(t);if(!n.success)throw b(D(n.error));await gl(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},Zh=/^\d+\.\d+\.\d+$/u,Qh=/^0+(?=\d)/u,$h=(e,t)=>{let n=e.replace(Qh,``),r=t.replace(Qh,``);return n.length===r.length?n===r?0:n<r?-1:1:n.length<r.length?-1:1},eg=(e,t)=>{if(!Zh.test(e)||!Zh.test(t))return;let n=e.split(`.`),r=t.split(`.`);return n.map((e,t)=>$h(e,r[t]??``)).find(e=>e!==0)??0},tg=Ds({version:F().regex(Zh)}),ng=Es({checked_at:sc(),latest_version:F().regex(Zh)}),rg=async e=>{try{let t=ng.safeParse(JSON.parse(await s(e.updateCachePath,`utf8`)));return t.success?t.data:void 0}catch{return}},ig=async(e,t)=>{try{await p(e.root),await gl(e.updateCachePath,`${JSON.stringify(t,void 0,2)}\n`)}catch{}},ag=(e,t)=>{let n=t-Date.parse(e.checked_at);return n>=0&&n<864e5},og=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=tg.safeParse(await t.json());return n.success?n.data.version:void 0}catch{return}},sg=async e=>{let t=await rg(e.home);if(t!==void 0&&ag(t,e.nowMs))return{latest:t.latest_version,refreshed:!1,stale:!1};let n=await og(e.fetch);return n===void 0?{latest:t?.latest_version,refreshed:!1,stale:!0}:(await ig(e.home,{checked_at:new Date(e.nowMs).toISOString(),latest_version:n}),{latest:n,refreshed:!0,stale:!1})},cg=(e,t)=>{let n=eg(e,t);return n!==void 0&&n<0},lg=(e,t)=>`refs ${t} is available (this is ${e}) — update: npm i -g @kaisers-io/refs@latest`,ug=e=>{let t=e.REFS_UPDATE_CHECK?.trim();if(t===`0`)return!1;if(t===`1`)return!0},dg=e=>{let t=e.CI?.trim().toLowerCase();return t!==void 0&&t!==``&&t!==`false`&&t!==`0`},fg={check:!0,notify:!0},pg=e=>{let t=ug(e.env);return t===void 0?(e.updates??fg).check?dg(e.env)?`ci`:`on`:`config`:t?`on`:`env`},mg=e=>pg(e)===`on`,hg=e=>mg(e)&&(e.updates??fg).notify,gg=async(e,t)=>{let n=await Gl(e,h(t,`package.json`));if(n.kind===`inside`)try{let e=JSON.parse(await s(n.real,`utf8`));return{description:tu(e),name:eu(e)}}catch{return}},_g=async(e,t)=>{let n=await gg(e,h(e,t));if(n===void 0)return{diagnostic:{kind:`manifest_unreadable`,path:t}};let r=ah(t,n);return r===void 0?{diagnostic:{kind:`manifest_missing_name`,path:t}}:{pkg:r}},vg=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}},yg=new Set([`ENOENT`,`ENOTDIR`]),bg=async(e,t)=>{let n=await Gl(e,h(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`}},xg=async e=>{try{return{entries:await c(e,{withFileTypes:!0})}}catch(e){return{code:e.code??``}}},Sg=(e,t,n)=>Promise.all(n.map(n=>bg(e,h(t,n.name)))),Cg=(e,t,n)=>e.filter((e,r)=>n(t[r])).map(e=>e.name),wg=async e=>{let{baseDir:t,dirs:n,fullPath:r,repoDir:i,symlinks:a}=e,o=e=>ae.join(t===`.`?``:t,e),[s,c]=await Promise.all([Sg(i,r,n),Sg(i,r,a)]);return{diagnostics:[...Cg(n,s,e=>e===`rejected`).map(e=>({kind:`manifest_unreadable`,path:o(e)})),...Cg(a,c,e=>e!==`none`).map(e=>({kind:`candidate_not_inspected`,path:o(e)}))],dirs:ih(t,n.map(e=>e.name),s.map(e=>e===`manifest`))}},Tg=async e=>{let t=await _g(e,`.`);return`pkg`in t?[t]:[]},Eg=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]},Dg=async e=>{let[t]=await Tg(e);return t!==void 0&&`pkg`in t?t.pkg:void 0},Og=(e,t)=>$m(ae.join(t.baseDir===`.`?``:t.baseDir,e.name),t.pattern),kg=async(e,t)=>{let n=h(e,t),r=await Gl(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 xg(n);return`code`in i?{result:yg.has(i.code)?{diagnostics:[],dirs:[]}:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}}:{entries:i.entries}},Ag=async(e,t,n)=>{let{baseDir:r}=t,i=await kg(e,r);if(`result`in i)return i.result;let a=r===`.`?``:r,o=e=>Og(e,t)&&!n.has(ae.join(a,e.name)),s={entries:i.entries};return wg({baseDir:r,dirs:s.entries.filter(e=>e.isDirectory()&&o(e)),fullPath:h(e,r),repoDir:e,symlinks:s.entries.filter(e=>e.isSymbolicLink()&&o(e))})},jg=async(e,t)=>{let n=await bg(e,h(e,t));return n===`manifest`?{diagnostics:[],dirs:[nh(t)]}:n===`rejected`?{diagnostics:[{kind:`manifest_unreadable`,path:t}],dirs:[]}:{diagnostics:[],dirs:[]}},Mg=(e,t,n)=>{let r=th(t.body);return r.kind===`expand-children`?Ag(e,r,n):r.kind===`probe-dir`?n.has(nh(r.dir))?Promise.resolve({diagnostics:[],dirs:[]}):jg(e,r.dir):Promise.resolve({diagnostics:[{kind:`unsupported_pattern`,pattern:t.declared}],dirs:[]})},Ng=(e,t)=>$m(Xm(e),Xm(t)),Pg=e=>({negations:e.filter(e=>Ym(e)),patterns:e.filter(e=>!Ym(e))}),Fg=e=>{let t=e.reduce((e,t)=>Ym(t)?{negations:[...e.negations,t],patterns:e.patterns}:{negations:e.negations.filter(e=>!Ng(t,e)),patterns:[...e.patterns,t]},{negations:[],patterns:[]});return{negations:t.negations,patterns:t.patterns.filter(e=>!t.negations.some(t=>Ng(e,t)))}},Ig=e=>e.endsWith(`/`)?e:`${e}/`,Lg=(e,t)=>e.some(e=>$m(Ig(t),Ig(Xm(e)))),Rg=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]}},zg=async(e,t)=>{let{negations:n,patterns:r}=t,i={has:e=>Lg(n,e)},a=Rg(await Promise.all(r.map(t=>Mg(e,{body:Xm(t),declared:t},i))));return{diagnostics:a.diagnostics,dirs:a.dirs}},Bg=async(e,t)=>{let n=Fg(t.npm),r=Pg(t.pnpm),i=await Promise.all([zg(e,n),zg(e,r)]);return Rg(i)},Vg=async e=>{let t=await cu(e);if(t.npm.length===0&&t.pnpm.length===0)return{diagnostics:dh([...t.diagnostics,{kind:`no_workspace_declaration`}]),packages:[]};let n=await Bg(e,t),[r,i]=await Promise.all([Tg(e),Promise.all(n.dirs.map(t=>_g(e,t)))]),a=vg([...r,...i]);return{diagnostics:dh([...t.diagnostics,...n.diagnostics,...a.diagnostics]),packages:Eg(oh(a.packages))}},Hg=async e=>(await Vg(e)).packages;var Ug=`0.12.0`;const Wg=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},Gg=()=>{try{return me()}catch{return``}},Kg=()=>({cliVersion:Ug,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:(e,t)=>fetch(e,t),homedir:Gg(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:Wg,runner:new Bh});var qg=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}},Jg=class extends qg{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},Yg=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 Jg(`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 Xg(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var Zg=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=>Xg(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(`
324
+ `)}displayWidth(e){return be(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,`
324
325
  `+` `.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(`
325
- `)}},Yp=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=Qp(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 Gp(`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?Zp(this.name().replace(/^no-/,``)):Zp(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}},Xp=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 Zp(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Qp(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}
326
+ `)}},Qg=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=t_(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 Jg(`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?e_(this.name().replace(/^no-/,``)):e_(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}},$g=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 e_(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function t_(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}
326
327
  - a short flag is a single dash and a single character
327
328
  - either use a single dash and a single character (for a short flag)
328
329
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
329
330
  - too many short flags`):i.test(t)?Error(`${n}
330
331
  - too many long flags`):Error(`${n}
331
- - 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 $p(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 em(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=$p(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 tm=class e extends pe{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=>g.stdout.write(e),writeErr:e=>g.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>g.stdout.isTTY?g.stdout.columns:void 0,getErrHelpWidth:()=>g.stderr.isTTY?g.stderr.columns:void 0,getOutHasColors:()=>rm()??(g.stdout.isTTY&&g.stdout.hasColors?.()),getErrHasColors:()=>rm()??(g.stderr.isTTY&&g.stderr.hasColors?.()),stripColor:e=>_e(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 Jp,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
332
- - 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 Kp(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}'.
333
- 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 Wp(e,t,n)),g.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 Yp(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}'
334
- - 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 Yp)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){g.versions?.electron&&(t.from=`electron`);let e=g.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=g.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`:g.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.
335
- - 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(ce.existsSync(e))return;let r=`'${e}' does not exist
332
+ - 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 n_(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=n_(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 i_=class e extends ge{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=>g.stdout.write(e),writeErr:e=>g.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>g.stdout.isTTY?g.stdout.columns:void 0,getErrHelpWidth:()=>g.stderr.isTTY?g.stderr.columns:void 0,getOutHasColors:()=>o_()??(g.stdout.isTTY&&g.stdout.hasColors?.()),getErrHasColors:()=>o_()??(g.stderr.isTTY&&g.stderr.hasColors?.()),stripColor:e=>be(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 Zg,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
333
+ - 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 Yg(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}'.
334
+ 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 qg(e,t,n)),g.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 Qg(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}'
335
+ - 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 Qg)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){g.versions?.electron&&(t.from=`electron`);let e=g.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=g.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`:g.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.
336
+ - 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(de.existsSync(e))return;let r=`'${e}' does not exist
336
337
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
337
338
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
338
- - ${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=m.resolve(e,t);if(ce.existsSync(r))return r;if(n.includes(m.extname(t)))return;let i=n.find(e=>ce.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=ce.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=m.resolve(m.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=m.basename(this._scriptPath,m.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(m.extname(i)),s;g.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=nm(g.execArgv).concat(t),s=he.spawn(g.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=nm(g.execArgv).concat(t),s=he.spawn(g.argv[0],t,{stdio:`inherit`})):s=he.spawn(i,t,{stdio:`inherit`}),s.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{g.on(e,()=>{s.killed===!1&&s.exitCode===null&&s.kill(e)})});let c=this._exitCallback;s.on(`close`,e=>{e??=1,c?c(new Wp(e,`commander.executeSubCommandAsync`,`(close)`)):g.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)g.exit(1);else{let e=new Wp(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(`
339
- `),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 g.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()}`,g.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Xp(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=em(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=em(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=>qp(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=m.basename(e,m.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(g.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.
340
- 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 nm(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 rm(){if(g.env.NO_COLOR||g.env.FORCE_COLOR===`0`||g.env.FORCE_COLOR===`false`)return!1;if(g.env.FORCE_COLOR||g.env.CLICOLOR_FORCE!==void 0)return!0}new tm;const im=[],am=e=>Array.isArray(e)?e:[e],om=e=>e===void 0?im:[e],sm=e=>e instanceof Error?e.message:String(e),Z=e=>{let t=e.optsWithGlobals();return{json:t.json===!0,verbose:t.verbose===!0}},Q=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??im};e.out(JSON.stringify(t));return}for(let t of am(n))e.out(t);for(let t of i??im)e.errLine(`refs: warning: ${t}`)},cm=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},lm=(e,t)=>{e.errLine(`refs: ${t}`)},$=(e,t,n)=>async()=>{try{await n()}catch(n){let r=be(n,{verbose:t.verbose});cm(e,t,r),process.exitCode=r.exitCode}},um=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`}},dm=/^v(?<major>\d+)\.(?<minor>\d+)/u,fm=e=>{let t=dm.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},pm=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,mm=e=>{let{nodeVersion:t}=e;return pm(fm(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},hm=()=>Ac.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),gm=async e=>{try{return{config:await W(e)}}catch(e){return{config:hm(),errorMessage:sm(e)}}},_m=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},vm={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)`},ym=(e,t,n)=>{if(dp(e,t)){let r=n?` (npm was unreachable just now; this was its last answer)`:``;return{detail:`${fp(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`}},bm=async(e,t)=>{let n=gp({env:e.env,updates:t.updates});if(n!==`on`)return{detail:vm[n],name:`cli-update`,status:`ok`};let{latest:r,stale:i}=await up({fetch:e.fetcher,home:H(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`}:ym(e.cliVersion,r,i)},xm=(e,t)=>Object.keys(t.refs).map(t=>({dest:U(e,z.parse(t)),key:t})).filter(e=>G(e.dest)),Sm=[`pre-commit`,`pre-push`],Cm=async(t,r)=>{try{return await e(h(t.hooksDir,r),n.X_OK),!0}catch{return!1}},wm=async e=>{let t=await Promise.all(Sm.map(t=>Cm(e,t)));return Sm.filter((e,n)=>!t[n])},Tm=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},Em=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:`${Sm.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},Dm=async(e,t,n)=>{let r=xm(t,n),[i,a]=await Promise.all([wm(t),Promise.all(r.map(n=>Tm(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return Em({badKeys:o,checkoutCount:r.length,missingHooks:i})},Om=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}},km=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`}},Am=async(e,t,n)=>{let r=xm(t,n),i=await Promise.all(r.map(t=>Om(e,t)));return km(i)},jm=async e=>{try{return await X(e)}catch{return Xf.parse({})}},Mm=async e=>{try{return(await s(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(V(e))return[];throw e}},Nm=async(e,t)=>{if(G(e))return[[...t]];let n=await Mm(e);return(await Promise.all(n.map(n=>Nm(h(e,n),[...t,n])))).flat()},Pm=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},Fm=(e,t,n)=>Pm(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: rm -rf ${e.dest}`,Im=(e,t)=>({dest:h(e.sourcesDir,...t),key:t.join(`/`)}),Lm=async(e,t,n)=>{let r=(await Nm(e.sourcesDir,[])).map(t=>Im(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=>Fm(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},Rm=[`.agents`,`skills`,`refs`,`SKILL.md`],zm=[`skills`,`refs`,`SKILL.md`],Bm=[`.claude`,`skills`,`refs`,`SKILL.md`],Vm=`npx skills add kaisers-io/refs`,Hm=`npm i -g @kaisers-io/refs@latest`,Um=(e,t)=>e===void 0?void 0:{display:t,path:e},Wm=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}:Um(r===void 0?void 0:h(r,t),`~/${t}`)},Gm=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:Um(t,`~/.agents`),segments:Rm},{label:`Claude Code`,root:Wm({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:zm},{label:`Codex`,root:Wm({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:zm},{label:`project ./.agents`,root:Um(e.cwd,`./.agents`),segments:Rm},{label:`project ./.claude`,root:Um(e.cwd,`./.claude`),segments:Bm}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:h(t.path,...n)}])},Km=async(e,t)=>{try{let n=await c(e);return{label:t,realPath:n,source:await o(n,`utf8`)}}catch{return}},qm=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},Jm=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,Ym=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,Xm=e=>{let t=Jm.exec(e)?.groups?.body;if(t!==void 0)return Ym.exec(t)?.groups?.version},Zm=(e,t)=>{if(e===t)return`match`;let n=rp(e,t);return n===void 0?`unknown`:n===0?`match`:n>0?`cli-older`:`skill-older`},Qm={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${Hm}`,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: ${Vm}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${Hm} and ${Vm}`},$m=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: ${Vm}`,name:`skill`,status:`warn`};let i=Zm(r,t);return{detail:`${n}: ${Qm[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},eh=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: ${Vm}`,name:`skill`,status:`warn`}),th=async e=>{let t=Gm(e),n=await Promise.all(t.map(e=>Km(e.path,e.label))),r=qm(n.filter(e=>e!==void 0)).map(t=>$m({cliVersion:e.cliVersion,label:t.label,skillVersion:Xm(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??eh(t)},nh=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,rh=e=>e===``?{}:{user:e},ih=e=>e===``?{}:{port:e},ah=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...rh(t.username),...ih(t.port)}:void 0}catch{return}},oh=e=>{let t=nh.exec(e),n=t?.groups?.host;return n===void 0?ah(e):{host:n,user:t?.groups?.user??`git`}},sh=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,ch=e=>e.user===void 0?sh(e):`${e.user}@${sh(e)}`,lh=e=>{let t=Object.values(e.refs).map(e=>oh(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(ch(e),e);return[...n.values()].toSorted((e,t)=>ch(e).localeCompare(ch(t)))},uh=/Permission denied/u,dh=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],fh=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,ph=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=fh(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},mh=async(e,t,n)=>{let r=ch(t),i=await e.runner.run(`ssh`,ph(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:uh.test(i.stderr)?{host:r,outcome:`denied`}:dh.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},hh=(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`}},gh=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`}},_h=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`}},vh=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),yh=(e,t)=>hh(e,t)??gh(e)??_h(e)??vh(e),bh=async(e,t,n)=>{let r=lh(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>mh(e,t,i)));return yh(a,i)},xh=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${sm(t)}`,name:e.name,status:`fail`}}},Sh=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await xh(t),i=await Sh(n);return r===void 0?i:[r,...i]},Ch=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>um(n)},{name:`node`,run:()=>Promise.resolve(mm(n))},{name:`config`,run:()=>Promise.resolve(_m(t.errorMessage))},{name:`hooks-guard`,run:()=>Dm(n,r,t.config)},{name:`dirty-checkouts`,run:()=>Am(n,r,t.config)},{name:`orphans`,run:()=>Lm(r,t.config,i)},{name:`skill`,run:()=>th(n)},{name:`cli-update`,run:()=>bm(n,t.config)},{name:`ssh-auth`,run:()=>bh(n,t.config)}]},wh=async e=>{let t=H(e.env),n=await gm(t),r=await jm(t);return Sh(Ch({configLoad:n,ctx:e,home:t,state:r}))},Th={fail:`FAIL`,ok:`OK`,warn:`WARN`},Eh=e=>e.map(e=>`[${Th[e.status]}] ${e.name}: ${e.detail}`),Dh=e=>e.some(e=>e.status===`fail`),Oh=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, ssh).`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await wh(t);Q(t,r,Eh(e),{checks:e}),Dh(e)&&(process.exitCode=_.UNEXPECTED)})()})},kh=async e=>{let t=H(e.env),n=await J(t,`home`,()=>Ml(t,Bp));return n===`migrated`?{backup:ul(t),result:n}:{backup:null,result:n}},Ah=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${ee(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,jh=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await kh(t);Q(t,r,Ah(e),e)})()})},Mh=`never`,Nh=(e,t,n)=>e===void 0||n-Date.parse(e)>t,Ph=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,Fh=(e,t)=>{if(e===void 0)return Mh;let n=t-Date.parse(e);if(Number.isNaN(n))return Mh;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return Ph(i,`minute`);let a=Math.floor(i/60);if(a<24)return Ph(a,`hour`);let o=Math.floor(a/24);return o<365?Ph(o,`day`):Ph(Math.floor(o/365),`year`)},Ih=e=>{let t=Fh(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==Mh&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},Lh=(e,t,n)=>{let r=e.state.refs[t],i=_c(Y(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:Y(`clone_mode`,n,e.settings),description:n.description,key:t,...r?.last_fetched_at===void 0?{}:{last_fetched_at:r.last_fetched_at},missing:!G(U(e.home,z.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:Nh(r?.last_fetched_at,i,e.now)}},Rh=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])=>Lh(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},zh=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=await X(r);return Rh({config:i,home:r,includePackages:t,now:n,state:a})},Bh=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...Ih({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],Vh=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...Bh(n,t)),e),[]),Hh=e=>e.split(`/`),Uh=(e,t)=>{let n=Hh(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},Wh=(e,t)=>{if(Object.hasOwn(e.refs,t))return z.parse(t);let n=Hh(t),r=Object.keys(e.refs).filter(e=>Uh(e,n)).toSorted(),[i]=r;if(i===void 0)throw y(`no ref matches '${t}'`);if(r.length>1)throw b(`'${t}' matches more than one ref: ${r.join(`, `)}`);return z.parse(i)},Gh=(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=Z(n);return $(t,r,async()=>{let n=Date.now(),i=await zh(t,e.packages===!0,n);Q(t,r,Vh(i,n),i)})()})},Kh=e=>`ref.${e.replaceAll(`/`,`_`)}`,qh=e=>e.REFS_ALLOW_FILE_URLS===`1`,Jh=(e,t)=>{let n=Hu(t,{allowFileUrls:qh(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},Yh=async(e,t)=>{if(t===``)throw b(`refs add npm: requires a package name, e.g. npm:left-pad`);lm(e,`resolving npm package '${t}'…`);let n=await Gd(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},Xh=(e,t)=>t.startsWith(`npm:`)?Yh(e,t.slice(4)):Promise.resolve(Jh(e,t)),Zh=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Y(`git_transport`,void 0,t);return{...e,cloneUrl:$u(e.cloneUrl,n)}},Qh=e=>`ref '${e}' already exists — use refs edit or refs remove`,$h=(e,t)=>{if(e.refs[t]!==void 0)throw ve(Qh(t))},eg=async e=>{try{return await s(e,{withFileTypes:!0})}catch(e){if(V(e))return;throw e}},tg=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),ng=async(e,t)=>{let n=await eg(e);if(n===void 0)return{kind:`stop`};let r=tg(n);if(r.includes(t))return{kind:`continue`,nextDir:h(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},rg=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await ng(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):rg(a.nextDir,i,[...n,r])},ig=[],ag=async(e,t)=>{let n=await rg(e.sourcesDir,t.split(`/`),ig);if(n!==void 0)throw ve(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},og=async e=>{try{return await i(e),!0}catch(e){if(V(e))return!1;throw e}},sg=async e=>{try{return await s(e)}catch(e){if(V(e))return;throw e}},cg=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(V(e))return;throw e}},lg=async e=>{let t=await sg(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await d(e)}catch(e){if(!V(e))throw e}return!0},ug=async e=>{let t=await cg(e);return t===void 0?!0:t?lg(e):!1},dg=async(e,t)=>{t!==e.sourcesDir&&await ug(t)&&await dg(e,te(t))},fg=async(e,t)=>await og(t)?(ml(e,t),await u(t,{force:!0,recursive:!0}),await dg(e,te(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},pg=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),mg=async(e,t)=>{let n=await W(e),r={...n,refs:pg(n.refs,t)};await Sl(e,r);let i=await X(e),a={...i,refs:pg(i.refs,t)};await $f(e,a)},hg=async(e,t)=>{let n=H(e.env),r=await W(n),i=Wh(r,t),a=U(n,i),{removedCheckout:o,warning:s}=await J(n,Kh(i),()=>fg(n,a));return await J(n,`home`,()=>mg(n,i)),{data:{key:i,removed_checkout:o},warnings:om(s)}},gg=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],_g=(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=Z(r);return $(t,i,async()=>{let{data:n,warnings:r}=await hg(t,e);Q(t,i,gg(n),n,r)})()})},vg=async e=>{let t=await yf(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`}:bg(e)},yg=(e,t)=>({path:e.configuredPath,reason:t,status:`unverifiable`}),bg=async e=>{let t=await Rp(e.checkoutDir),n=Sf(t.packages,e.packageName),r=tf(t);return n.kind===`ambiguous`?{candidates:n.paths,configuredPath:e.configuredPath,path:null,status:`ambiguous`}:r?n.kind===`found`?{configuredPath:e.configuredPath,path:n.path,status:`relocated`}:xg(e,t):yg(e,n.kind===`found`?`workspace detection was incomplete, so the new location is not confirmed unique`:`workspace detection was incomplete`)},xg=(e,t)=>nf(t)?{configuredPath:e.configuredPath,path:null,status:`missing`}:yg(e,`this repo declares no workspaces, so there was nowhere to search`),Sg=async e=>{try{return await J(e.home,Kh(e.key),()=>vg(e),e.lockTimeoutMs===void 0?void 0:{timeoutMs:e.lockTimeoutMs})}catch(t){if(t instanceof v&&t.code===`conflict`)return{path:e.configuredPath,reason:`could not acquire the ref lock in time`,status:`unverifiable`};throw t}},Cg=async e=>{if(!G(e.checkoutDir))return{path:e.configuredPath,status:`unmaterialized`};let t=await yf(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?.(),Sg(e))},wg=async e=>{let t=await Cg(e);return{...t.candidates===void 0?{}:{candidates:t.candidates},...t.configuredPath===void 0?{}:{configured_path:t.configuredPath},local_path:t.path===null?null:h(e.checkoutDir,t.path),name:e.packageName,path:t.path,...t.reason===void 0?{}:{reason:t.reason},status:t.status}},Tg=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}`]],Eg=(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},Dg=(e,t)=>{if(!G(e))throw y(`checkout for '${t}' is missing — run: refs sync ${t}`)},Og=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw y(`no package '${n}' registered on ref '${t}'`);return r},kg=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,Ag=/^[a-z][a-z0-9+.-]*:\/\//iu,jg=/^git@[^:/\s]+:[^\s]+$/u,Mg=e=>Ag.test(e)||jg.test(e),Ng=(e,t)=>{try{return Hu(e,t)}catch{if(Mg(e))throw x(`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}},Pg=(e,t,n)=>{let r=Ng(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw y(kg(t))}},Fg=(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:z.parse(r)})}return n},Ig=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — use the full ref key`,Lg=(e,t)=>{let n=Fg(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw b(Ig(t,n.map(e=>e.key)));return r}},Rg=(e,t)=>{let n=t.split(`/`);for(let t=n.length-1;t>=1;--t){let r=n.slice(0,t).join(`/`),i=Lg(e,r);if(i!==void 0)return{...i,name:r}}},zg=(e,t)=>{try{return Wh(e,t)}catch(e){throw e instanceof v&&e.code===`not_found`?y(kg(t)):e}},Bg=(e,t,n)=>{let r=Pg(e,t,n);if(r!==void 0)return r;let i=Lg(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=Rg(e,t);return a===void 0?{key:zg(e,t)}:{key:a.key,packageMatch:a}},Vg=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=Bg(i,t,{allowFileUrls:qh(e.env)}),o=Eg(i,a.key),s=await X(r),c=U(r,a.key),l=_c(Y(`sync_ttl`,o,i.settings)),u=s.refs[a.key]?.last_fetched_at;return{key:a.key,...u===void 0?{}:{last_fetched_at:u},local_path:c,missing:!G(c),package:a.packageMatch===void 0?null:await wg({checkoutDir:c,configuredPath:a.packageMatch.entry.path,home:r,key:a.key,packageName:a.packageMatch.name}),stale:Nh(u,l,n)}},Hg=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...Ih({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})];return e.package!==null&&n.push(...Tg(e.package)),n},Ug=(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`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let n=Date.now(),r=await Vg(t,e,n);Q(t,i,Hg(r,n),r)})()})},Wg={},Gg=async(e,t)=>{if(!G(t))return{tags:[]};try{return{tags:await iu(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${sm(e)}`}}},Kg=async(e,t,n,r)=>{let i=H(e.env),a=await W(i),o=Wh(a,t),s=Eg(a,o),c=await X(i),l=U(i,o),{packages:u,...d}=s,f=n.tags?await Gg(e,l):void 0,p=c.refs[o]??Wg;return{data:{...d,key:o,local_path:l,missing:!G(l),...n.packages?{packages:u??{}}:{},packages_count:Object.keys(u??{}).length,...f===void 0?{}:{sample_tags:f.tags},stale:Nh(p.last_fetched_at,_c(Y(`sync_ttl`,s,a.settings)),r),state:p},warnings:om(f?.warning)}},qg=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...Ih({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},Jg=(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=Z(r);return $(t,i,async()=>{let r={packages:n.packages===!0,tags:!i.json||n.tags===!0},a=Date.now(),{data:o,warnings:s}=await Kg(t,e,r,a);Q(t,i,qg(o,a),o,s)})()})},Yg=(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},Xg=async(e,t,n)=>{let r=await W(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await Sl(e,r))},Zg=(e,t,n)=>J(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await Xg(e,t,n.branchRenamedTo);let r=await X(e);r.refs[t]=Yg(r.refs[t],n),await $f(e,r)}),Qg=async(e,t,n)=>{try{await J(e,`home`,async()=>{let r=await X(e);r.refs[t]={...r.refs[t],last_error:n},await $f(e,r)})}catch{}},$g=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()}}},e_=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},t_=(e,t,n)=>`checkout at ${e} points at '${q(t)}' — expected '${q(n)}'; remove the checkout directory or run refs remove before retrying`,n_=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,r_=(e,t)=>{try{return Hu(e,{allowFileUrls:t}).key}catch{return}},i_=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=n_(n),i=r_(t.expectedUrl,t.allowFileUrls),a=r_(r,t.allowFileUrls);if(i===void 0||a!==i)throw ve(t_(t.dest,r,t.expectedUrl))},a_=e=>`checkout at ${e} exists but is not refs-managed — remove it (rm -rf ${e}) and retry`,o_=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 ve(a_(t.dest))},s_=async(e,t)=>{await a(te(t.dest),{recursive:!0}),lm(e,`cloning ${q(t.cloneUrl)} into ${t.dest}…`);let n=await Yl(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},c_=async(e,t)=>(ml(t.home,t.dest),G(t.dest)?(await i_(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await o_(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):s_(e,t)),l_=(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`,u_=(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`,d_=async(e,t)=>{await i_(e,t),await o_(e,{dest:t.dest,hooksDir:t.hooksDir});let n=await e.run(`git`,[`rev-parse`,`HEAD`],{cwd:t.dest});if(n.exitCode!==0)throw x(l_(t.key,t.dest));let r=n.stdout.trim();if(!Yf.shape.head_sha.safeParse(r).success)throw x(u_(t.key,t.dest,r));return r},f_=(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`,p_=(e,t,n)=>{if(!Yf.shape.head_sha.safeParse(n).success)throw x(f_(e,t,n));return n},m_=(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},h_=async(e,t,n)=>{await a(te(n),{recursive:!0});let r=Y(`clone_mode`,t.ref,t.settings),i=await Yl(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Zl(e.runner,n),s=await d_(e.runner,{allowFileUrls:qh(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return m_(t,i,{actualBranch:o,headSha:s})},g_=async(e,t,n)=>{await o_(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await i_(e.runner,{allowFileUrls:qh(e.env),dest:n,expectedUrl:t.ref.url});let r=await ru(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:p_(t.key,n,r.newSha),status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},__=(e,t)=>J(t.home,Kh(t.key),()=>{let n=U(t.home,t.key);return ml(t.home,n),G(n)?g_(e,t,n):h_(e,t,n)}),v_=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(` | `)},y_=(e,t)=>{let n={key:e,status:t.status},r=v_(t);return r!==void 0&&(n.warning=r),n},b_=async(e,t)=>{try{let n=await __(e,t);return await Zg(t.home,t.key,n),y_(t.key,n)}catch(e){let n=sm(e);return await Qg(t.home,t.key,n),{error:n,key:t.key,status:`failed`}}},x_=(e,t)=>e.status===`rejected`?{error:sm(e.reason),key:t,status:`failed`}:e.value,S_=async(e,t)=>{let n=$g(4);return(await Promise.allSettled(t.map(t=>e_(n,()=>b_(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return x_(e,r.key)})},C_=(e,t,n)=>({home:e,key:n,ref:Eg(t,n),settings:t.settings}),w_=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>C_(e,t,z.parse(n))):n.map(n=>C_(e,t,Wh(t,n))),T_=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=_c(Y(`sync_ttl`,t.ref,t.settings)),a=Nh(n.refs[t.key]?.last_fetched_at,i,r),o=!G(U(e,t.key));return a||o})},E_=async(e,t,n)=>{if(!vp({env:e.env,updates:n.updates}))return[];let{latest:r,refreshed:i}=await up({fetch:e.fetcher,home:t,nowMs:Date.now()});return!i||r===void 0||!dp(e.cliVersion,r)?[]:[fp(e.cliVersion,r)]},D_=async(e,t,n)=>{if(!n)return t;let r=await X(e);return T_(e,t,r)},O_=async(e,t)=>{let n=H(e.env),r=await W(n),i=w_(n,r,t.refs),a=await D_(n,i,t.staleOnly),[o,s]=await Promise.all([S_(e,a),a.length>0?E_(e,n,r):Promise.resolve([])]);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o,warnings:s}},k_=[`updated`,`fresh`,`cloned`,`restored`,`failed`],A_={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},j_=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},M_=e=>e.status===`failed`?` ${e.key}: ${e.error??`unknown error`}`:e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`,N_=e=>{let t=j_(e),n=[k_.map(e=>`${A_[e]} (${t[e].length})`).join(` / `)];for(let e of k_)for(let r of t[e])n.push(M_(r));return n},P_=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),F_=(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=Z(r);return $(t,i,async()=>{let r=await O_(t,P_(e,n));Q(t,i,N_(r.results),{results:r.results},r.warnings),r.failedCount>0&&(process.exitCode=_.UNEXPECTED)})()})},I_=(e,t,n)=>n===void 0?e.tag_format:Og(e,t,n).tag_format??e.tag_format,L_=e=>`'${e.replaceAll(`'`,String.raw`'\''`)}'`,R_=(e,t,n)=>{if(e!==void 0)return e;let r=n===void 0?`ref '${t}'`:`package '${n}'`,i=n===void 0?``:` --package ${L_(n)}`;throw x(`${r} has no tag_format configured — inspect the repository's real tags and set one with: refs edit ${L_(t)} tag_format '<format>'${i}`)},z_=async(e,t)=>{let n=H(e.env),r=await W(n),i=Wh(r,t.query),a=Eg(r,i),o=R_(I_(a,i,t.opts.packageName),i,t.opts.packageName),s=U(n,i);Dg(s,i);let c=await yu(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},B_=e=>[`${e.key}@${e.version} -> ${e.tag}`],V_=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},H_=[Oh,jh,_g,Ug,Jg,F_,(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=Z(i);return $(t,a,async()=>{let i=await z_(t,{opts:V_(r),query:e,version:n});Q(t,a,B_(i),i)})()})}],U_=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},W_=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,U_(e)])):n===void 0?{}:{[n]:{path:t??`.`}},G_=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}},K_=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,G_(t)]))},q_=e=>e.description===void 0||e.description===``,J_=e=>Object.entries(e).filter(([,e])=>q_(e)).map(([e])=>e).toSorted(),Y_=e=>{let t=J_(e);if(t.length!==0)throw x(`packages without a detected description: ${t.join(`, `)} — run the two-phase flow instead: refs add <source> --dry-run --json > proposal.json, fill in the package descriptions, then refs add --proposal proposal.json`)},X_=e=>{if(Object.keys(e).length!==0)return e},Z_=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},Q_=async(e,t,n)=>{let r=await Zl(e.runner,t),i=await iu(e.runner,t),a=_u(i);lm(e,`detecting workspace packages…`);let o=await zp(t);return{defaultBranch:r,packages:W_(o,n.npmDirectory,n.npmPkgName),tagFormatCandidate:a}},$_=(e,t)=>J(t.home,Kh(t.resolved.key),async()=>{let n=await c_(e,{allowFileUrls:qh(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await Q_(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),ev=e=>{let t={default_branch:e.cloneResult.fields.defaultBranch,description:``,key:e.resolved.key,packages:e.cloneResult.fields.packages,tag_format_candidate:e.cloneResult.fields.tagFormatCandidate,url:e.resolved.cloneUrl},n={dest:e.dest,proposal:t};return e.cloneResult.effectiveMode!==void 0&&(n.effectiveCloneMode=e.cloneResult.effectiveMode),e.cloneResult.warning!==void 0&&(n.warning=e.cloneResult.warning),n},tv=async(e,t)=>{let n=H(e.env),r=await W(n),i=Zh(await Xh(e,t),r.settings);$h(r,i.key),await ag(n,i.key);let a=U(n,i.key),o=Y(`clone_mode`,void 0,r.settings),s=await $_(e,{cloneMode:o,dest:a,home:n,resolved:i});return ev({cloneResult:s,dest:a,resolved:i})},nv=(e,t,n)=>J(e,`home`,async()=>{let r=await W(e);$h(r,t);let i=await X(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 $f(e,i)}),rv=(e,t)=>{let n=Ac.safeParse(e);if(!n.success)throw x(O(n.error));let r=Xf.safeParse(t);if(!r.success)throw x(O(r.error));return{config:n.data,state:r.data}},iv=async(e,t)=>{let n=await W(e.home);$h(n,e.ref.key);let r=Z_(e.ref);n.refs[e.ref.key]=r;let i=await X(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Y(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...rv(n,i),entry:r}},av=async(e,t)=>{let n=qh(e.env),r=await J(t.home,Kh(t.ref.key),()=>(ml(t.home,t.dest),d_(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return J(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await iv(t,r);return await $f(t.home,i),await Sl(t.home,e),{entry:n,key:t.ref.key}})},ov=(e,t)=>t===`-`?e.readStdin():o(t,`utf8`),sv=e=>{try{return JSON.parse(e)}catch(e){throw x(`invalid JSON in proposal: ${sm(e)}`)}},cv=e=>typeof e==`object`&&!!e&&!Array.isArray(e),lv=e=>cv(e)&&`ok`in e&&!(`key`in e),uv=e=>{if(!lv(e))return e;if(e.ok===!1)throw x(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(cv(e.data))return e.data;throw x(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},dv=e=>e.code===`unrecognized_keys`,fv=e=>e.path.length===0,pv=(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}`},mv=e=>{let t=new Map;for(let n of e){let e=Pt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>pv(e,t))},hv=e=>`✖ invalid proposal: ${e.message}`,gv=e=>{let t=e.issues.filter(e=>dv(e)),n=e.issues.filter(e=>!dv(e)),r=n.filter(e=>fv(e));if(t.length===0&&r.length===0)return O(e);let i=n.filter(e=>!fv(e)),a=[...mv(t),...r.map(e=>hv(e))];return i.length>0&&a.push(O({issues:i})),a.join(`
341
- `)},_v=e=>{let t=Jf.safeParse(e);if(!t.success)throw x(gv(t.error));return t.data},vv=async(e,t)=>{let n=await ov(e,t);return _v(uv(sv(n)))},yv=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],bv=async(e,t)=>{let n=await tv(e,t),r=H(e.env);await nv(r,n.proposal.key,n.effectiveCloneMode);let i=om(n.warning);return{data:n.proposal,human:yv(n.proposal.key,n.dest),warnings:i}},xv=e=>[`refs add: '${e}' added to config`],Sv=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=X_(e.packages);return n!==void 0&&(t.packages=n),t},Cv=async(e,t)=>{let n=await vv(e,t),r=H(e.env),i=U(r,n.key);if(!G(i))throw y(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let a=Sv(n),{entry:o,key:s}=await av(e,{dest:i,home:r,ref:a});return{data:{entry:o,key:s},human:xv(s),warnings:[]}},wv=(e,t)=>{Y_(e.proposal.packages);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,url:e.proposal.url};e.proposal.tag_format_candidate!==null&&(n.tag_format=e.proposal.tag_format_candidate);let r=K_(e.proposal.packages);return r!==void 0&&(n.packages=r),n},Tv=async(e,t,n)=>{let r=await tv(e,t),i=H(e.env),a=wv(r,n),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await av(e,o),l=om(r.warning);return{data:{entry:s,key:c},human:xv(c),warnings:l}},Ev=e=>{let t=[e.dryRun,e.proposal!==void 0,e.description!==void 0].filter(Boolean).length;if(t>1)throw b(`refs add: use only one of --dry-run, --proposal, or --description`);if(t===0)throw b(`refs add needs --dry-run, --proposal, or --description`)},Dv=e=>{if(e===void 0||e===``)throw b(`refs add requires <source> (a git url or npm:<package>)`);return e},Ov=(e,t)=>(Ev(t),t.proposal===void 0?t.description===void 0?bv(e,Dv(t.source)):Tv(e,Dv(t.source),t.description):Cv(e,t.proposal)),kv=(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},Av=(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=Z(r);return $(t,i,async()=>{let r=await Ov(t,kv(e,n));Q(t,i,r.human,r.data,r.warnings)})()})},jv=e=>e===void 0?null:e,Mv=()=>Object.keys(Tc.shape).toSorted().join(`, `),Nv=e=>`unknown package field '${e}' — valid fields: ${Mv()}`,Pv=e=>Object.hasOwn(Tc.shape,e),Fv=(e,t,n)=>{if(!Pv(t))throw b(Nv(t));let r=e[t],i=Tc.safeParse({...e,[t]:n});if(!i.success)throw x(O(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},Iv=async e=>{let t=Og(e.entry,e.key,e.packageName),n=Fv(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await Sl(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:jv(n.newValue),old:jv(n.oldValue)}},Lv=`packages`,Rv=()=>Object.keys(Ec.shape).filter(e=>e!==Lv).toSorted().join(`, `),zv=e=>`unknown ref field '${e}' — valid fields: ${Rv()}`,Bv=e=>Object.hasOwn(Ec.shape,e),Vv=(e,t,n)=>`failed to rewrite git remote at ${e} to '${q(t)}': ${n.trim()}`,Hv=async(e,t)=>{if(ml(t.home,t.dest),!G(t.dest))return;let n=await e.runner.run(`git`,[`remote`,`set-url`,`--`,`origin`,t.cloneUrl],{cwd:t.dest});if(n.exitCode!==0)throw x(Vv(t.dest,t.cloneUrl,n.stderr))},Uv=async(e,t)=>{let n=Hu(t.value,{allowFileUrls:qh(e.env)});if(n.key!==t.key)throw x(`new url derives a different key — remove and re-add instead`);let r=U(t.home,t.key);return await Hv(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},Wv=(e,t,n)=>{let r={...e,[t]:n},i=Ec.safeParse(r);if(!i.success)throw x(O(i.error));return i.data},Gv=(e,t)=>t.field===`url`?Uv(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(Wv(t.entry,t.field,t.value)),Kv=async(e,t)=>{let{field:n}=t;if(n===Lv)throw b(`use --package <name> <field> <value>`);if(!Bv(n))throw b(zv(n));let r=t.entry[n],i=await Gv(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},qv=(e,t)=>{let n=H(e.env),{field:r,opts:i,query:a,value:o}=t;return J(n,`home`,async()=>{let t=await W(n),s=Wh(t,a),c=Eg(t,s);if(i.packageName!==void 0)return Iv({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await Kv(e,{entry:c,field:r,home:n,key:s,value:o});return await Sl(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:jv(l.new),old:jv(l.old)}})},Jv=`settings`,Yv=[],Xv=()=>Object.keys(Cc.shape).toSorted().join(`, `),Zv=e=>`unknown setting '${e}' — valid settings: ${Xv()}`,Qv=e=>Object.hasOwn(Cc.shape,e),$v=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,ey=e=>{try{let t=Wh(e,Jv);return[$v(`ref '${t}'`)]}catch(e){if(e instanceof v&&e.code===`usage`)return[$v("one of several matching refs — see `refs list`")];if(e instanceof v&&e.code===`not_found`)return Yv;throw e}},ty=e=>({data:{field:e.key,key:Jv,new:jv(e.parsed[e.key]),old:jv(e.old)},warnings:ey(e.config)}),ny=(e,t)=>{let n=H(e.env);return J(n,`home`,async()=>{let e=await W(n);if(!Qv(t.key))throw b(Zv(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=Cc.safeParse(i);if(!a.success)throw x(O(a.error));return await Sl(n,{...e,settings:a.data}),ty({config:e,key:t.key,old:r,parsed:a.data})})},ry=[],iy=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},ay=async(e,t)=>{if(t.first===`settings`){if(t.opts.packageName!==void 0)throw b(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return ny(e,{key:t.second,value:t.value})}return{data:await qv(e,{field:t.second,opts:t.opts,query:t.first,value:t.value}),warnings:ry}},oy=e=>e==null?`(unset)`:String(e),sy=e=>[`${e.key}: ${e.field} '${oy(e.old)}' -> '${oy(e.new)}'`],cy=(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.`).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`).action((e,n,r,i,a)=>{let o=Z(a);return $(t,o,async()=>{let{data:a,warnings:s}=await ay(t,{first:e,opts:iy(i),second:n,value:r});Q(t,o,sy(a),a,s)})()})},ly=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,uy={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},dy=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})},fy=async e=>{let t=H(e.env);return await dy(t),{config:await J(t,`home`,async()=>{let e=await Ml(t,Bp);return await su(t),e}),home:t.root,skill_hint:ly}},py=[(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=Z(n);return $(t,r,async()=>{let e=await fy(t);Q(t,r,[`home: ${e.home}`,`config: ${uy[e.config]}`,``,ly],e)})()})},Av,cy,Gh,...H_],my=(e,t)=>{for(let n of py)n(e,t)},hy=[``,`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(`
342
- `),gy=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),_y=`--json`,vy=`--verbose`,yy=/\n$/u,by=/^error: /u,xy=e=>e.replace(by,``),Sy=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},Cy=e=>Sy(e,_y),wy=e=>Sy(e,vy),Ty=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,Ey=e=>{let t=new tm().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(Bp).option(_y,`emit machine-readable JSON on stdout instead of human-readable text`).option(vy,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(yy,``))},writeOut:t=>{e.out(t.replace(yy,``))}});return t.addHelpText(`after`,hy),my(t,e),t},Dy=()=>{process.exitCode=_.OK},Oy=(e,t,n)=>{let r={code:`usage`,message:Ty(xy(n.message),n.stack,t.verbose)};cm(e,t,r),process.exitCode=_.USAGE},ky=(e,t,n)=>{if(gy.has(n.code)){Dy();return}Oy(e,t,n)},Ay=(e,t,n)=>{let r=be(n,{verbose:t.verbose});cm(e,t,r),process.exitCode=r.exitCode},jy=async(e,t,n)=>{let r={json:Cy(n),verbose:wy(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof Wp){ky(e,r,t);return}Ay(e,r,t)}},My=(e,t)=>jy(e,Ey(e),t);import.meta.main&&await My(Up(),process.argv);export{Ey as buildProgram,Z as cliOptsOf,Q as emit,cm as emitError,sm as errorMessageOf,lm as progress,Up as realContext,my as registerCommands,My as run,jy as runProgram,om as warningsFor,$ as wrapAction};
339
+ - ${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=m.resolve(e,t);if(de.existsSync(r))return r;if(n.includes(m.extname(t)))return;let i=n.find(e=>de.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=de.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=m.resolve(m.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=m.basename(this._scriptPath,m.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(m.extname(i)),s;g.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=a_(g.execArgv).concat(t),s=ve.spawn(g.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=a_(g.execArgv).concat(t),s=ve.spawn(g.argv[0],t,{stdio:`inherit`})):s=ve.spawn(i,t,{stdio:`inherit`}),s.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{g.on(e,()=>{s.killed===!1&&s.exitCode===null&&s.kill(e)})});let c=this._exitCallback;s.on(`close`,e=>{e??=1,c?c(new qg(e,`commander.executeSubCommandAsync`,`(close)`)):g.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)g.exit(1);else{let e=new qg(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(`
340
+ `),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 g.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()}`,g.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new $g(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=>Xg(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=m.basename(e,m.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(g.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.
341
+ 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 a_(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 o_(){if(g.env.NO_COLOR||g.env.FORCE_COLOR===`0`||g.env.FORCE_COLOR===`false`)return!1;if(g.env.FORCE_COLOR||g.env.CLICOLOR_FORCE!==void 0)return!0}new i_;const s_=[],c_=e=>Array.isArray(e)?e:[e],l_=e=>e===void 0?s_:[e],u_=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??s_};e.out(JSON.stringify(t));return}for(let t of c_(n))e.out(t);for(let t of i??s_)e.errLine(`refs: warning: ${t}`)},d_=(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}`)},f_=(e,t)=>{e.errLine(`refs: ${t}`)},Q=(e,t,n)=>async()=>{try{await n()}catch(n){let r=we(n,{verbose:t.verbose});d_(e,t,r),process.exitCode=r.exitCode}},p_=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},m_=e=>e.filter(e=>e.path!==`.`),h_=e=>e.find(e=>e.path===`.`),g_=e=>{let t=h_(e);return t===void 0?{}:{[t.name]:p_(t)}},__=(e,t,n)=>{let r=m_(e),i=g_(e);if(r.length>0)return{...i,...Object.fromEntries(r.map(e=>[e.name,p_(e)]))};if(n!==void 0){let e={path:t??`.`},r=i[n];return{...i,[n]:r?.path===e.path?r:e}}return i},v_=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}},y_=(e,t)=>{let n=Object.entries(e);if(n.length!==0)return Object.fromEntries(n.map(([e,n])=>[e,v_(e===t.rootPackageName?S_(n,t.refDescription):n)]))},b_=e=>e.description===void 0||e.description===``,x_=(e,t)=>{let[n]=Object.keys(g_(e));if(n!==void 0)return t[n]?.path===`.`?n:void 0},S_=(e,t)=>b_(e)?{...e,description:t}:e,C_=(e,t)=>Object.entries(e).filter(([e,n])=>b_(n)&&e!==t).map(([e])=>e).toSorted(),w_=(e,t)=>{let n=C_(e,t);if(n.length!==0)throw b(`packages without a detected description: ${n.join(`, `)} — run the two-phase flow instead: refs add <source> --dry-run --json > proposal.json, fill in the package descriptions, then refs add --proposal proposal.json`)},T_=e=>{if(Object.keys(e).length!==0)return e},E_=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},D_=`ref.`,O_=`${D_}_`,k_=`${O_}_`,A_=e=>`${k_}${le(`sha256`).update(e,`utf8`).digest(`hex`)}`,j_=e=>{let t=e.includes(`_`)?`${O_}${e.replaceAll(`_`,`_u`).replaceAll(`/`,`_s`)}`:`${D_}${e.replaceAll(`/`,`_`)}`;return Buffer.byteLength(t,`utf8`)>212?A_(e):t},M_=e=>e.REFS_ALLOW_FILE_URLS===`1`,N_=(e,t)=>{let n=Nd(t,{allowFileUrls:M_(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},P_=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);f_(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},F_=(e,t)=>t.startsWith(`npm:`)?P_(e,t.slice(4)):Promise.resolve(N_(e,t)),I_=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Kh(`git_transport`,void 0,t);return{...e,cloneUrl:Wd(e.cloneUrl,n)}},L_=e=>`ref '${e}' already exists — use refs edit or refs remove`,R_=(e,t)=>{if(e.refs[t]!==void 0)throw Se(L_(t))},z_=async e=>{try{return await c(e,{withFileTypes:!0})}catch(e){if(R(e))return;throw e}},B_=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),V_=async(e,t)=>{let n=await z_(e);if(n===void 0)return{kind:`stop`};let r=B_(n);if(r.includes(t))return{kind:`continue`,nextDir:h(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},H_=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await V_(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):H_(a.nextDir,i,[...n,r])},U_=[],W_=async(e,t)=>{let n=await H_(e.sourcesDir,t.split(`/`),U_);if(n!==void 0)throw Se(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},G_=e=>`'${e.replaceAll(`'`,String.raw`'\''`)}'`,K_=e=>`rm -rf -- ${G_(e)}`,q_=e=>`rmdir -- ${G_(e)}`,J_=(e,t,n)=>`checkout at ${e} points at '${W(t)}' — expected '${W(n)}'; remove the checkout directory or run refs remove before retrying`,Y_=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,X_=(e,t)=>{try{return Nd(e,{allowFileUrls:t}).key}catch{return}},Z_=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=Y_(n),i=X_(t.expectedUrl,t.allowFileUrls),a=X_(r,t.allowFileUrls);if(i===void 0||a!==i)throw Se(J_(t.dest,r,t.expectedUrl))},Q_=e=>`checkout at ${e} exists but is not refs-managed — remove it (${K_(e)}) and retry`,$_=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(Q_(t.dest))},ev=async(e,t)=>{await a(re(t.dest),{recursive:!0}),f_(e,`cloning ${W(t.cloneUrl)} into ${t.dest}…`);let n=await Bu(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},tv=async(e,t)=>(xl(t.home,t.dest),H(t.dest)?(await Z_(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await $_(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):ev(e,t)),nv=(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`,rv=(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`,iv=async(e,t)=>{await Z_(e,t),await $_(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(nv(t.key,t.dest));let r=n.stdout.trim();if(!Wh.shape.head_sha.safeParse(r).success)throw b(rv(t.key,t.dest,r));return r},av=async(e,t,n)=>{let r=await Hu(e.runner,t),i=await Yu(e.runner,t),a=cd(i);f_(e,`detecting workspace packages…`);let o=await Hg(t),s=__(o,n.npmDirectory,n.npmPkgName),c=x_(o,s);return{defaultBranch:r,packages:s,...c===void 0?{}:{rootPackageName:c},tagFormatCandidate:a}},ov=(e,t)=>G(t.home,j_(t.resolved.key),async()=>{let n=await tv(e,{allowFileUrls:M_(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await av(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),sv=e=>{let t={default_branch:e.cloneResult.fields.defaultBranch,description:``,key:e.resolved.key,packages:e.cloneResult.fields.packages,tag_format_candidate:e.cloneResult.fields.tagFormatCandidate,url:e.resolved.cloneUrl},n={dest:e.dest,proposal:t};return e.cloneResult.fields.rootPackageName!==void 0&&(n.rootPackageName=e.cloneResult.fields.rootPackageName),e.cloneResult.effectiveMode!==void 0&&(n.effectiveCloneMode=e.cloneResult.effectiveMode),e.cloneResult.warning!==void 0&&(n.warning=e.cloneResult.warning),n},cv=async(e,t)=>{let n=z(e.env),r=await V(n),i=I_(await F_(e,t),r.settings);R_(r,i.key),await W_(n,i.key);let a=B(n,i.key),o=Kh(`clone_mode`,void 0,r.settings),s=await ov(e,{cloneMode:o,dest:a,home:n,resolved:i});return sv({cloneResult:s,dest:a,resolved:i})},lv=(e,t,n)=>G(e,`home`,async()=>{let r=await V(e);R_(r,t);let i=await Yh(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 Xh(e,i)}),uv=(e,t)=>{let n=Lc.safeParse(e);if(!n.success)throw b(D(n.error));let r=Gh.safeParse(t);if(!r.success)throw b(D(r.error));return{config:n.data,state:r.data}},dv=async(e,t)=>{let n=await V(e.home);R_(n,e.ref.key);let r=E_(e.ref);n.refs[e.ref.key]=r;let i=await Yh(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Kh(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...uv(n,i),entry:r}},fv=async(e,t)=>{let n=M_(e.env),r=await G(t.home,j_(t.ref.key),()=>(xl(t.home,t.dest),iv(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 dv(t,r);return await Xh(t.home,i),await kl(t.home,e),{entry:n,key:t.ref.key}})},pv=(e,t)=>t===`-`?e.readStdin():s(t,`utf8`),mv=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${u_(e)}`)}},hv=e=>typeof e==`object`&&!!e&&!Array.isArray(e),gv=e=>hv(e)&&`ok`in e&&!(`key`in e),_v=e=>{if(!gv(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(hv(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},vv=e=>e.code===`unrecognized_keys`,yv=e=>e.path.length===0,bv=(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}`},xv=e=>{let t=new Map;for(let n of e){let e=Rt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>bv(e,t))},Sv=e=>`✖ invalid proposal: ${e.message}`,Cv=e=>{let t=e.issues.filter(e=>vv(e)),n=e.issues.filter(e=>!vv(e)),r=n.filter(e=>yv(e));if(t.length===0&&r.length===0)return D(e);let i=n.filter(e=>!yv(e)),a=[...xv(t),...r.map(e=>Sv(e))];return i.length>0&&a.push(D({issues:i})),a.join(`
342
+ `)},wv=e=>{let t=Uh.safeParse(e);if(!t.success)throw b(Cv(t.error));return t.data},Tv=async(e,t)=>{let n=await pv(e,t);return wv(_v(mv(n)))},Ev=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],Dv=async(e,t)=>{let n=await cv(e,t),r=z(e.env);await lv(r,n.proposal.key,n.effectiveCloneMode);let i=l_(n.warning);return{data:n.proposal,human:Ev(n.proposal.key,n.dest),warnings:i}},Ov=e=>[`refs add: '${e}' added to config`],kv=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=T_(e.packages);return n!==void 0&&(t.packages=n),t},Av=async(e,t)=>{let n=await Tv(e,t),r=z(e.env),i=B(r,n.key);if(!H(i))throw v(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let a=kv(n),{entry:o,key:s}=await fv(e,{dest:i,home:r,ref:a});return{data:{entry:o,key:s},human:Ov(s),warnings:[]}},jv=(e,t)=>{w_(e.proposal.packages,e.rootPackageName);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,url:e.proposal.url};e.proposal.tag_format_candidate!==null&&(n.tag_format=e.proposal.tag_format_candidate);let r=y_(e.proposal.packages,{refDescription:t,...e.rootPackageName===void 0?{}:{rootPackageName:e.rootPackageName}});return r!==void 0&&(n.packages=r),n},Mv=async(e,t,n)=>{let r=await cv(e,t),i=z(e.env),a=jv(r,n),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await fv(e,o),l=l_(r.warning);return{data:{entry:s,key:c},human:Ov(c),warnings:l}},Nv=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`)},Pv=e=>{if(e===void 0||e===``)throw y(`refs add requires <source> (a git url or npm:<package>)`);return e},Fv=(e,t)=>(Nv(t),t.proposal===void 0?t.description===void 0?Dv(e,Pv(t.source)):Mv(e,Pv(t.source),t.description):Av(e,t.proposal)),Iv=(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},Lv=(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 Fv(t,Iv(e,n));Z(t,i,r.human,r.data,r.warnings)})()})},Rv=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`}},zv=/^v(?<major>\d+)\.(?<minor>\d+)/u,Bv=e=>{let t=zv.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},Vv=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,Hv=e=>{let{nodeVersion:t}=e;return Vv(Bv(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},Uv=()=>Lc.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),Wv=async e=>{try{return{config:await V(e)}}catch(e){return{config:Uv(),errorMessage:u_(e)}}},Gv=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},Kv={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)`},qv=(e,t,n)=>{if(cg(e,t)){let r=n?` (npm was unreachable just now; this was its last answer)`:``;return{detail:`${lg(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`}},Jv=async(e,t)=>{let n=pg({env:e.env,updates:t.updates});if(n!==`on`)return{detail:Kv[n],name:`cli-update`,status:`ok`};let{latest:r,stale:i}=await sg({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`}:qv(e.cliVersion,r,i)},Yv=(e,t)=>Object.keys(t.refs).map(e=>Sc.parse(e)).map(t=>({dest:B(e,t),key:t})).filter(e=>H(e.dest)),Xv=[`pre-commit`,`pre-push`],Zv=async(t,r)=>{try{return await e(h(t.hooksDir,r),n.X_OK),!0}catch{return!1}},Qv=async e=>{let t=await Promise.all(Xv.map(t=>Zv(e,t)));return Xv.filter((e,n)=>!t[n])},$v=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},ey=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:`${Xv.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},ty=async(e,t,n)=>{let r=Yv(t,n),[i,a]=await Promise.all([Qv(t),Promise.all(r.map(n=>$v(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return ey({badKeys:o,checkoutCount:r.length,missingHooks:i})},ny=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}},ry=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`}},iy=async(e,t,n)=>{let r=Yv(t,n),i=await Promise.all(r.map(t=>ny(e,t)));return ry(i)},ay=async e=>{try{return await Yh(e)}catch{return Gh.parse({})}},oy=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}},sy=async(e,t)=>{if(H(e))return[[...t]];let n=await oy(e);return(await Promise.all(n.map(n=>sy(h(e,n),[...t,n])))).flat()},cy=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},ly=(e,t,n)=>cy(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: ${K_(e.dest)}`,uy=(e,t)=>({dest:h(e.sourcesDir,...t),key:t.join(`/`)}),dy=async(e,t,n)=>{let r=(await sy(e.sourcesDir,[])).map(t=>uy(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=>ly(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},fy=e=>e!==`unmaterialized`&&e!==`verified`,py=new Set([`ambiguous`,`missing`,`relocated`,`unregistered`]),my=e=>{let[t]=e;return t===void 0?{status:`ok`}:{packages:[...e],status:e.some(e=>py.has(e.status))?`drift`:`unknown`}},hy=`(unknown)`,gy=e=>fc(e.name)&&Oc.safeParse(e.path).success,_y=(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`:gy(e)?`${n}. To register it: refs edit ${G_(t)} --package ${G_(e.name)} --create --path ${G_(e.path)} --description "<what it is>"`:`${n}. Its name or path is one the configuration cannot hold, so there is no command for it — report it and leave it unregistered`},vy=e=>{let t=`configured: ${e.configured_path??hy}`;if(e.status===`relocated`)return`${e.name}: moved to ${e.path??hy} — update the entry's path (${t})`;if(e.status===`missing`)return`${e.name}: gone from this repo's workspaces — remove the entry, or repoint it if it moved out of them (${t})`;if(e.status===`ambiguous`){let n=(e.candidates??[]).join(`, `);return`${e.name}: declared at several paths (${n}) — point the entry at one (${t})`}return`${e.name}: could not be checked — ${e.reason??`(no reason given)`} (${t})`},yy=(e,t)=>e.status===`unregistered`?_y(e,t):vy(e),by=(e,t)=>e.reason===void 0?(e.packages??[]).map(e=>yy(e,t)):[`could not be checked — ${e.reason}`],xy=e=>{let t;return()=>(t??=Vg(e),t)},Sy=async(e,t,n)=>{let r=await Dg(e);if(r===void 0||t.some(e=>e.packageName===r.name))return[];let i=await n();if(!sh(i))return[];let a=_h(i.packages,r.name);return a.kind===`ambiguous`?[{candidates:a.paths,name:r.name,status:`unregistered`}]:a.kind===`found`?[{name:r.name,path:a.path,status:`unregistered`}]:[]},Cy=e=>{let t=new Map;for(let n of e)t.set(n.name,[...t.get(n.name)??[],n.path]);return t},wy=(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])},Ty=(e,t)=>t.length===1&&t[0]!==void 0?{name:e,path:t[0],status:`unregistered`}:{candidates:[...t],name:e,status:`unregistered`},Ey=async(e,t,n)=>{if(t.kind===`arrivals`&&t.changedDirs.length===0)return[];let r=await n();if(!sh(r))return[];let i=new Set(e.map(e=>e.packageName)),a=r.packages.filter(e=>e.path!==`.`),o=t.kind===`all`?void 0:wy(t,a);return[...Cy(a)].filter(([e])=>!i.has(e)).filter(([e])=>o===void 0||!o.has(e)).map(([e,t])=>Ty(e,t)).toSorted((e,t)=>e.name.localeCompare(t.name))},Dy=(e,t)=>({path:e.configuredPath,reason:t,status:`unverifiable`}),Oy=(e,t)=>ch(t)?{configuredPath:e.configuredPath,path:null,status:`missing`}:Dy(e,`this repo declares no workspaces, so there was nowhere to search`),ky=(e,t)=>t===e.configuredPath,Ay=e=>e.packages.filter(e=>e.path!==`.`),jy=(e,t)=>{let n=_h(Ay(t),e.packageName);return n.kind===`ambiguous`?{candidates:n.paths,configuredPath:e.configuredPath,path:null,status:`ambiguous`}:sh(t)?n.kind===`absent`?Oy(e,t):ky(e,n.path)?Dy(e,`the checkout changed while it was being inspected`):{configuredPath:e.configuredPath,path:n.path,status:`relocated`}:Dy(e,n.kind===`found`?`workspace detection was incomplete, so the new location is not confirmed unique`:`workspace detection was incomplete`)},My=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}]})},Ny=async(e,t)=>{let n=await mh(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`}},Py=e=>e.flatMap(e=>e.settled===void 0?[]:[{outcome:e.settled,query:e.query}]),Fy=async(e,t,n)=>{let r=await Promise.all(t.map(async t=>({query:t,settled:await Ny(e,t)})));if(r.every(e=>e.settled!==void 0))return Py(r);let i=await n();return r.map(e=>({outcome:e.settled??jy(e.query,i),query:e.query}))},Iy=e=>{let{outcome:t,query:n}=e;return fy(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}]:[]},Ly=(e,t)=>{let n=new Set(e.map(e=>e.name));return[...e,...t.filter(e=>!n.has(e.name))]},Ry=async(e,t,n)=>{let r=My(t),[i]=r;if(i===void 0)return{status:`ok`};let a=xy(e);try{let[t,i,o]=await Promise.all([Fy(e,r,a),Sy(e,r,a),Ey(r,n,a)]);return my([...t.flatMap(e=>Iy(e)),...Ly(i,o)])}catch(e){return{reason:u_(e),status:`unknown`}}},zy=async(e,t,n)=>{try{return await G(e,j_(n.key),()=>Ry(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}},By=`config-drift`,Vy=(e,t)=>{let[n]=e;return n===void 0?{detail:`every configured package path resolves in ${t} checkout(s)`,name:By,status:`ok`}:{detail:e.join(`; `),name:By,status:`warn`}},Hy=async(e,t,n)=>{let[r,...i]=n;if(r===void 0)return[];let a=await zy(e,t,r),o=await Hy(e,t,i);return[...by(a,r.key).map(e=>`${r.key}: ${e}`),...o]},Uy=async(e,t)=>{let n=Yv(e,t);return Vy(await Hy(e,t,n),n.length)},Wy=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},Gy=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`:`, ${Bf(t)} into a ${Bf(n)} window`},Ky=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`,qy=(e,t)=>{let n=h(e.locksDir,wf,t.name),r=t.diagnosis.ageMs===void 0?``:` for ${Bf(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, ${Jy}: ${q_(n)}`},Jy=`stop every refs process using this home — including suspended ones — and then run`,Yy=(e,t)=>{let{diagnosis:n}=t;if(vf(n))return`, reclaimable now`;if(!n.stale&&t.isDirectory)return``;let r=h(e.locksDir,t.name);return`, not automatically reclaimable — if it is genuinely abandoned, ${Jy}: ${K_(r)}`},Xy=(e,t)=>{let{diagnosis:n}=t,r=t.isDirectory?``:`not a directory, `,i=Yy(e,t);return`${t.name}: ${r}${Ky(n)}${Gy(n)}${i}`},Zy=async e=>{let t=await zf(e),[n]=t;return n===void 0?{detail:`no locks held`,name:`locks`,status:`ok`}:{detail:t.map(t=>t.kind===`claim`?qy(e,t):Xy(e,t)).join(`; `),name:`locks`,status:t.every(e=>Wy(e))?`ok`:`warn`}},Qy=[`.agents`,`skills`,`refs`,`SKILL.md`],$y=[`skills`,`refs`,`SKILL.md`],eb=[`.claude`,`skills`,`refs`,`SKILL.md`],tb=`npx skills add kaisers-io/refs`,nb=`npm i -g @kaisers-io/refs@latest`,rb=(e,t)=>e===void 0?void 0:{display:t,path:e},ib=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}:rb(r===void 0?void 0:h(r,t),`~/${t}`)},ab=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:rb(t,`~/.agents`),segments:Qy},{label:`Claude Code`,root:ib({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:$y},{label:`Codex`,root:ib({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:$y},{label:`project ./.agents`,root:rb(e.cwd,`./.agents`),segments:Qy},{label:`project ./.claude`,root:rb(e.cwd,`./.claude`),segments:eb}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:h(t.path,...n)}])},ob=async(e,t)=>{try{let n=await l(e);return{label:t,realPath:n,source:await s(n,`utf8`)}}catch{return}},sb=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},cb=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,lb=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,ub=e=>{let t=cb.exec(e)?.groups?.body;if(t!==void 0)return lb.exec(t)?.groups?.version},db=(e,t)=>{if(e===t)return`match`;let n=eg(e,t);return n===void 0?`unknown`:n===0?`match`:n>0?`cli-older`:`skill-older`},fb={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${nb}`,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: ${tb}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${nb} and ${tb}`},pb=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: ${tb}`,name:`skill`,status:`warn`};let i=db(r,t);return{detail:`${n}: ${fb[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},mb=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: ${tb}`,name:`skill`,status:`warn`}),hb=async e=>{let t=ab(e),n=await Promise.all(t.map(e=>ob(e.path,e.label))),r=sb(n.filter(e=>e!==void 0)).map(t=>pb({cliVersion:e.cliVersion,label:t.label,skillVersion:ub(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??mb(t)},gb=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,_b=e=>e===``?{}:{user:e},vb=e=>e===``?{}:{port:e},yb=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,..._b(t.username),...vb(t.port)}:void 0}catch{return}},bb=e=>{let t=gb.exec(e),n=t?.groups?.host;return n===void 0?yb(e):{host:n,user:t?.groups?.user??`git`}},xb=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,Sb=e=>e.user===void 0?xb(e):`${e.user}@${xb(e)}`,Cb=e=>{let t=Object.values(e.refs).map(e=>bb(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(Sb(e),e);return[...n.values()].toSorted((e,t)=>Sb(e).localeCompare(Sb(t)))},wb=/Permission denied/u,Tb=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],Eb=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,Db=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=Eb(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},Ob=async(e,t,n)=>{let r=Sb(t),i=await e.runner.run(`ssh`,Db(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:wb.test(i.stderr)?{host:r,outcome:`denied`}:Tb.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},kb=(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`}},Ab=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`}},jb=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`}},Mb=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),Nb=(e,t)=>kb(e,t)??Ab(e)??jb(e)??Mb(e),Pb=async(e,t,n)=>{let r=Cb(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>Ob(e,t,i)));return Nb(a,i)},Fb=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${u_(t)}`,name:e.name,status:`fail`}}},Ib=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await Fb(t),i=await Ib(n);return r===void 0?i:[r,...i]},Lb=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Rv(n)},{name:`node`,run:()=>Promise.resolve(Hv(n))},{name:`config`,run:()=>Promise.resolve(Gv(t.errorMessage))},{name:`hooks-guard`,run:()=>ty(n,r,t.config)},{name:`dirty-checkouts`,run:()=>iy(n,r,t.config)},{name:`config-drift`,run:()=>Uy(r,t.config)},{name:`orphans`,run:()=>dy(r,t.config,i)},{name:`locks`,run:()=>Zy(r)},{name:`skill`,run:()=>hb(n)},{name:`cli-update`,run:()=>Jv(n,t.config)},{name:`ssh-auth`,run:()=>Pb(n,t.config)}]},Rb=async e=>{let t=z(e.env),n=await Wv(t),r=await ay(t);return Ib(Lb({configLoad:n,ctx:e,home:t,state:r}))},zb={fail:`FAIL`,ok:`OK`,warn:`WARN`},Bb=e=>e.map(e=>`[${zb[e.status]}] ${e.name}: ${e.detail}`),Vb=e=>e.some(e=>e.status===`fail`),Hb=(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 Rb(t);Z(t,r,Bb(e),{checks:e}),Vb(e)&&(process.exitCode=xe.UNEXPECTED)})()})},Ub=(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},Wb=(e,t)=>{if(!H(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},Gb=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},Kb=`never`,qb=(e,t,n)=>e===void 0||n-Date.parse(e)>t,Jb=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,Yb=(e,t)=>{if(e===void 0)return Kb;let n=t-Date.parse(e);if(Number.isNaN(n))return Kb;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return Jb(i,`minute`);let a=Math.floor(i/60);if(a<24)return Jb(a,`hour`);let o=Math.floor(a/24);return o<365?Jb(o,`day`):Jb(Math.floor(o/365),`year`)},Xb=e=>{let t=Yb(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==Kb&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},Zb=(e,t,n)=>{let r=e.state.refs[t],i=wc(Kh(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:Kh(`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,Sc.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:qb(r?.last_fetched_at,i,e.now)}},Qb=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])=>Zb(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},$b=async(e,t,n)=>{let r=z(e.env),i=await V(r),a=await Yh(r);return Qb({config:i,home:r,includePackages:t,now:n,state:a})},ex=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...Xb({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],tx=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...ex(n,t)),e),[]),nx=e=>e.split(`/`),rx=(e,t)=>{let n=nx(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},ix=(e,t)=>{if(Object.hasOwn(e.refs,t))return Sc.parse(t);let n=nx(t),r=Object.keys(e.refs).filter(e=>rx(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 Sc.parse(i)},ax=(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 $b(t,e.packages===!0,n);Z(t,r,tx(i,n),i)})()})},ox=e=>e===void 0?null:e,sx=()=>Object.keys(Mc.shape).toSorted().join(`, `),cx=e=>`unknown package field '${e}' — valid fields: ${sx()}`,lx=e=>Object.hasOwn(Mc.shape,e),ux=(e,t,n)=>{if(!lx(t))throw y(cx(t));let r=e[t],i=Mc.safeParse({...e,[t]:n});if(!i.success)throw b(D(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},dx=async e=>{let t=Gb(e.entry,e.key,e.packageName),n=ux(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await kl(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:ox(n.newValue),old:ox(n.oldValue)}},fx=(e,t)=>`package '${e}' is already registered on ref '${t}' — edit its fields instead`,px=(e,t)=>{let n=z(e.env);return G(n,`home`,async()=>{let e=await V(n),r=ix(e,t.query),i=Ub(e,r);if(Object.hasOwn(i.packages??{},t.packageName))throw b(fx(t.packageName,r));let a=Nc.safeParse({...i,packages:{...i.packages,[t.packageName]:{description:t.description,path:t.path}}});if(!a.success)throw b(D(a.error));return await kl(n,{...e,refs:{...e.refs,[r]:a.data}}),{created:!0,field:`packages`,key:r,new:{description:t.description,name:t.packageName,path:t.path},old:null}})},mx=`packages`,hx=()=>Object.keys(Nc.shape).filter(e=>e!==mx).toSorted().join(`, `),gx=e=>`unknown ref field '${e}' — valid fields: ${hx()}`,_x=e=>Object.hasOwn(Nc.shape,e),vx=(e,t,n)=>`failed to rewrite git remote at ${e} to '${W(t)}': ${n.trim()}`,yx=async(e,t)=>{if(xl(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 b(vx(t.dest,t.cloneUrl,n.stderr))},bx=async(e,t)=>{let n=Nd(t.value,{allowFileUrls:M_(e.env)});if(n.key!==t.key)throw b(`new url derives a different key — remove and re-add instead`);let r=B(t.home,t.key);return await yx(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},xx=(e,t,n)=>{let r={...e,[t]:n},i=Nc.safeParse(r);if(!i.success)throw b(D(i.error));return i.data},Sx=(e,t)=>t.field===`url`?bx(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(xx(t.entry,t.field,t.value)),Cx=async(e,t)=>{let{field:n}=t;if(n===mx)throw y(`use --package <name> <field> <value>`);if(!_x(n))throw y(gx(n));let r=t.entry[n],i=await Sx(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},wx=(e,t)=>{let n=z(e.env),{field:r,opts:i,query:a,value:o}=t;return G(n,`home`,async()=>{let t=await V(n),s=ix(t,a),c=Ub(t,s);if(i.packageName!==void 0)return dx({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await Cx(e,{entry:c,field:r,home:n,key:s,value:o});return await kl(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:ox(l.new),old:ox(l.old)}})},Tx=`settings`,Ex=[],Dx=()=>Object.keys(Ac.shape).toSorted().join(`, `),Ox=e=>`unknown setting '${e}' — valid settings: ${Dx()}`,kx=e=>Object.hasOwn(Ac.shape,e),Ax=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,jx=e=>{try{let t=ix(e,Tx);return[Ax(`ref '${t}'`)]}catch(e){if(e instanceof _&&e.code===`usage`)return[Ax("one of several matching refs — see `refs list`")];if(e instanceof _&&e.code===`not_found`)return Ex;throw e}},Mx=e=>({data:{field:e.key,key:Tx,new:ox(e.parsed[e.key]),old:ox(e.old)},warnings:jx(e.config)}),Nx=(e,t)=>{let n=z(e.env);return G(n,`home`,async()=>{let e=await V(n);if(!kx(t.key))throw y(Ox(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=Ac.safeParse(i);if(!a.success)throw b(D(a.error));return await kl(n,{...e,settings:a.data}),Mx({config:e,key:t.key,old:r,parsed:a.data})})},Px=[],Fx=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Ix=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}},Lx=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}},Rx=async(e,t)=>{let{description:n,packageName:r,path:i}=Ix(t);return{data:await px(e,{description:n,packageName:r,path:i,query:t.first}),warnings:Px}},zx=(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 Nx(e,n)},Bx=async(e,t)=>{if(t.create.create===!0)return Rx(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}=Lx(t);return t.first===`settings`?zx(e,t,{key:n,value:r}):{data:await wx(e,{field:n,opts:t.opts,query:t.first,value:r}),warnings:Px}},Vx=e=>e==null?`(unset)`:String(e),Hx=e=>{if(e.created===!0){let t=e.new;return[`${e.key}: registered '${t.name}' at ${t.path}`]}return[`${e.key}: ${e.field} '${Vx(e.old)}' -> '${Vx(e.new)}'`]},Ux=(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.`).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(`--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 Bx(t,{create:i,first:e,opts:Fx(i),second:n,value:r});Z(t,o,Hx(a),a,s)})()})},Wx=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,Gx={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},Kx=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})},qx=async e=>{let t=z(e.env);return await Kx(t),{config:await G(t,`home`,async()=>{let e=await zl(t,Ug);return await Qu(t),e}),home:t.root,skill_hint:Wx}},Jx=(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 qx(t);Z(t,r,[`home: ${e.home}`,`config: ${Gx[e.config]}`,``,Wx],e)})()})},Yx=async e=>{let t=z(e.env),n=await G(t,`home`,()=>zl(t,Ug));return n===`migrated`?{backup:_l(t),result:n}:{backup:null,result:n}},Xx=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${ne(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,Zx=(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 Yx(t);Z(t,r,Xx(e),e)})()})},Qx=async e=>{try{return await i(e),!0}catch(e){if(R(e))return!1;throw e}},$x=async e=>{try{return await c(e)}catch(e){if(R(e))return;throw e}},eS=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(R(e))return;throw e}},tS=async e=>{let t=await $x(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},nS=async e=>{let t=await eS(e);return t===void 0?!0:t?tS(e):!1},rS=async(e,t)=>{t!==e.sourcesDir&&await nS(t)&&await rS(e,re(t))},iS=async(e,t)=>await Qx(t)?(xl(e,t),await d(t,{force:!0,recursive:!0}),await rS(e,re(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},aS=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),oS=async(e,t)=>{let n=await V(e),r={...n,refs:aS(n.refs,t)};await kl(e,r);let i=await Yh(e),a={...i,refs:aS(i.refs,t)};await Xh(e,a)},sS=async(e,t)=>{let n=z(e.env),r=await V(n),i=ix(r,t),a=B(n,i),{removedCheckout:o,warning:s}=await G(n,j_(i),()=>iS(n,a));return await G(n,`home`,()=>oS(n,i)),{data:{key:i,removed_checkout:o},warnings:l_(s)}},cS=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],lS=(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 sS(t,e);Z(t,i,cS(n),n,r)})()})},uS=async e=>{let t=await mh(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`}:dS(e)},dS=async e=>jy(e,await Vg(e.checkoutDir)),fS=async e=>{try{return await G(e.home,j_(e.key),()=>uS(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}},pS=async e=>{if(!H(e.checkoutDir))return{path:e.configuredPath,status:`unmaterialized`};let t=await mh(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?.(),fS(e))},mS=(e,t)=>({local_path:null,name:e,path:null,reason:t,status:`unverifiable`}),hS=async e=>{if(!e.checkoutManaged)return mS(e.packageName,e.checkoutReason);let t=await pS(e);return{...t.candidates===void 0?{}:{candidates:t.candidates},...t.configuredPath===void 0?{}:{configured_path:t.configuredPath},local_path:t.path===null?null:h(e.checkoutDir,t.path),name:e.packageName,path:t.path,...t.reason===void 0?{}:{reason:t.reason},status:t.status}},gS=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}`]],_S=`node_modules`,vS=[`.pnp.cjs`,`.pnp.js`],yS=new Set([``,`.`,`..`]),bS=e=>!ie(e)&&!e.includes(`\\`)&&e.split(`/`).every(e=>!yS.has(e)),xS=function*(e){let t=se(e);for(;;){ne(t)!==_S&&(yield h(t,_S));let e=re(t);if(e===t)return;t=e}},SS=async e=>{if(await TS(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`}}},CS=new Set([`ENOENT`,`ENOTDIR`]),wS=async e=>{try{return(await c(e)).length===0}catch{return!1}},TS=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&&CS.has(t)?`absent`:`unreadable`}},ES=async e=>{for(let t of xS(e)){let e=re(t);if((await Promise.all(vS.map(t=>TS(h(e,t))))).includes(`present`))return!0}return!1},DS=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}`)}},OS=async e=>{let t=await TS(e);if(t===`unreadable`)return{reason:`slot_unreadable`,status:`unverifiable`};if(t===`absent`)return;let n=await SS(h(e,`package.json`));return n===void 0?await wS(e)?void 0:{reason:`installed_without_manifest`,status:`unverifiable`}:n},kS=async(e,t)=>{if(!bS(t))return{reason:`unsupported_package_name`,status:`unverifiable`};for(let n of xS(e)){let e=await OS(h(n,...t.split(`/`)));if(e!==void 0)return e}return await ES(e)?{reason:`yarn_pnp`,status:`unsupported_layout`}:{status:`not_materialized`}},AS={'"':`"`,"\\":`\\`,b:`\b`,n:`
343
+ `,t:` `},jS={'"':`"`,"\\":`\\`},MS=new Set([` `,` `]),$=Symbol(`malformed git config`),NS=e=>e!==void 0&&!e.quoted&&MS.has(e.char),PS=e=>{let t=0,n=e.length;for(;t<n&&NS(e[t]);)t+=1;for(;n>t&&NS(e[n-1]);)--n;return e.slice(t,n).map(e=>e.char).join(``)},FS=e=>{let t=[],n=!1;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`\\`){r+=1;let n=AS[e[r]??``];if(n===void 0)return $;t.push({char:n,quoted:!0})}else if(i===`"`)n=!n;else if(!n&&(i===`#`||i===`;`))return PS(t);else t.push({char:i??``,quoted:n})}return n?$:PS(t)},IS=e=>{let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`\\`){n+=1;let r=jS[e[n]??``];if(r===void 0)return $;t+=r}else t+=r??``}return t},LS=/^[ \t]+|[ \t]+$/gu,RS=e=>e.replace(LS,``),zS=/^\[[ \t]*(?<section>[A-Za-z0-9.-]+)[ \t]*(?:"(?<subsection>(?:[^"\\]|\\.)*)")?[ \t]*\]/u,BS=/^(?<name>[A-Za-z][A-Za-z0-9-]*)[ \t]*(?:=[ \t]*(?<value>.*))?$/u,VS=function*(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`
344
+ `)yield t,t=``,n=!1,r=!1;else if(a!==`\r`||e[i+1]!==`
345
+ `){if(r)t+=a;else if(a===`\\`){let n=e[i+1];n===`
346
+ `||n===`\r`&&e[i+2]===`
347
+ `?i+=n===`\r`?2:1:(t+=a+(n??``),i+=1)}else a===`"`?n=!n:!n&&(a===`#`||a===`;`)&&(r=!0),t+=a}}t!==``&&(yield t)},HS=(e,t)=>e.subsection===void 0?`${e.name}.${t.toLowerCase()}`:`${e.name}.${e.subsection}.${t.toLowerCase()}`,US=(e,t)=>{let n=e.toLowerCase();if(t===void 0)return{name:n};let r=IS(t);return r===$?$:{name:n,subsection:r}},WS=e=>{let t=zS.exec(e),n=t?.groups?.section;if(n===void 0)return;let r=RS(e.slice(t?.[0].length??0)),i=US(n,t?.groups?.subsection);return i===$?$:{rest:r,section:i}},GS=e=>e===``||e.startsWith(`#`)||e.startsWith(`;`),KS=e=>{let t=BS.exec(e),n=t?.groups?.name;if(n===void 0)return $;let r=FS(t?.groups?.value??``);return r===$?$:{name:n,value:r}},qS=(e,t)=>{let n=KS(t.line);if(n===$)return`malformed`;let r=HS(t.section,n.name);return t.wanted.includes(r)&&e.set(r,[...e.get(r)??[],n.value]),`ok`},JS=(e,t,n)=>t.rest===``||GS(t.rest)?t.section:qS(e,{line:t.rest,section:t.section,wanted:n})===`malformed`?$:t.section,YS=(e,t)=>{let n=WS(t.line);return n===$?$:n===void 0?t.section===XS||qS(e,t)===`malformed`?$:t.section:JS(e,n,t.wanted)},XS={name:``},ZS=(e,t)=>{let n=new Map,r=XS;for(let i of VS(e)){let e=RS(i),a=GS(e)?r:YS(n,{line:e,section:r,wanted:t});if(a===$)return;r=a}return n},QS=`core.hookspath`,$S=`remote.origin.url`,eC=[QS,$S],tC={status:`managed`},nC={status:`missing`},rC=e=>({reason:e,status:`unmanaged`}),iC=e=>({reason:e,status:`unverifiable`}),aC=new Set([`ENOENT`,`ENOTDIR`]),oC=e=>typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0,sC=async e=>{try{return await i(e),`present`}catch(e){let t=oC(e);return t!==void 0&&aC.has(t)?`absent`:`unreadable`}},cC=async e=>{try{let t=await i(h(e,`.git`));return t.isSymbolicLink()?rC(`git_is_symlink`):t.isDirectory()?void 0:rC(`git_is_file`)}catch(e){let t=oC(e);return t!==void 0&&aC.has(t)?rC(`no_git`):iC(`git_unreadable`)}},lC=(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},uC=(e,t,n)=>{try{return Nd(e,{allowFileUrls:n}).key===Nd(t,{allowFileUrls:n}).key}catch{return!1}},dC=e=>(e.get(QS)?.length??0)>1||(e.get($S)?.length??0)>1,fC=(e,t)=>{let n=ZS(e,eC);return n===void 0?iC(`config_malformed`):dC(n)?iC(`duplicate_config_values`):pC(n,t)},pC=(e,t)=>{if(lC(e,QS)!==t.hooksDir)return rC(`no_refs_marker`);let n=lC(e,$S);return n===void 0?rC(`no_origin`):uC(n,t.expectedUrl,t.allowFileUrls)?tC:rC(`origin_mismatch`)},mC={missing:nC,outside:rC(`outside_sources`),unreadable:iC(`path_unreadable`)},hC=async e=>{let t=await Gl(e.sourcesDir,e.dest);if(t.kind!==`inside`)return t.kind===`unreadable`?await sC(e.sourcesDir)===`absent`?nC:mC.unreadable:mC[t.kind]},gC=async e=>{let t=await hC(e);if(t!==void 0)return t;let n=await cC(e.dest);if(n!==void 0)return n;try{return fC(await s(h(e.dest,`.git`,`config`),`utf8`),e)}catch{return iC(`config_unreadable`)}},_C=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`,vC=e=>`ref '${e}' is not in the active refs configuration — to track it: refs add <url>`,yC=e=>`--ref '${e}' matched no configured ref — pass a full ref key or a unique suffix of one. Run: refs list --json`,bC=/^[a-z][a-z0-9+.-]*:\/\//iu,xC=/^git@[^:/\s]+:[^\s]+$/u,SC=e=>bC.test(e)||xC.test(e),CC=(e,t)=>{try{return Nd(e,t)}catch{if(SC(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}},wC=(e,t,n)=>{let r=CC(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v(vC(r.key),`ref_not_registered`)}},TC=(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:Sc.parse(r)})}return n},EC=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — pick one with: refs resolve ${e} --ref <ref>`,DC=(e,t)=>{let n=TC(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y(EC(t,n.map(e=>e.key)));return r}},OC=function*(e){let t=e.split(`/`);for(let e=t.length-1;e>=1;--e)yield t.slice(0,e).join(`/`)},kC=(e,t)=>{for(let n of OC(t)){let t=DC(e,n);if(t!==void 0)return{...t,name:n}}},AC=(e,t,n)=>{try{return ix(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v(n,`unmatched_query`):e}},jC=(e,t)=>{let n=e[t];if(n!==void 0)return{entry:n,name:t};for(let n of OC(t)){let t=e[n];if(t!==void 0)return{entry:t,name:n}}},MC=(e,t,n)=>{let r=AC(e,n,yC(n)),i=jC(e.refs[r]?.packages??{},t);if(i===void 0)throw v(SC(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}}},NC=(e,t,n)=>{let r=wC(e,t,n);if(r!==void 0)return r;let i=DC(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=kC(e,t);return a===void 0?{key:AC(e,t,_C(t))}:{key:a.key,packageMatch:a}},PC=(e,t,n)=>n.ref===void 0?NC(e,t,n):MC(e,t,n.ref),FC=(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},IC=async(e,t,n)=>{let r=await V(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await kl(e,r))},LC=(e,t,n)=>G(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await IC(e,t,n.branchRenamedTo);let r=await Yh(e);r.refs[t]=FC(r.refs[t],n),await Xh(e,r)}),RC=async(e,t,n)=>{try{await G(e,`home`,async()=>{let r=await Yh(e);r.refs[t]={...r.refs[t],last_error:n},await Xh(e,r)})}catch{}},zC=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()}}},BC=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},VC=(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`,HC=(e,t,n)=>{if(!Wh.shape.head_sha.safeParse(n).success)throw b(VC(e,t,n));return n},UC=(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},WC=async(e,t,n)=>{await a(re(n),{recursive:!0});let r=Kh(`clone_mode`,t.ref,t.settings),i=await Bu(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Hu(e.runner,n),s=await iv(e.runner,{allowFileUrls:M_(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return UC(t,i,{actualBranch:o,headSha:s})},GC=async(e,t,n)=>{await $_(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await Z_(e.runner,{allowFileUrls:M_(e.env),dest:n,expectedUrl:t.ref.url});let r=await Ju(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:HC(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},KC=(e,t,n)=>(xl(t.home,n),H(n)?GC(e,t,n):WC(e,t,n)),qC={changedDirs:[],kind:`arrivals`,namesBefore:[]},JC=async(e,t,n)=>{if(n.previousSha===void 0)return qC;let r=await ku(e.runner,{dir:t,from:n.previousSha,to:n.headSha});return r===void 0?qC:{...r,kind:`arrivals`}},YC=(e,t)=>G(t.home,j_(t.key),async()=>{let n=B(t.home,t.key),r=await KC(e,t,n),i=await JC(e,n,r);return{...r,structure:await Ry(n,t.ref.packages,i)}}),XC=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(` | `)},ZC=(e,t)=>{let n={key:e,status:t.status},r=XC(t);return r!==void 0&&(n.warning=r),t.structure!==void 0&&(n.structure=t.structure),n},QC=async(e,t)=>{try{let n=await YC(e,t);return await LC(t.home,t.key,n),n}catch(e){throw await RC(t.home,t.key,u_(e)),e}},$C=async(e,t)=>{try{return ZC(t.key,await QC(e,t))}catch(e){return{error:u_(e),key:t.key,status:`failed`}}},ew=(e,t)=>e.status===`rejected`?{error:u_(e.reason),key:t,status:`failed`}:e.value,tw=async(e,t)=>{let n=zC(4);return(await Promise.allSettled(t.map(t=>BC(n,()=>$C(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return ew(e,r.key)})},nw=async e=>{let{packageMatch:t}=e.match;return t===void 0?null:await hS({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})},rw=(e,t,n)=>PC(t,n.query,{allowFileUrls:M_(e.env),...n.ref===void 0?{}:{ref:n.ref}}),iw=async(e,t)=>{let n=z(e.env),r=await V(n);return{config:r,home:n,match:rw(e,r,t),state:await Yh(n)}},aw=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 kS(t,n.name)},ow=(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`)},sw=async(e,t)=>(await QC(e,{home:t.home,key:t.match.key,ref:Ub(t.config,t.match.key),settings:t.config.settings})).status,cw=async(e,t)=>{t.project!==void 0&&await DS(t.project);let n=await iw(e,t),r=await uw(e,n,t);return t.syncIfStale!==!0||!(r.stale||r.missing)?r:(ow(r.checkout,r.key),await lw(e,{key:r.key,opts:t,target:n}))},lw=async(e,t)=>{let{key:n,opts:r}=t,i=await sw(e,t.target),a=await iw(e,r);if(a.match.key!==n)throw Se(`configuration changed while resolving '${r.query}' — retry`);return{...await uw(e,a,r),sync:{status:i}}},uw=async(e,t,n)=>{let{config:r,home:i,match:a,state:o}=t,{now:s}=n,c=Ub(r,a.key),l=B(i,a.key),u=wc(Kh(`sync_ttl`,c,r.settings)),d=o.refs[a.key]?.last_fetched_at,f=await gC({allowFileUrls:M_(e.env),dest:l,expectedUrl:c.url,hooksDir:i.hooksDir,sourcesDir:i.sourcesDir}),p=await aw(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 nw({checkout:f,dest:l,home:i,match:a}),stale:qb(d,u,s)}},dw=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...Xb({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(...gS(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},fw=(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}:{}}),pw=(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 cw(t,fw(e,r,n));Z(t,i,dw(a,r),a)})()})},mw={},hw=async(e,t)=>{if(!H(t))return{tags:[]};try{return{tags:await Yu(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${u_(e)}`}}},gw=async(e,t,n,r)=>{let i=z(e.env),a=await V(i),o=ix(a,t),s=Ub(a,o),c=await Yh(i),l=B(i,o),{packages:u,...d}=s,f=n.tags?await hw(e,l):void 0,p=c.refs[o]??mw;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:qb(p.last_fetched_at,wc(Kh(`sync_ttl`,s,a.settings)),r),state:p},warnings:l_(f?.warning)}},_w=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...Xb({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},vw=(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 gw(t,e,r,a);Z(t,i,_w(o,a),o,s)})()})},yw=(e,t,n)=>({home:e,key:n,ref:Ub(t,n),settings:t.settings}),bw=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>yw(e,t,Sc.parse(n))):n.map(n=>yw(e,t,ix(t,n))),xw=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=wc(Kh(`sync_ttl`,t.ref,t.settings)),a=qb(n.refs[t.key]?.last_fetched_at,i,r),o=!H(B(e,t.key));return a||o})},Sw=async(e,t,n)=>{if(!hg({env:e.env,updates:n.updates}))return[];let{latest:r,refreshed:i}=await sg({fetch:e.fetcher,home:t,nowMs:Date.now()});return!i||r===void 0||!cg(e.cliVersion,r)?[]:[lg(e.cliVersion,r)]},Cw=async(e,t,n)=>{if(!n)return t;let r=await Yh(e);return xw(e,t,r)},ww=async(e,t)=>{let n=z(e.env),r=await V(n),i=bw(n,r,t.refs),a=await Cw(n,i,t.staleOnly),[o,s]=await Promise.all([tw(e,a),a.length>0?Sw(e,n,r):Promise.resolve([])]);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o,warnings:s}},Tw=[`updated`,`fresh`,`cloned`,`restored`,`failed`],Ew={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},Dw=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},Ow=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,...by(e.structure,e.key).map(e=>` ${e}`)]},kw=e=>{let t=Dw(e),n=[Tw.map(e=>`${Ew[e]} (${t[e].length})`).join(` / `)];for(let e of Tw)for(let r of t[e])n.push(...Ow(r));return n},Aw=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),jw=(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 ww(t,Aw(e,n));Z(t,i,kw(r.results),{results:r.results},r.warnings),r.failedCount>0&&(process.exitCode=xe.UNEXPECTED)})()})},Mw=(e,t,n)=>n===void 0?e.tag_format:Gb(e,t,n).tag_format??e.tag_format,Nw=(e,t,n)=>{if(e!==void 0)return e;let r=n===void 0?`ref '${t}'`:`package '${n}'`,i=n===void 0?``:` --package ${G_(n)}`;throw b(`${r} has no tag_format configured — inspect the repository's real tags and set one with: refs edit ${G_(t)} tag_format '<format>'${i}`)},Pw=async(e,t)=>{let n=z(e.env),r=await V(n),i=ix(r,t.query),a=Ub(r,i),o=Nw(Mw(a,i,t.opts.packageName),i,t.opts.packageName),s=B(n,i);Wb(s,i);let c=await ud(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},Fw=e=>[`${e.key}@${e.version} -> ${e.tag}`],Iw=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Lw=[Jx,Lv,Ux,ax,Hb,Zx,lS,pw,vw,jw,(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 Pw(t,{opts:Iw(r),query:e,version:n});Z(t,a,Fw(i),i)})()})}],Rw=(e,t)=>{for(let n of Lw)n(e,t)},zw=[``,`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(`
348
+ `),Bw=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),Vw=`--json`,Hw=`--verbose`,Uw=/\n$/u,Ww=/^error: /u,Gw=e=>e.replace(Ww,``),Kw=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},qw=e=>Kw(e,Vw),Jw=e=>Kw(e,Hw),Yw=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,Xw=e=>{let t=new i_().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(Ug).option(Vw,`emit machine-readable JSON on stdout instead of human-readable text`).option(Hw,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(Uw,``))},writeOut:t=>{e.out(t.replace(Uw,``))}});return t.addHelpText(`after`,zw),Rw(t,e),t},Zw=()=>{process.exitCode=xe.OK},Qw=(e,t,n)=>{let r={code:`usage`,message:Yw(Gw(n.message),n.stack,t.verbose)};d_(e,t,r),process.exitCode=xe.USAGE},$w=(e,t,n)=>{if(Bw.has(n.code)){Zw();return}Qw(e,t,n)},eT=(e,t,n)=>{let r=we(n,{verbose:t.verbose});d_(e,t,r),process.exitCode=r.exitCode},tT=async(e,t,n)=>{let r={json:qw(n),verbose:Jw(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof qg){$w(e,r,t);return}eT(e,r,t)}},nT=(e,t)=>tT(e,Xw(e),t);import.meta.main&&await nT(Kg(),process.argv);export{Xw as buildProgram,X as cliOptsOf,Z as emit,d_ as emitError,u_ as errorMessageOf,f_ as progress,Kg as realContext,Rw as registerCommands,nT as run,tT as runProgram,l_ as warningsFor,Q as wrapAction};