@politty/zod 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +2 -2
  2. package/dist/argv-parser-CawJSYjw.js +1 -0
  3. package/dist/cli-main-C7vClSAF.js +2 -0
  4. package/dist/cli-main-dbj7bXjm.js +1 -0
  5. package/dist/cli-run-CitZgzLl.js +1 -0
  6. package/dist/cli.js +1 -1
  7. package/dist/completion-CizQSJgq.js +1 -0
  8. package/dist/{completion-OvSe3W9y.js → completion-nNzHfI1i.js} +3 -3
  9. package/dist/completion.js +1 -1
  10. package/dist/docs.js +12 -12
  11. package/dist/dynamic-DG-l9V-y.js +1 -0
  12. package/dist/dynamic-DbvYJg3o.js +6 -0
  13. package/dist/field-meta-D9ySul7J.js +1 -0
  14. package/dist/index.js +1 -1
  15. package/dist/log-collector-uhRWYT-z.js +1 -0
  16. package/dist/prompt-clack.js +1 -1
  17. package/dist/prompt-inquirer.js +1 -1
  18. package/dist/prompt.js +1 -1
  19. package/dist/register-TbOCQNeI.js +1 -0
  20. package/dist/runner-BKyUtmoD.js +1 -0
  21. package/dist/runner-CBG2DbVY.js +30 -0
  22. package/dist/schema-extractor-fZZ2_WAZ.js +1 -0
  23. package/dist/{schema-DhMPssIJ.js → schema-tWeEQULd.js} +1 -1
  24. package/dist/skill.js +1 -1
  25. package/dist/{subcommand-router-D8GTMXYL.js → subcommand-router-DR2KBQAt.js} +1 -1
  26. package/dist/{with-completion-command-CQcqFHq8.js → with-completion-command-DG-C9_0Z.js} +2 -2
  27. package/package.json +1 -1
  28. package/dist/argv-parser-DZQ0qnXG.js +0 -1
  29. package/dist/cli-main-BX5IVgNq.js +0 -1
  30. package/dist/cli-main-uRzr666k.js +0 -2
  31. package/dist/cli-run-DtG5fM18.js +0 -1
  32. package/dist/completion-8frPuaX8.js +0 -1
  33. package/dist/dynamic-4uRohypH.js +0 -6
  34. package/dist/dynamic-C5e2NuDv.js +0 -1
  35. package/dist/field-meta-_l-FHbh7.js +0 -1
  36. package/dist/log-collector-DICKib75.js +0 -1
  37. package/dist/register-BXOytPt7.js +0 -1
  38. package/dist/runner-BTD1-gUd.js +0 -30
  39. package/dist/runner-BTF0HIGj.js +0 -1
  40. package/dist/schema-extractor-Du9ipDD4.js +0 -1
