@frontstackdev/cli 0.0.0-canary-20250404110750 → 0.0.0-canary-20250404143222

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.
@@ -21,8 +21,8 @@ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
21
21
  `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");const n=this.parent?._findCommand(e);if(n){const i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;const t=this.registeredArguments.map(n=>Xe(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=$.basename(e,$.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};const t={error:!!e.error};let n;return t.error?n=l(i=>this._outputConfiguration.writeErr(i),"write"):n=l(i=>this._outputConfiguration.writeOut(i),"write"),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);const n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation(n);if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=O.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
22
  Expecting one of '${n.join("', '")}'`);const i=`${e}Help`;return this.on(i,o=>{let a;typeof t=="function"?a=t({error:o.error,command:o.command}):a=t,a&&o.write(`${a}
23
23
  `)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}},l(T,"Command"),T);function he(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?i=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],i=o[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}l(he,"incrementNodeInspectorPort"),se.Command=nt;const{Argument:pe}=D,{Command:B}=se,{CommanderError:it,InvalidArgumentError:fe}=k,{Help:rt}=M,{Option:de}=q;C.program=new B,C.createCommand=r=>new B(r),C.createOption=(r,e)=>new de(r,e),C.createArgument=(r,e)=>new pe(r,e),C.Command=B,C.Option=de,C.Argument=pe,C.Help=rt,C.CommanderError=it,C.InvalidArgumentError=fe,C.InvalidOptionArgumentError=fe;const{program:kn,createCommand:jn,createArgument:xn,createOption:Hn,CommanderError:Nn,InvalidArgumentError:In,InvalidOptionArgumentError:Vn,Command:ot,Argument:Fn,Option:Dn,Help:Ln}=C,st=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,at=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,ct=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function lt(r,e){if(r==="__proto__"||r==="constructor"&&e&&typeof e=="object"&&"prototype"in e){ut(r);return}return e}l(lt,"jsonParseTransform");function ut(r){console.warn(`[destr] Dropping "${r}" key to prevent prototype pollution.`)}l(ut,"warnKeyDropped");function ht(r,e={}){if(typeof r!="string")return r;const t=r.trim();if(r[0]==='"'&&r.endsWith('"')&&!r.includes("\\"))return t.slice(1,-1);if(t.length<=9){const n=t.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!ct.test(r)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return r}try{if(st.test(r)||at.test(r)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(r,lt)}return JSON.parse(r)}catch(n){if(e.strict)throw n;return r}}l(ht,"destr");const pt=/#/g,ft=/&/g,dt=/\//g,mt=/=/g,K=/\+/g,gt=/%5e/gi,_t=/%60/gi,yt=/%7c/gi,Ot=/%20/gi;function bt(r){return encodeURI(""+r).replace(yt,"|")}l(bt,"encode");function z(r){return bt(typeof r=="string"?r:JSON.stringify(r)).replace(K,"%2B").replace(Ot,"+").replace(pt,"%23").replace(ft,"%26").replace(_t,"`").replace(gt,"^").replace(dt,"%2F")}l(z,"encodeQueryValue");function Q(r){return z(r).replace(mt,"%3D")}l(Q,"encodeQueryKey");function me(r=""){try{return decodeURIComponent(""+r)}catch{return""+r}}l(me,"decode");function wt(r){return me(r.replace(K," "))}l(wt,"decodeQueryKey");function Ct(r){return me(r.replace(K," "))}l(Ct,"decodeQueryValue");function At(r=""){const e={};r[0]==="?"&&(r=r.slice(1));for(const t of r.split("&")){const n=t.match(/([^=]+)=?(.*)/)||[];if(n.length<2)continue;const i=wt(n[1]);if(i==="__proto__"||i==="constructor")continue;const o=Ct(n[2]||"");e[i]===void 0?e[i]=o:Array.isArray(e[i])?e[i].push(o):e[i]=[e[i],o]}return e}l(At,"parseQuery");function Et(r,e){return(typeof e=="number"||typeof e=="boolean")&&(e=String(e)),e?Array.isArray(e)?e.map(t=>`${Q(r)}=${z(t)}`).join("&"):`${Q(r)}=${z(e)}`:Q(r)}l(Et,"encodeQueryItem");function $t(r){return Object.keys(r).filter(e=>r[e]!==void 0).map(e=>Et(e,r[e])).filter(Boolean).join("&")}l($t,"stringifyQuery");const vt=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,St=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,Tt=/^([/\\]\s*){2,}[^/\\]/,Rt=/^\.?\//;function ge(r,e={}){return typeof e=="boolean"&&(e={acceptRelative:e}),e.strict?vt.test(r):St.test(r)||(e.acceptRelative?Tt.test(r):!1)}l(ge,"hasProtocol");function Pt(r="",e){return r.endsWith("/")}l(Pt,"hasTrailingSlash");function kt(r="",e){return(Pt(r)?r.slice(0,-1):r)||"/"}l(kt,"withoutTrailingSlash");function jt(r="",e){return r.endsWith("/")?r:r+"/"}l(jt,"withTrailingSlash");function xt(r,e){if(Nt(e)||ge(r))return r;const t=kt(e);return r.startsWith(t)?r:Vt(t,r)}l(xt,"withBase");function Ht(r,e){const t=Ft(r),n={...At(t.search),...e};return t.search=$t(n),Dt(t)}l(Ht,"withQuery");function Nt(r){return!r||r==="/"}l(Nt,"isEmptyURL");function It(r){return r&&r!=="/"}l(It,"isNonEmptyURL");function Vt(r,...e){let t=r||"";for(const n of e.filter(i=>It(i)))if(t){const i=n.replace(Rt,"");t=jt(t)+i}else t=n;return t}l(Vt,"joinURL");const _e=Symbol.for("ufo:protocolRelative");function Ft(r="",e){const t=r.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(t){const[,h,f=""]=t;return{protocol:h.toLowerCase(),pathname:f,href:h+f,auth:"",host:"",search:"",hash:""}}if(!ge(r,{acceptRelative:!0}))return ye(r);const[,n="",i,o=""]=r.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[];let[,a="",c=""]=o.match(/([^#/?]*)(.*)?/)||[];n==="file:"&&(c=c.replace(/\/(?=[A-Za-z]:)/,""));const{pathname:u,search:p,hash:s}=ye(c);return{protocol:n.toLowerCase(),auth:i?i.slice(0,Math.max(0,i.length-1)):"",host:a,pathname:u,search:p,hash:s,[_e]:!n}}l(Ft,"parseURL");function ye(r=""){const[e="",t="",n=""]=(r.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname:e,search:t,hash:n}}l(ye,"parsePath");function Dt(r){const e=r.pathname||"",t=r.search?(r.search.startsWith("?")?"":"?")+r.search:"",n=r.hash||"",i=r.auth?r.auth+"@":"",o=r.host||"";return(r.protocol||r[_e]?(r.protocol||"")+"//":"")+i+o+e+t+n}l(Dt,"stringifyParsedURL");const ne=class ne extends Error{constructor(e,t){super(e,t),this.name="FetchError",t?.cause&&!this.cause&&(this.cause=t.cause)}};l(ne,"FetchError");let Y=ne;function Lt(r){const e=r.error?.message||r.error?.toString()||"",t=r.request?.method||r.options?.method||"GET",n=r.request?.url||String(r.request)||"/",i=`[${t}] ${JSON.stringify(n)}`,o=r.response?`${r.response.status} ${r.response.statusText}`:"<no response>",a=`${i}: ${o}${e?` ${e}`:""}`,c=new Y(a,r.error?{cause:r.error}:void 0);for(const u of["request","options","response"])Object.defineProperty(c,u,{get(){return r[u]}});for(const[u,p]of[["data","_data"],["status","status"],["statusCode","status"],["statusText","statusText"],["statusMessage","statusText"]])Object.defineProperty(c,u,{get(){return r.response&&r.response[p]}});return c}l(Lt,"createFetchError");const qt=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function Oe(r="GET"){return qt.has(r.toUpperCase())}l(Oe,"isPayloadMethod");function Ut(r){if(r===void 0)return!1;const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(r)?!0:r.buffer?!1:r.constructor&&r.constructor.name==="Object"||typeof r.toJSON=="function"}l(Ut,"isJSONSerializable");const Mt=new Set(["image/svg","application/xml","application/xhtml","application/html"]),Wt=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Gt(r=""){if(!r)return"json";const e=r.split(";").shift()||"";return Wt.test(e)?"json":Mt.has(e)||e.startsWith("text/")?"text":"blob"}l(Gt,"detectResponseType");function Jt(r,e,t=globalThis.Headers){const n={...e,...r};if(e?.params&&r?.params&&(n.params={...e?.params,...r?.params}),e?.query&&r?.query&&(n.query={...e?.query,...r?.query}),e?.headers&&r?.headers){n.headers=new t(e?.headers||{});for(const[i,o]of new t(r?.headers||{}))n.headers.set(i,o)}return n}l(Jt,"mergeFetchOptions");const Bt=new Set([408,409,425,429,500,502,503,504]),Kt=new Set([101,204,205,304]);function be(r={}){const{fetch:e=globalThis.fetch,Headers:t=globalThis.Headers,AbortController:n=globalThis.AbortController}=r;async function i(c){const u=c.error&&c.error.name==="AbortError"&&!c.options.timeout||!1;if(c.options.retry!==!1&&!u){let s;typeof c.options.retry=="number"?s=c.options.retry:s=Oe(c.options.method)?0:1;const h=c.response&&c.response.status||500;if(s>0&&(Array.isArray(c.options.retryStatusCodes)?c.options.retryStatusCodes.includes(h):Bt.has(h))){const f=c.options.retryDelay||0;return f>0&&await new Promise(m=>setTimeout(m,f)),o(c.request,{...c.options,retry:s-1})}}const p=Lt(c);throw Error.captureStackTrace&&Error.captureStackTrace(p,o),p}l(i,"onError");const o=l(async function(u,p={}){const s={request:u,options:Jt(p,r.defaults,t),response:void 0,error:void 0};s.options.method=s.options.method?.toUpperCase(),s.options.onRequest&&await s.options.onRequest(s),typeof s.request=="string"&&(s.options.baseURL&&(s.request=xt(s.request,s.options.baseURL)),(s.options.query||s.options.params)&&(s.request=Ht(s.request,{...s.options.params,...s.options.query}))),s.options.body&&Oe(s.options.method)&&(Ut(s.options.body)?(s.options.body=typeof s.options.body=="string"?s.options.body:JSON.stringify(s.options.body),s.options.headers=new t(s.options.headers||{}),s.options.headers.has("content-type")||s.options.headers.set("content-type","application/json"),s.options.headers.has("accept")||s.options.headers.set("accept","application/json")):("pipeTo"in s.options.body&&typeof s.options.body.pipeTo=="function"||typeof s.options.body.pipe=="function")&&("duplex"in s.options||(s.options.duplex="half")));let h;if(!s.options.signal&&s.options.timeout){const m=new n;h=setTimeout(()=>m.abort(),s.options.timeout),s.options.signal=m.signal}try{s.response=await e(s.request,s.options)}catch(m){return s.error=m,s.options.onRequestError&&await s.options.onRequestError(s),await i(s)}finally{h&&clearTimeout(h)}if(s.response.body&&!Kt.has(s.response.status)&&s.options.method!=="HEAD"){const m=(s.options.parseResponse?"json":s.options.responseType)||Gt(s.response.headers.get("content-type")||"");switch(m){case"json":{const g=await s.response.text(),b=s.options.parseResponse||ht;s.response._data=b(g);break}case"stream":{s.response._data=s.response.body;break}default:s.response._data=await s.response[m]()}}return s.options.onResponse&&await s.options.onResponse(s),!s.options.ignoreResponseError&&s.response.status>=400&&s.response.status<600?(s.options.onResponseError&&await s.options.onResponseError(s),await i(s)):s.response},"$fetchRaw2"),a=l(async function(u,p){return(await o(u,p))._data},"$fetch2");return a.raw=o,a.native=(...c)=>e(...c),a.create=(c={})=>be({...r,defaults:{...r.defaults,...c}}),a}l(be,"createFetch");const Z=function(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")}(),zt=Z.fetch||(()=>Promise.reject(new Error("[ofetch] global.fetch is not supported!"))),Qt=Z.Headers,Yt=Z.AbortController,U=be({fetch:zt,Headers:Qt,AbortController:Yt}),Zt={apiRoot:process.env.FRONTSTACK_CLI_API_ROOT||(process.env.FRONTSTACK_CLI_DEV_MODE=="1"?"https://backend.frontstack.test/":"https://backend.frontstack.dev/")},L=Zt.apiRoot,Xt=`${L}login`,en=`${L}api/fetch-api/spec.yaml`,we=3008,Ce=`http://localhost:${we}`,Ae=`${Xt}?redirectUrl=${Ce}/callback`,tn=".frontstack-local/",v=_.join(process.cwd(),tn),X="api_session.jwt",Ee="project.json",j=l(()=>{const r=l(()=>{console.info("Not auth.login implemented yet")},"login"),e=l(async()=>{try{return a(),0}catch(h){console.log(h)}},"logout"),t=l(async(h=!1)=>{try{return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await U(`${L}profile`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i()}`}})}catch(f){return h&&console.log(f),1}},"getProfile"),n=l(async h=>{try{if(h==null)throw new Error(`You have no project selected
