UNPKG

env-prompt

Version:

A dependency-free utility that prompts you for your project's environment variables.

14 lines (13 loc) 13.1 kB
#!/usr/bin/env node (()=>{var ye=Object.create;var k=Object.defineProperty,Ee=Object.defineProperties,xe=Object.getOwnPropertyDescriptor,Le=Object.getOwnPropertyDescriptors,Pe=Object.getOwnPropertyNames,Y=Object.getOwnPropertySymbols,Ce=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var K=(e,t,n)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y=(e,t)=>{for(var n in t||(t={}))H.call(t,n)&&K(e,n,t[n]);if(Y)for(var n of Y(t))Te.call(t,n)&&K(e,n,t[n]);return e},C=(e,t)=>Ee(e,Le(t)),Ae=e=>k(e,"__esModule",{value:!0});var M=e=>{if(typeof require!="undefined")return require(e);throw new Error('Dynamic require of "'+e+'" is not supported')};var ke=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Pe(t))!H.call(e,r)&&r!=="default"&&k(e,r,{get:()=>t[r],enumerable:!(n=xe(t,r))||n.enumerable});return e},z=e=>ke(Ae(k(e!=null?ye(Ce(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);var ge=z(M("readline")),fe=z(M("fs")),he=z(M("path"));var D=class{constructor(){this.name="";this.message=""}setFilePath(t){return this.filePath=t,this}getFilePath(){return this.filePath}},F=class extends D{},V=class extends D{setChar(t){return this.char=t,this}getChar(){return this.char}setCoordinates(t){return this.coordinates=t,this}getCoordinates(){return this.coordinates}},L=class extends D{setToken(t){return this.token=t,this}getToken(){return this.token}},I=class extends L{},S=class extends L{},R=class extends L{},O=class extends L{},Q=class extends L{},T=class{constructor(){this.name="";this.message=""}setArgumentName(t){return this.argumentName=t,this}getArgumentName(){return this.argumentName}},$=class extends T{},W=class{constructor(){this.name="";this.message=""}setName(t){return this.name=t,this}},ee=e=>e instanceof F?De(e):e instanceof V?Fe(e):e instanceof L?Ve(e):e instanceof T?Ie(e):e instanceof W?Re(e):`ERROR: ${e.message}`,De=e=>`Could not locate ${e.getFilePath()}`,Fe=e=>{let t=e.getFilePath(),n=e.getCoordinates();return`Unrecognized token ${B(t,n)}`},Ve=e=>{let t=e.getToken(),n=e.getFilePath(),r=B(n,t);if(e instanceof I)return`Expected newline or end of document after comment ${r}`;if(e instanceof S)return`Expected = after variable "${t.value}" ${r}`;if(e instanceof R)return`Unexpected ${t.value} ${r}`;if(e instanceof O)return`Expected line break or comment after variable declaration ${r}`;if(e instanceof Q){let v=B(n,t);return`Duplicate variable declaration "${t.value}" ${v}`}return`Unknown parse error ${r}`},Ie=e=>e instanceof $?`Invalid newline type. Valid types: "${Object.values(h).join('", "')}"`:`Invalid argument ${e.getArgumentName()}`,Se=e=>e.split("").filter(t=>/^[-a-zA-Z]$/.test(t)).join(""),Re=({name:e})=>`Missing value for argument ${Se(e)}`,B=(e,{line:t,column:n})=>`at ${e}:${t}:${n}`;var h;(function(n){n.unix="unix",n.windows="windows"})(h||(h={}));var Oe={distFilePath:".env.dist",localFilePath:".env",prompts:!0,allowDuplicates:!1,newlineType:h.unix},te=({argv:e,env:t,platform:n})=>{let r=Ue(e),o=n==="win32"?h.windows:h.unix,s={};Object.entries(r).forEach(f=>Qe(f,s));let c={};return Object.entries(t).forEach(f=>$e(f,c)),y(y(C(y({},Oe),{newlineType:o}),c),s)},Qe=([e,t],n)=>{if(ie(e)){n.distFilePath=String(t);return}if(oe(e)){n.localFilePath=String(t);return}if(qe(e)){n.prompts=ae(t);return}if(Me(e)){n.allowDuplicates=ae(t);return}if(se(e)){if(!Object.values(h).find(o=>o===t))throw new $;n.newlineType=t;return}throw new T().setArgumentName(e)},$e=([e,t],n)=>{e==="CI"&&t==="true"&&(n.prompts=!1)},ne=/^(--?\w+)(?:=(.*))?/,re=e=>ne.test(e),We=e=>{let[t,n,r]=ne.exec(e);return[n,r]},ie=e=>e==="-d"||e==="--distFile",oe=e=>e==="-l"||e==="--localFile",qe=e=>e==="-p"||e==="--prompts",Me=e=>e==="-a"||e==="--allowDuplicates",se=e=>e==="-n"||e==="--newlineType",ze=e=>ie(e)||oe(e)||se(e),Be=(e,t)=>{let n=e[t],[r,i]=We(n);if(typeof i!="undefined")return[r,i];let s=t+1,l=e[s];if(!!!l&&ze(r))throw new W().setName(r);let v=e.length===s,f=re(l);return v||f?[r,!0]:[r,l]},Ue=e=>{let t={};return e.forEach((n,r)=>{if(!re(n))return;let[i,o]=Be(e,r);t[i]=o}),t},ae=e=>e!=="false";var U=class{constructor(t){this.readLineFactory=t}pause(){this.getReadLine().pause()}promptUser(t){return new Promise(n=>this.getReadLine().question(t,r=>n(r)))}getReadLine(){return this.readLine||(this.readLine=this.readLineFactory()),this.readLine}};var _e=e=>`${e}`,je=e=>`${e}`,_=e=>`${e}`,Xe=(e,t)=>{let r=t.trim().length>0?` (${_(t)})`:"";return`${_e(e)}${r}: `},j=class{constructor(t,n){this.console=t;this.stdIoReader=n}promptUserAboutNewVariables(){this.console.warn(_("New environment variables were found. When prompted, please enter their values."))}async promptUserForEnvironmentVariable({name:t,value:n}){let r=Xe(t,n),i=await this.stdIoReader.promptUser(r),s=i.trim().length===0?n:i;return this.stdIoReader.pause(),{name:t,value:s}}printError(t){let n=ee(t);this.console.error(je(n))}printWarning(t){this.console.error(_(t))}};var u;(function(l){l.literal="literal",l.quotedLiteral="quotedLiteral",l.identifier="identifier",l.variableDeclaration="variableDeclaration",l.comment="comment",l.newline="newline",l.document="document"})(u||(u={}));var b;(function(n){n.single="'",n.double='"'})(b||(b={}));var le=(e,t,{allowDuplicates:n})=>{let r={type:u.document,statements:[]},i={};for(let o=0;o<t.length;){let s=t[o++];if(s.type===a.whitespace)continue;if(s.type===a.newline){let m={type:u.newline};r.statements.push(m);continue}if(s.type===a.comment){let m=t[o++],d=!m,N=m&&m.type===a.newline;if(d||N){N&&o--;let P={type:u.comment,body:null};r.statements.push(P);continue}if(m.type===a.commentBody){let P={type:u.comment,body:m.value};r.statements.push(P);let g=t[o],q=!g,Z=g&&g.type===a.newline;if(q||Z)continue}throw new I().setToken(s).setFilePath(e)}if(s.type===a.identifier){let m=s.value,d;for(;o<t.length;){let g=t[o++];if(!(g.type===a.whitespace)){d=g;break}}if(!(d&&d.type===a.operator))throw new S().setToken(s).setFilePath(e);let p;for(;o<t.length;){let g=t[o++];if(g.type===a.whitespace)continue;if(g.type===a.quote){let A=!p||p.type!==u.quotedLiteral,G=p&&p.type===u.quotedLiteral;if(A){p={type:u.quotedLiteral,quoteType:g.value==='"'?b.double:b.single,content:null};continue}if(G)continue;throw new R().setToken(g).setFilePath(e)}if(g.type===a.literal){let A={type:u.literal,value:g.value};p&&p.type===u.quotedLiteral?p.content=A:p=A;continue}let Ne=g.type===a.newline,we=g.type===a.comment;if(Ne||we){o--;break}throw new O().setToken(s).setFilePath(e)}let w={type:u.variableDeclaration,identifier:{type:u.identifier,name:m},value:p},P=w.identifier.name in i;if(!n&&P)throw new Q().setToken(s).setFilePath(e);i[w.identifier.name]=w,r.statements.push(w);continue}}return{variablesByName:i,abstractSyntaxTree:r}};var a;(function(c){c.identifier="identifier",c.operator="operator",c.literal="literal",c.quote="quote",c.newline="newline",c.whitespace="whitespace",c.comment="comment",c.commentBody="commentBody"})(a||(a={}));var Je=/^["']$/,Ze=/^=$/,Ge=/^#$/,Ye=/^[a-zA-Z]$/,He=/^[^a-zA-Z0-9_-]$/,ce=(e,t)=>{let n=[];for(let r=0;r<t.length;){let i=Ke(e,t,r,n);n.push(i),r+=i.length}return n},Ke=(e,t,n,r)=>{let i=t[n],[o,s]=me(r),l=st(o,s);if(!(l&&o.value===b.double)&&(i===` `||i==="\r"))return tt(n,t,r);if(!l){if(mt(r))return rt(n,t,r);if(Ge.test(i))return nt(n,t,r);if(/^\s$/.test(i))return it(n,t,r);if(Je.test(i))return ue(n,t,r);if(Ze.test(i))return ot(n,t,r)}if(ut(r))return at(n,t,r);if(Ye.test(i))return lt(n,t,r);{let m=ct(r),d=et(m);throw new V().setChar(i).setCoordinates(d).setFilePath(e)}},et=e=>{if(!e)return{line:1,column:1,position:1};let t=e.position+e.length;return e.type===a.newline?{line:e.line+1,column:1,position:t}:{line:e.line,column:e.column+e.length,position:t}},E=e=>{if(e.length===0)return 1;let{type:n,line:r}=e[e.length-1];return n===a.newline?r+1:r},x=e=>{if(e.length===0)return 1;let{type:n,column:r,length:i}=e[e.length-1];return n===a.newline?1:r+i},tt=(e,t,n)=>{let r={type:a.newline,position:e,line:E(n),column:x(n)};if(t[e]==="\r"){let c=t[e+1]===` `?`\r `:"\r";return C(y({},r),{length:c.length,value:c})}return C(y({},r),{length:1,value:` `})},nt=(e,t,n)=>({type:a.comment,position:e,line:E(n),column:x(n),length:1,value:t[e]}),rt=(e,t,n)=>{let r=e,i=t[r++];for(;r<t.length;r++){let o=t[r];if(o===` `||o==="\r")break;i=`${i}${o}`}return{type:a.commentBody,position:e,line:E(n),column:x(n),length:i.length,value:i}},it=(e,t,n)=>({type:a.whitespace,position:e,line:E(n),column:x(n),length:1,value:t[e]}),ue=(e,t,n)=>({type:a.quote,position:e,line:E(n),column:x(n),length:1,value:t[e]}),ot=(e,t,n)=>({type:a.operator,position:e,line:E(n),column:x(n),length:1,value:t[e]}),st=(e,t)=>{if(!e||!t)return!1;let n=e.type===a.quote,r=t.type===a.quote,i=t.type===a.literal;return n&&!(r||i)},at=(e,t,n)=>{let r=e,i=t[r++],[o]=me(n),s=o.type===a.quote,c=i===(o==null?void 0:o.value);if(s&&c)return ue(e,t,n);for(;r<t.length;r++){let d=t[r],N=t[r-1],p=d===o.value;if(s&&p&&!(N==="\\")||(d===` `||d==="\r")&&!s||d==="#"&&!s)break;i=`${i}${d}`}let[f]=/(\s*)$/.exec(i),m=s?i.length:i.length-f.length;return s||(i=i.substr(0,m)),{type:a.literal,position:e,line:E(n),column:x(n),length:m,value:i}},lt=(e,t,n)=>{let r=e,i=t[r++];for(;r<t.length;r++){let o=t[r];if(He.test(o))break;i=`${i}${o}`}return{type:a.identifier,position:e,line:E(n),column:x(n),length:i.length,value:i}},ct=e=>e.length>0?e[e.length-1]:null,me=e=>{let t=null,n=null;for(let r=e.length-1;r>=0;r--){let i=e[r];if(!(i.type===a.whitespace)){if(!!t){n=i;break}t=i}}return[t,n]},ut=e=>{for(let t=e.length-1;t>=0;t--){let{type:n,value:r}=e[t];if(n===a.operator&&r==="=")return!0;if(n===a.newline)return!1}return!1},mt=e=>e.length>0&&e[e.length-1].type===a.comment;var de=(e,t)=>e.statements.map(n=>dt(n,t)).join(""),dt=(e,t)=>e.type===u.variableDeclaration?pt(e):e.type===u.newline?gt(t):vt(e),pt=({identifier:e,value:t})=>`${e.name}=${ft(t)}`,gt=({newlineType:e})=>e===h.windows?`\r `:` `,ft=e=>{if(!e)return"";if(e.type===u.literal){let{value:r}=e;return/\\./.test(r)?ht(e):r}return pe(e)},ht=e=>{let t={type:u.quotedLiteral,quoteType:b.double,content:e};return pe(t)},pe=({quoteType:e,content:t})=>{let r=!t?"":t.value,i=bt(e,r);return`${e}${i}${e}`},bt=(e,t)=>e===b.double?t.replace(/"/g,'\\"'):t.replace(/'/g,"\\'"),vt=({body:e})=>`#${e||""}`;var X="utf8",J=class{setCliPrompter(t){return this.cliPrompter=t,this}setAnalyzeEnvSourceCode(t){return this.analyzeEnvSourceCode=t,this}setParseEnvTokens(t){return this.parseEnvTokens=t,this}setRender(t){return this.render=t,this}setFs(t){return this.fs=t,this}setPath(t){return this.path=t,this}async merge(t){let n=this.parseDistDocument(t),r=this.parseLocalDocument(t),i=await this.mergeDocuments(n,r,t);this.writeLocalEnvFile(t,i)}analyzeDistEnvFile(t){if(!this.fs.existsSync(t))throw new F().setFilePath(t);let r=this.fs.readFileSync(t,{encoding:X}).toString();return this.analyzeEnvSourceCode(t,r)}analyzeLocalEnvFile(t){if(!this.fs.existsSync(t))return[];let r=this.fs.readFileSync(t,{encoding:X}).toString();return this.analyzeEnvSourceCode(t,r)}writeLocalEnvFile(t,n){let r=this.render(n.abstractSyntaxTree,t);this.fs.writeFileSync(t.localFilePath,r,{encoding:X})}async mergeDocuments(t,n,r){let i=y({},n),o=!1,s=Object.keys(t.variablesByName);for(let l of s){if(l in n.variablesByName)continue;!o&&r.prompts&&(this.cliPrompter.promptUserAboutNewVariables(),o=!0);let v=t.variablesByName[l],f=wt(v),m=f;r.prompts&&(m=(await this.cliPrompter.promptUserForEnvironmentVariable({name:l,value:f})).value);let d=yt(l,m,r);Nt(d,i)}return i}parseDistDocument(t){let n=this.path.resolve(t.distFilePath),r=this.analyzeDistEnvFile(n);return this.parseEnvTokens(n,r,t)}parseLocalDocument(t){let n=this.path.resolve(t.localFilePath),r=this.analyzeLocalEnvFile(n);return this.parseEnvTokens(n,r,t)}},Nt=(e,t)=>{t.abstractSyntaxTree.statements.push(e);let n={type:u.newline};t.abstractSyntaxTree.statements.push(n);let{name:r}=e.identifier;t.variablesByName[r]=e},wt=e=>{if(!!!e.value)return"";if(e.value.type===u.literal)return e.value.value;let r=e.value;return!r.content?"":r.content.value},yt=(e,t,{newlineType:n})=>{let r={type:u.identifier,name:e};if(!t)return{type:u.variableDeclaration,identifier:r};let o=t.indexOf(` `)>-1||t.indexOf("\r")>-1,s=t.indexOf("'")>-1,l=t.indexOf('"')>-1;if(o||(s||l)){let f=s&&l,m=f||s||o?b.double:b.single,d=f?t.replace(/"/g,'\\"'):t,N=o?Et(d,n):d,p={type:u.literal,value:N},w={type:u.quotedLiteral,quoteType:m,content:p};return{type:u.variableDeclaration,identifier:r,value:w}}let v={type:u.literal,value:t};return{type:u.variableDeclaration,identifier:r,value:v}},Et=(e,t)=>{let r=t===h.windows?`\r `:` `;return e.replace(/(?:\r\n)|(?:\r)|(?:\n)/g,r)};var xt=()=>ge.default.createInterface(process.stdin,process.stdout),Lt=new U(xt),be=new j(console,Lt),Pt=new J().setCliPrompter(be).setAnalyzeEnvSourceCode(ce).setParseEnvTokens(le).setRender(de).setFs(fe.default).setPath(he.default),Ct=async()=>{try{let e=te(process);await Pt.merge(e)}catch(e){be.printError(e),process.exit(1)}};Ct();})();