@gqty/cli
Version:
Interactive codegen for GQty
5 lines (4 loc) • 2.67 kB
JavaScript
import{readFile as l}from"fs/promises";import{extname as p}from"path";import"@commander-js/extra-typings";import"@graphql-codegen/core";import"@graphql-codegen/typescript";import"@graphql-tools/utils";import{schemaFromExecutor as w}from"@graphql-tools/wrap";import*as g from"@inquirer/prompts";import"cosmiconfig";import{fetch as y}from"cross-fetch";import v from"fast-glob";import{buildSchema as x,printSchema as E}from"graphql";import"lodash-es/sortBy.js";import"prettier";import{convertHeadersInput as S}from"./convertHeadersInput.mjs";import{logger as f}from"./logger.mjs";var b=Object.defineProperty,F=(e,r,t)=>r in e?b(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t,q=(e,r,t)=>F(e,typeof r!="symbol"?r+"":r,t);const P=[".gql",".graphql"];class u extends Error{constructor(r,t){super(`Received status code ${t.status} when introspecting ${t.url}`),this.request=r,this.response=t,q(this,"name","FetchError")}}async function _(e,r={}){const t=[];r.headersByEndpoint||(r.headersByEndpoint={}),Array.isArray(e)||(e=[e]);for(const i of e){const{headers:o,headersByEndpoint:n}=r,c=async()=>{const s=await $(i,{headers:o??n[i]?.headers,silent:r.silent});s!==void 0&&t.push(s)};try{await c()}catch(s){if(s instanceof u&&s.response.status===401&&o===void 0&&n[i]?.headers===void 0){process.stdout.write("\r");const a=await N();if(a===void 0)throw s;n[s.response.url]={headers:a},await c()}else throw s}}if(t.length===0)throw new Error("No schemas found.");return r.silent||(f.successProgress("Schema introspection completed."),console.log("")),x(t.join(`
`))}const $=async(e,r)=>{if(d(e)){r?.silent||f.infoProgress(`Fetching schema from remote endpoint '${e}'...`);const i=await w(async({document:o,variables:n,extensions:c={}})=>{const{print:s}=await import("graphql"),a={method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify({query:s(o),variables:n,extensions:{...c,endpoint:e}})},m=await y(e,a);if(m.status>=400)throw new u(a,m);const h=await m.text();try{return JSON.parse(h)}catch{throw new SyntaxError(`Invalid JSON received from ${e}: "${h.length>50?h.slice(0,50).replace(/\n/g,"")+"...":h}".`)}});return E(i)}else{const t=await v(e).then(o=>o.filter(n=>P.includes(p(n))));if(t.length===0)return;const i=[];for(const o of t)r?.silent||f.infoProgress(`Reading schema file ${o} ...`),i.push(await l(o,{encoding:"utf-8"}));return i.join(`
`)}},N=async()=>{if(!process.stdin.isTTY)return;const e=await g.input({message:"Any request headers? (Authorization: Bearer <token>, X-Foo: <bar>)"});return S(e.split(/,/))},d=e=>/^https?:\/\//.test(e);export{u as FetchError,_ as fetchSchema,d as isURL};