24
- Run ${d.hex("#7c3bed")("frontstack project")} to select a frontstack project`);return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await U(en,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${i()}`,"FS-Project":h},parseResponse:l(m=>{try{return ie.load(m)}catch{throw new Error("Invalid API specification. The API specification must be a valid YAML file.")}},"parseResponse")})}catch(f){throw"data"in f&&"message"in f.data?new Error(`Server error: ${f.data.message}`):f}},"getFetchApiSpec"),i=l(()=>{const h=_.join(v,X);return y.existsSync(h)?y.readFileSync(h,"utf8"):null},"getToken"),o=l(h=>(y.existsSync(v)||y.mkdirSync(v),y.writeFileSync(_.join(v,X),h),0),"writeToken"),a=l(()=>{const h=_.join(v,X);y.existsSync(h)&&y.unlinkSync(h)},"deleteToken"),c=l(async()=>(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await U(`${L}api/project`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${i()}`},parseResponse:l(h=>JSON.parse(h),"parseResponse")})),"getProjects"),u=l(()=>{const h=_.join(v,Ee);if(!y.existsSync(h))return null;try{return JSON.parse(y.readFileSync(h,"utf8")).projectId}catch{console.error("[Error] Corrupt project file - please run 'frontstack project'")}},"getProjectId");return{login:r,logout:e,getProfile:t,getFetchApiSpec:n,getToken:i,writeToken:o,deleteToken:a,getProjects:c,getProject:l(async(h=void 0)=>{try{return h===void 0&&(h=u()),h===void 0?void 0:(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await U(`${L}api/project/${h}`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${i()}`},parseResponse:l(f=>JSON.parse(f),"parseResponse")}))}catch(f){return{error:f.message}}},"getProject"),getProjectId:u,writeProject:l(h=>(y.existsSync(v)||y.mkdirSync(v),y.writeFileSync(_.join(v,Ee),JSON.stringify({projectId:h})),0),"writeProject")}},"auth"),{writeToken:nn}=j(),rn=l(async(r,e)=>new Promise(t=>{const n=new Set,i=Ne.createServer((o,a)=>{const c=Ce;if(o.url===void 0)return;const p=new URL(o.url,c).searchParams.get("token");p&&(a.writeHead(200,{"Content-Type":"text/html"}),a.end('<html><head><script>// window.close()<\/script></head><body style="font-family: sans-serif;"><div style="height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;"><div style="text-align: center"><h1 style="color: #7c3bed;">Login Successful</h1><p>You can <a href="#" onClick="window.close()">close</a> this browser window and return to the terminal.<p style="font-size: .8rem; color: #666; text-align: left; margin-top: 20px;">&copy; 2024 frontstack</p></div></div></html>'),a.on("finish",async()=>{for(const h of n)h.destroy();nn(p)!==0?(console.error("Login failed."),i.close(),t(!1)):(console.log(`${d.hex("#008000")("[SUCCESS]")} Login successful`),i.close(),t(!0))}))}).listen(r,()=>{console.log(`Please continue login in your browser at ${d.hex("#7c3bed")(e)}`)});i.on("connection",o=>{n.add(o),o.on("close",()=>n.delete(o))}),setTimeout(()=>{i.close(),t(!1)},6e4)}),"login$1"),$e=l(async()=>(await Ie(Ae),await rn(we,Ae)),"login"),on=j(),sn=l(async r=>{await on.logout()!==0&&(console.error("Logout failed."),process.exit(1)),console.log("Logout successful."),process.exit(0)},"logout"),{getFetchApiSpec:an}=j();A.registerHelper("eq",function(r,e,t){return r===e}),A.registerHelper("uc",function(r){return r.toUpperCase()}),A.registerHelper("and",function(r,e,t){return r&&e}),A.registerHelper("contains",function(r,e,t){return r===void 0?!1:r.includes(e)}),A.registerHelper("endsWith",function(r,e,t){return r===void 0?!1:r.endsWith(e)}),A.registerHelper("blockNameFromOperationId",function(r){return r.replace("get","").replace("Block","")});const ee=l((r,e=!1)=>r.$ref?`components['schemas']['${r.$ref.split("/").pop()}']`:r.type==="array"?`Array<${ee(r.items,!0)}>`:r.type==="object"?`{ ${Object.keys(r.properties).map(n=>`${n}: ${ee(r.properties[n])}`).join("; ")} }`:r.type,"getSchemaType");A.registerHelper("getSchemaType",r=>ee(r)),A.registerHelper("stringInArray",function(r,e,t){return e==null||e.length===0?!1:t.fn?e.indexOf(r)>-1?t.fn(this):t.inverse(this):e.indexOf(r)>-1});var cn=l(async r=>{const e=_.dirname(new URL(import.meta.url).pathname),t=_.join(e,"src/commands/generate/templates"),n=_.join(t,"types.js.hbs"),i=y.readFileSync(n,"utf8"),o=A.compile(i),a=_.join(t,"client.js.hbs"),c=y.readFileSync(a,"utf8"),u=A.compile(c),p=_.join(t,"query.js.hbs"),s=y.readFileSync(p,"utf8");let h;if(h=await an(r),h.error)throw new Error(`Issue fetching API specification. Check more information below.
25
- `+h.error);let f="";try{f=await Ve(h)}catch(b){throw new Error(`Invalid API Specification: ${b.message}`)}const m=o({paths:h.paths,components:h.components}),g=u({components:h.components,paths:h.paths,servers:h.servers});return{_schemaTypes:f,_types:m,_client:g,_query:s,_specFile:h}},"generate");const{getProjects:ln,writeProject:ve}=j(),Se=l(async r=>{let e=r.project??void 0,t=[];try{t=await ln()}catch{console.log(`You are not logged in. Please run ${d.hex("#7c3bed")("frontstack login")} to login`);return}if(t.length<1){console.log("No projects found. Please create a new project in your Admin dashboard");return}if(e!==void 0){const o=t.find(a=>a.id===e);if(o){console.log(`Project ${d.hex("#7c3bed")(o.name)} selected`),ve(o.id);return}else{console.log(`Project with ID "${e}" not found. Please select a valid project ID`);return}}const n={type:"select",name:"projectId",message:"Pick a project (Use arrow keys and Enter)",choices:t.map(o=>({title:(o.id===e?"(\u2714) ":"")+`${o.name}`,value:o.id}))};async function i(){const o=await re(n),a=t.find(c=>c.id===o.projectId);if(a===void 0){console.log(`Project with ID "${o.projectId}" not found. Please select a valid project ID`);return}console.log(`Project ${d.hex("#7c3bed")(a.name)} selected`),ve(o.projectId)}l(i,"getProject"),await i()},"project"),un=l(async r=>{const e=r.verbose||!1,t=r.persistOas||!1,{getProject:n,getProfile:i}=j(),o=await i(e);if(!o||o===1){console.info("User not logged in"),await $e()||(console.info(`${d.hex("#b90404")("[ERROR]")} Login failed`),process.exit(1));const E=await i();(!E||E===1)&&(console.info(`${d.hex("#b90404")("[ERROR]")} Login failed`),process.exit(1))}let a=await n();if(!a||"error"in a){console.info("No project selected"),console.info("Running project selection..."),await Se({});const w=await n();if(!w||"error"in w){console.info(`${d.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${d.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`);return}a=w}let c=a;if(!a||"error"in a){console.info(`${d.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${d.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`);return}if(r.env&&a.environments.length>0){let w;if(r.env!=="develop"){if(w=a.environments.find(E=>E.environment===r.env),!w){console.info(`${d.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${d.hex("#b90404")("[ERROR]")} Environment ${r.env} not found`);return}c=w}}if(!r.env&&a.environments.length>0){const w={type:"select",name:"projectId",message:"Pick an environment (use arrow keys and enter)",choices:[{title:`${a.name} (${a.environment})`,value:a.id},...a.environments.map(P=>({title:(P.id===c?.id?"(\u2714) ":"")+`${P.name} (${P.environment})`,value:P.id}))]},E=await re(w);c=a.environments.find(P=>P.id===E.projectId)??a}let u,p,s,h,f;try{e&&console.log("Generating Javascript client"),{_schemaTypes:u,_types:p,_client:s,_query:h,_specFile:f}=await cn(c.id)}catch(w){console.info(`${d.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${d.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`),e?console.info(`${d.hex("#b90404")("[ERROR]")} ${w.message}`):(console.info("Are you..."),console.info(` * logged in using the ${d.hex("#7c3bed")("frontstack login")} command?`),console.info(" * connected to the internet?"),console.info(`Alternatively, run ${d.hex("#7c3bed")("frontstack generate -v")} for additional output.`));return}let m=r.output||".frontstack";process.stdout.write("Generating Javascript client"),m.startsWith("/")||(m=_.join(process.cwd(),m)),m.endsWith("/")||(m+="/");const g=_.join(m,"fetch-api.d.ts"),b=_.join(m,"generated-types.d.ts"),R=_.join(m,"generated-client.ts"),Re=_.join(m,"query-types.ts");if(e&&(console.log(`
24
+ Run ${d.hex("#7c3bed")("frontstack project")} to select a frontstack project`);return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await U(en,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${i()}`,"FS-Project":h},parseResponse:l(m=>{try{return ie.load(m)}catch{throw new Error("Invalid API specification. The API specification must be a valid YAML file.")}},"parseResponse")})}catch(f){throw"data"in f&&"message"in f.data?new Error(`Server error: ${f.data.message}`):f}},"getFetchApiSpec"),i=l(()=>{const h=_.join(v,X);return y.existsSync(h)?y.readFileSync(h,"utf8"):null},"getToken"),o=l(h=>(y.existsSync(v)||y.mkdirSync(v),y.writeFileSync(_.join(v,X),h),0),"writeToken"),a=l(()=>{const h=_.join(v,X);y.existsSync(h)&&y.unlinkSync(h)},"deleteToken"),c=l(async()=>(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await U(`${L}api/project`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${i()}`},parseResponse:l(h=>JSON.parse(h),"parseResponse")})),"getProjects"),u=l(()=>{const h=_.join(v,Ee);if(!y.existsSync(h))return null;try{return JSON.parse(y.readFileSync(h,"utf8")).projectId}catch{console.error("[Error] Corrupt project file - please run 'frontstack project'")}},"getProjectId");return{login:r,logout:e,getProfile:t,getFetchApiSpec:n,getToken:i,writeToken:o,deleteToken:a,getProjects:c,getProject:l(async(h=void 0)=>{try{return h===void 0&&(h=u()),h===void 0?void 0:(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await U(`${L}api/project/${h}`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${i()}`},parseResponse:l(f=>JSON.parse(f),"parseResponse")}))}catch(f){return{error:f.message}}},"getProject"),getProjectId:u,writeProject:l(h=>(y.existsSync(v)||y.mkdirSync(v),y.writeFileSync(_.join(v,Ee),JSON.stringify({projectId:h})),0),"writeProject")}},"auth"),{writeToken:nn}=j(),rn=l(async(r,e,t=!1)=>new Promise(n=>{const i=new Set,o=Ne.createServer((a,c)=>{const u=Ce;if(a.url===void 0)return;const s=new URL(a.url,u).searchParams.get("token");s&&(c.writeHead(200,{"Content-Type":"text/html"}),c.end('<html><head><script>// window.close()<\/script></head><body style="font-family: sans-serif;"><div style="height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;"><div style="text-align: center"><h1 style="color: #7c3bed;">Login Successful</h1><p>You can <a href="#" onClick="window.close()">close</a> this browser window and return to the terminal.<p style="font-size: .8rem; color: #666; text-align: left; margin-top: 20px;">&copy; 2024 frontstack</p></div></div></html>'),c.on("finish",async()=>{for(const f of i)f.destroy();nn(s)!==0?(console.error("Login failed."),o.close(),n(!1)):(console.log(`${d.hex("#008000")("[SUCCESS]")} Login successful`),o.close(),n(!0)),t&&process.exit(0)}))}).listen(r,()=>{console.log(`Please continue login in your browser at ${d.hex("#7c3bed")(e)}`)});o.on("connection",a=>{i.add(a),a.on("close",()=>i.delete(a))}),setTimeout(()=>{o.close(),n(!1)},6e4)}),"login$1"),$e=l(async(r=!0)=>(await Ie(Ae),await rn(we,Ae,r)),"login"),on=j(),sn=l(async r=>{await on.logout()!==0&&(console.error("Logout failed."),process.exit(1)),console.log("Logout successful."),process.exit(0)},"logout"),{getFetchApiSpec:an}=j();A.registerHelper("eq",function(r,e,t){return r===e}),A.registerHelper("uc",function(r){return r.toUpperCase()}),A.registerHelper("and",function(r,e,t){return r&&e}),A.registerHelper("contains",function(r,e,t){return r===void 0?!1:r.includes(e)}),A.registerHelper("endsWith",function(r,e,t){return r===void 0?!1:r.endsWith(e)}),A.registerHelper("blockNameFromOperationId",function(r){return r.replace("get","").replace("Block","")});const ee=l((r,e=!1)=>r.$ref?`components['schemas']['${r.$ref.split("/").pop()}']`:r.type==="array"?`Array<${ee(r.items,!0)}>`:r.type==="object"?`{ ${Object.keys(r.properties).map(n=>`${n}: ${ee(r.properties[n])}`).join("; ")} }`:r.type,"getSchemaType");A.registerHelper("getSchemaType",r=>ee(r)),A.registerHelper("stringInArray",function(r,e,t){return e==null||e.length===0?!1:t.fn?e.indexOf(r)>-1?t.fn(this):t.inverse(this):e.indexOf(r)>-1});var cn=l(async r=>{const e=_.dirname(new URL(import.meta.url).pathname),t=_.join(e,"src/commands/generate/templates"),n=_.join(t,"types.js.hbs"),i=y.readFileSync(n,"utf8"),o=A.compile(i),a=_.join(t,"client.js.hbs"),c=y.readFileSync(a,"utf8"),u=A.compile(c),p=_.join(t,"query.js.hbs"),s=y.readFileSync(p,"utf8");let h;if(h=await an(r),h.error)throw new Error(`Issue fetching API specification. Check more information below.
25
+ `+h.error);let f="";try{f=await Ve(h)}catch(b){throw new Error(`Invalid API Specification: ${b.message}`)}const m=o({paths:h.paths,components:h.components}),g=u({components:h.components,paths:h.paths,servers:h.servers});return{_schemaTypes:f,_types:m,_client:g,_query:s,_specFile:h}},"generate");const{getProjects:ln,writeProject:ve}=j(),Se=l(async r=>{let e=r.project??void 0,t=[];try{t=await ln()}catch{console.log(`You are not logged in. Please run ${d.hex("#7c3bed")("frontstack login")} to login`);return}if(t.length<1){console.log("No projects found. Please create a new project in your Admin dashboard");return}if(e!==void 0){const o=t.find(a=>a.id===e);if(o){console.log(`Project ${d.hex("#7c3bed")(o.name)} selected`),ve(o.id);return}else{console.log(`Project with ID "${e}" not found. Please select a valid project ID`);return}}const n={type:"select",name:"projectId",message:"Pick a project (Use arrow keys and Enter)",choices:t.map(o=>({title:(o.id===e?"(\u2714) ":"")+`${o.name}`,value:o.id}))};async function i(){const o=await re(n),a=t.find(c=>c.id===o.projectId);if(a===void 0){console.log(`Project with ID "${o.projectId}" not found. Please select a valid project ID`);return}console.log(`Project ${d.hex("#7c3bed")(a.name)} selected`),ve(o.projectId)}l(i,"getProject"),await i()},"project"),un=l(async r=>{const e=r.verbose||!1,t=r.persistOas||!1,{getProject:n,getProfile:i}=j(),o=await i(e);if(!o||o===1){console.info("User not logged in"),await $e(!1)||(console.info(`${d.hex("#b90404")("[ERROR]")} Login failed`),process.exit(1));const E=await i();(!E||E===1)&&(console.info(`${d.hex("#b90404")("[ERROR]")} Login failed`),process.exit(1))}let a=await n();if(!a||"error"in a){console.info("No project selected"),console.info("Running project selection..."),await Se({});const w=await n();if(!w||"error"in w){console.info(`${d.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${d.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`);return}a=w}let c=a;if(!a||"error"in a){console.info(`${d.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${d.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`);return}if(r.env&&a.environments.length>0){let w;if(r.env!=="develop"){if(w=a.environments.find(E=>E.environment===r.env),!w){console.info(`${d.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${d.hex("#b90404")("[ERROR]")} Environment ${r.env} not found`);return}c=w}}if(!r.env&&a.environments.length>0){const w={type:"select",name:"projectId",message:"Pick an environment (use arrow keys and enter)",choices:[{title:`${a.name} (${a.environment})`,value:a.id},...a.environments.map(P=>({title:(P.id===c?.id?"(\u2714) ":"")+`${P.name} (${P.environment})`,value:P.id}))]},E=await re(w);c=a.environments.find(P=>P.id===E.projectId)??a}let u,p,s,h,f;try{e&&console.log("Generating Javascript client"),{_schemaTypes:u,_types:p,_client:s,_query:h,_specFile:f}=await cn(c.id)}catch(w){console.info(`${d.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${d.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`),e?console.info(`${d.hex("#b90404")("[ERROR]")} ${w.message}`):(console.info("Are you..."),console.info(` * logged in using the ${d.hex("#7c3bed")("frontstack login")} command?`),console.info(" * connected to the internet?"),console.info(`Alternatively, run ${d.hex("#7c3bed")("frontstack generate -v")} for additional output.`));return}let m=r.output||".frontstack";process.stdout.write("Generating Javascript client"),m.startsWith("/")||(m=_.join(process.cwd(),m)),m.endsWith("/")||(m+="/");const g=_.join(m,"fetch-api.d.ts"),b=_.join(m,"generated-types.d.ts"),R=_.join(m,"generated-client.ts"),Re=_.join(m,"query-types.ts");if(e&&(console.log(`
26
26
  Schema types path: ${d.dim(g)}`),console.log(`Types path: ${d.dim(b)}`),console.log(`Client path: ${d.dim(R)}`),console.log(`Target directory: ${d.dim(m)}`)),y.mkdirSync(m,{recursive:!0}),t){const w=ie.dump(f,{indent:2}),E=_.join(m,"fetch-api.spec.yaml");console.log(`
27
27
  Persisting OpenAPI Specification file in ${E}`),y.writeFileSync(_.join(E),w)}y.writeFileSync(_.join(g),u),y.writeFileSync(_.join(b),p),y.writeFileSync(_.join(R),s),y.writeFileSync(_.join(Re),h),e?console.log(`Javascript client generated for ${d.hex("#7c3bed")(`${c.name} (${c.environment})`)}`):(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(d.green(`Javascript client generated for ${d.hex("#7c3bed")(`${c.name} (${c.environment})`)}
28
28
  `))),console.log(`
@@ -30,10 +30,6 @@ Use the following imports in your project:
30
30
  `),console.log(" "+d.hex("#7c3bed")("import client from '@frontstack/client';")),console.log(`
31
31
  and use the client like this:
32
32
  `),console.log(" "+d.hex("#7c3bed")("const productDetail = await client.block('DetailPage', { key: 'my-product-id' });")),console.log(`
33
- If you make changes to your schema, run ${d.hex("#7c3bed")("frontstack generate")} again to update the client.`),process.exit(0)},"generateCommand"),{getToken:hn,getProfile:pn,getProject:fn}=j(),dn=l(async()=>{if(hn()===null){console.log(`Status: Not logged in.
34
- `),console.log("Run "+d.hex("#7c3bed")("frontstack login")+" to login.");return}try{const e=await pn(),t=await fn();if(t===void 0||"error"in t){console.log(`Status: No project selected.
35
- `),console.log("Run "+d.hex("#7c3bed")("frontstack project")+" to select a frontstack project");return}if(e===1){console.log(`Not logged in.
36
- `),console.log("Run "+d.hex("#7c3bed")("frontstack login")+" to login.");return}console.log("Logged in as "+d.hex("#7c3bed")(e.email)+`
37
- `),console.log(`Organization: ${e.organization.name}`),console.log(`Current Project: ${t.name??"[No active project selected]"}`)}catch(e){console.log(e)}},"info"),mn=_.dirname(new URL(import.meta.url).pathname),Te=xe(_.join(mn,"version"),"utf8");let te="0.0.1-dev";Te&&(te=Te.trim());const S=new ot;S.name("frontstack").alias("fst").description(`${d.bgHex("#7c3bed").bold("frontstack CLI")}
33
+ If you make changes to your schema, run ${d.hex("#7c3bed")("frontstack generate")} again to update the client.`),process.exit(0)},"generateCommand"),{getToken:hn,getProfile:pn,getProject:fn}=j(),dn=l(async()=>{if(hn()===null){console.log("Status: Not logged in."),console.log("Run "+d.hex("#7c3bed")("frontstack login")+" to login.");return}try{const e=await pn();if(e===void 0||e===1){console.log("Status: Not logged in."),console.log("Run "+d.hex("#7c3bed")("frontstack login")+" to login.");return}console.log("Logged in as "+d.hex("#7c3bed")(e.email)),console.log(`Organization: ${e.organization.name}`);const t=await fn();if(t===void 0||"error"in t){console.log("Status: No project selected."),console.log("Run "+d.hex("#7c3bed")("frontstack project")+" to select a frontstack project");return}console.log(`Current Project: ${t.name??"[No active project selected]"}`)}catch(e){console.log(e)}},"info"),mn=_.dirname(new URL(import.meta.url).pathname),Te=xe(_.join(mn,"version"),"utf8");let te="0.0.1-dev";Te&&(te=Te.trim());const S=new ot;S.name("frontstack").alias("fst").description(`${d.bgHex("#7c3bed").bold("frontstack CLI")}
38
34
  Manage frontstack projects from the command line.
39
35
  ${d.dim(`Version: ${te}`)}`).version(te),S.command("login").description("Login to frontstack account").action(()=>{$e()}),S.command("logout").description("Logout from frontstack account").action(async r=>{await sn()}),S.command("generate").description("Generate a JavaScript client for the current project").option("-o, --output <path>","Output path",".frontstack").option("-v, --verbose","Enable verbose logging").option("-e --env <alias>",'Pass an environment alias like "develop" or "preview"').option("-s --persist-oas","Persist OpenAPI specification file").action(async r=>{await un(r)}),S.command("info").description("Display information about the current organization, project, and user").action(async()=>{await dn()}),S.command("project").description("Select current working project which will be used for schema and client updates").option("-p --project <project-id>","Set current project ID").action(async r=>{await Se(r)});const gn=l(()=>{try{S.parse(process.argv)}catch(r){console.log(r)}},"run");var _n=gn();export{_n as default};
package/dist/version CHANGED
@@ -1 +1 @@
1
- 0.0.0-canary-20250404110750
1
+ 0.0.0-canary-20250404143222
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontstackdev/cli",
3
- "version": "0.0.0-canary-20250404110750",
3
+ "version": "0.0.0-canary-20250404143222",
4
4
  "description": "frontstack CLI for managing projects",
5
5
  "type": "module",
6
6
  "module": "dist/frontstack.mjs",