args-json
Version:
Zero-dependency typed command-line argument parser
2 lines (1 loc) • 1.26 kB
JavaScript
function d(e){let i=e.replace(/^[-_.\s~+]|[-_.\s~+]$/g,"");return/[-_.\s~+]/.test(i)?i.toLowerCase().replace(/[-_.\s~+](\S)/g,(r,o)=>o.toUpperCase()):i.slice(0,1).toLowerCase()+i.slice(1)}function p(e){if(e){if(e.startsWith("--")&&e.length>2)return d(e.slice(2));if(e.startsWith("-")&&e.length===2)return d(e.slice(1))}}function h(e){let i=[],r="",o=!1,n=!1;for(let s=0;s<e.length;s++){let t=e[s];if(/^\s/.test(t)&&!o&&!n){r&&i.push(r),r="";continue}t==="'"&&e[s-1]!=="\\"&&(o=!o),t==='"'&&e[s-1]!=="\\"&&(n=!n),r+=t}return r&&i.push(r),i}function c(){return typeof process===void 0?[]:process.argv}function A(e,i){let r,o;e===void 0?r=c():typeof e=="string"?r=h(e):Array.isArray(e)?r=e.map(t=>String(t)):e!==null&&typeof e=="object"?(r=c(),o=e):r=[],r=r.map(t=>{let f=t.trim(),l=f.indexOf("=");return l===-1?f:[f.slice(0,l),f.slice(l+1)]}).flat(),i&&(o=i);let n="",s={};for(let t of r){t=t.trim(),(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1));let f=p(t);if(f!==void 0){let g=o?.[f]??f;n&&g!==n&&s[n]===void 0&&(s[n]=!0),n=g;continue}let l;if(t)try{l=JSON.parse(t)}catch{l=t}else l=!0;let a=s[n],u;a===void 0?u=l:Array.isArray(a)?u=[...a,l]:u=[a,l],s[n]=u}return n&&s[n]===void 0&&(s[n]=!0),s}export{A as parseArgs};