@@ -0,0 +1,6 @@
1
+ import{i as e,n as t}from"./field-meta-D9ySul7J.js";import{a as n,l as r,n as i}from"./schema-extractor-fZZ2_WAZ.js";import{n as a}from"./command-tLHaJHe6.js";import{c as o,i as s}from"./subcommand-router-DR2KBQAt.js";import{i as c}from"./argv-parser-CawJSYjw.js";import{t as l}from"./schema-tWeEQULd.js";import{execSync as u}from"node:child_process";function d(e,t,n){return{fieldName:e.name,isArrayOption:e.valueType===`array`,isGlobal:e.isGlobal===!0,resolvedDeps:p(e.valueCompletion,e.isGlobal===!0,t,n)}}function f(e,t,n){return{fieldName:e.name,isArrayOption:!1,isGlobal:!1,resolvedDeps:p(e.valueCompletion,!1,t,n)}}function p(e,t,n,r=[]){if(e?.type!==`expand`)return[];let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set;for(let e of n)e.isGlobal===!0?i.add(e.name):a.add(e.name);for(let e of r)a.add(e.name);return e.dependsOn.map(e=>({name:e,isGlobal:t||i.has(e)&&!a.has(e)}))}function m(e){let t=`$'`;for(let n of e){let e=n.codePointAt(0);t+=n===`\\`?`\\\\`:n===`'`?`\\'`:n===`
2
+ `?`\\n`:n===`\r`?`\\r`:n===` `?`\\t`:e<32||e===127?`\\x${e.toString(16).padStart(2,`0`)}`:n}return t+=`'`,t}function h(e){return`'${e.replace(/'/g,`'\\''`)}'`}function g(e,t){let n=t.withSize?`%Y:%s`:`%Y`,r=t.withSize?`%m:%z`:`%m`,i=`stat -L -c '${n}' "${e}" 2>/dev/null`,a=`stat -L -f '${r}' "${e}" 2>/dev/null`;return t.shell===`fish`?`(${i}; or ${a})`:`$(${i} || ${a})`}function _(e){return e.length===1?`-${e}`:`--${e}`}function v(t,n){y(t,_(n)),n.length===1?y(t,`--${n}`):n.includes(`-`)&&y(t,`--${e(n)}`)}function y(e,t){e.includes(t)||e.push(t)}function b(t,n){let r=[`--${t}`];t.length===1&&r.push(`-${t}`),t.includes(`-`)&&r.push(`--${e(t)}`);for(let e of n??[])v(r,e);return r}function x(e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n.isGlobal===!0){n.cliName.length===1&&t.add(`-${n.cliName}`);for(let e of n.alias??[])e.length===1&&t.add(`-${e}`)}return t}function S(t,n,r,i){let a=new Set(b(t,n));if(r&&(a.add(`--${r}`),r.includes(`-`)&&a.add(`--${e(r)}`)),i?.frameOptions){if(i.isGlobal===!0){for(let e of i.frameOptions)if(e.isGlobal!==!0)for(let t of E(e.cliName,e.alias))a.delete(t)}else{let e=x(i.frameOptions);if(e.size>0){let t=new Set((n??[]).filter(e=>e.length===1).map(e=>`-${e}`));for(let n of e)t.has(n)||a.delete(n)}}}return[...a].map(e=>`"${e}"`)}function C(e,t){return e.map(e=>{let n=t.find(t=>t.isGlobal!==!0&&t.name===e.name);return n&&S(n.cliName,n.alias,n.negation,{frameOptions:t})})}function w(e,t,n,r=`$_pos_count`){let i=C(e,t);if(i.every(e=>e===void 0))return;let a=[` local _slot=-1 _left=${r}`];return e.forEach((e,t)=>{let r=i[t],o=r?` && __${n}_not_used ${r.join(` `)}`:``,s=e.variadic?`_slot=${e.position}`:`if (( _left == 0 )); then _slot=${e.position}; else (( _left-- )); fi`;a.push(` if (( _slot < 0 ))${o}; then ${s}; fi`)}),a}function T(e,t){let n=[`__${e}_track_positionals() {`,` local _k=0 _w`,' for _w in "${_pos_words[@]}"; do',` local _slot=$_k`,` case "$_subcmd" in`];for(let r of t){n.push(` ${r.pathStrs.map(e=>`"${e}"`).join(`|`)})`);for(let t of w(r.positionals,r.options,e,`$_k`)??[])n.push(` ${t}`);n.push(` ;;`)}return n.push(` esac`,` __${e}_track_pos "$_subcmd" "$_slot" "$_w"`,` (( _k++ ))`,` done`,`}`,``),n}function E(t,n){let r=[`--${t}`];t.includes(`-`)&&r.push(`--${e(t)}`);for(let e of n??[])v(r,e);return r}function D(e){let t=e.completion;if(t?.custom){let n=t.custom,r=[];if(n.expand&&r.push(`expand`),n.resolve&&r.push(`resolve`),n.choices&&n.choices.length>0&&r.push(`choices`),n.shellCommand&&r.push(`shellCommand`),r.length>1)throw Error(`Field "${e.name??`<unknown>`}": completion.custom may only specify one of choices, shellCommand, resolve, expand (got ${r.join(`, `)}).`);if(n.expand)return{type:`pending-expand`,spec:n.expand};if(n.resolve)return{type:`dynamic`,resolve:n.resolve};if(n.choices&&n.choices.length>0)return{type:`choices`,choices:n.choices};if(n.shellCommand)return{type:`command`,shellCommand:n.shellCommand}}if(t?.type){if(t.type===`file`)return t.matcher?{type:`file`,matcher:t.matcher}:t.extensions?{type:`file`,extensions:t.extensions}:{type:`file`};if(t.type===`directory`)return{type:`directory`};if(t.type===`none`)return{type:`none`}}if(e.enumValues&&e.enumValues.length>0)return{type:`choices`,choices:e.enumValues}}function O(e){if(e)return e.type===`pending-expand`?{type:`runtime-expand`,dependsOn:e.spec.dependsOn,enumerate:e.spec.enumerate}:e}function ee(e){return e.args?te(e.args):[]}function te(e){return n(i(e)).map(k)}function k(e){let n=t(e);return{name:e.name,cliName:e.cliName,alias:n.length>0?n:void 0,negation:e.negationDisplay,negationDescription:e.negationDescription,description:e.description,takesValue:e.type!==`boolean`,valueType:e.type,required:e.required,defaultNegationAccepted:e.type===`boolean`&&e.negation===!0,valueCompletion:O(D(e))}}function A(e){return new Set(b(e.cliName,e.alias))}function ne(e,t){let n=A(t);for(let t of e)for(let e of A(t))if(n.has(e))return t}function re(e,t,n){let r=/* @__PURE__ */ new Set;if(t.length===0)return r;let i=/* @__PURE__ */ new Set,a=(e,t)=>{B(n,e,t,i),r.add(e.name)},o=0;for(;o<e.length;){let i=e[o];if(i===`--`||!i.startsWith(`-`))break;if(!i.startsWith(`--`)&&i.length>2){let e=i.indexOf(`=`);if((e>=0?i.slice(1,e):i.slice(1)).length>1)break}let s=F(i),c=U(t,s);if(!c){if(le(t,s)){o++;continue}break}if(c.takesValue){if(I(i)){let e=i.indexOf(`=`);a(c,i.slice(e+1)),o++}else if(o+1<e.length){let t=e[o+1];if(t.startsWith(`-`)){o++;continue}a(c,t),o+=2}else break}else n[c.name]=!V(c,s),r.add(c.name),o++}return r}function ie(e,t){return t.valueType===`array`?Array.isArray(e)?e:[e]:Array.isArray(e)?e.at(-1):e}function j(e,t){return t.length===0?e:[...e,...t]}function M(e,t){let n=t.length-1;if(!(n<0))return e>n?n:e}function N(e,t){return n=>{let r={...e};return c(n,e).forEach((e,n)=>{n<t.length&&(r[e.name]=t[n])}),r}}function ae(e,t,n){if(!e.args)return;let a=i(e.args),o=r(a,N(t,n));if(o!==a)return o.fields.filter(e=>e.named).map(k)}function oe(e,t,n){if(!e.args)return[];let a=r(i(e.args),N(t,n));return c(a,t).map((e,t)=>({name:e.name,cliName:e.cliName,position:t,description:e.description,required:e.required,variadic:e.type===`array`,valueCompletion:O(D(e))}))}function se(e){if(!e.subCommands)return[];let t=[];for(let[n,r]of Object.entries(e.subCommands)){if(n.startsWith(`__`))continue;t.push(n);let e=o(r);e?.aliases&&t.push(...e.aliases)}return t}function ce(e,t){if(!e.subCommands)return null;let n=Object.hasOwn(e.subCommands,t)?e.subCommands[t]:void 0;if(n)return o(n);let r=s(e,t);return r?o(e.subCommands[r]):null}function P(e){return e.startsWith(`-`)}function F(e){if(e.startsWith(`--`)){let t=e.slice(2),n=t.indexOf(`=`);return{name:n>=0?t.slice(0,n):t,isLong:!0}}return e.startsWith(`-`)?{name:e.slice(1,2),isLong:!1}:{name:e,isLong:!0}}function I(e){return e.includes(`=`)}function L(t,n,r){if(!r||t.valueType!==`boolean`)return!1;let i=[t.cliName,...t.alias??[]];for(let t of i){let r=`no-${t}`;if(n===r||n===e(r))return!0}return!1}function R(e,t,n){return e.defaultNegationAccepted===!0&&L(e,t,n)}function le(e,t){return e.some(e=>e.defaultNegationAccepted!==!0&&L(e,t.name,t.isLong))}function z(t,n){return t!==void 0&&t.includes(`-`)&&e(t)===n}function B(e,t,n,r){if(t.valueType!==`array`){e[t.name]=n;return}if(r.has(t.name)){let r=e[t.name];e[t.name]=Array.isArray(r)?[...r,n]:[n]}else e[t.name]=[n],r.add(t.name)}function V(e,t){return t.isLong?e.negation!==void 0&&(e.negation===t.name||z(e.negation,t.name))?!0:R(e,t.name,t.isLong):!1}function H(e,t,n){if(e.cliName===t&&(n||e.cliName.length===1))return!0;if(e.alias){for(let r of e.alias)if(r===t&&(n||r.length===1))return!0}return n&&e.negation===t?!0:!n||t.length<=1?!1:z(e.cliName,t)||e.alias?.some(e=>z(e,t))?!0:z(e.negation,t)}function U(e,t){if(!t.isLong){let n=e.find(e=>e.isGlobal!==!0&&e.alias?.includes(t.name)===!0);if(n)return n;let r=e.find(e=>e.isGlobal===!0&&H(e,t.name,t.isLong));if(r)return r}return e.find(e=>H(e,t.name,t.isLong))||e.find(e=>R(e,t.name,t.isLong))}function W(e,t,n){let r=G(e,t,n);return r.variantOptions?G(e,t,n,{command:r.context.currentCommand,options:r.variantOptions}).context:r.context}function G(e,t,n,r){let i=e=>e===r?.command?r.options:ee(e),a=t,o=[],s=n?te(n).map(e=>({...e,isGlobal:!0})):[],c=/* @__PURE__ */ new Set,l=!1,u=0,d={},f=[],p={},m=/* @__PURE__ */ new Set,h=0,g=/* @__PURE__ */ new Set,_=e=>{c.add(e.cliName);for(let t of e.alias??[])c.add(t);e.negation&&c.add(e.negation),l=!0},v=(e,t)=>{B(e.isGlobal===!0?p:d,e,t,g)},y=(e,t)=>{let n=e.isGlobal===!0?p:d;n[e.name]=!V(e,t)},b=0,x=j(i(a),s),S=!1;for(;b<e.length-1;){let t=e[b];if(!S&&t===`--`){S=!0,b++;continue}if(!S&&t.startsWith(`-`)&&!t.startsWith(`--`)&&t.length>2&&!t.includes(`=`)){l=!0;let e=Array.from(t.slice(1)),n=x.filter(e=>e.isGlobal!==!0);for(let t of e){let e=U(n,{name:t,isLong:!1});e&&!e.takesValue&&(_(e),y(e,{name:t,isLong:!1}))}b++;continue}if(!S&&P(t)){l=!0;let n=F(t),r=U(x,n);if(r){if(_(r),r.takesValue){if(I(t)){let e=t.indexOf(`=`);v(r,t.slice(e+1))}else if(b+1<e.length-1){let t=e[b+1];P(t)||(v(r,t),b++)}}else y(r,n)}b++;continue}let n=S?null:ce(a,t);if(n){o.push(t);let r=i(a),l=e.slice(h,b);for(let e of re(l,s,p))m.add(e);a=n,x=j(i(a),s);for(let e of Object.keys(d)){let t=r.find(t=>t.name===e),n=s.find(t=>t.name===e)??(t?ne(s,t):void 0);n&&(m.has(n.name)||(p[n.name]=ie(d[e],n)))}c.clear(),u=0,d={},f=[],g=/* @__PURE__ */ new Set,h=b+1,b++;continue}f.push(t),u++,b++}let C=e[e.length-1]??``,w=e[e.length-2]??``,T=ae(a,d,f),E=oe(a,d,f),D=se(a);for(let e=0;e<E.length;e++){let t=E[e];if(t.variadic){d[t.name]=f.slice(e);break}e<f.length&&(d[t.name]=f[e])}let O,k,A;if(!S&&w&&P(w)&&!I(w)){let e=U(x,F(w));e&&e.takesValue?(O=`option-value`,k=e):C.startsWith(`-`)?O=`option-name`:(O=K(C,D,E,u),O===`positional`&&(A=u))}else if(!S&&C.startsWith(`-`)&&I(C)){let e=U(x,F(C));e&&e.takesValue?(O=`option-value`,k=e):O=`option-name`}else!S&&C.startsWith(`-`)?O=`option-name`:(O=K(C,D,E,u,S),O===`positional`&&(A=u));let N=[];if(k){if(k.valueType===`array`){let e=(k.isGlobal===!0?p:d)[k.name];N=Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}}else if(O===`positional`&&A!==void 0){let e=M(A,E);e!==void 0&&E[e]?.variadic&&(N=f.slice(e))}let L={...p,...d};return{context:{subcommandPath:o,currentCommand:a,currentWord:C,previousWord:w,completionType:O,targetOption:k,positionalIndex:A,options:x,subcommands:D,positionals:E,usedOptions:c,hasAnyOptionBeenUsed:l,providedPositionalCount:u,parsedArgs:L,previousValues:N},variantOptions:T}}function K(e,t,n,r,i){return i?`positional`:t.length>0&&(t.filter(t=>t.startsWith(e)).length>0||e===``)?`subcommand`:r<n.length||n.length>0&&n[n.length-1].variadic?`positional`:`subcommand`}const q={Default:0,NoSpace:1,NoFileCompletion:2,FilterPrefix:4,KeepOrder:8,FileCompletion:16,DirectoryCompletion:32,Error:64};function J(e){if(!e.startsWith(`-`))return;let t=e.indexOf(`=`);if(!(t<=0))return e.slice(0,t+1)}async function Y(e,t){switch(e.completionType){case`subcommand`:return ve(e);case`option-name`:return Z(e);case`option-value`:{let n=e.targetOption,r=n?J(e.currentWord):void 0;return xe(r?{...e,currentWord:e.currentWord.slice(r.length)}:e,t,n?.name,n?.valueCompletion,void 0,n?.valueType===`array`)}case`positional`:{let n=ue(e);return n?xe(e,t,n.name,n.valueCompletion,n.description,!1):{candidates:[],directive:q.NoFileCompletion}}}}function ue(e){let t=e.positionalIndex??0,n=M(t,e.positionals);if(n===void 0)return;let r=e.positionals[n];if(r)return n===t||r.variadic?r:void 0}function de(e){try{return u(e,{encoding:`utf-8`,timeout:5e3}).split(`
3
+ `).map(e=>e.trim()).filter(e=>e.length>0).map(e=>({value:e,type:`value`}))}catch{return[]}}function X(e){return e?.type===`choices`?e.choices:void 0}function fe(e,t){let n=e.options.find(e=>e.name===t&&e.isGlobal!==!0);if(n)return X(n.valueCompletion);let r=e.positionals.find(e=>e.name===t);return X(r?r.valueCompletion:e.options.find(e=>e.name===t&&e.isGlobal===!0)?.valueCompletion)}function pe(e,t){let n=!t.includes(`=`),r=n?me(e):he(e,t);return{candidates:r,hasEqSuffix:n&&r.some(e=>e.value.endsWith(`=`))}}function me(e){let t=/* @__PURE__ */ new Set,n=[];for(let r of e){let e=r.value.indexOf(`=`);if(e<=0){n.push(r);continue}let i=r.value.slice(0,e+1);t.has(i)||(t.add(i),n.push({...r,value:i}))}return n}function he(e,t){let n=t.slice(0,t.indexOf(`=`)+1);return e.filter(e=>e.value!==n)}async function ge(e,t,n,r,i){let a=[],o=q.FilterPrefix,s,c;switch(e.type){case`choices`:if(e.choices)for(let t of e.choices)a.push({value:t,description:r,type:`value`});o|=q.NoFileCompletion;break;case`file`:e.matcher&&e.matcher.length>0?(c=e.matcher.filter(e=>e.trim().length>0),c.length===0&&(c=void 0,o|=q.FileCompletion)):e.extensions&&e.extensions.length>0?(s=Array.from(new Set(e.extensions.map(e=>e.trim().replace(/^\./,``)).filter(e=>e.length>0))),s.length===0&&(s=void 0,o|=q.FileCompletion)):o|=q.FileCompletion;break;case`directory`:o|=q.DirectoryCompletion;break;case`command`:e.shellCommand&&a.push(...de(e.shellCommand)),o|=q.NoFileCompletion;break;case`none`:o|=q.NoFileCompletion;break;case`dynamic`:try{let n=await e.resolve(t);for(let e of n.candidates){let t=typeof e==`string`?{value:e}:e;a.push({...t,type:`value`})}o=n.directive??q.FilterPrefix|q.NoFileCompletion}catch{o=q.NoFileCompletion|q.Error}break;case`expand`:o|=q.NoFileCompletion;break;case`runtime-expand`:{let r={},i=!1;for(let a of e.dependsOn){let e=t.parsedArgs[a],o=Array.isArray(e)?e[e.length-1]:e,s=fe(n,a);if(typeof o!=`string`||s===void 0||!s.includes(o)){i=!0;break}r[a]=o}if(!i)try{let t=/* @__PURE__ */ new Set;for(let n of e.enumerate(r)){let e=typeof n==`string`?{value:n}:n;t.has(e.value)||(t.add(e.value),a.push({...e,type:`value`}))}}catch{o=q.NoFileCompletion|q.Error;break}o|=q.NoFileCompletion;break}}if(e.type===`dynamic`||e.type===`expand`||e.type===`runtime-expand`){let n=pe(e.type===`runtime-expand`&&i===!0?_e(a,t.previousValues):a,t.currentWord);return n.hasEqSuffix&&(o|=q.NoSpace),{candidates:n.candidates,directive:o,fileExtensions:s,fileMatchers:c}}return{candidates:a,directive:o,fileExtensions:s,fileMatchers:c}}function _e(e,t){let n=/* @__PURE__ */ new Set;for(let e of t){let t=e.indexOf(`=`);t>0&&n.add(e.slice(0,t))}return n.size===0?[...e]:e.filter(e=>{let t=e.value.indexOf(`=`);return t<=0||!n.has(e.value.slice(0,t))})}function ve(e){let t=[];for(let n of e.subcommands){let r=e.currentCommand.subCommands,i=r?.[n],a=i?void 0:s(e.currentCommand,n),c=i??(a?r?.[a]:void 0),l=c?o(c)?.description:void 0;t.push({value:n,description:l,type:`subcommand`})}if(t.length===0||e.currentWord.startsWith(`-`)){let n=Z(e);t.push(...n.candidates)}return{candidates:t,directive:q.FilterPrefix|q.NoFileCompletion}}function Z(e){let t=[],n=e.options.filter(t=>t.valueType===`array`||!(e.usedOptions.has(t.cliName)||t.alias&&t.alias.some(t=>e.usedOptions.has(t))||t.negation&&e.usedOptions.has(t.negation)));for(let e of n)t.push({value:`--${e.cliName}`,description:e.description,type:`option`}),e.negation&&t.push({value:`--${e.negation}`,description:e.negationDescription??e.description,type:`option`});return e.hasAnyOptionBeenUsed||t.push({value:`--help`,description:`Show help information`,type:`option`},{value:`--help-all`,description:`Show help with all subcommand options`,type:`option`},{value:`--help-json`,description:`Show help as JSON`,type:`option`}),{candidates:t,directive:q.FilterPrefix|q.NoFileCompletion}}function ye(e,t,n){return{currentWord:e.currentWord,shell:t.shell,parsedArgs:be(e.parsedArgs,n),previousValues:e.previousValues,subcommandPath:e.subcommandPath}}function be(e,t){if(t===void 0||!(t in e))return e;let n={...e};return delete n[t],n}async function xe(e,t,n,r,i,a){return r?ge(r,ye(e,t,n),e,i,a):{candidates:[],directive:q.FilterPrefix}}function Q(e,t){switch(t.shell){case`bash`:return Se(e,t);case`zsh`:return Ce(e,t);case`fish`:return we(e,t)}}function $(e,t){let n=`:${t.directive}`;t.fileExtensions&&t.fileExtensions.length>0&&(n+=`\t@ext:${t.fileExtensions.join(`,`)}`),t.fileMatchers&&t.fileMatchers.length>0&&(n+=`\t@matcher:${t.fileMatchers.join(`,`)}`),e.push(n)}function Se(e,t){let n=((e.directive&q.FilterPrefix)!==0&&t.currentWord?e.candidates.filter(e=>e.value.startsWith(t.currentWord)):e.candidates).map(e=>t.inlinePrefix?`${t.inlinePrefix}${e.value}`:e.value);return $(n,e),n.join(`
4
+ `)}function Ce(e,t){let n=e.candidates.map(e=>{let t=e.value.replace(/:/g,`\\:`);return e.description?`${t}:${e.description.replace(/:/g,`\\:`)}`:t});return $(n,e),n.join(`
5
+ `)}function we(e,t){let n=e.candidates.map(e=>e.description?`${e.value}\t${e.description}`:e.value);return $(n,e),n.join(`
6
+ `)}function Te(e,t,n){return a({name:`__complete`,args:l,async run(t){let r=W(t.args,e,n),i=r.completionType===`option-value`&&r.targetOption?J(r.currentWord):void 0,a=i?r.currentWord.slice(i.length):r.currentWord,o=Q(await Y(r,{shell:t.shell}),{shell:t.shell,currentWord:a,inlinePrefix:i});console.log(o)}})}function Ee(e){return!!e.subCommands?.__complete}export{S as _,Y as a,m as c,E as d,C as f,T as g,w as h,q as i,b as l,f as m,Ee as n,W as o,d as p,Q as r,D as s,Te as t,x as u,h as v,g as y};
@@ -0,0 +1 @@
1
+ let e;function t(t){e=t}function n(){if(!e)throw Error('No validator adapter registered. Import politty through an adapter package (e.g. `import { defineCommand } from "@politty/zod"` or `from "politty"`) so the schema library integration is set up.');return e}const r=/* @__PURE__ */ new Set([`help`,`help-all`,`help-json`,`version`]);function i(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}function a(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function o(e){return!e.alias&&!e.hiddenAlias?[]:[...e.alias??[],...e.hiddenAlias??[]]}function s(e,t){let n=t.argMeta,a=n?.description??t.description,o=i(e),s=/^[A-Za-z0-9][A-Za-z0-9-]*$/,c=(t,n)=>{if(t==null)return;let r=(Array.isArray(t)?t:[t]).map(t=>{if(typeof t!=`string`)throw Error(`Invalid ${n} for field "${e}": expected string or string[], received ${typeof t}.`);let r=t.trim().replace(/^-+/,``);if(r.length===0||!s.test(r))throw Error(`Invalid ${n} "${t}" for field "${e}": aliases must match ${s}.`);return r}),i=Array.from(new Set(r));return i.length>0?i:void 0},l=c(n?.alias,`alias`),u=new Set(l??[]),d=c(n?.hiddenAlias,`hiddenAlias`)?.filter(e=>!u.has(e)),f=d&&d.length>0?d:void 0,p=t.type,m=n?.negation,h;if(m!=null){if(typeof m==`boolean`){if(p!==`boolean`)throw Error(`Invalid negation for field "${e}": negation can only be used on boolean fields.`);h=m}else{if(typeof m!=`string`)throw Error(`Invalid negation for field "${e}": expected string or boolean, received ${typeof m}.`);let t=m.trim().replace(/^-+/,``);if(t.length===0||!s.test(t))throw Error(`Invalid negation "${m}" for field "${e}": negation names must match ${s}.`);if(r.has(t))throw Error(`Invalid negation "${m}" for field "${e}": negation cannot use reserved built-in flag names (${[...r].map(e=>`--${e}`).join(`, `)}).`);if(p!==`boolean`)throw Error(`Invalid negation for field "${e}": negation can only be used on boolean fields.`);h=t}}let g=n?.negationDescription,_;if(g!=null){if(typeof g!=`string`)throw Error(`Invalid negationDescription for field "${e}": expected string, received ${typeof g}.`);if(h===!1)throw Error(`Invalid negationDescription for field "${e}": negationDescription cannot be used when negation is false.`);if(h===void 0)throw Error(`Invalid negationDescription for field "${e}": negationDescription requires \`negation\` to be set (string or true).`);let t=g.trim();if(t.length===0)throw Error(`Invalid negationDescription for field "${e}": negationDescription must be a non-empty string.`);_=t}let v=typeof h==`string`?h:h===!0?`no-${o}`:void 0,y=n?.positional,b={name:e,cliName:o,alias:l,hiddenAlias:f,description:a,positional:y!==void 0&&y!==!1,named:typeof y==`object`?y.named===!0:y!==!0,placeholder:n?.placeholder,env:n?.env,required:t.required,defaultValue:t.defaultValue,type:p,schema:t.schema,enumValues:t.enumValues,completion:n?.completion,prompt:n?.prompt,negation:h,negationDisplay:v,negationDescription:_,effect:n?.effect};return n&&`overrideBuiltinAlias`in n&&n.overrideBuiltinAlias===!0&&(b.overrideBuiltinAlias=!0),b}export{i as a,a as i,o as n,n as o,s as r,t as s,r as t};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as e,i as t}from"./field-meta-_l-FHbh7.js";import{t as n}from"./register-BXOytPt7.js";import{i as r,n as i}from"./schema-extractor-Du9ipDD4.js";import{n as a,t as o}from"./cli-main-uRzr666k.js";import{n as s,t as c}from"./command-tLHaJHe6.js";import{C as l,D as u,E as d,O as f,S as p,T as m,_ as h,a as g,b as _,c as v,d as y,f as b,g as x,h as S,i as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,t as j,u as M,v as N,w as P,x as F,y as I}from"./runner-BTD1-gUd.js";import{o as L,s as R}from"./subcommand-router-D8GTMXYL.js";import{a as z,i as B,n as V,r as H,t as U}from"./logger-CoeDrmRr.js";import{r as W}from"./argv-parser-DZQ0qnXG.js";import{t as G}from"./with-completion-command-CQcqFHq8.js";const K=a(`@politty/zod`),q=s,J=c,Y=n;export{x as CaseVariantCollisionError,h as DefaultSubCommandError,N as DuplicateAliasError,I as DuplicateFieldError,_ as DuplicateNegationError,F as FieldTypeConflictError,p as PositionalConfigError,l as ReservedAliasError,P as ReservedFieldNameError,Y as arg,a as createCompileCacheShimGenerator,J as createDefineCommand,k as createDualCaseProxy,q as defineCommand,i as extractFields,g as formatCommandValidationErrors,C as formatValidationErrors,K as generateCompileCacheShim,m as generateHelp,d as generateHelpData,r as getUnknownKeysMode,U as isColorEnabled,L as isLazyCommand,R as lazy,V as logger,W as parseArgv,u as renderInline,f as renderMarkdown,j as runCommand,E as runMain,o as runPolittyCli,H as setColorEnabled,B as styles,z as symbols,t as toCamelCase,e as toKebabCase,D as validateCaseVariantCollisions,A as validateCommand,v as validateCrossSchemaCollisions,w as validateDefaultSubCommand,M as validateDuplicateAliases,y as validateDuplicateFields,b as validateDuplicateNegations,O as validatePositionalConfig,T as validateReservedAliases,S as validateReservedFieldNames,G as withCompletionCommand};
1
+ import{a as e,i as t}from"./field-meta-D9ySul7J.js";import{t as n}from"./register-TbOCQNeI.js";import{i as r,n as i}from"./schema-extractor-fZZ2_WAZ.js";import{n as a,t as o}from"./cli-main-C7vClSAF.js";import{n as s,t as c}from"./command-tLHaJHe6.js";import{C as l,D as u,E as d,O as f,S as p,T as m,_ as h,a as g,b as _,c as v,d as y,f as b,g as x,h as S,i as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,t as j,u as M,v as N,w as P,x as F,y as I}from"./runner-CBG2DbVY.js";import{o as L,s as R}from"./subcommand-router-DR2KBQAt.js";import{a as z,i as B,n as V,r as H,t as U}from"./logger-CoeDrmRr.js";import{r as W}from"./argv-parser-CawJSYjw.js";import{t as G}from"./with-completion-command-DG-C9_0Z.js";const K=a(`@politty/zod`),q=s,J=c,Y=n;export{x as CaseVariantCollisionError,h as DefaultSubCommandError,N as DuplicateAliasError,I as DuplicateFieldError,_ as DuplicateNegationError,F as FieldTypeConflictError,p as PositionalConfigError,l as ReservedAliasError,P as ReservedFieldNameError,Y as arg,a as createCompileCacheShimGenerator,J as createDefineCommand,k as createDualCaseProxy,q as defineCommand,i as extractFields,g as formatCommandValidationErrors,C as formatValidationErrors,K as generateCompileCacheShim,m as generateHelp,d as generateHelpData,r as getUnknownKeysMode,U as isColorEnabled,L as isLazyCommand,R as lazy,V as logger,W as parseArgv,u as renderInline,f as renderMarkdown,j as runCommand,E as runMain,o as runPolittyCli,H as setColorEnabled,B as styles,z as symbols,t as toCamelCase,e as toKebabCase,D as validateCaseVariantCollisions,A as validateCommand,v as validateCrossSchemaCollisions,w as validateDefaultSubCommand,M as validateDuplicateAliases,y as validateDuplicateFields,b as validateDuplicateNegations,O as validatePositionalConfig,T as validateReservedAliases,S as validateReservedFieldNames,G as withCompletionCommand};
@@ -0,0 +1 @@
1
+ import{StringDecoder as e}from"node:string_decoder";const t={log:`stdout`,info:`stdout`,debug:`stdout`,warn:`stderr`,error:`stderr`},n=[`log`,`info`,`debug`,`warn`,`error`];function r(e){return e.map(e=>{if(e instanceof Error)return e.message;if(typeof e==`object`&&e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}).join(` `)}function i(e){return e.replace(/\r?\n$/,``)}function a(a={}){let o=[],s=a.levels??n,c=a.passthrough??!0,l=null,u=null,d=null,f=!1,p=(e,t,n)=>{o.push({message:n,timestamp:/* @__PURE__ */ new Date,level:e,stream:t})},m=(e,n)=>(...i)=>{p(e,t[e],r(i)),f=!0;try{c&&n.apply(console,i)}finally{f=!1}},h=(t,n,r)=>{let a=new e(`utf8`);return((e,o,s)=>{if(!f){let r=typeof e==`string`?typeof o==`string`&&o!==`utf8`&&o!==`utf-8`?Buffer.from(e,o).toString(`utf8`):e:a.write(e);r!==``&&p(t,n,i(r))}if(c)return r.call(process[n],e,o,s);let l=typeof o==`function`?o:s;return typeof l==`function`&&l(),!0})};return{getLogs(){return{entries:[...o]}},start(){if(l===null){l={log:console.log,info:console.info,debug:console.debug,warn:console.warn,error:console.error};for(let e of s)console[e]=m(e,l[e]);s.includes(`log`)&&(u=process.stdout.write,process.stdout.write=h(`log`,`stdout`,u)),s.includes(`error`)&&(d=process.stderr.write,process.stderr.write=h(`error`,`stderr`,d))}},stop(){if(l!==null){for(let e of s)console[e]=l[e];l=null,u!==null&&(process.stdout.write=u,u=null),d!==null&&(process.stderr.write=d,d=null)}}}}function o(...e){return{entries:e.flatMap(e=>e.entries).sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}}function s(){return{entries:[]}}export{s as n,o as r,a as t};
@@ -1 +1 @@
1
- import"./register-BXOytPt7.js";import{t as e}from"./prompt-CqmGq1_N.js";import{confirm as t,isCancel as n,password as r,select as i,text as a}from"@clack/prompts";function o(){return{text:e=>a({message:e.message,...e.placeholder!==void 0&&{placeholder:e.placeholder}}),password:e=>r(e),confirm:e=>t(e),select:e=>i(e),isCancelled:n}}const s=(t,n)=>e(t,n,{adapter:o()});export{s as prompt};
1
+ import"./register-TbOCQNeI.js";import{t as e}from"./prompt-CqmGq1_N.js";import{confirm as t,isCancel as n,password as r,select as i,text as a}from"@clack/prompts";function o(){return{text:e=>a({message:e.message,...e.placeholder!==void 0&&{placeholder:e.placeholder}}),password:e=>r(e),confirm:e=>t(e),select:e=>i(e),isCancelled:n}}const s=(t,n)=>e(t,n,{adapter:o()});export{s as prompt};
@@ -1 +1 @@
1
- import"./register-BXOytPt7.js";import{t as e}from"./prompt-CqmGq1_N.js";import{confirm as t,input as n,password as r,select as i}from"@inquirer/prompts";const a=Symbol(`inquirer-cancel`);async function o(e){try{return await e()}catch(e){if(e instanceof Error&&e.name===`ExitPromptError`)return a;throw e}}function s(){return{text:e=>o(()=>n({message:e.message,...e.placeholder!==void 0&&{default:e.placeholder}})),password:e=>o(()=>r({message:e.message})),confirm:e=>o(()=>t({message:e.message})),select:e=>o(()=>i({message:e.message,choices:e.options.map(e=>({name:e.label,value:e.value}))})),isCancelled:e=>e===a}}const c=(t,n)=>e(t,n,{adapter:s()});export{c as prompt};
1
+ import"./register-TbOCQNeI.js";import{t as e}from"./prompt-CqmGq1_N.js";import{confirm as t,input as n,password as r,select as i}from"@inquirer/prompts";const a=Symbol(`inquirer-cancel`);async function o(e){try{return await e()}catch(e){if(e instanceof Error&&e.name===`ExitPromptError`)return a;throw e}}function s(){return{text:e=>o(()=>n({message:e.message,...e.placeholder!==void 0&&{default:e.placeholder}})),password:e=>o(()=>r({message:e.message})),confirm:e=>o(()=>t({message:e.message})),select:e=>o(()=>i({message:e.message,choices:e.options.map(e=>({name:e.label,value:e.value}))})),isCancelled:e=>e===a}}const c=(t,n)=>e(t,n,{adapter:s()});export{c as prompt};
package/dist/prompt.js CHANGED
@@ -1 +1 @@
1
- import"./register-BXOytPt7.js";import{i as e,n as t,r as n,t as r}from"./prompt-CqmGq1_N.js";export{n as getFieldsToPrompt,t as isInteractive,r as promptMissingArgs,e as resolvePromptConfig};
1
+ import"./register-TbOCQNeI.js";import{i as e,n as t,r as n,t as r}from"./prompt-CqmGq1_N.js";export{n as getFieldsToPrompt,t as isInteractive,r as promptMissingArgs,e as resolvePromptConfig};
@@ -0,0 +1 @@
1
+ import{r as e,s as t}from"./field-meta-D9ySul7J.js";const n=/* @__PURE__ */ new WeakMap;function r(e,t){return t&&n.set(e,t),e}function i(e){return n.get(e)}function a(e,t=/* @__PURE__ */ new Set){if(t.has(e))return;t.add(e);let n=i(e);if(n)return n;if(typeof e.meta==`function`){let t=e.meta();if(t&&typeof t==`object`)return t}let r=e,s=r.def??r._def;if(s?.argMeta)return s.argMeta;if(s?.meta)return s.meta;let c=o(e);if(c===`optional`||c===`nullable`||c==="default"){let e=s?.innerType;if(e)return a(e,t)}if(c===`pipe`){let e=s?.in??s?.schema;if(e)return a(e,t)}}function o(e){let t=e;return t.def?.type??t._def?.type??t.type}function s(e){let t=c(e),n=(t.def??t._def)?.catchall;if(!n)return`strip`;let r=o(n);return r===`never`?`strict`:r===`unknown`||r===`any`?`passthrough`:`strip`}function c(e){let t=o(e),n=e,r=n.def??n._def;if(t===`optional`||t===`nullable`||t==="default"){let e=r?.innerType;if(e)return c(e)}if(t===`pipe`){let e=r?.in??r?.schema;if(e)return c(e)}return e}function l(e){switch(o(c(e))){case`string`:case`enum`:return`string`;case`number`:case`int`:return`number`;case`boolean`:return`boolean`;case`array`:return`array`;default:return`unknown`}}function u(e){let t=c(e),n=o(t),r=t,i=r.def??r._def;if(n===`enum`){let e=i?.entries;if(e&&typeof e==`object`)return Object.values(e);let t=i?.values;if(Array.isArray(t))return t;let n=r.options;if(Array.isArray(n))return n}if(n===`array`){let e=i?.element;if(e)return u(e)}if(n===`union`){let e=i?.options;if(Array.isArray(e)){let t=[];for(let n of e)if(o(n)===`literal`){let e=n.def??n._def,r=e?.value,i=e?.values,a=r??i?.[0];typeof a==`string`&&t.push(a)}if(t.length===e.length&&t.length>0)return t}}}function d(e){return!e.isOptional()}function f(e){let t=o(e),n=e,r=n.def??n._def;if(t==="default"){let e=r?.defaultValue;return typeof e==`function`?e():e}if(t===`optional`||t===`nullable`){let e=r?.innerType;if(e)return f(e)}if(t===`pipe`){let e=r?.in??r?.schema;if(e)return f(e)}}function p(e){if(e.description)return e.description;let t=o(e),n=e,r=n.def??n._def;if(t===`optional`||t===`nullable`||t==="default"){let e=r?.innerType;if(e)return p(e)}if(t===`pipe`){let e=r?.in??r?.schema;if(e)return p(e)}}function m(t,n){let r=a(n);return e(t,{argMeta:r,description:p(n),required:d(n),defaultValue:f(n),type:l(n),enumValues:u(n),schema:n})}function h(e){let t=e;return(t.def??t._def)?.shape??t.shape??{}}function g(e){let t=h(e);return Object.entries(t).map(([e,t])=>m(e,t))}function _(e){let t=e,n=t.def??t._def,r=n?.discriminator??``,i=n?.options??[],a=/* @__PURE__ */ new Map,c=[];for(let e of i){let t=h(e),n=[],i=``,s=t[r];if(s){let e=o(s);if(e===`literal`){let e=s.def??s._def,t=e?.value,n=e?.values;i=String(t??n?.[0]??``)}else if(e===`enum`){let e=u(s);e&&e.length===1&&(i=e[0])}}for(let[e,r]of Object.entries(t)){let t=m(e,r);n.push(t),a.has(e)||a.set(e,t)}let l=p(e);c.push({discriminatorValue:i,fields:n,...l?{description:l}:{}})}let l=p(e);return{fields:Array.from(a.values()),schema:e,schemaType:`discriminatedUnion`,unknownKeysMode:s(e),discriminator:r,variants:c,...l?{description:l}:{}}}function v(e,t){let n=e,r=(n.def??n._def)?.options??[],i=/* @__PURE__ */ new Map,a=[];for(let e of r){let t=x(e);a.push(t);for(let e of t.fields)i.has(e.name)||i.set(e.name,e)}let o=p(e);return{fields:Array.from(i.values()),schema:e,schemaType:t,unknownKeysMode:s(e),unionOptions:a,...o?{description:o}:{}}}function y(e){let t=e,n=t.def??t._def,r=n?.left,i=n?.right,a=/* @__PURE__ */ new Map,o=e=>{if(!e)return;let t=x(e);for(let e of t.fields)a.has(e.name)||a.set(e.name,e)};o(r),o(i);let c=p(e);return{fields:Array.from(a.values()),schema:e,schemaType:`intersection`,unknownKeysMode:s(e),...c?{description:c}:{}}}const b=/* @__PURE__ */ new WeakMap;function x(e){let t=b.get(e);if(t)return t;let n=e,r,i=o(n),a=n,c=a.def??a._def;switch(i){case`object`:{let t=p(n);r={fields:g(n),schema:e,schemaType:`object`,unknownKeysMode:s(n),...t?{description:t}:{}};break}case`union`:r=c?.discriminator?_(n):v(n,`union`);break;case`xor`:r=v(n,`xor`);break;case`intersection`:r=y(n);break;case`optional`:case`nullable`:case`default`:case`pipe`:{let t=c?.innerType??c?.in??c?.schema;if(t){let i=x(t),a=p(n);r={...i,schema:e,...a?{description:a}:{}};break}let i=p(n);r={fields:[],schema:e,schemaType:`object`,unknownKeysMode:s(n),...i?{description:i}:{}};break}default:{let t=p(n);r={fields:[],schema:e,schemaType:`object`,unknownKeysMode:s(n),...t?{description:t}:{}};break}}return b.set(e,r),r}function S(e){return e.issues.map(e=>({path:e.path.map(String),message:e.message,code:e.code,received:`received`in e?e.received:void 0,expected:`expected`in e?String(e.expected):void 0}))}function C(e,t){let n=t.safeParse(e);return n.success?{success:!0,data:n.data}:{success:!1,errors:S(n.error)}}t({vendor:`zod`,extractFields:x,resolveFieldMeta:(e,t)=>m(e,t),getUnknownKeysMode:e=>s(e),validate:C});export{r as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./runner-CBG2DbVY.js";export{e as runCommand};
@@ -0,0 +1,30 @@
1
+ import{a as e,i as t,n,o as r,t as i}from"./field-meta-D9ySul7J.js";import{a,c as o,f as s,l as c,n as l,o as u,p as d,r as f,s as p,t as m}from"./schema-extractor-fZZ2_WAZ.js";import{n as h}from"./compile-cache-6u9hgeWu.js";import{n as g,r as _,t as v}from"./log-collector-uhRWYT-z.js";import{a as ee,c as y,n as b,o as x,r as S,t as C}from"./subcommand-router-DR2KBQAt.js";import{a as w,i as T}from"./logger-CoeDrmRr.js";import{a as E,i as D,n as O,o as k,r as A,s as j,t as M}from"./argv-parser-CawJSYjw.js";import{stripVTControlCharacters as N}from"node:util";async function P(e,t,n={}){let r,i,a=n.captureLogs??!1?v():null;a?.start();let o={args:t},s={args:t,error:r},c;n.handleSignals&&(c=async t=>{c&&(process.off(`SIGINT`,c),process.off(`SIGTERM`,c));let r=/* @__PURE__ */ Error(`Process interrupted`);if(s.error=r,e.cleanup)try{await e.cleanup(s)}catch(e){console.error(`Error during signal cleanup:`,e)}if(n.globalCleanup)try{await n.globalCleanup({error:r})}catch(e){console.error(`Error during global signal cleanup:`,e)}a?.stop(),process.stdout.writableNeedDrain&&await new Promise(e=>{let t=setTimeout(()=>{process.stdout.off(`drain`,n),e()},200),n=()=>{clearTimeout(t),e()};process.stdout.once(`drain`,n)}),process.exit(1)},process.on(`SIGINT`,c),process.on(`SIGTERM`,c));try{e.setup&&await e.setup(o),e.run&&(i=await e.run(t))}catch(e){r=e instanceof Error?e:Error(String(e))}finally{c&&(process.off(`SIGINT`,c),process.off(`SIGTERM`,c))}if(e.cleanup){s.error=r;try{await e.cleanup(s)}catch(e){r||=e instanceof Error?e:Error(String(e))}}a?.stop();let l=n.existingLogs??g(),u=a?.getLogs()??g(),d=_(l,u);return r?{success:!1,error:r,exitCode:1,logs:d}:{success:!0,result:i,exitCode:0,logs:d}}function te(e){return e<=31||e>=127&&e<=159||e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071||e===8203||e>=8204&&e<=8207||e===65279||e>=65024&&e<=65039||e>=917760&&e<=917999}function ne(e){return e>=4352&&e<=4447||e>=11904&&e<=12350||e>=12353&&e<=13311||e>=13312&&e<=19903||e>=19968&&e<=40959||e>=40960&&e<=42191||e>=43360&&e<=43391||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=110592&&e<=110959||e>=127488&&e<=127569||e>=131072&&e<=262141||e>=9728&&e<=10175||e>=126976&&e<=129791}function re(e){let t=!1,n=!1,r=!1;for(let i of e){let e=i.codePointAt(0);if(e===65039){r=!0;continue}te(e)||(t=!0,ne(e)&&(n=!0))}return t?n||r?2:1:0}const ie=(()=>{try{return new Intl.Segmenter(`en`,{granularity:`grapheme`})}catch{return}})();function F(e){if(e.length===0)return 0;let t=e.includes(`\x1B`)||e.includes(`›`)?N(e):e,n=0;if(ie)for(let{segment:e}of ie.segment(t))n+=re(e);else for(let e of t)n+=re(e);return n}function I(e){let t=[],n=e.replace(/`([^`]+)`/g,(e,n)=>{let r=t.length;return t.push(T.cyan(n)),`\x00CODE${r}\x00`});return n=n.replace(/\*\*(.+?)\*\*/g,(e,t)=>T.bold(t)),n=n.replace(/__(.+?)__/g,(e,t)=>T.bold(t)),n=n.replace(/\*(.+?)\*/g,(e,t)=>T.italic(t)),n=n.replace(/(?<!\w)_(.+?)_(?!\w)/g,(e,t)=>T.italic(t)),n=n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(e,t,n)=>`${T.underline(t)} ${T.dim(`(${n})`)}`),n=n.replace(/\x00CODE(\d+)\x00/g,(e,n)=>t[Number(n)]),n}function ae(e){return he(e.split(`
2
+ `)).map(be).join(`
3
+
4
+ `)}const oe=/^(#{1,6})\s+(.+)$/,se=/^(?:---+|\*\*\*+|___+)\s*$/,ce=/^>\s?(.*)$/,le=/^-\s+(.+)$/,ue=/^(\d+)[.)]\s+(.+)$/,de=/^(`{3,}|~{3,})(\S*)\s*$/,fe=/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/,pe=/^\|(.+)\|$/,me=/^\|(\s*:?-+:?\s*\|)+$/;function he(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.trim()===``){n++;continue}let i=r.match(de);if(i){let r=i[1],a=i[2]??``,o=[];for(n++;n<e.length;){if(e[n].startsWith(r.charAt(0).repeat(r.length))&&e[n].trim()===r.charAt(0).repeat(Math.max(r.length,e[n].trim().length))){n++;break}o.push(e[n]),n++}t.push({type:`code`,lang:a,lines:o});continue}let a=r.match(oe);if(a){t.push({type:`heading`,level:a[1].length,content:a[2]}),n++;continue}if(se.test(r)){t.push({type:`hr`}),n++;continue}if(ce.test(r)){let r=[];for(;n<e.length;){let t=e[n].match(ce);if(t)r.push(t[1]),n++;else break}if(r.length>0){let e=r[0].match(fe);if(e){let n=r.slice(1).filter(e=>e!==``);t.push({type:`alert`,alertType:e[1],lines:n});continue}}t.push({type:`blockquote`,lines:r});continue}if(le.test(r)){let r=[];for(;n<e.length;){let t=e[n].match(le);if(t)r.push(t[1]),n++;else break}t.push({type:`ul`,items:r});continue}let o=r.match(ue);if(o){let r=Number(o[1]),i=[];for(;n<e.length;){let t=e[n].match(ue);if(t)i.push(t[2]),n++;else break}t.push({type:`ol`,items:i,start:r});continue}if(pe.test(r)&&n+1<e.length&&me.test(e[n+1])){let i=ge(r),a=_e(e[n+1]);n+=2;let o=[];for(;n<e.length&&pe.test(e[n]);)o.push(ge(e[n])),n++;t.push({type:`table`,headers:i,alignments:a,rows:o});continue}let s=[];for(;n<e.length;){let t=e[n];if(t.trim()===``||oe.test(t)||se.test(t)||ce.test(t)||le.test(t)||ue.test(t)||de.test(t)||pe.test(t)&&n+1<e.length&&me.test(e[n+1]))break;s.push(t),n++}s.length>0&&t.push({type:`paragraph`,lines:s})}return t}function ge(e){return e.slice(1,-1).split(`|`).map(e=>e.trim())}function _e(e){return e.slice(1,-1).split(`|`).map(e=>{let t=e.trim();return t.startsWith(`:`)&&t.endsWith(`:`)?`center`:t.endsWith(`:`)?`right`:`left`})}function ve(e,t,n){let r=F(e),i=Math.max(0,t-r);if(n===`right`)return` `.repeat(i)+e;if(n===`center`){let t=Math.floor(i/2);return` `.repeat(t)+e+` `.repeat(i-t)}return e+` `.repeat(i)}const ye={NOTE:{icon:`ℹ`,label:`Note`,styleFn:T.cyan},TIP:{icon:`💡`,label:`Tip`,styleFn:T.green},IMPORTANT:{icon:`❗`,label:`Important`,styleFn:T.magenta},WARNING:{icon:`⚠`,label:`Warning`,styleFn:T.yellow},CAUTION:{icon:`🔴`,label:`Caution`,styleFn:T.red}};function be(e){switch(e.type){case`heading`:return T.green(T.bold(I(e.content)));case`hr`:return T.dim(`─`.repeat(40));case`blockquote`:{let t=T.dim(`│ `);return e.lines.map(e=>`${t}${I(e)}`).join(`
5
+ `)}case`alert`:{let{icon:t,label:n,styleFn:r}=ye[e.alertType],i=r(T.bold(`│`))+` `,a=`${i}${r(t)} ${r(n)}`;return e.lines.length===0?a:`${a}\n${e.lines.map(e=>`${i}${I(e)}`).join(`
6
+ `)}`}case`ul`:return e.items.map(e=>`${T.dim(`•`)} ${I(e)}`).join(`
7
+ `);case`ol`:{let t=e.start+e.items.length-1,n=String(t).length;return e.items.map((t,r)=>{let i=String(e.start+r).padStart(n,` `);return`${T.dim(`${i}.`)} ${I(t)}`}).join(`
8
+ `)}case`table`:{let t=e.headers.length,n=e.headers.map(e=>I(e)),r=e.rows.map(e=>Array.from({length:t},(t,n)=>I(e[n]??``))),i=n.map((e,t)=>{let n=F(e),i=r.map(e=>F(e[t]));return Math.max(n,...i)}),a=T.dim(`│`),o=T.dim(`┌─${i.map(e=>`─`.repeat(e)).join(`─┬─`)}─┐`),s=T.dim(`├─${i.map(e=>`─`.repeat(e)).join(`─┼─`)}─┤`),c=T.dim(`└─${i.map(e=>`─`.repeat(e)).join(`─┴─`)}─┘`);return[o,`${a} ${n.map((t,n)=>T.bold(ve(t,i[n],e.alignments[n]??`left`))).join(` ${a} `)} ${a}`,s,...r.map(t=>{let n=t.map((t,n)=>ve(t,i[n],e.alignments[n]??`left`));return`${a} ${n.join(` ${a} `)} ${a}`}),c].join(`
9
+ `)}case`code`:return e.lines.map(e=>` ${T.yellow(e)}`).join(`
10
+ `);case`paragraph`:return I(e.lines.join(` `))}}const L={help:`Show help`,helpAll:`Show help with all subcommand options`,helpJson:`Show help as JSON`,version:`Show version`};function xe(e){return!e.startsWith(`__`)}function R(e){return Object.entries(e).filter(([e])=>xe(e))}function Se(e,t){return t?.rootName&&t.commandPath&&t.commandPath.length>0?t.commandPath.join(` `):e.name??`command`}function Ce(e,t){return t?.rootName&&t.commandPath&&t.commandPath.length>0?`${t.rootName} ${t.commandPath.join(` `)}`:e.name??`command`}function we(e,t){let n=[],r=Ce(e,t);n.push(T.commandName(r)),t?.globalExtracted?.fields.length&&n.push(T.placeholder(`[global options]`));let i=f(e);if(i){let t=o(i);p(i).length>0&&n.push(T.placeholder(`[options]`)),e.subCommands&&R(e.subCommands).length>0&&(e.run||e.defaultSubCommand?n.push(T.placeholder(`[command]`)):n.push(T.option(`<command>`)));for(let e of t)e.required?n.push(T.option(`<${e.name}>`)):n.push(T.placeholder(`[${e.name}]`))}else e.subCommands&&R(e.subCommands).length>0&&(e.run||e.defaultSubCommand?n.push(T.placeholder(`[command]`)):n.push(T.option(`<command>`)));return n.join(` `)}function Te(e,t){let n=`${T.dim(`When`)} ${T.option(e)}=${T.bold(t.discriminatorValue)}:`;return t.description?`${n} ${t.description}`:n}function Ee(e,t){return` ${T.bold(`${e.description??`Variant ${t+1}`}:`)}`}function De(e,t=0){let n=e.required?T.option(`<${e.name}>`):T.placeholder(`[${e.name}]`),r=e.named?`${n}, ${B(e)}`:n,i=[e.description,e.defaultValue===void 0?void 0:T.defaultValue(`(default: ${JSON.stringify(e.defaultValue)})`)].filter(Boolean).join(` `);return i?H(r,i,t):`${` `.repeat(t)} ${r}`}function Oe(e){let t=f(e);if(!t)return``;let n=[];if(t.schemaType===`discriminatedUnion`&&t.discriminator){let e=t.discriminator;n=(t.variants??[]).map(t=>({label:Te(e,t),fields:t.fields}))}else(t.schemaType===`union`||t.schemaType===`xor`)&&t.unionOptions&&(n=t.unionOptions.map((e,t)=>({label:Ee(e,t),fields:e.fields})));let r=n.length>0?m(n):void 0,i=t.fields.filter(e=>e.positional&&(r===void 0||r.has(e.name))).map(e=>De(e));for(let e of n){let t=e.fields.filter(e=>e.positional&&!r?.has(e.name));t.length!==0&&i.push(``,e.label,...t.map(e=>De(e,1)))}return i.join(`
11
+ `)}function ke(e,t={},r){let i=[],a={help:t.help??L.help,helpAll:t.helpAll??L.helpAll,helpJson:t.helpJson??L.helpJson,version:t.version??L.version},o=f(e),s=o?.fields.some(e=>e.overrideBuiltinAlias===!0&&n(e).includes(`h`))??!1,c=o?.fields.some(e=>e.overrideBuiltinAlias===!0&&n(e).includes(`H`))??!1;if(s?i.push(H(T.option(`--help`),a.help)):i.push(H(`${T.option(`-h`)}, ${T.option(`--help`)}`,a.help)),c?i.push(H(T.option(`--help-all`),a.helpAll)):i.push(H(`${T.option(`-H`)}, ${T.option(`--help-all`)}`,a.helpAll)),i.push(H(T.option(`--help-json`),a.helpJson)),r?.rootVersion&&i.push(H(T.option(`--version`),a.version)),!o)return i.join(`
12
+ `);if(o.schemaType===`discriminatedUnion`&&o.discriminator)return Ae(o,e,i);if(o.schemaType===`union`&&o.unionOptions||o.schemaType===`xor`&&o.unionOptions)return je(o,e,i);let l=[],u=o.fields.filter(e=>!e.positional);for(let e of u){let t=B(e),n=e.description??``;e.defaultValue!==void 0&&(n+=` ${T.defaultValue(`(default: ${JSON.stringify(e.defaultValue)})`)}`),e.required&&(n+=` ${T.required(`(required)`)}`);let r=V(e.env);r&&(n+=` ${r}`),l.push(H(t,n));let i=z(e);i&&l.push(i)}return l.push(...i),l.join(`
13
+ `)}function z(e,t=0,n=0){return!e.negationDisplay||!e.negationDescription?null:H(T.option(`--${e.negationDisplay}`),`${e.negationDescription} ${T.dim(`(↔ --${e.cliName})`)}`,t,n)}function Ae(e,t,n){let r=[],i=e.discriminator,a=e.variants??[],o=u(e,i);if(o){let t=a.map(e=>e.discriminatorValue).join(`|`),n=`${T.option(`--${i}`)} ${T.placeholder(`<${t}>`)}`,s=e.description??o.description??`Action to perform`;r.push(H(n,s))}let s=m(a,i);for(let t of s){let n=e.fields.find(e=>e.name===t);if(n&&!n.positional){let e=B(n),t=n.description??``;n.defaultValue!==void 0&&(t+=` ${T.defaultValue(`(default: ${JSON.stringify(n.defaultValue)})`)}`);let i=V(n.env);i&&(t+=` ${i}`),r.push(H(e,t));let a=z(n);a&&r.push(a)}}r.push(...n);for(let e of a){let t=e.fields.filter(e=>e.name!==i&&!s.has(e.name)&&!e.positional);if(t.length>0){r.push(``),r.push(Te(i,e));for(let e of t){let t=B(e),n=e.description??``;e.defaultValue!==void 0&&(n+=` ${T.defaultValue(`(default: ${JSON.stringify(e.defaultValue)})`)}`),e.required&&(n+=` ${T.required(`(required)`)}`);let i=V(e.env);i&&(n+=` ${i}`),r.push(H(t,n,1));let a=z(e,1);a&&r.push(a)}}}return r.join(`
14
+ `)}function je(e,t,n){let r=[],i=e.unionOptions??[],a=m(i);for(let t of a){let n=e.fields.find(e=>e.name===t);if(n&&!n.positional){let e=B(n),t=n.description??``;n.defaultValue!==void 0&&(t+=` ${T.defaultValue(`(default: ${JSON.stringify(n.defaultValue)})`)}`);let i=V(n.env);i&&(t+=` ${i}`),r.push(H(e,t));let a=z(n);a&&r.push(a)}}r.push(...n);for(let e=0;e<i.length;e++){let t=i[e];if(!t)continue;let n=t.fields.filter(e=>!a.has(e.name)&&!e.positional),o=Ee(t,e);if(n.length>0){r.push(``),r.push(o);for(let e of n){let t=B(e),n=e.description??``;e.defaultValue!==void 0&&(n+=` ${T.defaultValue(`(default: ${JSON.stringify(e.defaultValue)})`)}`),e.required&&(n+=` ${T.required(`(required)`)}`);let i=V(e.env);i&&(n+=` ${i}`),r.push(H(t,n,1));let a=z(e,1);a&&r.push(a)}}else r.push(``),r.push(o),r.push(` ${T.dim(T.italic(`no options`))}`)}return r.join(`
15
+ `)}function B(e){let t=[];if(e.alias)for(let n of e.alias)n.length===1&&t.push(T.option(`-${n}`));let n=T.option(`--${e.cliName}`);if(e.type!==`boolean`){let t=e.placeholder??e.cliName.toUpperCase();n+=` ${T.placeholder(`<${t}>`)}`}if(t.push(n),e.alias){for(let n of e.alias)if(n.length>1){let r=T.option(`--${n}`);if(e.type!==`boolean`){let t=e.placeholder??e.cliName.toUpperCase();r+=` ${T.placeholder(`<${t}>`)}`}t.push(r)}}let r=t.join(`, `);return e.type===`boolean`&&e.negationDisplay&&!e.negationDescription?`${r} / ${T.option(`--${e.negationDisplay}`)}`:r}function V(e){if(!e)return``;let t=Array.isArray(e)?e:[e];return T.dim(`[env: ${t.join(`, `)}]`)}function Me(e){return e.replace(/\x1B\[[0-9;]*m/g,``)}function Ne(e,t){let n=Me(e).length,r=Math.max(0,t-n);return e+` `.repeat(r)}function Pe(e,t){if(!e.includes(`
16
+ `))return e;let n=` `.repeat(t);return e.split(`
17
+ `).join(`\n${n}`)}function H(e,t,n=0,r=0){let i=` `.repeat(n),a=Me(e).length,o=32-n*2+r,s=o+2+n*2,c=Pe(t,s);return a>=o?`${i} ${e}\n${` `.repeat(s)}${c}`:`${i} ${Ne(e,o)}${c}`}function Fe(e,t=0,n=0){let r=B(e),i=e.description??``;e.defaultValue!==void 0&&(i+=` ${T.defaultValue(`(default: ${JSON.stringify(e.defaultValue)})`)}`),e.required&&(i+=` ${T.required(`(required)`)}`);let a=V(e.env);return a&&(i+=` ${a}`),H(r,i,t,n)}function Ie(e){let t=[];for(let n of e.fields){if(n.positional)continue;t.push(Fe(n));let e=z(n);e&&t.push(e)}return t.join(`
18
+ `)}function Le(e,t){let n=[],r=f(e);if(r){let e=r.fields.filter(e=>!e.positional);for(let r of e){let e=B(r),i=r.description??``;r.defaultValue!==void 0&&(i+=` ${T.defaultValue(`(default: ${JSON.stringify(r.defaultValue)})`)}`);let a=V(r.env);a&&(i+=` ${a}`),n.push(H(e,i,t,2));let o=z(r,t,2);o&&n.push(o)}}return n}function Re(e,t,n){let r=[];for(let[i,a]of R(e)){let e=y(a),o=t?`${t} ${i}`:i,s=e?.description??``,c=e?.aliases,l=c&&c.length>0?`${o}, ${c.join(`, `)}`:o;if(r.push(H(T.command(l),s,n)),e){let t=Le(e,n+1);r.push(...t);let i=e.subCommands?Object.fromEntries(R(e.subCommands)):void 0;if(i&&Object.keys(i).length>0){let e=Re(i,o,n);r.push(...e)}}}return r}function U(e,t){let n=[],r=t.context,i=Se(e,r);if(i){let e=T.commandName(i);r?.rootName&&r.commandPath&&r.commandPath.length>0?r.rootVersion?e+=` ${T.version(`(${r.rootName} v${r.rootVersion})`)}`:e+=` ${T.version(`(${r.rootName})`)}`:r?.rootVersion&&(e+=` ${T.version(`v${r.rootVersion}`)}`),n.push(e)}r?.aliasFor&&n.push(T.dim(`Alias for ${T.commandName(r.aliasFor)}`)),e.description&&n.push(e.description),!r?.aliasFor&&e.aliases&&e.aliases.length>0&&n.push(`${T.sectionHeader(`Aliases:`)} ${e.aliases.map(e=>T.command(e)).join(`, `)}`),n.push(`${T.sectionHeader(`Usage:`)} ${we(e,r)}`);let a=Oe(e);a&&n.push(`${T.sectionHeader(`Arguments:`)}\n${a}`);let o=ke(e,t.descriptions,r);if(o&&n.push(`${T.sectionHeader(`Options:`)}\n${o}`),r?.globalExtracted?.fields.length&&n.push(`${T.sectionHeader(`Global Options:`)}\n${Ie(r.globalExtracted)}`),t.showSubcommands!==!1&&e.subCommands&&R(e.subCommands).length>0){let i=r?.commandPath?.join(` `)??``,a=Object.fromEntries(R(e.subCommands));if(t.showSubcommandOptions){let e=Re(a,i,0);n.push(`${T.sectionHeader(`Commands:`)}\n${e.join(`
19
+ `)}`)}else{let e=[];for(let[t,n]of Object.entries(a)){let r=y(n),a=r?.description??``,o=i?`${i} ${t}`:t,s=r?.aliases,c=s&&s.length>0?`${o}, ${s.join(`, `)}`:o;e.push(H(T.command(c),a))}n.push(`${T.sectionHeader(`Commands:`)}\n${e.join(`
20
+ `)}`)}}if(e.examples&&e.examples.length>0){let t=Be(e.examples,r);n.push(`${T.sectionHeader(`Examples:`)}\n${t}`)}if(e.notes){let t=ae(e.notes).split(`
21
+ `).map(e=>e===``?``:` ${e}`).join(`
22
+ `);n.push(`${T.sectionHeader(`Notes:`)}\n${t}`)}return`\n${n.join(`
23
+
24
+ `)}\n`}function W(e){let t={name:e.name,cliName:e.cliName,positional:e.positional,named:e.named,required:e.required,type:e.type};return e.alias&&(t.alias=e.alias),e.description!==void 0&&(t.description=e.description),e.placeholder!==void 0&&(t.placeholder=e.placeholder),e.env!==void 0&&(t.env=e.env),e.defaultValue!==void 0&&(t.defaultValue=e.defaultValue),e.enumValues!==void 0&&(t.enumValues=e.enumValues),e.negation!==void 0&&(t.negation=e.negation),e.negationDisplay!==void 0&&(t.negationDisplay=e.negationDisplay),e.negationDescription!==void 0&&(t.negationDescription=e.negationDescription),t}function ze(e,t){let n=Ce(e,t),r=!!t?.globalExtracted?.fields.length,i=e.subCommands&&R(e.subCommands).length>0?e.run?`optional`:`required`:void 0,a=f(e);return{commandName:n,hasGlobalOptions:r,hasOptions:a?p(a).length>0:!1,subcommand:i,positionals:a?o(a).map(e=>({name:e.name,required:e.required})):[]}}function G(e,t={}){let n=t.context,r=n?.commandPath??[],i={help:t.descriptions?.help??L.help,helpAll:t.descriptions?.helpAll??L.helpAll,helpJson:t.descriptions?.helpJson??L.helpJson,...n?.rootVersion?{version:t.descriptions?.version??L.version}:{}},a=f(e),s,c=[],l=[],d,p,h;if(a){if(s=a.schemaType,c=o(a).map(W),a.schemaType===`discriminatedUnion`&&a.discriminator&&a.variants){let e=a.discriminator;d=e;let t=a.variants,n=m(t,e),r=u(a,e),i=a.fields.filter(e=>!e.positional&&n.has(e.name));l=[...r?[{...W(r),description:a.description??r.description??`Action to perform`}]:[],...i.map(W)],p=t.map(t=>({discriminatorValue:t.discriminatorValue,description:t.description,fields:t.fields.filter(t=>t.name!==e&&!n.has(t.name)).map(W)}))}else if((a.schemaType===`union`||a.schemaType===`xor`)&&a.unionOptions){let e=a.unionOptions,t=m(e);l=a.fields.filter(e=>!e.positional&&t.has(e.name)).map(W),h=e.map(e=>({description:e.description,fields:e.fields.filter(e=>!t.has(e.name)).map(W)}))}else l=a.fields.filter(e=>!e.positional).map(W)}let g=n?.globalExtracted?.fields.length?n.globalExtracted.fields.filter(e=>!e.positional).map(W):void 0,_;if(e.subCommands){let i=R(e.subCommands);i.length>0&&(_=i.map(([i,a])=>{let o=y(a);if(!o)return{name:i,unresolved:!0};let s={commandPath:[...r,i],rootName:n?.rootName??e.name,rootVersion:n?.rootVersion,globalExtracted:n?.globalExtracted};return{name:i,aliases:o.aliases,data:G(o,{descriptions:t.descriptions,context:s})}}))}return{name:e.name??`command`,commandPath:r,rootName:n?.rootName,version:n?.rootVersion,aliasFor:n?.aliasFor,description:e.description,aliases:e.aliases,usage:ze(e,n),builtinOptions:i,schemaType:s,positionals:c,options:l,discriminator:d,variants:p,unionOptions:h,globalOptions:g,subcommands:_,examples:e.examples,notes:e.notes}}function Be(e,t){let n=[],r=t?.rootName?`${t.rootName} `:``,i=t?.commandPath?.join(` `)??``,a=i?`${r}${i} `:r;for(let t of e){if(n.push(` ${T.dim(t.desc).split(`
25
+ `).join(`
26
+ `)}`),n.push(` ${T.dim(`$`)} ${a}${t.cmd}`),t.output)for(let e of t.output.split(`
27
+ `))n.push(` ${e}`);n.push(``)}return n.length>0&&n[n.length-1]===``&&n.pop(),n.join(`
28
+ `)}var Ve=class extends Error{constructor(e){super(e),this.name=`PositionalConfigError`}},He=class extends Error{constructor(e){super(e),this.name=`ReservedAliasError`}},Ue=class extends Error{constructor(e){super(e),this.name=`DuplicateFieldError`}},We=class extends Error{constructor(e){super(e),this.name=`DuplicateAliasError`}},K=class extends Error{constructor(e){super(e),this.name=`CaseVariantCollisionError`}},Ge=class extends Error{constructor(e){super(e),this.name=`DuplicateNegationError`}},Ke=class extends Error{constructor(e){super(e),this.name=`ReservedFieldNameError`}},qe=class extends Error{constructor(e){super(e),this.name=`DefaultSubCommandError`}},Je=class extends Error{constructor(e){super(e),this.name=`FieldTypeConflictError`}};function Ye(e,t){let n=[],r=/* @__PURE__ */ new Map;for(let i of e.fields)r.has(i.name)&&n.push({commandPath:t,type:`duplicate_field`,message:`Duplicate field name "${i.name}" detected.`,field:i.name}),r.set(i.name,i.name);return n}function Xe(e,n){let r=[],i=/* @__PURE__ */ new Map;for(let a of e.fields){let e=t(a.name),o=i.get(e);o&&o!==a.name&&r.push({commandPath:n,type:`case_variant_collision`,message:`Fields "${o}" and "${a.name}" are case variants of each other and would collide.`,field:a.name}),i.set(e,a.name)}return r}function Ze(e,r){let i=[],a=/* @__PURE__ */ new Map,o=new Set(e.fields.map(e=>e.name)),s=new Set(e.fields.map(e=>e.cliName)),c=(e,t,n)=>{(o.has(e)||s.has(e))&&i.push({commandPath:r,type:`duplicate_alias`,message:`Alias "${e}" for field "${t}" conflicts with existing field name or CLI name "${e}".`,field:t});let c=a.get(e);if(c&&c!==t){let a=n?` (derived camelCase variant)`:``;i.push({commandPath:r,type:`duplicate_alias`,message:`Duplicate alias "${e}"${a} detected. Both "${c}" and "${t}" use the same alias.`,field:t})}a.set(e,t)};for(let r of e.fields){let e=n(r);if(e.length!==0){for(let n of e)if(c(n,r.name,!1),n.length>1&&n.includes(`-`)){let e=t(n);e!==n&&!o.has(e)&&c(e,r.name,!0)}}}return i}function Qe(e,r){let i=[],a=/* @__PURE__ */ new Map,o=(e,t,n)=>{a.has(e)||a.set(e,{field:t,kind:n})};for(let r of e.fields){if(o(r.name,r.name,`field name`),r.name.includes(`-`)){let e=t(r.name);e!==r.name&&o(e,r.name,`field name`)}if(r.cliName!==r.name&&o(r.cliName,r.name,`CLI name`),r.cliName.includes(`-`)){let e=t(r.cliName);e!==r.cliName&&o(e,r.name,`CLI name`)}for(let e of n(r))if(o(e,r.name,`alias`),e.length>1&&e.includes(`-`)){let n=t(e);n!==e&&o(n,r.name,`alias`)}if(r.type===`boolean`&&r.negation===!0){let e=`no-${r.cliName}`;o(e,r.name,`default negation`);let n=t(r.cliName),i=`no${n[0]?.toUpperCase()??``}${n.slice(1)}`;i!==e&&o(i,r.name,`default negation`)}}let s=/* @__PURE__ */ new Map,c=(e,t,n)=>{let o=a.get(e);if(o){let a=n?` (derived camelCase variant)`:``,s=o.field===t?`the same field's own ${o.kind} "${e}"`:`${o.kind} "${e}" of field "${o.field}"`;i.push({commandPath:r,type:`duplicate_negation`,message:`Negation "${e}"${a} for field "${t}" conflicts with ${s}.`,field:t})}let c=s.get(e);if(c&&c!==t){let a=n?` (derived camelCase variant)`:``;i.push({commandPath:r,type:`duplicate_negation`,message:`Duplicate negation "${e}"${a} detected. Both "${c}" and "${t}" use the same negation name.`,field:t})}s.set(e,t)};for(let n of e.fields)if(typeof n.negation==`string`&&(c(n.negation,n.name,!1),n.negation.includes(`-`))){let e=t(n.negation);e!==n.negation&&c(e,n.name,!0)}return i}function $e(e,t){let n=[e,...e.variants??[],...e.unionOptions??[]],r=/* @__PURE__ */ new Set;return n.flatMap(e=>et(e.fields,t)).filter(e=>!r.has(e.message)&&r.add(e.message))}function et(e,t){let n=[],r=e.filter(e=>e.positional),i=null,a=null;for(let e of r)i!==null&&n.push({commandPath:t,type:`positional_config`,message:`Positional argument "${e.name}" cannot follow array positional argument "${i}".`,field:e.name}),e.type===`array`&&a!==null&&n.push({commandPath:t,type:`positional_config`,message:`Array positional "${e.name}" cannot be used with optional positional "${a}" (ambiguous parsing).`,field:e.name}),a!==null&&e.required&&n.push({commandPath:t,type:`positional_config`,message:`Required positional "${e.name}" cannot follow optional positional "${a}".`,field:e.name}),e.type===`array`&&(i=e.name),e.required||(a=e.name);return n}function tt(e,t){let r=[];for(let a of e.fields){if(a.overrideBuiltinAlias!==!0)for(let e of n(a))(e===`h`||e===`H`)&&r.push({commandPath:t,type:`reserved_alias`,message:`Alias "${e}" is reserved for --${e===`h`?`help`:`help-all`}. To override this, set { overrideBuiltinAlias: true } for "${a.name}" and keep the alias where it is currently defined (in alias or hiddenAlias).`,field:a.name});let e=/* @__PURE__ */ new Set([a.cliName,...n(a)]);for(let n of e){if(!i.has(n))continue;let e=n===a.cliName;r.push({commandPath:t,type:`reserved_alias`,message:`${e?`Field "${a.name}"`:`Alias "${n}" for field "${a.name}"`} collides with the built-in --${n} option, which always takes precedence. Rename the field or its alias; this collision cannot be overridden.`,field:a.name})}}return r}function nt(e,t){let n=[];for(let r of e.fields)r.name.startsWith(`$`)&&n.push({commandPath:t,type:`reserved_field_name`,message:`Field "${r.name}" starts with "$", which is reserved for framework-injected helpers (e.g. $source).`,field:r.name});return n}function q(e){let t=Ye(e,[]);if(t.length>0)throw new Ue(`Duplicate field name "${t[0]?.field??`unknown`}" detected. Each field must have a unique name.`)}function J(e){let t=Ze(e,[]);if(t.length>0){let e=t[0];throw new We(e.message)}}function rt(e){let t=$e(e,[]);if(t.length>0){let e=t[0];throw new Ve(e.message)}}function Y(e,t){let n=tt(e,[]);if(n.length>0)throw new He(n[0].message)}function it(e){let t=nt(e,[]);if(t.length>0){let e=t[0];throw new Ke(e.message)}}function at(e){let t=Qe(e,[]);if(t.length>0){let e=t[0];throw new Ge(e.message)}}function ot(e){let t=Xe(e,[]);if(t.length>0){let e=t[0];throw new K(e.message)}}function st(e,t){if(e.type!==t.type||e.positional!==t.positional)return!1;let n=e.enumValues,r=t.enumValues;if(!n&&!r)return!0;if(!n||!r)return!1;let i=new Set(n),a=new Set(r);if(i.size!==a.size)return!1;for(let e of i)if(!a.has(e))return!1;return!0}function ct(e,n,r){let i=[],a=/* @__PURE__ */ new Map;for(let n of e.fields)a.set(t(n.name),n);for(let e of n.fields){let n=t(e.name),o=a.get(n);if(o){if(o.name!==e.name){i.push({commandPath:r,type:`case_variant_collision`,message:`Global field "${o.name}" and command field "${e.name}" are case variants of each other and would collide.`,field:e.name});continue}st(o,e)||i.push({commandPath:r,type:`field_type_conflict`,message:`Global field "${o.name}" and command field "${e.name}" share the same name but have different definitions.`,field:e.name})}}return i}function lt(e,t){let n=ct(e,t,[])[0];if(n)throw n.type===`case_variant_collision`?new K(n.message):new Je(n.message)}function ut(e,t,n){return[...Ye(e,n),...Xe(e,n),...Ze(e,n),...Qe(e,n),...$e(e,n),...tt(e,n),...nt(e,n)]}function dt(e,t){let n=e,r=[];if(n.defaultSubCommand===void 0)return r;n.run&&r.push({commandPath:t,type:`default_subcommand_conflict`,message:`Command "${n.name}" defines both "run" and "defaultSubCommand". Define only one.`});let i=e.subCommands?Object.keys(e.subCommands):[];return i.includes(n.defaultSubCommand)||r.push({commandPath:t,type:`default_subcommand_not_found`,message:`defaultSubCommand "${n.defaultSubCommand}" does not match any subCommands key of "${n.name}". Registered: ${i.length>0?i.join(`, `):`(none)`}.`,field:n.defaultSubCommand}),r}function ft(e){let t=dt(e,[]);if(t.length>0)throw new qe(t[0].message)}function pt(e,t){let n=[];if(!e.subCommands)return n;let r=/* @__PURE__ */ new Map;for(let[t]of Object.entries(e.subCommands))r.set(t,t);for(let[i,a]of Object.entries(e.subCommands)){let e=x(a)?a.meta:typeof a==`function`?null:a;if(!e?.aliases)continue;let o=[...t,i];for(let t of e.aliases){if(!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(t)){n.push({commandPath:o,type:`invalid_alias`,message:`Alias "${t}" is invalid. Aliases must start with an alphanumeric character and contain only alphanumeric characters, hyphens, or underscores.`,field:i});continue}if(t===i){n.push({commandPath:o,type:`duplicate_alias`,message:`Alias "${t}" conflicts with its own name.`,field:i});continue}let e=r.get(t);e?e===i?n.push({commandPath:o,type:`duplicate_alias`,message:`Alias "${t}" is duplicated within the alias list.`,field:i}):n.push({commandPath:o,type:`duplicate_alias`,message:`Alias "${t}" conflicts with existing subcommand or alias "${e}".`,field:i}):r.set(t,i)}}return n}function mt(e,t,n){return e===t?[]:[{commandPath:[...n,e],type:`subcommand_key_name_mismatch`,message:`Subcommand registered as "${e}" but its own name is "${t}".`,field:e}]}async function ht(e,t={}){let n=t.commandPath??[e.name],r=[],i=e.subCommands?Object.keys(e.subCommands).length>0:!1,a=t.globalArgs?l(t.globalArgs):void 0;if(e.args){let t=l(e.args);r.push(...ut(t,i,n)),a&&r.push(...ct(a,t,n))}if(r.push(...pt(e,n)),r.push(...dt(e,n)),e.subCommands)for(let[i,a]of Object.entries(e.subCommands)){let e=await S(a);r.push(...mt(i,e.name,n));let o=await ht(e,{commandPath:[...n,i],...t.globalArgs?{globalArgs:t.globalArgs}:{}});o.valid||r.push(...o.errors)}return r.length===0?{valid:!0}:{valid:!1,errors:r}}function gt(e){if(e.length===0)return``;let t=[`Command definition errors:`];for(let n of e){let e=n.commandPath.join(` > `);t.push(` - [${e}] ${n.message}`)}return t.join(`
29
+ `)}function _t(e){let{aliasMap:t=/* @__PURE__ */ new Map,booleanFlags:r=/* @__PURE__ */ new Set,definedNames:i=/* @__PURE__ */ new Set,negationMap:a=/* @__PURE__ */ new Map,defaultNegationDisabledFields:o=/* @__PURE__ */ new Set}=M(e),s=/* @__PURE__ */ new Set;for(let t of e.fields)for(let e of n(t))e.length===1&&s.add(e);return{aliasMap:t,booleanFlags:r,definedNames:i,flagNames:new Set(e.fields.map(e=>e.name)),cliNames:new Set(e.fields.map(e=>e.cliName)),aliases:s,negationMap:a,defaultNegationDisabledFields:o}}function vt(e,t){let{resolvedName:n,withoutDashes:r,isNegated:i,isCustomNegation:a,isSuppressedNegation:o}=k(e,t);if(o)return{resolvedName:n,withoutDashes:r,isNegated:!1,isGlobal:!1,isSuppressedNegation:o};let s=i&&!a?r.startsWith(`no-`)?r.slice(3):r[2].toLowerCase()+r.slice(3):r;return{resolvedName:n,withoutDashes:r,isNegated:i,isGlobal:t.flagNames.has(n)||t.cliNames.has(r)||t.cliNames.has(s),isSuppressedNegation:!1}}function yt(e,t,n,r,i){return!e.includes(`=`)&&!i.has(t)&&!n&&r!==void 0&&!r.startsWith(`-`)}function X(e,t,n,r,i,a){let o=e[t];return a.push(o),yt(o,n,r,e[t+1],i)?(a.push(e[t+1]),2):1}function bt(e,t,n){let r=_t(n),i=new Set(t),a=[],o=[],s=0;for(;s<e.length;){let t=e[s];if(t===`--`||xt.has(t))break;if(!t.startsWith(`-`)&&i.has(t))return{subCommandIndex:s,globalTokensBefore:a,tokensAfterSubcommand:e.slice(s+1),suppressedTokens:o};if(t.startsWith(`--`)){let{resolvedName:n,withoutDashes:i,isNegated:c,isGlobal:l,isSuppressedNegation:u}=vt(t,r);if(l){s+=X(e,s,n,c,r.booleanFlags,a);continue}if(u){o.push(i),s++;continue}break}if(t.startsWith(`-`)&&t.length>1){let n=t.includes(`=`)?t.slice(1,t.indexOf(`=`)):t.slice(1);if(n.length===1){let t=r.aliasMap.get(n)??n;if(r.aliases.has(n)||r.flagNames.has(t)){s+=X(e,s,t,!1,r.booleanFlags,a);continue}}break}break}return{subCommandIndex:-1,globalTokensBefore:a,tokensAfterSubcommand:[],suppressedTokens:o}}const xt=/* @__PURE__ */ new Set([`--help`,`-h`,`--help-all`,`-H`,`--help-json`,`--version`]);function St(e,t,n={}){let r=n.stopOnSuppressedNegation===!0||t?.unknownKeysMode===`strict`,i=t?_t(t):{aliasMap:/* @__PURE__ */ new Map,booleanFlags:/* @__PURE__ */ new Set,definedNames:/* @__PURE__ */ new Set,flagNames:/* @__PURE__ */ new Set,cliNames:/* @__PURE__ */ new Set,aliases:/* @__PURE__ */ new Set,negationMap:/* @__PURE__ */ new Map,defaultNegationDisabledFields:/* @__PURE__ */ new Set};for(let t=0;t<e.length;t++){let n=e[t];if(!n.startsWith(`-`))return t;if(n===`--`||xt.has(n))return-1;if(n.startsWith(`--`)){let{resolvedName:a,isNegated:o,isGlobal:s,isSuppressedNegation:c}=vt(n,i);if(s){yt(n,a,o,e[t+1],i.booleanFlags)&&t++;continue}if(c){if(r)return-1;continue}return-1}let a=n.includes(`=`)?n.slice(1,n.indexOf(`=`)):n.slice(1);if(a.length===1){let r=i.aliasMap.get(a)??a;if(i.aliases.has(a)||i.flagNames.has(r)){yt(n,r,!1,e[t+1],i.booleanFlags)&&t++;continue}}return-1}return-1}function Ct(e,t){let n=St(e,t);return n>=0?e[n]:void 0}function wt(e,t,r={}){let i=C(t),o=[...i],s=o.length>0;if(s&&e.length>0){if(r.globalExtracted){let t=bt(e,o,r.globalExtracted);if(t.subCommandIndex>=0){let n=Ot(t.globalTokensBefore,r.globalExtracted);return{helpRequested:!1,helpAllRequested:!1,helpJsonRequested:!1,versionRequested:!1,subCommand:e[t.subCommandIndex],remainingArgs:t.tokensAfterSubcommand,rawArgs:{},positionals:[],rest:[],unknownFlags:t.suppressedTokens,unknownGlobalFlags:t.suppressedTokens,rawGlobalArgs:n}}}else{let t=e[0];if(t&&!t.startsWith(`-`)&&i.has(t))return{helpRequested:!1,helpAllRequested:!1,helpJsonRequested:!1,versionRequested:!1,subCommand:t,remainingArgs:e.slice(1),rawArgs:{},positionals:[],rest:[],unknownFlags:[]}}}let c;t.args&&(c=l(t.args),r.skipValidation||(q(c),ot(c),J(c),at(c),rt(c),Y(c,s),it(c),r.globalExtracted&&lt(r.globalExtracted,c)));let u=e,d,f=[];if(r.globalExtracted){let t=c?a(c):[],n=new Set(t.map(e=>e.name)),{separated:i,globalParsed:o,suppressedTokens:s}=kt(e,r.globalExtracted,c&&{...c,fields:[...t,...c.fields.filter(e=>!n.has(e.name))]});u=i,d=o,f=s}let p=e.indexOf(`--`),m=p>=0?e.slice(0,p):e,h=c?.fields.some(e=>e.overrideBuiltinAlias===!0&&n(e).includes(`H`))??!1,g=c?.fields.some(e=>e.overrideBuiltinAlias===!0&&n(e).includes(`h`))??!1,_=m.includes(`--help-all`)||!h&&m.includes(`-H`),v=m.includes(`--help-json`),ee=!_&&!v&&(m.includes(`--help`)||!g&&m.includes(`-h`)),y=m.includes(`--version`);if(ee||_||v||y)return{helpRequested:ee,helpAllRequested:_,helpJsonRequested:v,versionRequested:y,subCommand:void 0,remainingArgs:[],rawArgs:{},positionals:[],rest:[],unknownFlags:[],unknownGlobalFlags:f,rawGlobalArgs:d};if(!c){let e=u.indexOf(`--`);return{helpRequested:!1,helpAllRequested:!1,helpJsonRequested:!1,versionRequested:!1,subCommand:void 0,remainingArgs:[],rawArgs:{},positionals:e>=0?u.slice(0,e):u,rest:e>=0?u.slice(e+1):[],unknownFlags:[],unknownGlobalFlags:f,rawGlobalArgs:d}}let b=Tt(c,u,{promptAvailable:r.promptAvailable===!0,inheritedNames:r.inheritedNames??/* @__PURE__ */ new Set});if(!b)return{helpRequested:!1,helpAllRequested:!1,helpJsonRequested:!1,versionRequested:!1,subCommand:void 0,remainingArgs:[],rawArgs:{},positionals:[],rest:[],unknownFlags:[],unknownGlobalFlags:f,extractedFields:c,matchesNoUnionOption:!0,rawGlobalArgs:d};let x=M(b),S=A(u,x),w=O(S,b),T=Et(w,b),E=b.fields.filter(e=>e.named),k=new Set(E.map(e=>e.name)),j=new Set(E.map(e=>e.cliName)),N=/* @__PURE__ */ new Set;for(let e of E)for(let t of n(e))N.add(t);if(r.globalExtracted)for(let e of r.globalExtracted.fields){k.add(e.name),j.add(e.cliName);for(let t of n(e))N.add(t)}let P=[];for(let e of Object.keys(S.options))!k.has(e)&&!j.has(e)&&!N.has(e)&&P.push(e);return{helpRequested:!1,helpAllRequested:!1,helpJsonRequested:!1,versionRequested:!1,subCommand:void 0,remainingArgs:[],rawArgs:w,positionals:S.positionals,rest:S.rest,unknownFlags:P,unknownGlobalFlags:f,extractedFields:c,optionFields:E,positionalSlotFields:D(b,S.options),rawGlobalArgs:d,envFallbackFields:T}}function Tt(e,t,n){let{discriminator:r,variants:i,unionOptions:a}=e;if(r&&i){let n=e=>{let n=O(A(t,M(e)),e);return Et(n,e),n},a=c(e,n);if(a!==e)return a;let o=new Set(i.map(e=>e.discriminatorValue));return i.some(t=>o.has(n({...e,fields:t.fields})[r]))?void 0:e}if(a){let r=n.promptAvailable?a.filter(e=>Dt(e,t,void 0)):[],i=a.find(e=>Dt(e,t,n.inheritedNames))??(r.length===1?r[0]:void 0);return i&&{...e,fields:i.fields}}return e}function Et(e,t){let n=/* @__PURE__ */ new Set;for(let r of t.fields)if(r.env&&e[r.name]===void 0)for(let t of[r.env].flat()){let i=process.env[t];if(i!==void 0){e[r.name]=j(i,r.type),n.add(r.name);break}}return n}function Dt(e,t,r){let i=A(t,M(e)),a=e.fields.filter(e=>e.named),o=new Set(a.flatMap(e=>[e.name,e.cliName,...n(e)]));if(Object.keys(i.options).some(e=>!o.has(e)))return!1;let s=D(e,i.options),c=i.positionals.length+i.rest.length;if(!s.some(e=>e.type===`array`)&&c>s.length)return!1;let l=O(i,e);return e.fields.some(e=>e.type!==`boolean`&&[l[e.name]].flat().includes(!0))?!1:r===void 0||(Et(l,e),e.fields.every(e=>!e.required||l[e.name]!==void 0||r.has(e.name)))}function Ot(e,t){if(e.length===0)return{};let n=M(t),r=A(e,n);return O(r,t)}function kt(e,r,i){let a=_t(r),o=new Set(i?.fields.map(e=>e.name)??[]),s=new Set(i?.fields.map(e=>e.cliName)??[]),c=i?M(i):void 0,l=new Set(c?.aliasMap?.keys()??[]),u=new Set(c?.negationMap?.keys()??[]),d=/* @__PURE__ */ new Set;for(let e of i?.fields??[])if(e.type===`boolean`&&e.negation===!0)for(let r of[e.cliName,...n(e)]){let e=`no-${r}`;d.add(e),d.add(t(e))}let f=[],p=[],m=[];for(let t=0;t<e.length;t++){let n=e[t];if(n===`--`){p.push(...e.slice(t));break}if(n.startsWith(`--`)){let{resolvedName:r,withoutDashes:i,isNegated:c,isGlobal:p,isSuppressedNegation:h}=vt(n,a),g=r,_=o.has(i)||o.has(g)||s.has(i)||s.has(g)||l.has(i)||l.has(g)||u.has(i)||u.has(g)||d.has(i);if(p&&!_){t+=X(e,t,r,c,a.booleanFlags,f)-1;continue}if(h&&!_){m.push(i);continue}}else if(n.startsWith(`-`)&&n.length>1){let r=n.includes(`=`)?n.slice(1,n.indexOf(`=`)):n.slice(1);if(r.length===1){let n=a.aliasMap.get(r)??r;if((a.aliases.has(r)||a.flagNames.has(n))&&!l.has(r)){t+=X(e,t,n,!1,a.booleanFlags,f)-1;continue}}}p.push(n)}return{separated:p,globalParsed:Ot(f,r),suppressedTokens:m}}function At(e,t){return s(t)?d(e,t):r().validate(e,t)}function Z(e){return e.map(e=>`${e.path.length>0?`${e.path.join(`.`)}: `:``}${e.message}`).join(`
30
+ `)}function jt(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=[e];for(let t=0;t<=e.length;t++)n[0][t]=t;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++)t.charAt(r-1)===e.charAt(i-1)?n[r][i]=n[r-1][i-1]:n[r][i]=Math.min(n[r-1][i-1]+1,n[r][i-1]+1,n[r-1][i]+1);return n[t.length][e.length]}function Mt(e,t){let n=Math.max(2,Math.floor(e.length/2));return t.map(t=>({candidate:t,distance:jt(e.toLowerCase(),t.toLowerCase())})).filter(({distance:e})=>e<=n).sort((e,t)=>e.distance-t.distance).map(({candidate:e})=>e).slice(0,3)}function Nt(e,t){let n=Mt(e.replace(/^-{1,2}/,``),t),r=`${T.warning(`Warning: Unknown option:`)} ${T.bold(e)}`;if(n.length>0){r+=`\n\n${T.info(`Did you mean?`)}`;for(let e of n)r+=`\n ${w.arrow} ${T.option(`--${e}`)}`}return r}function Pt(e,t){return t&&e.stack?`${T.error(`Error:`)} ${e.message}\n\n${T.dim(e.stack)}`:`${T.error(`Error:`)} ${e.message}`}function Q(n){return new Proxy(n,{get(n,r,i){if(typeof r==`string`){if(r in n)return Reflect.get(n,r,i);let a=t(r);if(a!==r&&a in n)return Reflect.get(n,a,i);let o=e(r);if(o!==r&&o in n)return Reflect.get(n,o,i)}return Reflect.get(n,r,i)},has(n,r){if(typeof r==`string`){if(r in n)return!0;let i=t(r);if(i!==r&&i in n)return!0;let a=e(r);if(a!==r&&a in n)return!0}return Reflect.has(n,r)}})}async function Ft(e,t,n){for(let r of t.fields)r.effect&&await r.effect(e[r.name],{name:r.name,args:e,...n!=null&&{globalArgs:n}})}const It={log:e=>console.log(e),error:e=>console.error(e),warn:e=>console.warn(e)};function Lt(n,r){Object.defineProperty(n,"$source",{value:n=>r.get(n)??r.get(t(n))??r.get(e(n))??`default`,enumerable:!1})}function Rt(e,t){Object.defineProperty(e,"$invocation",{value:t,enumerable:!1})}function zt(e,t){let n=t.commandPath?.at(-1)??e.name;return t.aliasFor?{name:n,aliasFor:t.aliasFor}:{name:n}}async function Bt(e,t,n={}){let r=Wt(n),i=n.captureLogs??!1,a=i?v():null;if(n.setup){a?.start();try{await n.setup({})}catch(e){let t=e instanceof Error?e:Error(String(e));if(n.cleanup)try{await n.cleanup({error:t})}catch{}return a?.stop(),{success:!1,error:t,exitCode:1,logs:a?.getLogs()??g()}}a?.stop()}let o=await $(e,t,{...n,handleSignals:!1,_globalExtracted:r,_globalCleanup:n.cleanup,_existingLogs:a?.getLogs()});if(n.cleanup){let e=i?v():null;e?.start();let t={error:o.success?void 0:o.error};try{await n.cleanup(t)}catch(t){if(o.success){let n=t instanceof Error?t:Error(String(t));return e?.stop(),{success:!1,error:n,exitCode:1,logs:_(o.logs,e?.getLogs()??g())}}}e?.stop();let r=e?.getLogs()??g();if(r.entries.length>0)return{...o,logs:_(o.logs,r)}}return o}function Vt(e,t,n){let r=Ct(t,n);return!r||!r.startsWith(`__`)?!1:Object.hasOwn(e.subCommands??{},r)}async function Ht(e,t={}){if(t.compileCache!==!1&&h(typeof t.compileCache==`string`?{cacheDir:t.compileCache}:{programName:e.name}),e.runMainHook)try{e.runMainHook(process.argv.slice(2))}catch{}let n=process.argv.slice(2),r;if(t.globalArgs)try{r=l(t.globalArgs)}catch{}let i=t;if(Vt(e,n,r)){let{setup:e,cleanup:n,prompt:r,globalArgs:a,...o}=t;i=o}let a=Wt(i);if(i.skipValidation||ft(e),i.onUnknownSubcommand&&!e.run&&!Vt(e,n,r)){let t=C(e);if(t.size>0){let e=St(n,a,{stopOnSuppressedNegation:a?.unknownKeysMode!==`passthrough`}),r=e>=0?n[e]:void 0;if(r&&!t.has(r)){let t=n.slice(e+1),a=await i.onUnknownSubcommand({commandPath:[],name:r,args:t,precedingArgs:n.slice(0,e)});if(typeof a==`number`)return await Ut(),process.exit(a)}}}if(i.setup)try{await i.setup({})}catch(e){let t=e instanceof Error?e:Error(String(e));if(i.cleanup)try{await i.cleanup({error:t})}catch{}process.exit(1)}let o=await $(e,n,{debug:i.debug,captureLogs:i.captureLogs,skipValidation:i.skipValidation,handleSignals:!0,logger:i.logger,globalArgs:i.globalArgs,prompt:i.prompt,onUnknownSubcommand:i.onUnknownSubcommand,_globalExtracted:a,_globalCleanup:i.cleanup,_context:{commandPath:[],rootName:e.name,rootVersion:i.version,globalExtracted:a}});if((i.displayErrors??!0)&&!o.success&&o.error&&(i.logger??It).error(Pt(o.error,i.debug??!1)),i.cleanup){let e={error:o.success?void 0:o.error};try{await i.cleanup(e)}catch{}}await Ut(),process.exit(o.exitCode)}async function Ut(){await Promise.all([process.stdout,process.stderr].map(e=>e.writableLength>0?new Promise(t=>e.write(``,()=>t())):Promise.resolve()))}async function $(e,t,n={}){let r=n.logger??It,i=n._context??{commandPath:[],rootName:e.name,globalExtracted:n._globalExtracted},a=n.captureLogs??!1?v():null;a?.start();let o=()=>{let e=n._existingLogs??g(),t=a?.getLogs()??g();return _(e,t)};try{n.skipValidation||ft(e);let s=wt(t,e,{skipValidation:n.skipValidation,globalExtracted:n._globalExtracted,promptAvailable:n.prompt!==void 0,inheritedNames:new Set(Object.keys(n._parsedGlobalArgs??{}))}),c={...n._parsedGlobalArgs,...s.rawGlobalArgs},l=i.commandPath??[];if(n.onUnknownSubcommand&&!e.run&&l.length>0){let r=C(e);if(r.size>0){let e=St(t,n._globalExtracted,{stopOnSuppressedNegation:n._globalExtracted?.unknownKeysMode!==`passthrough`}),i=e>=0?t[e]:void 0;if(i&&!r.has(i)){let r=t.slice(e+1),s=await n.onUnknownSubcommand({commandPath:l,name:i,args:r,precedingArgs:[...n._precedingArgs??[],...t.slice(0,e)]});if(typeof s==`number`){if(a?.stop(),n.handleSignals){if(n._globalCleanup)try{await n._globalCleanup({error:void 0})}catch{}await Ut(),process.exit(s)}return s===0?{success:!0,result:void 0,exitCode:0,logs:o()}:{success:!1,error:/* @__PURE__ */ Error(`Plugin "${[...l,i].join(` `)}" exited with code ${s}`),exitCode:s,logs:o()}}}}}if(s.helpRequested||s.helpAllRequested||s.helpJsonRequested){let c=!1,l=b(e),u=C(e);if(l.length>0){let e=Ct(t,i.globalExtracted);e&&!u.has(e)&&(c=!0)}if(s.helpJsonRequested){let t=G(e,{context:i});r.log(JSON.stringify(t))}else{let t=U(e,{showSubcommands:n.showSubcommands??!0,showSubcommandOptions:s.helpAllRequested||n.showSubcommandOptions,context:i});r.log(t)}if(a?.stop(),c){let e=Ct(t,i.globalExtracted)??``,n=Mt(e,[...u]),r=n.length>0?` Did you mean: ${n.join(`, `)}?`:``;return{success:!1,error:/* @__PURE__ */ Error(`Unknown subcommand: ${e}${r?`.${r}`:``}`),exitCode:1,logs:o()}}return{success:!0,result:void 0,exitCode:0,logs:o()}}if(s.unknownGlobalFlags&&s.unknownGlobalFlags.length>0){let e=i.globalExtracted?.unknownKeysMode??`strip`;if(e===`strict`)return a?.stop(),{success:!1,error:/* @__PURE__ */ Error(`Unknown flags: ${s.unknownGlobalFlags.join(`, `)}`),exitCode:1,logs:o()};if(e===`strip`){let e=i.globalExtracted?.fields.map(e=>e.name)??[];for(let t of s.unknownGlobalFlags)r.error(Nt(t,e))}}if(s.versionRequested){let e=i.rootVersion;return e&&r.log(e),a?.stop(),{success:!0,result:void 0,exitCode:0,logs:o()}}if(s.subCommand){let r=await ee(e,s.subCommand);if(r){let e={commandPath:[...i.commandPath??[],s.subCommand],rootName:i.rootName,rootVersion:i.rootVersion,globalExtracted:i.globalExtracted,aliasFor:r.aliasFor};a?.stop();let l=new Set(n._globalExtracted?.unknownKeysMode===`passthrough`?[]:s.unknownGlobalFlags??[]),u=e=>e.startsWith(`--`)&&l.has(E(e)),d=t.slice(0,t.length-s.remainingArgs.length-1).filter(e=>!u(e));return $(r.command,s.remainingArgs,{...n,_context:e,_existingLogs:o(),_parsedGlobalArgs:c,_precedingArgs:[...n._precedingArgs??[],...d]})}}let u=s.positionalSlotFields??[],d=u.some(e=>e.type===`array`),f=[...s.positionals,...s.rest],p=d?[]:f.slice(u.length),m=d?[]:s.positionals.slice(u.length);if(s.matchesNoUnionOption)return a?.stop(),{success:!1,error:/* @__PURE__ */ Error(`Arguments match none of the accepted forms. See --help for the accepted forms.`),exitCode:1,logs:o()};if(b(e).length>0&&!s.subCommand&&!e.run&&p.length===0){if(e.defaultSubCommand&&s.unknownFlags.length===0){let r=e.subCommands?.[e.defaultSubCommand];if(r){let l=await S(r),u={commandPath:[...i.commandPath??[],e.defaultSubCommand],rootName:i.rootName,rootVersion:i.rootVersion,globalExtracted:i.globalExtracted};a?.stop();let d=new Set(n._globalExtracted?.unknownKeysMode===`passthrough`?[]:s.unknownGlobalFlags??[]),f=e=>e.startsWith(`--`)&&d.has(E(e)),p=t.filter(e=>!f(e));return $(l,[],{...n,_context:u,_existingLogs:o(),_parsedGlobalArgs:c,_precedingArgs:[...n._precedingArgs??[],...p]})}}let l=U(e,{showSubcommands:n.showSubcommands??!0,context:i});return r.log(l),a?.stop(),{success:!0,result:void 0,exitCode:0,logs:o()}}if(s.unknownFlags.length>0){let e=s.extractedFields?.unknownKeysMode??`strip`,t=s.optionFields?.map(e=>e.name)??[];if(e===`strict`)return a?.stop(),{success:!1,error:/* @__PURE__ */ Error(`Unknown flags: ${s.unknownFlags.join(`, `)}`),exitCode:1,logs:o()};if(e===`strip`)for(let e of s.unknownFlags)r.error(Nt(e,t))}if(p.length>0){let t=C(e);if(t.size>0){let e=m.find(e=>!e.startsWith(`-`)&&!t.has(e));if(e){let n=Mt(e,[...t]),r=n.length>0?` Did you mean: ${n.join(`, `)}?`:``;return a?.stop(),{success:!1,error:/* @__PURE__ */ Error(`Unknown subcommand: ${e}${r?`.${r}`:``}`),exitCode:1,logs:o()}}}let n=s.extractedFields?.unknownKeysMode??`strip`;if(n===`strict`)return a?.stop(),{success:!1,error:/* @__PURE__ */ Error(`Unexpected positional argument${p.length>1?`s`:``}: ${p.join(`, `)}`),exitCode:1,logs:o()};if(n===`strip`)for(let e of p)(r.warn??r.error)(`Warning: Unexpected positional argument: ${e}`)}let h={},g=e.name===`__complete`,_=new Set(Object.keys(c)),v=/* @__PURE__ */ new Set;if(n.globalArgs&&n._globalExtracted&&!g){for(let e of n._globalExtracted.fields)if(e.env&&c[e.name]===void 0){let t=Array.isArray(e.env)?e.env:[e.env];for(let n of t){let t=process.env[n];if(t!==void 0){c[e.name]=j(t,e.type),v.add(e.name);break}}}if(n.prompt){let e=await n.prompt(c,n._globalExtracted);for(let[t,n]of Object.entries(e))n!==void 0&&(c[t]=n)}let e=At(c,n.globalArgs);if(!e.success)return a?.stop(),{success:!1,error:Error(Z(e.errors)),exitCode:1,logs:o()};h=e.data}if(!e.args){let t=/* @__PURE__ */ new Map;for(let e of _)t.set(e,`cli`);for(let e of v)t.set(e,`env`);Lt(h,t),Rt(h,zt(e,i));let r=Q(h);return n._globalExtracted&&!g&&await Ft(r,n._globalExtracted,r),a?.stop(),await P(e,r,{handleSignals:n.handleSignals,captureLogs:n.captureLogs,existingLogs:o(),globalCleanup:n._globalCleanup})}let y=s.rawArgs,x=/* @__PURE__ */ new Set;if(n.prompt&&s.extractedFields){let e=await n.prompt(y,s.extractedFields),t={...y};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r,x.add(n));y=t}let w=/* @__PURE__ */ new Set;if(s.extractedFields)for(let e of s.extractedFields.fields)!(Object.hasOwn(s.rawArgs,e.name)||x.has(e.name))&&_.has(e.name)&&Object.hasOwn(h,e.name)&&(y={...y,[e.name]:h[e.name]},w.add(e.name));let T=At(y,e.args);if(!T.success)return a?.stop(),{success:!1,error:Error(Z(T.errors)),exitCode:1,logs:o()};let D=Q(T.data),O=/* @__PURE__ */ new Map;for(let e of _)O.set(e,`cli`);for(let e of v)O.set(e,`env`);Lt(h,O),Rt(h,zt(e,i));let k=Q(h);n._globalExtracted&&!g&&await Ft(k,n._globalExtracted,k),s.extractedFields&&!g&&await Ft(D,s.extractedFields,k);let A={...k,...D},M=new Map(O),N=s.envFallbackFields??/* @__PURE__ */ new Set;for(let e of s.extractedFields?.fields??[]){if(w.has(e.name)){M.set(e.name,`cli`);continue}let t=Object.hasOwn(s.rawArgs,e.name)||N.has(e.name);M.set(e.name,t?N.has(e.name)?`env`:`cli`:`default`)}Lt(A,M),Rt(A,zt(e,i));let te=Q(A);return a?.stop(),await P(e,te,{handleSignals:n.handleSignals,captureLogs:n.captureLogs,existingLogs:o(),globalCleanup:n._globalCleanup})}catch(e){let t=e instanceof Error?e:Error(String(e));return a?.stop(),{success:!1,error:t,exitCode:1,logs:o()}}}function Wt(e){if(!e.globalArgs)return;let t=l(e.globalArgs);if(!e.skipValidation){q(t),ot(t),J(t),at(t),Y(t,!0),it(t);let e=t.fields.filter(e=>e.positional).map(e=>e.name);if(e.length>0)throw Error(`Global options schema must not contain positional arguments. Found: ${e.join(`, `)}`)}return t}export{He as C,I as D,G as E,ae as O,Ve as S,U as T,qe as _,gt as a,Ge as b,lt as c,q as d,at as f,K as g,it as h,Z as i,ft as l,Y as m,Ht as n,ot as o,rt as p,Q as r,ht as s,Bt as t,J as u,We as v,Ke as w,Je as x,Ue as y};
@@ -0,0 +1 @@
1
+ import{o as e,r as t}from"./field-meta-D9ySul7J.js";const n=`__polittyInternalArgs`,r={string(e){return{kind:`string`,optional:!1,meta:e}},optionalString(e){return{kind:`string`,optional:!0,meta:e}},boolean(e){return{kind:`boolean`,optional:!1,defaultValue:!1,meta:e}},enum(e,t){return{kind:`enum`,enumValues:e,optional:!1,meta:t}},optionalEnum(e,t){return{kind:`enum`,enumValues:e,optional:!0,meta:t}},stringArray(e){return{kind:`string-array`,optional:!1,defaultValue:[],meta:e}},optionalStringArray(e){return{kind:`string-array`,optional:!0,meta:e}}};function i(e,t={}){return{[n]:!0,fields:e,unknownKeys:t.unknownKeys??`strip`}}function a(e){return typeof e==`object`&&!!e&&e[n]===!0}const o={string:`string`,boolean:`boolean`,enum:`string`,"string-array":`array`},s=/* @__PURE__ */ new WeakMap;function c(e){let n=s.get(e);if(n)return n;let r={fields:Object.entries(e.fields).map(([e,n])=>t(e,{argMeta:n.meta,description:void 0,required:!n.optional&&n.defaultValue===void 0,defaultValue:n.defaultValue,type:o[n.kind],enumValues:n.enumValues?[...n.enumValues]:void 0,schema:n})),schema:e,schemaType:`object`,unknownKeysMode:e.unknownKeys};return s.set(e,r),r}function l(e){switch(e.kind){case`enum`:return`one of ${(e.enumValues??[]).map(e=>JSON.stringify(e)).join(` | `)}`;case`string-array`:return`array`;default:return e.kind}}function u(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function d(e,t,n){return{path:[e],message:`Invalid input: expected ${l(t)}, received ${u(n)}`,code:`invalid_type`,received:n,expected:l(t)}}function f(e,t,n){switch(t.kind){case`string`:return typeof n==`string`?null:d(e,t,n);case`boolean`:return typeof n==`boolean`?null:d(e,t,n);case`enum`:return typeof n!=`string`||!(t.enumValues??[]).includes(n)?{path:[e],message:`Invalid option: expected ${l(t)}`,code:`invalid_value`,received:n,expected:l(t)}:null;case`string-array`:return!Array.isArray(n)||n.some(e=>typeof e!=`string`)?d(e,t,n):null}}function p(e,t){let n=[],r={};for(let[i,a]of Object.entries(t.fields)){let t=e[i];if(t===void 0){a.defaultValue===void 0?a.optional||n.push(d(i,a,void 0)):r[i]=Array.isArray(a.defaultValue)?[...a.defaultValue]:a.defaultValue;continue}let o=f(i,a,t);if(o){n.push(o);continue}r[i]=t}let i=new Set(Object.keys(t.fields)),a=Object.keys(e).filter(e=>!i.has(e));if(a.length>0){if(t.unknownKeys===`strict`)n.push({path:[],message:`Unrecognized key${a.length>1?`s`:``}: ${a.map(e=>JSON.stringify(e)).join(`, `)}`,code:`unrecognized_keys`});else if(t.unknownKeys===`passthrough`)for(let t of a)Object.defineProperty(r,t,{value:e[t],enumerable:!0,writable:!0,configurable:!0})}return n.length>0?{success:!1,errors:n}:{success:!0,data:r}}function m(t){return a(t)?t.unknownKeys:e().getUnknownKeysMode(t)}function h(t){return a(t)?c(t):e().extractFields(t)}function g(e){return e.args?h(e.args):null}function _(e,t){let[n,...r]=e,i=/* @__PURE__ */ new Set;for(let e of n?.fields??[])e.name!==t&&r.every(t=>t.fields.some(t=>t.name===e.name&&t.positional===e.positional&&t.named===e.named))&&i.add(e.name);return i}function v(e){let t=x(e).filter(e=>e.named);return S(e,e=>e.named).map(e=>{let n=t.filter(t=>t.name===e.name),r=[...new Set(n.flatMap(e=>e.alias??[]))],i=[...new Set(n.flatMap(e=>e.hiddenAlias??[]))];return{...e,alias:r.length>0?r:e.alias,hiddenAlias:i.length>0?i:e.hiddenAlias}})}function y(e){return S(e,e=>e.positional)}function b(e){return S(e,e=>!e.positional)}function x(e){let t=e.variants??e.unionOptions??[];return[e.fields,...t.map(e=>e.fields)].flat()}function S(e,t){let n=/* @__PURE__ */ new Map;for(let r of x(e))t(r)&&!n.has(r.name)&&n.set(r.name,r);return[...n.values()]}function C(e,t){let{discriminator:n,variants:r}=e;if(!n||!r)return e;for(let i of r){let r={...e,fields:i.fields};if(t(r)[n]===i.discriminatorValue)return r}return e}function w(e,t){return b(e).find(e=>e.name===t)}export{v as a,y as c,r as d,a as f,m as i,C as l,h as n,w as o,p,g as r,b as s,_ as t,i as u};
@@ -1 +1 @@
1
- import{d as e,u as t}from"./schema-extractor-Du9ipDD4.js";const n=t({shell:e.enum([`bash`,`zsh`,`fish`],{description:`Target shell for output formatting`}),args:e.stringArray({positional:!0,description:`Arguments to complete`})});export{n as t};
1
+ import{d as e,u as t}from"./schema-extractor-fZZ2_WAZ.js";const n=t({shell:e.enum([`bash`,`zsh`,`fish`],{description:`Target shell for output formatting`}),args:e.stringArray({positional:!0,description:`Arguments to complete`})});export{n as t};
package/dist/skill.js CHANGED
@@ -1,2 +1,2 @@
1
- import"./register-BXOytPt7.js";import{d as e,n as t,u as n}from"./schema-extractor-Du9ipDD4.js";import{n as r}from"./command-tLHaJHe6.js";import{a as i,n as a}from"./logger-CoeDrmRr.js";import{copyFileSync as o,existsSync as s,lstatSync as c,mkdirSync as l,mkdtempSync as u,readFileSync as d,readdirSync as f,readlinkSync as p,realpathSync as m,renameSync as ee,rmSync as h,statSync as g,symlinkSync as te,unlinkSync as _}from"node:fs";import{basename as v,dirname as y,isAbsolute as b,join as x,parse as ne,relative as S,resolve as C,sep as w}from"node:path";import{parse as re}from"yaml";import{z as T}from"zod";const ie=/^[a-z0-9]+(-[a-z0-9]+)*$/;function E(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function ae(e){let t=[],n=(n,r)=>{let i=e[n];if(i===void 0){r.required&&t.push({path:[n],message:`Invalid input: expected string, received undefined`});return}if(typeof i!=`string`){t.push({path:[n],message:`Invalid input: expected string, received ${E(i)}`});return}r.min!==void 0&&i.length<r.min&&t.push({path:[n],message:`Too small: expected string to have >=${r.min} characters`}),r.max!==void 0&&i.length>r.max&&t.push({path:[n],message:`Too big: expected string to have <=${r.max} characters`})};n(`name`,{required:!0,min:1,max:64}),typeof e.name==`string`&&!ie.test(e.name)&&t.push({path:[`name`],message:`name must be lowercase alphanumerics separated by single hyphens`}),n(`description`,{required:!0,min:1,max:1024}),n(`license`,{min:1}),n(`compatibility`,{max:500}),n(`allowed-tools`,{});let r=e.metadata;if(r!==void 0){if(typeof r!=`object`||!r||Array.isArray(r))t.push({path:[`metadata`],message:`Invalid input: expected record, received ${E(r)}`});else for(let[e,n]of Object.entries(r))typeof n!=`string`&&t.push({path:[`metadata`,e],message:`Invalid input: expected string, received ${E(n)}`})}return t.length>0?{success:!1,issues:t}:{success:!0,data:{...e}}}const oe=/^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/;function D(e){let t=e.match(oe);if(!t)return{data:{},body:e};let n=t[1],r=t[2];try{let e=re(n);return se(e)?{data:e,body:r}:{data:{},body:r}}catch(e){return{data:{},body:r,parseError:e instanceof Error?e.message:String(e)}}}function se(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ce(e){let{data:t,body:n}=D(e),r=ae(t);return r.success?{frontmatter:r.data,body:n,rawContent:e}:null}const O=`.agents/skills`,k=[`.claude/skills`],A=`politty-cli`;function j(e){if(e.length<1||e.length>64||!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e))throw Error(`Invalid skill name: ${JSON.stringify(e)}`)}function le(e,t=process.cwd(),n={}){let r=e.frontmatter.name;j(r);let i=n.mode??`symlink`,a=e.frontmatter.metadata?.[`politty-cli`]??null;if(i===`copy`&&a===null)throw Error(`Refusing to install "${e.frontmatter.name}" in copy mode without an ownership stamp. Add metadata.${A}="{package}:{cli}" to the source SKILL.md so subsequent installs can replace the copy in place.`);let o=C(t,O),s=m(e.sourcePath),c=ue(e.sourcePath),u=[x(N(o),r),...k.map(e=>x(N(C(t,e)),r))].find(e=>ye(e,s));if(u!==void 0)throw Error(`Refusing to install "${r}": source ${s} overlaps install destination ${u}. Choose a sourceDir outside .agents/skills/ and any agent-specific slot directory (e.g. .claude/skills/).`);if(i===`symlink`){let e=N(o);M(x(e,r),S(e,c));for(let n of k){let i=N(C(t,n));M(x(i,r),x(S(i,e),r))}}l(o,{recursive:!0});let d=m(o),f=x(d,r);he(f,a),ge({linkTarget:S(d,c),linkPath:f,copyFrom:s,mode:i}),ve(t,r,f,a,i)}function M(e,t){if(b(t))throw Error(`Refusing to write an absolute symlink target at ${e} → ${t}. The skill source and install root appear to live on different filesystem roots (e.g. different Windows drive letters); retry with mode: "copy".`)}function ue(e){let t=C(e),{root:n}=ne(t),r=t.slice(n.length).split(w).filter(e=>e!==``),i=n;for(let[e,t]of r.entries()){let n=x(i,t),a;try{a=c(n)}catch{return x(i,...r.slice(e))}if(a.isSymbolicLink()){if(de(i))return x(i,...r.slice(e));i=m(n)}else i=n}return i}function de(e){return v(e)===`node_modules`||v(e).startsWith(`@`)&&v(y(e))===`node_modules`}function N(e){let t=e,n=[];for(;;)try{let e=m(t);return n.length===0?e:C(e,...n.reverse())}catch{let r=y(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[/\\]+/,``)),t=r}}function fe(e,t=process.cwd(),n={}){j(e);let r=n.expectedOwnership??null,i=C(t,O,e);for(let n of k)me(C(t,n,e),r,{restrictSymlinkTo:i});me(i,r)}function pe(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n);if(r===t)return!0;try{return m(r)===m(t)}catch{return!1}}function me(e,t,n={}){let r;try{r=c(e)}catch(e){if(R(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return;throw e}if(r.isSymbolicLink()){if(n.restrictSymlinkTo!==void 0){pe(e,n.restrictSymlinkTo)&&_(e);return}(t===null||F(e)===t)&&_(e);return}r.isDirectory()&&t!==null&&F(e)===t&&h(e,{recursive:!0,force:!0})}function he(e,t,n={}){let r;try{r=c(e)}catch(e){if(R(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return;throw e}if(r.isSymbolicLink()){if(n.restrictSymlinkTo===void 0||pe(e,n.restrictSymlinkTo)){_(e);return}throw Error(`Refusing to replace symlink at ${e}: it does not route to this CLI's canonical slot (${n.restrictSymlinkTo}). Remove or migrate the foreign symlink before retrying.`)}if(r.isDirectory()&&t!==null&&F(e)===t){h(e,{recursive:!0,force:!0});return}throw Error(`Refusing to replace non-symlink path at ${e}. This looks like a legacy or manual install; remove or migrate it before retrying.`)}function ge(e){let{linkTarget:t,linkPath:n,copyFrom:r,mode:i}=e;if(i===`copy`){_e(r,n);return}M(n,t);try{te(t,n,`dir`)}catch(e){let r=e instanceof Error?e.message:String(e);throw Error(`Failed to symlink ${n} → ${t}: ${r}. If this filesystem does not support symlinks (e.g. Windows without Developer Mode), retry with mode: "copy".`,{cause:e})}}function _e(e,t){let n=u(`${t}.partial-`);try{P(e,n),ee(n,t)}catch(e){try{h(n,{recursive:!0,force:!0})}catch{}throw e}}function P(e,t,n=new Set){let r=g(e);if(r.isDirectory()){let r=m(e);if(n.has(r))throw Error(`Refusing to recursively copy cyclic directory symlink at ${e} (resolves to ${r}, already on the copy stack).`);n.add(r);try{l(t,{recursive:!0});for(let r of f(e))P(x(e,r),x(t,r),n)}finally{n.delete(r)}return}r.isFile()&&o(e,t)}function F(e){let t;try{t=d(x(e,`SKILL.md`),`utf-8`)}catch(e){if(R(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return null;throw e}let{data:n}=D(t),r=n.metadata;if(!r||typeof r!=`object`||Array.isArray(r))return null;let i=r[A];return typeof i==`string`?i:null}function I(e,t=process.cwd()){return j(e),s(C(t,O,e,`SKILL.md`))}function L(e,t=process.cwd()){j(e);let n=C(t,O,e,`SKILL.md`),r;try{r=d(n,`utf-8`)}catch(e){if(R(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return null;throw e}let{data:i}=D(r),a=i.metadata;if(!a||typeof a!=`object`||Array.isArray(a))return null;let o=a[A];return typeof o==`string`?o:null}function ve(e,t,n,r,i){for(let a of k){let o=C(e,a);l(o,{recursive:!0});let s=m(o),c=x(s,t);he(c,r,{restrictSymlinkTo:n});let u=m(C(n,`..`));ge({linkTarget:x(S(s,u),t),linkPath:c,copyFrom:n,mode:i})}}function R(e){return e instanceof Error&&typeof e.code==`string`}function ye(e,t){if(e===t)return!0;let n=(e,t)=>{let n=S(t,e);return n===``||n===`.`||!b(n)&&n!==`..`&&!n.startsWith(`..${w}`)};return n(e,t)||n(t,e)}const z=`SKILL.md`;function B(e){let t=[],n=[];try{let r;try{r=g(e)}catch(r){return H(r)&&(r.code===`ENOENT`||r.code===`ENOTDIR`)?n.push({path:e,reason:`missing-source`,message:`Source directory does not exist: ${e}`}):n.push({path:e,reason:`read-failed`,message:`Failed to stat source directory ${e}: ${V(r)}`}),{skills:t,errors:n}}if(!r.isDirectory())return n.push({path:e,reason:`missing-source`,message:`Source path is not a directory: ${e}`}),{skills:t,errors:n};let i=x(e,z),a=Se(i);if(a.kind===`error`)return n.push({path:e,reason:`read-failed`,message:`Failed to check ${i}: ${a.message}`}),{skills:t,errors:n};if(a.kind===`present`)return xe(be(e,{enforceParentMatch:!1}),t,n),{skills:t,errors:n};let o=f(e,{withFileTypes:!0});for(let r of o){let i=x(e,r.name),a;try{a=g(i).isDirectory()}catch(e){if(H(e)&&e.code===`ENOENT`&&!r.isSymbolicLink())continue;n.push({path:i,reason:`read-failed`,message:r.isSymbolicLink()?`Dangling symlink at ${i}: ${V(e)}`:`Failed to stat ${i}: ${V(e)}`});continue}if(!a)continue;let o=x(i,z),s=Se(o);if(s.kind===`error`){n.push({path:i,reason:`read-failed`,message:`Failed to check ${o}: ${s.message}`});continue}s.kind!==`absent`&&xe(be(i,{enforceParentMatch:!0}),t,n)}}catch(t){n.push({path:e,reason:`read-failed`,message:`Failed to scan ${e}: ${V(t)}`})}return t.sort((e,t)=>e.frontmatter.name<t.frontmatter.name?-1:+(e.frontmatter.name>t.frontmatter.name)),{skills:t,errors:n}}function be(e,t){let n=x(e,z),r;try{r=d(n,`utf-8`)}catch(t){return{path:e,reason:`read-failed`,message:`Failed to read ${n}: ${V(t)}`}}let{data:i,parseError:a}=D(r);if(a!==void 0)return{path:e,reason:`parse-failed`,message:`Invalid SKILL.md frontmatter in ${e}: YAML parse error: ${a}`};let o=ae(i);if(!o.success)return{path:e,reason:`parse-failed`,message:`Invalid SKILL.md frontmatter in ${e}: ${o.issues.map(e=>`${e.path.join(`.`)||`<root>`}: ${e.message}`).join(`; `)}`};if(t.enforceParentMatch){let t=v(e);if(t!==o.data.name)return{path:e,reason:`name-mismatch`,message:`Skill name "${o.data.name}" does not match directory "${t}"`,skillName:o.data.name}}return{frontmatter:o.data,sourcePath:e,rawContent:r}}function xe(e,t,n){`frontmatter`in e?t.push(e):n.push(e)}function V(e){return e instanceof Error?e.message:String(e)}function H(e){return e instanceof Error&&typeof e.code==`string`}function Se(e){try{return c(e),{kind:`present`}}catch(e){return H(e)&&e.code===`ENOENT`?{kind:`absent`}:{kind:`error`,message:V(e)}}}function Ce(e,t={}){let n=0,r=!1;for(let i of e){if(i.reason===`missing-source`||i.path===t.sourceDir){r=!0,a.warn(`Failed to scan source directory ${i.path}: ${i.message}`);continue}n+=1,a.warn(`Skipping skill at ${i.path}: ${i.message}`)}t.silentStdout||(n>0&&a.info(`${i.warning} Skipped ${n} skill(s) due to scan errors (see warnings above).`),r&&a.info(`${i.warning} Source directory scan failed (see warnings above); subsequent operations may be skipped.`))}function U(e,t){let n=e.errors.some(e=>e.reason===`missing-source`||e.path===t),r=e.errors.length>0&&e.skills.length===0;return n||r}function W(e,t={}){let n=B(e.sourceDir);return Ce(n.errors,{...t,sourceDir:e.sourceDir}),n}function we(e){let t={description:`Skill names to exclude from sync`};return e.excludeAlias!==void 0&&(t.alias=e.excludeAlias),t}function Te(e){let t={description:`Print install paths and modes`};return e.verbose.alias!==void 0&&(t.alias=e.verbose.alias),t}function G(e,t){return!!e[t]}function Ee(t){function i(e,n){let{skills:r,errors:i}=W(t),o=t.stamp,s=new Set(r.map(e=>e.frontmatter.name)),c=new Set(Ie(o,t.cwd,t.sourceDir)),l=Array.from(new Set(e.exclude)).filter(e=>!s.has(e)&&!c.has(e));if(l.length>0){let e=l.length===1?`Skill`:`Skills`,t=l.map(e=>JSON.stringify(e)).join(`, `);throw Error(`--exclude: ${e} ${t} not found in source directory or among installed skills.\n`+q({source:r,installed:c}))}let u=new Set(e.exclude),d=r.filter(e=>!u.has(e.frontmatter.name)),f=U({skills:r,errors:i},t.sourceDir),p=0;if(!f){let e=new Set(d.map(e=>e.frontmatter.name)),n=new Set;for(let e of i)e.path!==t.sourceDir&&(n.add(v(e.path)),e.skillName!==void 0&&n.add(e.skillName));for(let r of c)e.has(r)||u.has(r)||n.has(r)||(Y(r,o,t.cwd,t.sourceDir),p+=1)}let m=0;for(let e of d)J(e,o,t,n),m+=1;if(m===0&&p===0){let e=f?`source directory scan failed; see warnings`:r.length>0&&d.length===0?`all skills excluded`:`no skills bundled`;a.info(`No skills installed (${e}).`)}else a.info(`Sync complete: ${m} installed, ${p} removed.`)}return t.verbose.disabled?r({name:`sync`,description:t.descriptions.sync,args:n({exclude:e.stringArray(we(t))},{unknownKeys:t.unknownKeys}),run(e){i(e,G(e,`verbose`))}}):r({name:`sync`,description:t.descriptions.sync,args:n({exclude:e.stringArray(we(t)),verbose:e.boolean(Te(t))},{unknownKeys:t.unknownKeys}),run(e){i(e,e.verbose)}})}function De(t){let i={positional:!0,description:`Skill name(s) to install (default: all)`,placeholder:`NAME`};function o(e,n){let r=W(t),i=r.skills,o=t.stamp;if(e.name.length>0){let r=new Set(i.map(e=>e.frontmatter.name)),a=Array.from(new Set(e.name)),s=a.filter(e=>!r.has(e));if(s.length>0){let e=s.length===1?`Skill`:`Skills`,t=s.map(e=>JSON.stringify(e)).join(`, `);throw Error(`${e} ${t} not found in source directory.\n`+q({source:i}))}let c=new Set(a);for(let e of i)c.has(e.frontmatter.name)&&J(e,o,t,n);return}if(i.length===0){U(r,t.sourceDir)?a.info(`No skills installed (source directory scan failed; see warnings).`):a.info(`No skills found in source directory.`);return}for(let e of i)J(e,o,t,n)}return t.verbose.disabled?r({name:t.commandNames.add.name,...t.commandNames.add.aliases.length>0?{aliases:t.commandNames.add.aliases}:{},description:t.descriptions.add,args:n({name:e.stringArray(i)},{unknownKeys:t.unknownKeys}),run(e){o(e,G(e,`verbose`))}}):r({name:t.commandNames.add.name,...t.commandNames.add.aliases.length>0?{aliases:t.commandNames.add.aliases}:{},description:t.descriptions.add,args:n({name:e.stringArray(i),verbose:e.boolean(Te(t))},{unknownKeys:t.unknownKeys}),run(e){o(e,e.verbose)}})}function Oe(t){return r({name:t.commandNames.remove.name,...t.commandNames.remove.aliases.length>0?{aliases:t.commandNames.remove.aliases}:{},description:t.descriptions.remove,args:n({name:e.optionalString({positional:!0,description:`Skill name to remove (default: all)`,placeholder:`NAME`})},{unknownKeys:t.unknownKeys}),run(e){let n=W(t),r=n.skills,i=t.stamp;if(e.name){if(r.some(t=>t.frontmatter.name===e.name)&&Me(r,e.name),!Y(e.name,i,t.cwd,t.sourceDir)){if(K(e.name,t.cwd))a.info(`${e.name} is installed without a ${A} stamp this CLI recognises; refusing to remove. Remove .agents/skills/${e.name} manually if intended.`);else{let n=new Set(Ie(i,t.cwd,t.sourceDir));a.info(`${e.name} is not installed; nothing to remove.\n`+q({installed:n}))}}return}if(r.length===0){U(n,t.sourceDir)?a.info(`No skills found (source directory scan failed; see warnings); nothing to remove.`):a.info(`No skills found in source directory; nothing to remove.`);return}let o=0;for(let e of r)Y(e.frontmatter.name,i,t.cwd,t.sourceDir)&&(o+=1);o===0&&a.info(`No installed skills owned by this CLI; nothing to remove.`)}})}function ke(e,t,n,r){let i;try{i=L(e,n)}catch(t){return a.warn(`Failed to read ownership for installed skill ${e}: ${Ae(t)}`),`unreadable`}if(i===t)return`installed`;if(i!==null)return`foreign`;if(!I(e,n)){let t=C(n,O,e);return Z(t)&&X(t,r)?`missing`:K(e,n)?`unstamped`:`not-installed`}return`unstamped`}function Ae(e){return e instanceof Error?e.message:String(e)}function K(e,t){try{return c(C(t,O,e)),!0}catch{return!1}}function je(t){function i(e){let n=W(t,{silentStdout:e}),r=n.skills,i=t.stamp;if(e){console.log(JSON.stringify(r.map(e=>({name:e.frontmatter.name,description:e.frontmatter.description,owner:e.frontmatter.metadata?.[`politty-cli`]??null,expectedOwner:i,status:ke(e.frontmatter.name,i,t.cwd,t.sourceDir),sourcePath:e.sourcePath}))));return}if(r.length===0){U(n,t.sourceDir)?a.info(`Source directory scan failed; see warnings.`):a.info(`No skills found in source directory.`);return}a.info(`Available skills:`);for(let e of r){let n=ke(e.frontmatter.name,i,t.cwd,t.sourceDir);a.info(` ${e.frontmatter.name.padEnd(20)} ${n.padEnd(14)} ${e.frontmatter.description}`)}}return t.json.disabled?r({name:`list`,description:t.descriptions.list,args:n({},{unknownKeys:t.unknownKeys}),run(e){i(G(e,`json`))}}):r({name:`list`,description:t.descriptions.list,args:n({json:e.boolean({description:`Output as JSON`})},{unknownKeys:t.unknownKeys}),run(e){i(e.json)}})}function Me(e,t){let n=e.find(e=>e.frontmatter.name===t);if(!n){let n=e.map(e=>e.frontmatter.name).join(`, `)||`<none>`;throw Error(`Skill "${t}" not found in source directory. Available: ${n}`)}return n}function q(e){let t=[];return e.source!==void 0&&t.push(` Source: ${e.source.map(e=>e.frontmatter.name).join(`, `)||`<none>`}`),e.installed!==void 0&&t.push(` Installed: ${[...e.installed].sort().join(`, `)||`<none>`}`),t.join(`
1
+ import"./register-TbOCQNeI.js";import{d as e,n as t,u as n}from"./schema-extractor-fZZ2_WAZ.js";import{n as r}from"./command-tLHaJHe6.js";import{a as i,n as a}from"./logger-CoeDrmRr.js";import{copyFileSync as o,existsSync as s,lstatSync as c,mkdirSync as l,mkdtempSync as u,readFileSync as d,readdirSync as f,readlinkSync as p,realpathSync as m,renameSync as ee,rmSync as h,statSync as g,symlinkSync as te,unlinkSync as _}from"node:fs";import{basename as v,dirname as y,isAbsolute as b,join as x,parse as ne,relative as S,resolve as C,sep as w}from"node:path";import{parse as re}from"yaml";import{z as T}from"zod";const ie=/^[a-z0-9]+(-[a-z0-9]+)*$/;function E(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function ae(e){let t=[],n=(n,r)=>{let i=e[n];if(i===void 0){r.required&&t.push({path:[n],message:`Invalid input: expected string, received undefined`});return}if(typeof i!=`string`){t.push({path:[n],message:`Invalid input: expected string, received ${E(i)}`});return}r.min!==void 0&&i.length<r.min&&t.push({path:[n],message:`Too small: expected string to have >=${r.min} characters`}),r.max!==void 0&&i.length>r.max&&t.push({path:[n],message:`Too big: expected string to have <=${r.max} characters`})};n(`name`,{required:!0,min:1,max:64}),typeof e.name==`string`&&!ie.test(e.name)&&t.push({path:[`name`],message:`name must be lowercase alphanumerics separated by single hyphens`}),n(`description`,{required:!0,min:1,max:1024}),n(`license`,{min:1}),n(`compatibility`,{max:500}),n(`allowed-tools`,{});let r=e.metadata;if(r!==void 0){if(typeof r!=`object`||!r||Array.isArray(r))t.push({path:[`metadata`],message:`Invalid input: expected record, received ${E(r)}`});else for(let[e,n]of Object.entries(r))typeof n!=`string`&&t.push({path:[`metadata`,e],message:`Invalid input: expected string, received ${E(n)}`})}return t.length>0?{success:!1,issues:t}:{success:!0,data:{...e}}}const oe=/^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/;function D(e){let t=e.match(oe);if(!t)return{data:{},body:e};let n=t[1],r=t[2];try{let e=re(n);return se(e)?{data:e,body:r}:{data:{},body:r}}catch(e){return{data:{},body:r,parseError:e instanceof Error?e.message:String(e)}}}function se(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ce(e){let{data:t,body:n}=D(e),r=ae(t);return r.success?{frontmatter:r.data,body:n,rawContent:e}:null}const O=`.agents/skills`,k=[`.claude/skills`],A=`politty-cli`;function j(e){if(e.length<1||e.length>64||!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e))throw Error(`Invalid skill name: ${JSON.stringify(e)}`)}function le(e,t=process.cwd(),n={}){let r=e.frontmatter.name;j(r);let i=n.mode??`symlink`,a=e.frontmatter.metadata?.[`politty-cli`]??null;if(i===`copy`&&a===null)throw Error(`Refusing to install "${e.frontmatter.name}" in copy mode without an ownership stamp. Add metadata.${A}="{package}:{cli}" to the source SKILL.md so subsequent installs can replace the copy in place.`);let o=C(t,O),s=m(e.sourcePath),c=ue(e.sourcePath),u=[x(N(o),r),...k.map(e=>x(N(C(t,e)),r))].find(e=>ye(e,s));if(u!==void 0)throw Error(`Refusing to install "${r}": source ${s} overlaps install destination ${u}. Choose a sourceDir outside .agents/skills/ and any agent-specific slot directory (e.g. .claude/skills/).`);if(i===`symlink`){let e=N(o);M(x(e,r),S(e,c));for(let n of k){let i=N(C(t,n));M(x(i,r),x(S(i,e),r))}}l(o,{recursive:!0});let d=m(o),f=x(d,r);he(f,a),ge({linkTarget:S(d,c),linkPath:f,copyFrom:s,mode:i}),ve(t,r,f,a,i)}function M(e,t){if(b(t))throw Error(`Refusing to write an absolute symlink target at ${e} → ${t}. The skill source and install root appear to live on different filesystem roots (e.g. different Windows drive letters); retry with mode: "copy".`)}function ue(e){let t=C(e),{root:n}=ne(t),r=t.slice(n.length).split(w).filter(e=>e!==``),i=n;for(let[e,t]of r.entries()){let n=x(i,t),a;try{a=c(n)}catch{return x(i,...r.slice(e))}if(a.isSymbolicLink()){if(de(i))return x(i,...r.slice(e));i=m(n)}else i=n}return i}function de(e){return v(e)===`node_modules`||v(e).startsWith(`@`)&&v(y(e))===`node_modules`}function N(e){let t=e,n=[];for(;;)try{let e=m(t);return n.length===0?e:C(e,...n.reverse())}catch{let r=y(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[/\\]+/,``)),t=r}}function fe(e,t=process.cwd(),n={}){j(e);let r=n.expectedOwnership??null,i=C(t,O,e);for(let n of k)me(C(t,n,e),r,{restrictSymlinkTo:i});me(i,r)}function pe(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n);if(r===t)return!0;try{return m(r)===m(t)}catch{return!1}}function me(e,t,n={}){let r;try{r=c(e)}catch(e){if(R(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return;throw e}if(r.isSymbolicLink()){if(n.restrictSymlinkTo!==void 0){pe(e,n.restrictSymlinkTo)&&_(e);return}(t===null||F(e)===t)&&_(e);return}r.isDirectory()&&t!==null&&F(e)===t&&h(e,{recursive:!0,force:!0})}function he(e,t,n={}){let r;try{r=c(e)}catch(e){if(R(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return;throw e}if(r.isSymbolicLink()){if(n.restrictSymlinkTo===void 0||pe(e,n.restrictSymlinkTo)){_(e);return}throw Error(`Refusing to replace symlink at ${e}: it does not route to this CLI's canonical slot (${n.restrictSymlinkTo}). Remove or migrate the foreign symlink before retrying.`)}if(r.isDirectory()&&t!==null&&F(e)===t){h(e,{recursive:!0,force:!0});return}throw Error(`Refusing to replace non-symlink path at ${e}. This looks like a legacy or manual install; remove or migrate it before retrying.`)}function ge(e){let{linkTarget:t,linkPath:n,copyFrom:r,mode:i}=e;if(i===`copy`){_e(r,n);return}M(n,t);try{te(t,n,`dir`)}catch(e){let r=e instanceof Error?e.message:String(e);throw Error(`Failed to symlink ${n} → ${t}: ${r}. If this filesystem does not support symlinks (e.g. Windows without Developer Mode), retry with mode: "copy".`,{cause:e})}}function _e(e,t){let n=u(`${t}.partial-`);try{P(e,n),ee(n,t)}catch(e){try{h(n,{recursive:!0,force:!0})}catch{}throw e}}function P(e,t,n=/* @__PURE__ */ new Set){let r=g(e);if(r.isDirectory()){let r=m(e);if(n.has(r))throw Error(`Refusing to recursively copy cyclic directory symlink at ${e} (resolves to ${r}, already on the copy stack).`);n.add(r);try{l(t,{recursive:!0});for(let r of f(e))P(x(e,r),x(t,r),n)}finally{n.delete(r)}return}r.isFile()&&o(e,t)}function F(e){let t;try{t=d(x(e,`SKILL.md`),`utf-8`)}catch(e){if(R(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return null;throw e}let{data:n}=D(t),r=n.metadata;if(!r||typeof r!=`object`||Array.isArray(r))return null;let i=r[A];return typeof i==`string`?i:null}function I(e,t=process.cwd()){return j(e),s(C(t,O,e,`SKILL.md`))}function L(e,t=process.cwd()){j(e);let n=C(t,O,e,`SKILL.md`),r;try{r=d(n,`utf-8`)}catch(e){if(R(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return null;throw e}let{data:i}=D(r),a=i.metadata;if(!a||typeof a!=`object`||Array.isArray(a))return null;let o=a[A];return typeof o==`string`?o:null}function ve(e,t,n,r,i){for(let a of k){let o=C(e,a);l(o,{recursive:!0});let s=m(o),c=x(s,t);he(c,r,{restrictSymlinkTo:n});let u=m(C(n,`..`));ge({linkTarget:x(S(s,u),t),linkPath:c,copyFrom:n,mode:i})}}function R(e){return e instanceof Error&&typeof e.code==`string`}function ye(e,t){if(e===t)return!0;let n=(e,t)=>{let n=S(t,e);return n===``||n===`.`||!b(n)&&n!==`..`&&!n.startsWith(`..${w}`)};return n(e,t)||n(t,e)}const z=`SKILL.md`;function B(e){let t=[],n=[];try{let r;try{r=g(e)}catch(r){return H(r)&&(r.code===`ENOENT`||r.code===`ENOTDIR`)?n.push({path:e,reason:`missing-source`,message:`Source directory does not exist: ${e}`}):n.push({path:e,reason:`read-failed`,message:`Failed to stat source directory ${e}: ${V(r)}`}),{skills:t,errors:n}}if(!r.isDirectory())return n.push({path:e,reason:`missing-source`,message:`Source path is not a directory: ${e}`}),{skills:t,errors:n};let i=x(e,z),a=Se(i);if(a.kind===`error`)return n.push({path:e,reason:`read-failed`,message:`Failed to check ${i}: ${a.message}`}),{skills:t,errors:n};if(a.kind===`present`)return xe(be(e,{enforceParentMatch:!1}),t,n),{skills:t,errors:n};let o=f(e,{withFileTypes:!0});for(let r of o){let i=x(e,r.name),a;try{a=g(i).isDirectory()}catch(e){if(H(e)&&e.code===`ENOENT`&&!r.isSymbolicLink())continue;n.push({path:i,reason:`read-failed`,message:r.isSymbolicLink()?`Dangling symlink at ${i}: ${V(e)}`:`Failed to stat ${i}: ${V(e)}`});continue}if(!a)continue;let o=x(i,z),s=Se(o);if(s.kind===`error`){n.push({path:i,reason:`read-failed`,message:`Failed to check ${o}: ${s.message}`});continue}s.kind!==`absent`&&xe(be(i,{enforceParentMatch:!0}),t,n)}}catch(t){n.push({path:e,reason:`read-failed`,message:`Failed to scan ${e}: ${V(t)}`})}return t.sort((e,t)=>e.frontmatter.name<t.frontmatter.name?-1:+(e.frontmatter.name>t.frontmatter.name)),{skills:t,errors:n}}function be(e,t){let n=x(e,z),r;try{r=d(n,`utf-8`)}catch(t){return{path:e,reason:`read-failed`,message:`Failed to read ${n}: ${V(t)}`}}let{data:i,parseError:a}=D(r);if(a!==void 0)return{path:e,reason:`parse-failed`,message:`Invalid SKILL.md frontmatter in ${e}: YAML parse error: ${a}`};let o=ae(i);if(!o.success)return{path:e,reason:`parse-failed`,message:`Invalid SKILL.md frontmatter in ${e}: ${o.issues.map(e=>`${e.path.join(`.`)||`<root>`}: ${e.message}`).join(`; `)}`};if(t.enforceParentMatch){let t=v(e);if(t!==o.data.name)return{path:e,reason:`name-mismatch`,message:`Skill name "${o.data.name}" does not match directory "${t}"`,skillName:o.data.name}}return{frontmatter:o.data,sourcePath:e,rawContent:r}}function xe(e,t,n){`frontmatter`in e?t.push(e):n.push(e)}function V(e){return e instanceof Error?e.message:String(e)}function H(e){return e instanceof Error&&typeof e.code==`string`}function Se(e){try{return c(e),{kind:`present`}}catch(e){return H(e)&&e.code===`ENOENT`?{kind:`absent`}:{kind:`error`,message:V(e)}}}function Ce(e,t={}){let n=0,r=!1;for(let i of e){if(i.reason===`missing-source`||i.path===t.sourceDir){r=!0,a.warn(`Failed to scan source directory ${i.path}: ${i.message}`);continue}n+=1,a.warn(`Skipping skill at ${i.path}: ${i.message}`)}t.silentStdout||(n>0&&a.info(`${i.warning} Skipped ${n} skill(s) due to scan errors (see warnings above).`),r&&a.info(`${i.warning} Source directory scan failed (see warnings above); subsequent operations may be skipped.`))}function U(e,t){let n=e.errors.some(e=>e.reason===`missing-source`||e.path===t),r=e.errors.length>0&&e.skills.length===0;return n||r}function W(e,t={}){let n=B(e.sourceDir);return Ce(n.errors,{...t,sourceDir:e.sourceDir}),n}function we(e){let t={description:`Skill names to exclude from sync`};return e.excludeAlias!==void 0&&(t.alias=e.excludeAlias),t}function Te(e){let t={description:`Print install paths and modes`};return e.verbose.alias!==void 0&&(t.alias=e.verbose.alias),t}function G(e,t){return!!e[t]}function Ee(t){function i(e,n){let{skills:r,errors:i}=W(t),o=t.stamp,s=new Set(r.map(e=>e.frontmatter.name)),c=new Set(Ie(o,t.cwd,t.sourceDir)),l=Array.from(new Set(e.exclude)).filter(e=>!s.has(e)&&!c.has(e));if(l.length>0){let e=l.length===1?`Skill`:`Skills`,t=l.map(e=>JSON.stringify(e)).join(`, `);throw Error(`--exclude: ${e} ${t} not found in source directory or among installed skills.\n`+q({source:r,installed:c}))}let u=new Set(e.exclude),d=r.filter(e=>!u.has(e.frontmatter.name)),f=U({skills:r,errors:i},t.sourceDir),p=0;if(!f){let e=new Set(d.map(e=>e.frontmatter.name)),n=/* @__PURE__ */ new Set;for(let e of i)e.path!==t.sourceDir&&(n.add(v(e.path)),e.skillName!==void 0&&n.add(e.skillName));for(let r of c)e.has(r)||u.has(r)||n.has(r)||(Y(r,o,t.cwd,t.sourceDir),p+=1)}let m=0;for(let e of d)J(e,o,t,n),m+=1;if(m===0&&p===0){let e=f?`source directory scan failed; see warnings`:r.length>0&&d.length===0?`all skills excluded`:`no skills bundled`;a.info(`No skills installed (${e}).`)}else a.info(`Sync complete: ${m} installed, ${p} removed.`)}return t.verbose.disabled?r({name:`sync`,description:t.descriptions.sync,args:n({exclude:e.stringArray(we(t))},{unknownKeys:t.unknownKeys}),run(e){i(e,G(e,`verbose`))}}):r({name:`sync`,description:t.descriptions.sync,args:n({exclude:e.stringArray(we(t)),verbose:e.boolean(Te(t))},{unknownKeys:t.unknownKeys}),run(e){i(e,e.verbose)}})}function De(t){let i={positional:!0,description:`Skill name(s) to install (default: all)`,placeholder:`NAME`};function o(e,n){let r=W(t),i=r.skills,o=t.stamp;if(e.name.length>0){let r=new Set(i.map(e=>e.frontmatter.name)),a=Array.from(new Set(e.name)),s=a.filter(e=>!r.has(e));if(s.length>0){let e=s.length===1?`Skill`:`Skills`,t=s.map(e=>JSON.stringify(e)).join(`, `);throw Error(`${e} ${t} not found in source directory.\n`+q({source:i}))}let c=new Set(a);for(let e of i)c.has(e.frontmatter.name)&&J(e,o,t,n);return}if(i.length===0){U(r,t.sourceDir)?a.info(`No skills installed (source directory scan failed; see warnings).`):a.info(`No skills found in source directory.`);return}for(let e of i)J(e,o,t,n)}return t.verbose.disabled?r({name:t.commandNames.add.name,...t.commandNames.add.aliases.length>0?{aliases:t.commandNames.add.aliases}:{},description:t.descriptions.add,args:n({name:e.stringArray(i)},{unknownKeys:t.unknownKeys}),run(e){o(e,G(e,`verbose`))}}):r({name:t.commandNames.add.name,...t.commandNames.add.aliases.length>0?{aliases:t.commandNames.add.aliases}:{},description:t.descriptions.add,args:n({name:e.stringArray(i),verbose:e.boolean(Te(t))},{unknownKeys:t.unknownKeys}),run(e){o(e,e.verbose)}})}function Oe(t){return r({name:t.commandNames.remove.name,...t.commandNames.remove.aliases.length>0?{aliases:t.commandNames.remove.aliases}:{},description:t.descriptions.remove,args:n({name:e.optionalString({positional:!0,description:`Skill name to remove (default: all)`,placeholder:`NAME`})},{unknownKeys:t.unknownKeys}),run(e){let n=W(t),r=n.skills,i=t.stamp;if(e.name){if(r.some(t=>t.frontmatter.name===e.name)&&Me(r,e.name),!Y(e.name,i,t.cwd,t.sourceDir)){if(K(e.name,t.cwd))a.info(`${e.name} is installed without a ${A} stamp this CLI recognises; refusing to remove. Remove .agents/skills/${e.name} manually if intended.`);else{let n=new Set(Ie(i,t.cwd,t.sourceDir));a.info(`${e.name} is not installed; nothing to remove.\n`+q({installed:n}))}}return}if(r.length===0){U(n,t.sourceDir)?a.info(`No skills found (source directory scan failed; see warnings); nothing to remove.`):a.info(`No skills found in source directory; nothing to remove.`);return}let o=0;for(let e of r)Y(e.frontmatter.name,i,t.cwd,t.sourceDir)&&(o+=1);o===0&&a.info(`No installed skills owned by this CLI; nothing to remove.`)}})}function ke(e,t,n,r){let i;try{i=L(e,n)}catch(t){return a.warn(`Failed to read ownership for installed skill ${e}: ${Ae(t)}`),`unreadable`}if(i===t)return`installed`;if(i!==null)return`foreign`;if(!I(e,n)){let t=C(n,O,e);return Z(t)&&X(t,r)?`missing`:K(e,n)?`unstamped`:`not-installed`}return`unstamped`}function Ae(e){return e instanceof Error?e.message:String(e)}function K(e,t){try{return c(C(t,O,e)),!0}catch{return!1}}function je(t){function i(e){let n=W(t,{silentStdout:e}),r=n.skills,i=t.stamp;if(e){console.log(JSON.stringify(r.map(e=>({name:e.frontmatter.name,description:e.frontmatter.description,owner:e.frontmatter.metadata?.[`politty-cli`]??null,expectedOwner:i,status:ke(e.frontmatter.name,i,t.cwd,t.sourceDir),sourcePath:e.sourcePath}))));return}if(r.length===0){U(n,t.sourceDir)?a.info(`Source directory scan failed; see warnings.`):a.info(`No skills found in source directory.`);return}a.info(`Available skills:`);for(let e of r){let n=ke(e.frontmatter.name,i,t.cwd,t.sourceDir);a.info(` ${e.frontmatter.name.padEnd(20)} ${n.padEnd(14)} ${e.frontmatter.description}`)}}return t.json.disabled?r({name:`list`,description:t.descriptions.list,args:n({},{unknownKeys:t.unknownKeys}),run(e){i(G(e,`json`))}}):r({name:`list`,description:t.descriptions.list,args:n({json:e.boolean({description:`Output as JSON`})},{unknownKeys:t.unknownKeys}),run(e){i(e.json)}})}function Me(e,t){let n=e.find(e=>e.frontmatter.name===t);if(!n){let n=e.map(e=>e.frontmatter.name).join(`, `)||`<none>`;throw Error(`Skill "${t}" not found in source directory. Available: ${n}`)}return n}function q(e){let t=[];return e.source!==void 0&&t.push(` Source: ${e.source.map(e=>e.frontmatter.name).join(`, `)||`<none>`}`),e.installed!==void 0&&t.push(` Installed: ${[...e.installed].sort().join(`, `)||`<none>`}`),t.join(`
2
2
  `)}function J(e,t,n,r){let o=e.frontmatter.name,s=n.cwd,c=n.mode,l=e.frontmatter.metadata?.[`politty-cli`]??null;if(l!==t)throw Error(`Refusing to install "${o}": source SKILL.md declares metadata.${A}=${JSON.stringify(l)}, expected ${JSON.stringify(t)}.`);let u=L(o,s);if(u!==null&&u!==t)throw Error(`Refusing to install "${o}": owned by ${JSON.stringify(u)}, not ${JSON.stringify(t)}. Check metadata.${A} in .agents/skills/${o}/SKILL.md.`);let d=C(s,O,o),f=Z(d)&&X(d,n.sourceDir);if(u===null&&K(o,s)&&!f)throw Error(`Refusing to install "${o}": .agents/skills/${o} exists without a ${A} stamp, so it was not installed by this CLI. Remove it manually (or add the stamp to take ownership) before running "skills add".`);if(le(e,s,c===void 0?{}:{mode:c}),a.info(`${i.success} Installed ${o}`),r){let e=c??`symlink`;a.info(` mode=${e} path=${d}`)}}function Y(e,t,n,r){let o=L(e,n);if(o===null)return Ne(e,n,r)?(a.info(`${i.success} Removed ${e} (broken symlink)`),!0):!1;if(o!==t)throw Error(`Refusing to remove "${e}": owned by ${JSON.stringify(o)}, not ${JSON.stringify(t)}. Check metadata.${A} in .agents/skills/${e}/SKILL.md.`);return fe(e,n,{expectedOwnership:t}),a.info(`${i.success} Removed ${e}`),!0}function Ne(e,t,n){let r=C(t,O,e);if(!Z(r)||!X(r,n))return!1;for(let n of k){let i=C(t,n,e);Z(i)&&Fe(i,r)&&_(i)}return _(r),!0}function X(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n),i=Pe(C(t)),a=Pe(r),o=S(i,a);return!(b(o)||o===`..`||o.startsWith(`..${w}`))}function Pe(e){let t=e,n=[];for(;;)try{let e=m(t);return n.length===0?e:C(e,...n.reverse())}catch{let r=y(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[/\\]+/,``)),t=r}}function Fe(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n);if(r===t)return!0;try{return m(r)===m(t)}catch{return!1}}function Z(e){let t;try{t=c(e)}catch{return!1}return t.isSymbolicLink()?!s(e):!1}function Ie(e,t,n){let r=C(t,O),i=[],o;try{o=f(r,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`||a.warn(`Failed to enumerate ${r}: ${e instanceof Error?e.message:String(e)}`),i}for(let s of o){if(!s.isDirectory()&&!s.isSymbolicLink()||s.name.length<1||s.name.length>64||!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(s.name))continue;let o;try{o=L(s.name,t)}catch(e){a.warn(`Failed to read ownership for ${s.name}: ${e instanceof Error?e.message:String(e)}`);continue}if(o===e){i.push(s.name);continue}let c=C(r,s.name);o===null&&Z(c)&&X(c,n)&&i.push(s.name)}return i}const Le=[`add`,`install`],Re=[`remove`,`uninstall`],Q={skills:`Manage agent skills`,sync:`Remove and reinstall all skills from source`,add:`Install skills from source`,remove:`Remove installed skills`,list:`List available skills from source`},ze=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/,Be=[`.git`,`package.json`];function Ve(e,t){return{sourceDir:e.sourceDir,package:e.package,mode:e.mode,cwd:Ue(e.cwd),excludeAlias:Ge(e.flags?.exclude?.alias),verbose:qe(e.flags?.verbose,e.globalArgs),json:{disabled:$(e.globalArgs,`json`)},commandNames:{add:Ke(e.commandMap?.add,Le,`add`),remove:Ke(e.commandMap?.remove,Re,`remove`)},unknownKeys:e.unknownKeys??`strip`,descriptionAppend:Je(e.descriptionAppend,t),stamp:`${e.package}:${t}`,descriptions:He(e.descriptions)}}function He(e){return{skills:e?.skills??Q.skills,sync:e?.sync??Q.sync,add:e?.add??Q.add,remove:e?.remove??Q.remove,list:e?.list??Q.list}}function Ue(e){if(e!==void 0)return C(e);let t=process.cwd();return We(t)??t}function We(e){let t=C(e);for(;;){for(let e of Be)if(s(C(t,e)))return t;let e=y(t);if(e===t)return null;t=e}}function Ge(e){if(e!==!1)return typeof e==`string`?e:`x`}function Ke(e,t,n){let r=e??t;if(r.length===0)throw Error(`SkillCommandOptions.commandMap.${n} must include at least one name.`);let i=r.find(e=>!ze.test(e));if(i!==void 0)throw Error(`SkillCommandOptions.commandMap.${n} contains an invalid entry ${JSON.stringify(i)}. Names/aliases must start with an alphanumeric character and contain only alphanumeric characters, hyphens, or underscores.`);return{name:r[0],aliases:r.slice(1)}}function qe(e,t){return{alias:e?.alias===!1?void 0:e?.alias??`v`,disabled:$(t,`verbose`)}}function $(e,n){return e?t(e).fields.some(e=>e.name===n&&e.named&&e.type===`boolean`):!1}function Je(e,t){return e===!1?!1:typeof e==`string`?e:`Manage agent skills with \`${t} skills <add|sync|remove|list>\`.`}const Ye=[`parse-failed`,`name-mismatch`,`read-failed`,`missing-source`];function Xe(e,t){if(e.subCommands&&Object.hasOwn(e.subCommands,`skills`))throw Error(`withSkillCommand: command "${e.name}" already defines a "skills" subcommand.`);let n=Ve(t,e.name),i=n.commandNames.add.name,a=n.commandNames.remove.name,o=[`sync`,`list`,i,...n.commandNames.add.aliases,a,...n.commandNames.remove.aliases],s=o.find((e,t)=>o.indexOf(e)!==t);if(s)throw Error(`withSkillCommand: commandMap produced duplicate subcommand name/alias "${s}".`);let c=r({name:`skills`,description:n.descriptions.skills,subCommands:{sync:Ee(n),[i]:De(n),[a]:Oe(n),list:je(n)}});return{...e,description:Ze(e.description,n.descriptionAppend),subCommands:{...e.subCommands,skills:c}}}function Ze(e,t){return t===!1||t===``?e:e?e.endsWith(t)?e:`${e}\n\n${t}`:t}const Qe=T.object({name:T.string().min(1).max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:`name must be lowercase alphanumerics separated by single hyphens`}),description:T.string().min(1).max(1024),license:T.string().min(1).optional(),compatibility:T.string().max(500).optional(),metadata:T.record(T.string(),T.string()).optional(),"allowed-tools":T.string().optional()}).passthrough();export{A as OWNERSHIP_METADATA_KEY,Ye as SCAN_ERROR_REASONS,I as hasInstalledSkill,le as installSkill,D as parseFrontmatter,ce as parseSkillMd,L as readInstalledOwnership,B as scanSourceDir,Qe as skillFrontmatterSchema,fe as uninstallSkill,Xe as withSkillCommand};
@@ -1 +1 @@
1
- const e=`__politty_lazy__`;function t(t){return typeof t==`object`&&!!t&&e in t&&t[e]===!0}function n(t,n){return{[e]:!0,meta:t,load:n}}function r(e){return t(e)?e.meta:typeof e==`function`?null:e}async function i(e){return t(e)?await e.load():typeof e==`function`?await e():e}async function a(e,t){if(!e.subCommands)return;let n=Object.hasOwn(e.subCommands,t)?e.subCommands[t]:void 0;if(n)return{command:await i(n),aliasFor:void 0};let r=o(e,t);if(r)return{command:await i(e.subCommands[r]),aliasFor:r}}function o(e,t){if(e.subCommands){for(let[n,i]of Object.entries(e.subCommands))if(r(i)?.aliases?.includes(t))return n}}function s(e){let t=new Set;if(!e.subCommands)return t;for(let[n,i]of Object.entries(e.subCommands)){t.add(n);let e=r(i);if(e?.aliases)for(let n of e.aliases)t.add(n)}return t}function c(e){return e.subCommands?Object.keys(e.subCommands):[]}export{a,r as c,o as i,c as n,t as o,i as r,n as s,s as t};
1
+ const e=`__politty_lazy__`;function t(t){return typeof t==`object`&&!!t&&e in t&&t[e]===!0}function n(t,n){return{[e]:!0,meta:t,load:n}}function r(e){return t(e)?e.meta:typeof e==`function`?null:e}async function i(e){return t(e)?await e.load():typeof e==`function`?await e():e}async function a(e,t){if(!e.subCommands)return;let n=Object.hasOwn(e.subCommands,t)?e.subCommands[t]:void 0;if(n)return{command:await i(n),aliasFor:void 0};let r=o(e,t);if(r)return{command:await i(e.subCommands[r]),aliasFor:r}}function o(e,t){if(e.subCommands){for(let[n,i]of Object.entries(e.subCommands))if(r(i)?.aliases?.includes(t))return n}}function s(e){let t=/* @__PURE__ */ new Set;if(!e.subCommands)return t;for(let[n,i]of Object.entries(e.subCommands)){t.add(n);let e=r(i);if(e?.aliases)for(let n of e.aliases)t.add(n)}return t}function c(e){return e.subCommands?Object.keys(e.subCommands):[]}export{a,r as c,o as i,c as n,t as o,i as r,n as s,s as t};
@@ -1,3 +1,3 @@
1
- import{d as e,u as t}from"./schema-extractor-Du9ipDD4.js";import{n}from"./command-tLHaJHe6.js";import{s as r}from"./subcommand-router-D8GTMXYL.js";import{t as i}from"./schema-DhMPssIJ.js";import{existsSync as a,readFileSync as o}from"node:fs";import{join as s}from"node:path";import{spawn as c}from"node:child_process";function l(){let e=(process.env.SHELL||``).split(`/`).pop()?.toLowerCase()||``;return e.includes(`bash`)?`bash`:e.includes(`zsh`)?`zsh`:e.includes(`fish`)?`fish`:null}function u(e){return`${process.env.XDG_CACHE_HOME??`${process.env.HOME??``}/.cache`}/${e}`}function d(e,t,n){if(t===`fish`){let t=process.env.XDG_CONFIG_HOME??`${process.env.HOME??``}/.config`;return s(t,`fish`,`completions`,`${e}.fish`)}let r=n??u(e);return s(r,`completion.${t}`)}function f(e){try{if(!a(e))return null;let t=o(e,`utf8`).split(`
1
+ import{d as e,u as t}from"./schema-extractor-fZZ2_WAZ.js";import{n}from"./command-tLHaJHe6.js";import{s as r}from"./subcommand-router-DR2KBQAt.js";import{t as i}from"./schema-tWeEQULd.js";import{existsSync as a,readFileSync as o}from"node:fs";import{join as s}from"node:path";import{spawn as c}from"node:child_process";function l(){let e=(process.env.SHELL||``).split(`/`).pop()?.toLowerCase()||``;return e.includes(`bash`)?`bash`:e.includes(`zsh`)?`zsh`:e.includes(`fish`)?`fish`:null}function u(e){return`${process.env.XDG_CACHE_HOME??`${process.env.HOME??``}/.cache`}/${e}`}function d(e,t,n){if(t===`fish`){let t=process.env.XDG_CONFIG_HOME??`${process.env.HOME??``}/.config`;return s(t,`fish`,`completions`,`${e}.fish`)}let r=n??u(e);return s(r,`completion.${t}`)}function f(e){try{if(!a(e))return null;let t=o(e,`utf8`).split(`
2
2
  `,6).join(`
3
- `).match(/^# politty-bin-sig: (\S+)/m);return t?t[1]:null}catch{return null}}function p(e,t){return f(d(e.programName,t,e.cacheDir))!==null}function m(e,t){try{c(process.execPath,[e,`__refresh-completion`,t],{detached:!0,stdio:`ignore`}).unref()}catch{}}const h=t({shell:e.optionalEnum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell type (bash, zsh, or fish)`,placeholder:`SHELL`}),instructions:e.boolean({alias:`i`,description:`Show installation instructions`}),loader:e.boolean({description:`Print just the rc loader snippet (bash/zsh). Add it to ~/.bashrc or ~/.zshrc; it auto-regenerates the cache when the binary changes.`}),install:e.boolean({description:`Write the completion script to its on-disk cache (bash/zsh) or autoload location (fish) instead of printing it.`}),static:e.boolean({description:`Generate the legacy static completion script with command metadata baked in.`}),dispatcher:e.boolean({description:`Generate the runtime dispatcher completion script. This is the default.`}),worker:e.boolean({description:`Generate an internal static worker artifact for dispatcher mode.`})}),g=t({shell:e.enum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell to refresh`,placeholder:`SHELL`}),target:e.optionalString({positional:!0,description:`Existing politty-generated completion file to refresh`,placeholder:`TARGET`}),static:e.boolean({description:`Refresh using the legacy static completion script mode.`}),worker:e.boolean({description:`Refresh an internal static worker completion script.`})}),_=t({shell:e.enum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell worker to locate`,placeholder:`SHELL`})});function v(e,t){let{programName:a,globalArgsSchema:o,cacheDir:s,programVersion:c,bundledWorker:l}=typeof t==`string`?{programName:t}:t??{},u=a??e.name,d={...s!==void 0&&{cacheDir:s},...c!==void 0&&{programVersion:c},...o!==void 0&&{globalArgsSchema:o},...l!==void 0&&{bundledWorker:l}},f={...e};return f.subCommands={...e.subCommands,completion:r(n({name:`completion`,description:`Generate shell completion script`,args:h,run(){}}),()=>import(`./completion-8frPuaX8.js`).then(e=>e.createCompletionCommand(f,a,o,d))),__complete:r(n({name:`__complete`,args:i,run(){}}),()=>import(`./dynamic-C5e2NuDv.js`).then(e=>e.createDynamicCompleteCommand(f,a,o))),"__refresh-completion":r(n({name:`__refresh-completion`,description:`(internal) Refresh the on-disk completion cache if stale.`,args:g,run(){}}),()=>import(`./completion-8frPuaX8.js`).then(e=>e.createRefreshCompletionCommand(f,u,d))),"__completion-worker-path":r(n({name:`__completion-worker-path`,description:`(internal) Print the bundled completion worker path when available.`,args:_,run(){}}),()=>import(`./completion-8frPuaX8.js`).then(e=>e.createCompletionWorkerPathCommand(u,d)))},f.runMainHook=e=>{y(e,{programName:u,...s!==void 0&&{cacheDir:s}})},f}function y(e,t){if(process.env.POLITTY_NO_COMPLETION_REFRESH)return;let n=e.find(e=>!e.startsWith(`-`));if(n===`__complete`||n===`__refresh-completion`||n===`__completion-worker-path`||n===`completion`)return;let r=l();if(!r)return;let i=process.argv[1];i&&p(t,r)&&m(i,r)}export{d as a,_ as i,h as n,f as o,g as r,l as s,v as t};
3
+ `).match(/^# politty-bin-sig: (\S+)/m);return t?t[1]:null}catch{return null}}function p(e,t){return f(d(e.programName,t,e.cacheDir))!==null}function m(e,t){try{c(process.execPath,[e,`__refresh-completion`,t],{detached:!0,stdio:`ignore`}).unref()}catch{}}const h=t({shell:e.optionalEnum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell type (bash, zsh, or fish)`,placeholder:`SHELL`}),instructions:e.boolean({alias:`i`,description:`Show installation instructions`}),loader:e.boolean({description:`Print just the rc loader snippet (bash/zsh). Add it to ~/.bashrc or ~/.zshrc; it auto-regenerates the cache when the binary changes.`}),install:e.boolean({description:`Write the completion script to its on-disk cache (bash/zsh) or autoload location (fish) instead of printing it.`}),static:e.boolean({description:`Generate the legacy static completion script with command metadata baked in.`}),dispatcher:e.boolean({description:`Generate the runtime dispatcher completion script. This is the default.`}),worker:e.boolean({description:`Generate an internal static worker artifact for dispatcher mode.`})}),g=t({shell:e.enum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell to refresh`,placeholder:`SHELL`}),target:e.optionalString({positional:!0,description:`Existing politty-generated completion file to refresh`,placeholder:`TARGET`}),static:e.boolean({description:`Refresh using the legacy static completion script mode.`}),worker:e.boolean({description:`Refresh an internal static worker completion script.`})}),_=t({shell:e.enum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell worker to locate`,placeholder:`SHELL`})});function v(e,t){let{programName:a,globalArgsSchema:o,cacheDir:s,programVersion:c,bundledWorker:l}=typeof t==`string`?{programName:t}:t??{},u=a??e.name,d={...s!==void 0&&{cacheDir:s},...c!==void 0&&{programVersion:c},...o!==void 0&&{globalArgsSchema:o},...l!==void 0&&{bundledWorker:l}},f={...e};return f.subCommands={...e.subCommands,completion:r(n({name:`completion`,description:`Generate shell completion script`,args:h,run(){}}),()=>import(`./completion-CizQSJgq.js`).then(e=>e.createCompletionCommand(f,a,o,d))),__complete:r(n({name:`__complete`,args:i,run(){}}),()=>import(`./dynamic-DG-l9V-y.js`).then(e=>e.createDynamicCompleteCommand(f,a,o))),"__refresh-completion":r(n({name:`__refresh-completion`,description:`(internal) Refresh the on-disk completion cache if stale.`,args:g,run(){}}),()=>import(`./completion-CizQSJgq.js`).then(e=>e.createRefreshCompletionCommand(f,u,d))),"__completion-worker-path":r(n({name:`__completion-worker-path`,description:`(internal) Print the bundled completion worker path when available.`,args:_,run(){}}),()=>import(`./completion-CizQSJgq.js`).then(e=>e.createCompletionWorkerPathCommand(u,d)))},f.runMainHook=e=>{y(e,{programName:u,...s!==void 0&&{cacheDir:s}})},f}function y(e,t){if(process.env.POLITTY_NO_COMPLETION_REFRESH)return;let n=e.find(e=>!e.startsWith(`-`));if(n===`__complete`||n===`__refresh-completion`||n===`__completion-worker-path`||n===`completion`)return;let r=l();if(!r)return;let i=process.argv[1];i&&p(t,r)&&m(i,r)}export{d as a,_ as i,h as n,f as o,g as r,l as s,v as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@politty/zod",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "A lightweight CLI framework inspired by citty with zod v4 registry integration for type-safe metadata management",
5
5
  "keywords": [
6
6
  "argument-parser",
@@ -1 +0,0 @@
1
- import{i as e,n as t}from"./field-meta-_l-FHbh7.js";const n=new Set([`1`,`t`,`T`,`TRUE`,`true`,`True`]),r=new Set([`0`,`f`,`F`,`FALSE`,`false`,`False`]);function i(e){return n.has(e)?!0:!r.has(e)&&e}function a(e,t){return t===`boolean`?i(e):e}function o(e){let t=e.indexOf(`=`);return t>=0?e.slice(2,t):e.slice(2)}function s(e,t){let n=o(e);if(!e.includes(`=`)){let e=t.negationMap.get(n);if(e&&t.booleanFlags.has(e))return{resolvedName:e,withoutDashes:n,isNegated:!0,isCustomNegation:!0,isSuppressedNegation:!1}}let r=e.includes(`=`);if(!r&&n.startsWith(`no-`)){let e=n.slice(3);if(e===e.toLowerCase()){let r=t.aliasMap.get(e)??e;if(t.booleanFlags.has(r)){let e=t.aliasMap.get(n)??n;if(!t.definedNames.has(e))return t.defaultNegationDisabledFields.has(r)?{resolvedName:r,withoutDashes:n,isNegated:!1,isCustomNegation:!1,isSuppressedNegation:!0}:{resolvedName:r,withoutDashes:n,isNegated:!0,isCustomNegation:!1,isSuppressedNegation:!1}}}}if(!r&&n.length>2&&n.startsWith(`no`)&&/[A-Z]/.test(n[2])){let e=n[2].toLowerCase()+n.slice(3),r=t.aliasMap.get(e)??e;if(t.booleanFlags.has(r)){let e=t.aliasMap.get(n)??n;if(!t.definedNames.has(e))return t.defaultNegationDisabledFields.has(r)?{resolvedName:r,withoutDashes:n,isNegated:!1,isCustomNegation:!1,isSuppressedNegation:!0}:{resolvedName:r,withoutDashes:n,isNegated:!0,isCustomNegation:!1,isSuppressedNegation:!1}}}return{resolvedName:t.aliasMap.get(n)??n,withoutDashes:n,isNegated:!1,isCustomNegation:!1,isSuppressedNegation:!1}}const c=/^-\.?\d/;function l(e){return c.test(e)}function u(e,t={}){let{aliasMap:n=new Map,booleanFlags:r=new Set,arrayFlags:a=new Set,definedNames:o=new Set,negationMap:c=new Map,defaultNegationDisabledFields:u}=t,d={aliasMap:n,booleanFlags:r,definedNames:o,negationMap:c,defaultNegationDisabledFields:u??new Set(r)},f={options:{},positionals:[],rest:[]},p=0,m=!1,h=(e,t)=>{let r=n.get(e)??e;if(a.has(r)){let e=f.options[r];Array.isArray(e)?e.push(t):e===void 0?f.options[r]=[t]:f.options[r]=[e,t]}else f.options[r]=t};for(;p<e.length;){let t=e[p];if(m){f.rest.push(t),p++;continue}if(t===`--`){m=!0,p++;continue}if(t.startsWith(`--`)){let a=t.slice(2),o=s(t,d);if(o.isSuppressedNegation){h(o.withoutDashes,!0),p++;continue}if(o.isNegated){h(o.resolvedName,!1),p++;continue}let c=a.indexOf(`=`);if(c!==-1){let e=a.slice(0,c),t=a.slice(c+1),o=n.get(e)??e;h(e,r.has(o)?i(t):t),p++}else{let t=a,i=n.get(t)??t;if(r.has(i))h(t,!0),p++;else{let n=e[p+1];n!==void 0&&(!n.startsWith(`-`)||l(n))?(h(t,n),p+=2):(h(t,!0),p++)}}continue}if(t.startsWith(`-`)&&t.length>1&&!t.startsWith(`--`)){let a=t.slice(1),o=a.indexOf(`=`);if(o!==-1){let e=a.slice(0,o),t=a.slice(o+1),s=n.get(e)??e;h(e,r.has(s)?i(t):t),p++}else if(a.length===1){let t=a,i=n.get(t)??t;if(r.has(i))h(t,!0),p++;else{let n=e[p+1];n!==void 0&&(!n.startsWith(`-`)||l(n))?(h(t,n),p+=2):(h(t,!0),p++)}}else{for(let e of a)h(e,!0);p++}continue}f.positionals.push(t),p++}return f}function d(n){let r=new Map,i=new Set,a=new Set,o=new Set,s=new Map,c=new Set;for(let e of n.fields)o.add(e.name);for(let l of n.fields){if(!l.named)continue;l.cliName!==l.name&&r.set(l.cliName,l.name);for(let n of t(l))if(r.set(n,l.name),n.length>1&&n.includes(`-`)){let t=e(n);t!==n&&!o.has(t)&&!r.has(t)&&r.set(t,l.name)}let n=e(l.name);if(n!==l.name&&!o.has(n)&&!r.has(n)&&r.set(n,l.name),l.type===`boolean`&&i.add(l.name),l.type===`array`&&a.add(l.name),l.type===`boolean`&&l.negation!==!0&&(c.add(l.name),typeof l.negation==`string`&&(s.set(l.negation,l.name),l.negation.includes(`-`)))){let t=e(l.negation);t!==l.negation&&s.set(t,l.name)}}return{aliasMap:r,booleanFlags:i,arrayFlags:a,definedNames:o,negationMap:s,defaultNegationDisabledFields:c}}function f(e,t){return e.fields.filter(e=>e.positional&&!(e.named&&Object.hasOwn(t,e.name)))}function p(e,t){let n={...e.options},r=t.fields.filter(e=>e.positional),i=e.rest.length>0?[...e.positionals,...e.rest]:e.positionals;for(let e of r)e.named||delete n[e.name];let a=0;for(let r of f(t,e.options)){if(a>=i.length)break;if(r.type===`array`){n[r.name]=i.slice(a);break}n[r.name]=i[a],a++}return n}export{o as a,f as i,p as n,s as o,u as r,a as s,d as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./cli-main-uRzr666k.js";export{e as runPolittyCli};
@@ -1,2 +0,0 @@
1
- import{d as e,u as t}from"./schema-extractor-Du9ipDD4.js";import{n}from"./command-tLHaJHe6.js";import{n as r}from"./runner-BTD1-gUd.js";import{chmodSync as i,existsSync as a,mkdirSync as o,readFileSync as s,writeFileSync as c}from"node:fs";import{basename as l,dirname as u,extname as d,isAbsolute as f,join as p,relative as m,resolve as h}from"node:path";import{fileURLToPath as g}from"node:url";const _=`Generated by politty: compile-cache bin shim`,v=[`./cli.js`,`./cli.mjs`,`./index.js`,`./index.mjs`];function y(e){let t=h(e);for(;;){let e=p(t,`package.json`);if(a(e))return{pkg:JSON.parse(s(e,`utf8`)),dir:t};let n=u(t);if(n===t)return;t=n}}function b(e){if(!e)return[];if(typeof e.bin==`string`&&e.bin){let t=x(e);return t?[[t,e.bin]]:[]}return typeof e.bin==`object`&&e.bin!==null?Object.entries(e.bin).filter(e=>typeof e[1]==`string`&&e[1]!==``):[]}function x(e){if(e){if(typeof e.bin==`object`&&e.bin!==null){let[t]=Object.keys(e.bin);if(t)return t}if(typeof e.name==`string`&&e.name){let t=e.name;return t.startsWith(`@`)?t.split(`/`)[1]??t:t}}}function S(e){let t=u(e),n=l(e);for(let e of v)if(l(e)!==n&&a(p(t,e)))return e}function C(e,t,n){return[`#!/usr/bin/env node`,``,`// ${_}.`,`// Enables the Node.js on-disk compile cache (V8 code cache) before the`,`// CLI module graph is compiled, so warm starts skip recompilation`,`// (Node >= 22.8.0; silent no-op otherwise).`,`try {`,` const { enableCompileCache } = await import(${JSON.stringify(n)});`,` enableCompileCache(${JSON.stringify(e)});`,`} catch {`,` // ${n} is not resolvable from here (e.g. a fully`,` // bundled CLI) — start without the compile cache rather than failing`,` // the CLI.`,`}`,`await import(${JSON.stringify(t)});`,``].join(`
2
- `)}function w(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function T(e){return(t={})=>E(`${e}/compile-cache`,t)}function E(e,t){let n=t.cwd??process.cwd(),r=y(n),l=r?.pkg,p=w(t.entry),m=w(t.out),T=b(l),E;if(m.length>0){if(p.length>0&&p.length!==m.length)throw Error(`--entry count (${p.length}) does not match --out count (${m.length}); pass one --out per --entry or omit --out entirely.`);E=m.map(e=>f(e)?e:h(n,e))}else{if(T.length===0||r===void 0)throw Error(`Cannot derive the output path: no bin entry in package.json. Pass --out explicitly.`);if(p.length>0&&p.length!==T.length)throw Error(`--entry count (${p.length}) does not match the package's bin entries (${T.length}); pass one --entry per bin (in declaration order) or matching --out paths.`);E=T.map(([,e])=>h(r.dir,e))}if(new Set(E).size!==E.length)throw Error(`Duplicate output paths; each shim needs a distinct output file. Check the --out values (or the bin paths in package.json when --out is omitted).`);let O=new Map;if(r)for(let[e,t]of T)O.set(h(r.dir,t),e);let k=[],A=t.compileCacheSpecifier??e;if(/[\r\n\u2028\u2029]/.test(A))throw Error(`Invalid compile-cache specifier ${JSON.stringify(A)}: a module specifier cannot contain a line terminator.`);let j=E.map((e,r)=>{let i=O.get(e),o=t.program??i??x(l);if(!o)throw Error(`Cannot derive a program name: no bin or name in package.json. Pass --program explicitly.`);if(t.program===void 0&&i===void 0&&m.length>0&&k.push(`Warning: ${D(e,n)} does not match any bin path in package.json, so its cache directory uses the program name ${JSON.stringify(o)}. Pass --program to override.`),e.endsWith(`.cjs`))throw Error(`The generated shim is an ES module and cannot be written to a .cjs file. Use a .mjs (or .js in a "type": "module" package) output path.`);if(d(e)===``)throw Error(`The generated shim is an ES module and cannot be written to an extensionless file (it would not load on every supported Node.js version). Use a .mjs (or .js in a "type": "module" package) output path.`);if(e.endsWith(`.js`)&&l?.type!==`module`)throw Error(l===void 0?`The generated shim is an ES module, and no package.json was found to confirm .js files are treated as ESM. Write it to a .mjs file instead (e.g. --out dist/bin.mjs).`:`The generated shim is an ES module, but the package is not "type": "module". Write it to a .mjs file instead (e.g. --out dist/bin.mjs).`);let c=p[r]??S(e);if(c===void 0)throw Error(`Cannot derive an entry: none of ${v.join(`, `)} exist next to ${e}. Pass --entry explicitly.`);if(!c.startsWith(`./`)&&!c.startsWith(`../`)&&!c.startsWith(`file:`))throw Error(`Invalid entry ${c}: pass a specifier relative to the shim file ("./..." or "../...") or a file: URL.`);let f;if(c.startsWith(`file:`))try{f=g(c)}catch{f=void 0}else f=h(u(e),c);if(f===e)throw Error(`The shim at ${e} would import itself (entry ${c}). Point bin at a separate shim path (e.g. dist/bin.js) or pass a different --entry.`);if(a(e)&&!s(e,`utf8`).includes(_))throw Error(`Refusing to overwrite ${e}: it exists and was not generated by politty. If bin currently points at your real CLI entry, point it at a separate shim path (e.g. dist/bin.js) or pass --out explicitly.`);return{outputPath:e,program:o,entry:c,compileCacheSpecifier:A}});for(let e of k)console.warn(e);for(let{outputPath:e,program:t,entry:n}of j)o(u(e),{recursive:!0}),c(e,C(t,n,A)),i(e,493);return j}function D(e,t){let n=m(t,e);return n&&!n.startsWith(`..`)?n:e}const O=t({bin:e.string({description:`CLI binary or built JS entry file to invoke`,placeholder:`PATH`}),program:e.string({description:`Program name embedded in worker metadata`,placeholder:`NAME`}),shell:e.enum([`bash`,`zsh`,`fish`],{description:`Shell worker to generate`,placeholder:`SHELL`}),out:e.optionalString({description:`Output worker path (defaults to dist/completion/<shell>-worker.<ext>)`,placeholder:`PATH`}),verify:e.boolean({description:`Verify __completion-worker-path resolves to the generated worker`})}),k=n({name:`generate-worker`,description:`Generate and verify a bundled shell completion worker`,args:O,async run(e){let{generateBundledCompletionWorker:t}=await import(`./completion-8frPuaX8.js`);await t({bin:e.bin,programName:e.program,shell:e.shell,...e.out!==void 0&&{outputPath:e.out},verify:e.verify})}}),A=t({entry:e.optionalStringArray({description:`Module specifier the shim imports, relative to the shim file; repeatable, one per bin/--out (defaults to ./cli.js, ./cli.mjs, ./index.js, or ./index.mjs next to each shim)`,placeholder:`SPECIFIER`}),out:e.optionalStringArray({description:`Output path for the generated shim; repeatable, one per --entry (defaults to the bin paths in package.json)`,placeholder:`PATH`}),program:e.optionalString({description:`Program name for the cache directory, applied to all shims (defaults per shim to its bin name)`,placeholder:`NAME`}),compileCacheSpecifier:e.optionalString({description:`Module specifier the shim imports enableCompileCache from (defaults to the compile-cache subpath of the politty package running this command)`,placeholder:`SPECIFIER`})});function j(e){let t=T(e),i=n({name:`generate-shim`,description:`Generate a compile-cache bin shim that loads the real CLI via dynamic import`,args:A,run(e){let n=process.cwd(),r=t({...e.entry!==void 0&&{entry:e.entry},...e.out!==void 0&&{out:e.out},...e.program!==void 0&&{program:e.program},...e.compileCacheSpecifier!==void 0&&{compileCacheSpecifier:e.compileCacheSpecifier},cwd:n});for(let e of r)console.log(`Generated compile-cache shim: ${D(e.outputPath,n)} (program: ${e.program}, entry: ${e.entry}, compile-cache: ${e.compileCacheSpecifier})`)}}),a=n({name:`politty`,description:`politty development utilities`,subCommands:{"generate-shim":i,"generate-worker":k}});return r(a).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)})}export{T as n,j as t};
@@ -1 +0,0 @@
1
- import"./register-BXOytPt7.js";const{runPolittyCli:e}=await import(`./cli-main-BX5IVgNq.js`);await e(`@politty/zod`);export{};
@@ -1 +0,0 @@
1
- import"./with-completion-command-CQcqFHq8.js";import"./dynamic-4uRohypH.js";import{c as e,n as t,r as n,t as r}from"./completion-OvSe3W9y.js";export{r as createCompletionCommand,t as createCompletionWorkerPathCommand,n as createRefreshCompletionCommand,e as generateBundledCompletionWorker};
@@ -1,6 +0,0 @@
1
- import{i as e,n as t}from"./field-meta-_l-FHbh7.js";import{a as n,l as r,n as i}from"./schema-extractor-Du9ipDD4.js";import{n as a}from"./command-tLHaJHe6.js";import{c as o,i as s}from"./subcommand-router-D8GTMXYL.js";import{i as c}from"./argv-parser-DZQ0qnXG.js";import{t as l}from"./schema-DhMPssIJ.js";import{execSync as u}from"node:child_process";function d(e,t,n){return{fieldName:e.name,isArrayOption:e.valueType===`array`,isGlobal:e.isGlobal===!0,resolvedDeps:p(e.valueCompletion,e.isGlobal===!0,t,n)}}function f(e,t,n){return{fieldName:e.name,isArrayOption:!1,isGlobal:!1,resolvedDeps:p(e.valueCompletion,!1,t,n)}}function p(e,t,n,r=[]){if(e?.type!==`expand`)return[];let i=new Set,a=new Set;for(let e of n)e.isGlobal===!0?i.add(e.name):a.add(e.name);for(let e of r)a.add(e.name);return e.dependsOn.map(e=>({name:e,isGlobal:t||i.has(e)&&!a.has(e)}))}function m(e){let t=`$'`;for(let n of e){let e=n.codePointAt(0);t+=n===`\\`?`\\\\`:n===`'`?`\\'`:n===`
2
- `?`\\n`:n===`\r`?`\\r`:n===` `?`\\t`:e<32||e===127?`\\x${e.toString(16).padStart(2,`0`)}`:n}return t+=`'`,t}function h(e){return`'${e.replace(/'/g,`'\\''`)}'`}function g(e,t){let n=t.withSize?`%Y:%s`:`%Y`,r=t.withSize?`%m:%z`:`%m`,i=`stat -L -c '${n}' "${e}" 2>/dev/null`,a=`stat -L -f '${r}' "${e}" 2>/dev/null`;return t.shell===`fish`?`(${i}; or ${a})`:`$(${i} || ${a})`}function _(e){return e.length===1?`-${e}`:`--${e}`}function v(t,n){y(t,_(n)),n.length===1?y(t,`--${n}`):n.includes(`-`)&&y(t,`--${e(n)}`)}function y(e,t){e.includes(t)||e.push(t)}function b(t,n){let r=[`--${t}`];t.length===1&&r.push(`-${t}`),t.includes(`-`)&&r.push(`--${e(t)}`);for(let e of n??[])v(r,e);return r}function x(e){let t=new Set;for(let n of e)if(n.isGlobal===!0){n.cliName.length===1&&t.add(`-${n.cliName}`);for(let e of n.alias??[])e.length===1&&t.add(`-${e}`)}return t}function S(t,n,r,i){let a=new Set(b(t,n));if(r&&(a.add(`--${r}`),r.includes(`-`)&&a.add(`--${e(r)}`)),i?.frameOptions){if(i.isGlobal===!0){for(let e of i.frameOptions)if(e.isGlobal!==!0)for(let t of E(e.cliName,e.alias))a.delete(t)}else{let e=x(i.frameOptions);if(e.size>0){let t=new Set((n??[]).filter(e=>e.length===1).map(e=>`-${e}`));for(let n of e)t.has(n)||a.delete(n)}}}return[...a].map(e=>`"${e}"`)}function C(e,t){return e.map(e=>{let n=t.find(t=>t.isGlobal!==!0&&t.name===e.name);return n&&S(n.cliName,n.alias,n.negation,{frameOptions:t})})}function w(e,t,n,r=`$_pos_count`){let i=C(e,t);if(i.every(e=>e===void 0))return;let a=[` local _slot=-1 _left=${r}`];return e.forEach((e,t)=>{let r=i[t],o=r?` && __${n}_not_used ${r.join(` `)}`:``,s=e.variadic?`_slot=${e.position}`:`if (( _left == 0 )); then _slot=${e.position}; else (( _left-- )); fi`;a.push(` if (( _slot < 0 ))${o}; then ${s}; fi`)}),a}function T(e,t){let n=[`__${e}_track_positionals() {`,` local _k=0 _w`,' for _w in "${_pos_words[@]}"; do',` local _slot=$_k`,` case "$_subcmd" in`];for(let r of t){n.push(` ${r.pathStrs.map(e=>`"${e}"`).join(`|`)})`);for(let t of w(r.positionals,r.options,e,`$_k`)??[])n.push(` ${t}`);n.push(` ;;`)}return n.push(` esac`,` __${e}_track_pos "$_subcmd" "$_slot" "$_w"`,` (( _k++ ))`,` done`,`}`,``),n}function E(t,n){let r=[`--${t}`];t.includes(`-`)&&r.push(`--${e(t)}`);for(let e of n??[])v(r,e);return r}function D(e){let t=e.completion;if(t?.custom){let n=t.custom,r=[];if(n.expand&&r.push(`expand`),n.resolve&&r.push(`resolve`),n.choices&&n.choices.length>0&&r.push(`choices`),n.shellCommand&&r.push(`shellCommand`),r.length>1)throw Error(`Field "${e.name??`<unknown>`}": completion.custom may only specify one of choices, shellCommand, resolve, expand (got ${r.join(`, `)}).`);if(n.expand)return{type:`pending-expand`,spec:n.expand};if(n.resolve)return{type:`dynamic`,resolve:n.resolve};if(n.choices&&n.choices.length>0)return{type:`choices`,choices:n.choices};if(n.shellCommand)return{type:`command`,shellCommand:n.shellCommand}}if(t?.type){if(t.type===`file`)return t.matcher?{type:`file`,matcher:t.matcher}:t.extensions?{type:`file`,extensions:t.extensions}:{type:`file`};if(t.type===`directory`)return{type:`directory`};if(t.type===`none`)return{type:`none`}}if(e.enumValues&&e.enumValues.length>0)return{type:`choices`,choices:e.enumValues}}function O(e){if(e)return e.type===`pending-expand`?{type:`runtime-expand`,dependsOn:e.spec.dependsOn,enumerate:e.spec.enumerate}:e}function ee(e){return e.args?te(e.args):[]}function te(e){return n(i(e)).map(k)}function k(e){let n=t(e);return{name:e.name,cliName:e.cliName,alias:n.length>0?n:void 0,negation:e.negationDisplay,negationDescription:e.negationDescription,description:e.description,takesValue:e.type!==`boolean`,valueType:e.type,required:e.required,defaultNegationAccepted:e.type===`boolean`&&e.negation===!0,valueCompletion:O(D(e))}}function A(e){return new Set(b(e.cliName,e.alias))}function ne(e,t){let n=A(t);for(let t of e)for(let e of A(t))if(n.has(e))return t}function re(e,t,n){let r=new Set;if(t.length===0)return r;let i=new Set,a=(e,t)=>{B(n,e,t,i),r.add(e.name)},o=0;for(;o<e.length;){let i=e[o];if(i===`--`||!i.startsWith(`-`))break;if(!i.startsWith(`--`)&&i.length>2){let e=i.indexOf(`=`);if((e>=0?i.slice(1,e):i.slice(1)).length>1)break}let s=F(i),c=U(t,s);if(!c){if(le(t,s)){o++;continue}break}if(c.takesValue){if(I(i)){let e=i.indexOf(`=`);a(c,i.slice(e+1)),o++}else if(o+1<e.length){let t=e[o+1];if(t.startsWith(`-`)){o++;continue}a(c,t),o+=2}else break}else n[c.name]=!V(c,s),r.add(c.name),o++}return r}function ie(e,t){return t.valueType===`array`?Array.isArray(e)?e:[e]:Array.isArray(e)?e.at(-1):e}function j(e,t){return t.length===0?e:[...e,...t]}function M(e,t){let n=t.length-1;if(!(n<0))return e>n?n:e}function N(e,t){return n=>{let r={...e};return c(n,e).forEach((e,n)=>{n<t.length&&(r[e.name]=t[n])}),r}}function ae(e,t,n){if(!e.args)return;let a=i(e.args),o=r(a,N(t,n));if(o!==a)return o.fields.filter(e=>e.named).map(k)}function oe(e,t,n){if(!e.args)return[];let a=r(i(e.args),N(t,n));return c(a,t).map((e,t)=>({name:e.name,cliName:e.cliName,position:t,description:e.description,required:e.required,variadic:e.type===`array`,valueCompletion:O(D(e))}))}function se(e){if(!e.subCommands)return[];let t=[];for(let[n,r]of Object.entries(e.subCommands)){if(n.startsWith(`__`))continue;t.push(n);let e=o(r);e?.aliases&&t.push(...e.aliases)}return t}function ce(e,t){if(!e.subCommands)return null;let n=Object.hasOwn(e.subCommands,t)?e.subCommands[t]:void 0;if(n)return o(n);let r=s(e,t);return r?o(e.subCommands[r]):null}function P(e){return e.startsWith(`-`)}function F(e){if(e.startsWith(`--`)){let t=e.slice(2),n=t.indexOf(`=`);return{name:n>=0?t.slice(0,n):t,isLong:!0}}return e.startsWith(`-`)?{name:e.slice(1,2),isLong:!1}:{name:e,isLong:!0}}function I(e){return e.includes(`=`)}function L(t,n,r){if(!r||t.valueType!==`boolean`)return!1;let i=[t.cliName,...t.alias??[]];for(let t of i){let r=`no-${t}`;if(n===r||n===e(r))return!0}return!1}function R(e,t,n){return e.defaultNegationAccepted===!0&&L(e,t,n)}function le(e,t){return e.some(e=>e.defaultNegationAccepted!==!0&&L(e,t.name,t.isLong))}function z(t,n){return t!==void 0&&t.includes(`-`)&&e(t)===n}function B(e,t,n,r){if(t.valueType!==`array`){e[t.name]=n;return}if(r.has(t.name)){let r=e[t.name];e[t.name]=Array.isArray(r)?[...r,n]:[n]}else e[t.name]=[n],r.add(t.name)}function V(e,t){return t.isLong?e.negation!==void 0&&(e.negation===t.name||z(e.negation,t.name))?!0:R(e,t.name,t.isLong):!1}function H(e,t,n){if(e.cliName===t&&(n||e.cliName.length===1))return!0;if(e.alias){for(let r of e.alias)if(r===t&&(n||r.length===1))return!0}return n&&e.negation===t?!0:!n||t.length<=1?!1:z(e.cliName,t)||e.alias?.some(e=>z(e,t))?!0:z(e.negation,t)}function U(e,t){if(!t.isLong){let n=e.find(e=>e.isGlobal!==!0&&e.alias?.includes(t.name)===!0);if(n)return n;let r=e.find(e=>e.isGlobal===!0&&H(e,t.name,t.isLong));if(r)return r}return e.find(e=>H(e,t.name,t.isLong))||e.find(e=>R(e,t.name,t.isLong))}function W(e,t,n){let r=G(e,t,n);return r.variantOptions?G(e,t,n,{command:r.context.currentCommand,options:r.variantOptions}).context:r.context}function G(e,t,n,r){let i=e=>e===r?.command?r.options:ee(e),a=t,o=[],s=n?te(n).map(e=>({...e,isGlobal:!0})):[],c=new Set,l=!1,u=0,d={},f=[],p={},m=new Set,h=0,g=new Set,_=e=>{c.add(e.cliName);for(let t of e.alias??[])c.add(t);e.negation&&c.add(e.negation),l=!0},v=(e,t)=>{B(e.isGlobal===!0?p:d,e,t,g)},y=(e,t)=>{let n=e.isGlobal===!0?p:d;n[e.name]=!V(e,t)},b=0,x=j(i(a),s),S=!1;for(;b<e.length-1;){let t=e[b];if(!S&&t===`--`){S=!0,b++;continue}if(!S&&t.startsWith(`-`)&&!t.startsWith(`--`)&&t.length>2&&!t.includes(`=`)){l=!0;let e=Array.from(t.slice(1)),n=x.filter(e=>e.isGlobal!==!0);for(let t of e){let e=U(n,{name:t,isLong:!1});e&&!e.takesValue&&(_(e),y(e,{name:t,isLong:!1}))}b++;continue}if(!S&&P(t)){l=!0;let n=F(t),r=U(x,n);if(r){if(_(r),r.takesValue){if(I(t)){let e=t.indexOf(`=`);v(r,t.slice(e+1))}else if(b+1<e.length-1){let t=e[b+1];P(t)||(v(r,t),b++)}}else y(r,n)}b++;continue}let n=S?null:ce(a,t);if(n){o.push(t);let r=i(a),l=e.slice(h,b);for(let e of re(l,s,p))m.add(e);a=n,x=j(i(a),s);for(let e of Object.keys(d)){let t=r.find(t=>t.name===e),n=s.find(t=>t.name===e)??(t?ne(s,t):void 0);n&&(m.has(n.name)||(p[n.name]=ie(d[e],n)))}c.clear(),u=0,d={},f=[],g=new Set,h=b+1,b++;continue}f.push(t),u++,b++}let C=e[e.length-1]??``,w=e[e.length-2]??``,T=ae(a,d,f),E=oe(a,d,f),D=se(a);for(let e=0;e<E.length;e++){let t=E[e];if(t.variadic){d[t.name]=f.slice(e);break}e<f.length&&(d[t.name]=f[e])}let O,k,A;if(!S&&w&&P(w)&&!I(w)){let e=U(x,F(w));e&&e.takesValue?(O=`option-value`,k=e):C.startsWith(`-`)?O=`option-name`:(O=K(C,D,E,u),O===`positional`&&(A=u))}else if(!S&&C.startsWith(`-`)&&I(C)){let e=U(x,F(C));e&&e.takesValue?(O=`option-value`,k=e):O=`option-name`}else!S&&C.startsWith(`-`)?O=`option-name`:(O=K(C,D,E,u,S),O===`positional`&&(A=u));let N=[];if(k){if(k.valueType===`array`){let e=(k.isGlobal===!0?p:d)[k.name];N=Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}}else if(O===`positional`&&A!==void 0){let e=M(A,E);e!==void 0&&E[e]?.variadic&&(N=f.slice(e))}let L={...p,...d};return{context:{subcommandPath:o,currentCommand:a,currentWord:C,previousWord:w,completionType:O,targetOption:k,positionalIndex:A,options:x,subcommands:D,positionals:E,usedOptions:c,hasAnyOptionBeenUsed:l,providedPositionalCount:u,parsedArgs:L,previousValues:N},variantOptions:T}}function K(e,t,n,r,i){return i?`positional`:t.length>0&&(t.filter(t=>t.startsWith(e)).length>0||e===``)?`subcommand`:r<n.length||n.length>0&&n[n.length-1].variadic?`positional`:`subcommand`}const q={Default:0,NoSpace:1,NoFileCompletion:2,FilterPrefix:4,KeepOrder:8,FileCompletion:16,DirectoryCompletion:32,Error:64};function J(e){if(!e.startsWith(`-`))return;let t=e.indexOf(`=`);if(!(t<=0))return e.slice(0,t+1)}async function Y(e,t){switch(e.completionType){case`subcommand`:return ve(e);case`option-name`:return Z(e);case`option-value`:{let n=e.targetOption,r=n?J(e.currentWord):void 0;return xe(r?{...e,currentWord:e.currentWord.slice(r.length)}:e,t,n?.name,n?.valueCompletion,void 0,n?.valueType===`array`)}case`positional`:{let n=ue(e);return n?xe(e,t,n.name,n.valueCompletion,n.description,!1):{candidates:[],directive:q.NoFileCompletion}}}}function ue(e){let t=e.positionalIndex??0,n=M(t,e.positionals);if(n===void 0)return;let r=e.positionals[n];if(r)return n===t||r.variadic?r:void 0}function de(e){try{return u(e,{encoding:`utf-8`,timeout:5e3}).split(`
3
- `).map(e=>e.trim()).filter(e=>e.length>0).map(e=>({value:e,type:`value`}))}catch{return[]}}function X(e){return e?.type===`choices`?e.choices:void 0}function fe(e,t){let n=e.options.find(e=>e.name===t&&e.isGlobal!==!0);if(n)return X(n.valueCompletion);let r=e.positionals.find(e=>e.name===t);return X(r?r.valueCompletion:e.options.find(e=>e.name===t&&e.isGlobal===!0)?.valueCompletion)}function pe(e,t){let n=!t.includes(`=`),r=n?me(e):he(e,t);return{candidates:r,hasEqSuffix:n&&r.some(e=>e.value.endsWith(`=`))}}function me(e){let t=new Set,n=[];for(let r of e){let e=r.value.indexOf(`=`);if(e<=0){n.push(r);continue}let i=r.value.slice(0,e+1);t.has(i)||(t.add(i),n.push({...r,value:i}))}return n}function he(e,t){let n=t.slice(0,t.indexOf(`=`)+1);return e.filter(e=>e.value!==n)}async function ge(e,t,n,r,i){let a=[],o=q.FilterPrefix,s,c;switch(e.type){case`choices`:if(e.choices)for(let t of e.choices)a.push({value:t,description:r,type:`value`});o|=q.NoFileCompletion;break;case`file`:e.matcher&&e.matcher.length>0?(c=e.matcher.filter(e=>e.trim().length>0),c.length===0&&(c=void 0,o|=q.FileCompletion)):e.extensions&&e.extensions.length>0?(s=Array.from(new Set(e.extensions.map(e=>e.trim().replace(/^\./,``)).filter(e=>e.length>0))),s.length===0&&(s=void 0,o|=q.FileCompletion)):o|=q.FileCompletion;break;case`directory`:o|=q.DirectoryCompletion;break;case`command`:e.shellCommand&&a.push(...de(e.shellCommand)),o|=q.NoFileCompletion;break;case`none`:o|=q.NoFileCompletion;break;case`dynamic`:try{let n=await e.resolve(t);for(let e of n.candidates){let t=typeof e==`string`?{value:e}:e;a.push({...t,type:`value`})}o=n.directive??q.FilterPrefix|q.NoFileCompletion}catch{o=q.NoFileCompletion|q.Error}break;case`expand`:o|=q.NoFileCompletion;break;case`runtime-expand`:{let r={},i=!1;for(let a of e.dependsOn){let e=t.parsedArgs[a],o=Array.isArray(e)?e[e.length-1]:e,s=fe(n,a);if(typeof o!=`string`||s===void 0||!s.includes(o)){i=!0;break}r[a]=o}if(!i)try{let t=new Set;for(let n of e.enumerate(r)){let e=typeof n==`string`?{value:n}:n;t.has(e.value)||(t.add(e.value),a.push({...e,type:`value`}))}}catch{o=q.NoFileCompletion|q.Error;break}o|=q.NoFileCompletion;break}}if(e.type===`dynamic`||e.type===`expand`||e.type===`runtime-expand`){let n=pe(e.type===`runtime-expand`&&i===!0?_e(a,t.previousValues):a,t.currentWord);return n.hasEqSuffix&&(o|=q.NoSpace),{candidates:n.candidates,directive:o,fileExtensions:s,fileMatchers:c}}return{candidates:a,directive:o,fileExtensions:s,fileMatchers:c}}function _e(e,t){let n=new Set;for(let e of t){let t=e.indexOf(`=`);t>0&&n.add(e.slice(0,t))}return n.size===0?[...e]:e.filter(e=>{let t=e.value.indexOf(`=`);return t<=0||!n.has(e.value.slice(0,t))})}function ve(e){let t=[];for(let n of e.subcommands){let r=e.currentCommand.subCommands,i=r?.[n],a=i?void 0:s(e.currentCommand,n),c=i??(a?r?.[a]:void 0),l=c?o(c)?.description:void 0;t.push({value:n,description:l,type:`subcommand`})}if(t.length===0||e.currentWord.startsWith(`-`)){let n=Z(e);t.push(...n.candidates)}return{candidates:t,directive:q.FilterPrefix|q.NoFileCompletion}}function Z(e){let t=[],n=e.options.filter(t=>t.valueType===`array`||!(e.usedOptions.has(t.cliName)||t.alias&&t.alias.some(t=>e.usedOptions.has(t))||t.negation&&e.usedOptions.has(t.negation)));for(let e of n)t.push({value:`--${e.cliName}`,description:e.description,type:`option`}),e.negation&&t.push({value:`--${e.negation}`,description:e.negationDescription??e.description,type:`option`});return e.hasAnyOptionBeenUsed||t.push({value:`--help`,description:`Show help information`,type:`option`},{value:`--help-all`,description:`Show help with all subcommand options`,type:`option`},{value:`--help-json`,description:`Show help as JSON`,type:`option`}),{candidates:t,directive:q.FilterPrefix|q.NoFileCompletion}}function ye(e,t,n){return{currentWord:e.currentWord,shell:t.shell,parsedArgs:be(e.parsedArgs,n),previousValues:e.previousValues,subcommandPath:e.subcommandPath}}function be(e,t){if(t===void 0||!(t in e))return e;let n={...e};return delete n[t],n}async function xe(e,t,n,r,i,a){return r?ge(r,ye(e,t,n),e,i,a):{candidates:[],directive:q.FilterPrefix}}function Q(e,t){switch(t.shell){case`bash`:return Se(e,t);case`zsh`:return Ce(e,t);case`fish`:return we(e,t)}}function $(e,t){let n=`:${t.directive}`;t.fileExtensions&&t.fileExtensions.length>0&&(n+=`\t@ext:${t.fileExtensions.join(`,`)}`),t.fileMatchers&&t.fileMatchers.length>0&&(n+=`\t@matcher:${t.fileMatchers.join(`,`)}`),e.push(n)}function Se(e,t){let n=((e.directive&q.FilterPrefix)!==0&&t.currentWord?e.candidates.filter(e=>e.value.startsWith(t.currentWord)):e.candidates).map(e=>t.inlinePrefix?`${t.inlinePrefix}${e.value}`:e.value);return $(n,e),n.join(`
4
- `)}function Ce(e,t){let n=e.candidates.map(e=>{let t=e.value.replace(/:/g,`\\:`);return e.description?`${t}:${e.description.replace(/:/g,`\\:`)}`:t});return $(n,e),n.join(`
5
- `)}function we(e,t){let n=e.candidates.map(e=>e.description?`${e.value}\t${e.description}`:e.value);return $(n,e),n.join(`
6
- `)}function Te(e,t,n){return a({name:`__complete`,args:l,async run(t){let r=W(t.args,e,n),i=r.completionType===`option-value`&&r.targetOption?J(r.currentWord):void 0,a=i?r.currentWord.slice(i.length):r.currentWord,o=Q(await Y(r,{shell:t.shell}),{shell:t.shell,currentWord:a,inlinePrefix:i});console.log(o)}})}function Ee(e){return!!e.subCommands?.__complete}export{S as _,Y as a,m as c,E as d,C as f,T as g,w as h,q as i,b as l,f as m,Ee as n,W as o,d as p,Q as r,D as s,Te as t,x as u,h as v,g as y};
@@ -1 +0,0 @@
1
- import{t as e}from"./dynamic-4uRohypH.js";export{e as createDynamicCompleteCommand};
@@ -1 +0,0 @@
1
- let e;function t(t){e=t}function n(){if(!e)throw Error('No validator adapter registered. Import politty through an adapter package (e.g. `import { defineCommand } from "@politty/zod"` or `from "politty"`) so the schema library integration is set up.');return e}const r=new Set([`help`,`help-all`,`help-json`,`version`]);function i(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}function a(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function o(e){return!e.alias&&!e.hiddenAlias?[]:[...e.alias??[],...e.hiddenAlias??[]]}function s(e,t){let n=t.argMeta,a=n?.description??t.description,o=i(e),s=/^[A-Za-z0-9][A-Za-z0-9-]*$/,c=(t,n)=>{if(t==null)return;let r=(Array.isArray(t)?t:[t]).map(t=>{if(typeof t!=`string`)throw Error(`Invalid ${n} for field "${e}": expected string or string[], received ${typeof t}.`);let r=t.trim().replace(/^-+/,``);if(r.length===0||!s.test(r))throw Error(`Invalid ${n} "${t}" for field "${e}": aliases must match ${s}.`);return r}),i=Array.from(new Set(r));return i.length>0?i:void 0},l=c(n?.alias,`alias`),u=new Set(l??[]),d=c(n?.hiddenAlias,`hiddenAlias`)?.filter(e=>!u.has(e)),f=d&&d.length>0?d:void 0,p=t.type,m=n?.negation,h;if(m!=null){if(typeof m==`boolean`){if(p!==`boolean`)throw Error(`Invalid negation for field "${e}": negation can only be used on boolean fields.`);h=m}else{if(typeof m!=`string`)throw Error(`Invalid negation for field "${e}": expected string or boolean, received ${typeof m}.`);let t=m.trim().replace(/^-+/,``);if(t.length===0||!s.test(t))throw Error(`Invalid negation "${m}" for field "${e}": negation names must match ${s}.`);if(r.has(t))throw Error(`Invalid negation "${m}" for field "${e}": negation cannot use reserved built-in flag names (${[...r].map(e=>`--${e}`).join(`, `)}).`);if(p!==`boolean`)throw Error(`Invalid negation for field "${e}": negation can only be used on boolean fields.`);h=t}}let g=n?.negationDescription,_;if(g!=null){if(typeof g!=`string`)throw Error(`Invalid negationDescription for field "${e}": expected string, received ${typeof g}.`);if(h===!1)throw Error(`Invalid negationDescription for field "${e}": negationDescription cannot be used when negation is false.`);if(h===void 0)throw Error(`Invalid negationDescription for field "${e}": negationDescription requires \`negation\` to be set (string or true).`);let t=g.trim();if(t.length===0)throw Error(`Invalid negationDescription for field "${e}": negationDescription must be a non-empty string.`);_=t}let v=typeof h==`string`?h:h===!0?`no-${o}`:void 0,y=n?.positional,b={name:e,cliName:o,alias:l,hiddenAlias:f,description:a,positional:y!==void 0&&y!==!1,named:typeof y==`object`?y.named===!0:y!==!0,placeholder:n?.placeholder,env:n?.env,required:t.required,defaultValue:t.defaultValue,type:p,schema:t.schema,enumValues:t.enumValues,completion:n?.completion,prompt:n?.prompt,negation:h,negationDisplay:v,negationDescription:_,effect:n?.effect};return n&&`overrideBuiltinAlias`in n&&n.overrideBuiltinAlias===!0&&(b.overrideBuiltinAlias=!0),b}export{i as a,a as i,o as n,n as o,s as r,t as s,r as t};
@@ -1 +0,0 @@
1
- import{StringDecoder as e}from"node:string_decoder";const t={log:`stdout`,info:`stdout`,debug:`stdout`,warn:`stderr`,error:`stderr`},n=[`log`,`info`,`debug`,`warn`,`error`];function r(e){return e.map(e=>{if(e instanceof Error)return e.message;if(typeof e==`object`&&e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}).join(` `)}function i(e){return e.replace(/\r?\n$/,``)}function a(a={}){let o=[],s=a.levels??n,c=a.passthrough??!0,l=null,u=null,d=null,f=!1,p=(e,t,n)=>{o.push({message:n,timestamp:new Date,level:e,stream:t})},m=(e,n)=>(...i)=>{p(e,t[e],r(i)),f=!0;try{c&&n.apply(console,i)}finally{f=!1}},h=(t,n,r)=>{let a=new e(`utf8`);return((e,o,s)=>{if(!f){let r=typeof e==`string`?typeof o==`string`&&o!==`utf8`&&o!==`utf-8`?Buffer.from(e,o).toString(`utf8`):e:a.write(e);r!==``&&p(t,n,i(r))}if(c)return r.call(process[n],e,o,s);let l=typeof o==`function`?o:s;return typeof l==`function`&&l(),!0})};return{getLogs(){return{entries:[...o]}},start(){if(l===null){l={log:console.log,info:console.info,debug:console.debug,warn:console.warn,error:console.error};for(let e of s)console[e]=m(e,l[e]);s.includes(`log`)&&(u=process.stdout.write,process.stdout.write=h(`log`,`stdout`,u)),s.includes(`error`)&&(d=process.stderr.write,process.stderr.write=h(`error`,`stderr`,d))}},stop(){if(l!==null){for(let e of s)console[e]=l[e];l=null,u!==null&&(process.stdout.write=u,u=null),d!==null&&(process.stderr.write=d,d=null)}}}}function o(...e){return{entries:e.flatMap(e=>e.entries).sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}}function s(){return{entries:[]}}export{s as n,o as r,a as t};
@@ -1 +0,0 @@
1
- import{r as e,s as t}from"./field-meta-_l-FHbh7.js";const n=new WeakMap;function r(e,t){return t&&n.set(e,t),e}function i(e){return n.get(e)}function a(e,t=new Set){if(t.has(e))return;t.add(e);let n=i(e);if(n)return n;if(typeof e.meta==`function`){let t=e.meta();if(t&&typeof t==`object`)return t}let r=e,s=r.def??r._def;if(s?.argMeta)return s.argMeta;if(s?.meta)return s.meta;let c=o(e);if(c===`optional`||c===`nullable`||c==="default"){let e=s?.innerType;if(e)return a(e,t)}if(c===`pipe`){let e=s?.in??s?.schema;if(e)return a(e,t)}}function o(e){let t=e;return t.def?.type??t._def?.type??t.type}function s(e){let t=c(e),n=(t.def??t._def)?.catchall;if(!n)return`strip`;let r=o(n);return r===`never`?`strict`:r===`unknown`||r===`any`?`passthrough`:`strip`}function c(e){let t=o(e),n=e,r=n.def??n._def;if(t===`optional`||t===`nullable`||t==="default"){let e=r?.innerType;if(e)return c(e)}if(t===`pipe`){let e=r?.in??r?.schema;if(e)return c(e)}return e}function l(e){switch(o(c(e))){case`string`:case`enum`:return`string`;case`number`:case`int`:return`number`;case`boolean`:return`boolean`;case`array`:return`array`;default:return`unknown`}}function u(e){let t=c(e),n=o(t),r=t,i=r.def??r._def;if(n===`enum`){let e=i?.entries;if(e&&typeof e==`object`)return Object.values(e);let t=i?.values;if(Array.isArray(t))return t;let n=r.options;if(Array.isArray(n))return n}if(n===`array`){let e=i?.element;if(e)return u(e)}if(n===`union`){let e=i?.options;if(Array.isArray(e)){let t=[];for(let n of e)if(o(n)===`literal`){let e=n.def??n._def,r=e?.value,i=e?.values,a=r??i?.[0];typeof a==`string`&&t.push(a)}if(t.length===e.length&&t.length>0)return t}}}function d(e){return!e.isOptional()}function f(e){let t=o(e),n=e,r=n.def??n._def;if(t==="default"){let e=r?.defaultValue;return typeof e==`function`?e():e}if(t===`optional`||t===`nullable`){let e=r?.innerType;if(e)return f(e)}if(t===`pipe`){let e=r?.in??r?.schema;if(e)return f(e)}}function p(e){if(e.description)return e.description;let t=o(e),n=e,r=n.def??n._def;if(t===`optional`||t===`nullable`||t==="default"){let e=r?.innerType;if(e)return p(e)}if(t===`pipe`){let e=r?.in??r?.schema;if(e)return p(e)}}function m(t,n){let r=a(n);return e(t,{argMeta:r,description:p(n),required:d(n),defaultValue:f(n),type:l(n),enumValues:u(n),schema:n})}function h(e){let t=e;return(t.def??t._def)?.shape??t.shape??{}}function g(e){let t=h(e);return Object.entries(t).map(([e,t])=>m(e,t))}function _(e){let t=e,n=t.def??t._def,r=n?.discriminator??``,i=n?.options??[],a=new Map,c=[];for(let e of i){let t=h(e),n=[],i=``,s=t[r];if(s){let e=o(s);if(e===`literal`){let e=s.def??s._def,t=e?.value,n=e?.values;i=String(t??n?.[0]??``)}else if(e===`enum`){let e=u(s);e&&e.length===1&&(i=e[0])}}for(let[e,r]of Object.entries(t)){let t=m(e,r);n.push(t),a.has(e)||a.set(e,t)}let l=p(e);c.push({discriminatorValue:i,fields:n,...l?{description:l}:{}})}let l=p(e);return{fields:Array.from(a.values()),schema:e,schemaType:`discriminatedUnion`,unknownKeysMode:s(e),discriminator:r,variants:c,...l?{description:l}:{}}}function v(e,t){let n=e,r=(n.def??n._def)?.options??[],i=new Map,a=[];for(let e of r){let t=x(e);a.push(t);for(let e of t.fields)i.has(e.name)||i.set(e.name,e)}let o=p(e);return{fields:Array.from(i.values()),schema:e,schemaType:t,unknownKeysMode:s(e),unionOptions:a,...o?{description:o}:{}}}function y(e){let t=e,n=t.def??t._def,r=n?.left,i=n?.right,a=new Map,o=e=>{if(!e)return;let t=x(e);for(let e of t.fields)a.has(e.name)||a.set(e.name,e)};o(r),o(i);let c=p(e);return{fields:Array.from(a.values()),schema:e,schemaType:`intersection`,unknownKeysMode:s(e),...c?{description:c}:{}}}const b=new WeakMap;function x(e){let t=b.get(e);if(t)return t;let n=e,r,i=o(n),a=n,c=a.def??a._def;switch(i){case`object`:{let t=p(n);r={fields:g(n),schema:e,schemaType:`object`,unknownKeysMode:s(n),...t?{description:t}:{}};break}case`union`:r=c?.discriminator?_(n):v(n,`union`);break;case`xor`:r=v(n,`xor`);break;case`intersection`:r=y(n);break;case`optional`:case`nullable`:case`default`:case`pipe`:{let t=c?.innerType??c?.in??c?.schema;if(t){let i=x(t),a=p(n);r={...i,schema:e,...a?{description:a}:{}};break}let i=p(n);r={fields:[],schema:e,schemaType:`object`,unknownKeysMode:s(n),...i?{description:i}:{}};break}default:{let t=p(n);r={fields:[],schema:e,schemaType:`object`,unknownKeysMode:s(n),...t?{description:t}:{}};break}}return b.set(e,r),r}function S(e){return e.issues.map(e=>({path:e.path.map(String),message:e.message,code:e.code,received:`received`in e?e.received:void 0,expected:`expected`in e?String(e.expected):void 0}))}function C(e,t){let n=t.safeParse(e);return n.success?{success:!0,data:n.data}:{success:!1,errors:S(n.error)}}t({vendor:`zod`,extractFields:x,resolveFieldMeta:(e,t)=>m(e,t),getUnknownKeysMode:e=>s(e),validate:C});export{r as t};