Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cli): export cli actions as node apis #135

Merged
merged 1 commit into from
Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fresh-pillows-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gql.tada/cli-utils': minor
---

Abstract core logic for `generate-schema` and `generate-output` CLI commands into importable Node.js API's
281 changes: 148 additions & 133 deletions packages/cli-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,140 @@ import type { GraphQLSPConfig } from './lsp';
import { hasGraphQLSP } from './lsp';
import { ensureTadaIntrospection } from './tada';

interface GenerateSchemaOptions {
headers?: Record<string, string>;
output?: string;
cwd?: string;
}

export async function generateSchema(
target: string,
{ headers, output, cwd = process.cwd() }: GenerateSchemaOptions
) {
let url: URL | undefined;

try {
url = new URL(target);
} catch (e) {}

let introspection: IntrospectionQuery;
if (url) {
const response = await fetch(url!.toString(), {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: getIntrospectionQuery({
descriptions: true,
schemaDescription: false,
inputValueDeprecation: false,
directiveIsRepeatable: false,
specifiedByUrl: false,
}),
}),
});

if (response.ok) {
const text = await response.text();

try {
const result = JSON.parse(text);
if (result.data) {
introspection = (result as { data: IntrospectionQuery }).data;
} else {
console.error(`Got invalid response ${JSON.stringify(result)}`);
return;
}
} catch (e) {
console.error(`Got invalid JSON ${text}`);
return;
}
} else {
console.error(`Got invalid response ${await response.text()}`);
return;
}
} else {
const path = resolve(cwd, target);
const fileContents = await fs.readFile(path, 'utf-8');

try {
introspection = JSON.parse(fileContents);
} catch (e) {
console.error(`Got invalid JSON ${fileContents}`);
return;
}
}

const schema = buildClientSchema(introspection!);

let destination = output;
if (!destination) {
const tsconfigpath = path.resolve(cwd, 'tsconfig.json');
const hasTsConfig = existsSync(tsconfigpath);
if (!hasTsConfig) {
console.error(`Could not find a tsconfig in the working-directory.`);
return;
}

const tsconfigContents = await fs.readFile(tsconfigpath, 'utf-8');
let tsConfig: TsConfigJson;
try {
tsConfig = parse(tsconfigContents) as TsConfigJson;
} catch (err) {
console.error(err);
return;
}

if (!hasGraphQLSP(tsConfig)) {
console.error(`Could not find a "@0no-co/graphqlsp" plugin in your tsconfig.`);
return;
}

const foundPlugin = tsConfig.compilerOptions!.plugins!.find(
(plugin) => plugin.name === '@0no-co/graphqlsp'
) as GraphQLSPConfig;

destination = foundPlugin.schema;

if (!foundPlugin.schema.endsWith('.graphql')) {
console.error(`Found "${foundPlugin.schema}" which is not a path to a GraphQL Schema.`);
return;
}
}

await fs.writeFile(resolve(cwd, destination), printSchema(schema), 'utf-8');
}

export async function generateTadaTypes(cwd: string = process.cwd()) {
const tsconfigpath = path.resolve(cwd, 'tsconfig.json');
const hasTsConfig = existsSync(tsconfigpath);
if (!hasTsConfig) {
console.error('Missing tsconfig.json');
return;
}

const tsconfigContents = await fs.readFile(tsconfigpath, 'utf-8');
let tsConfig: TsConfigJson;
try {
tsConfig = parse(tsconfigContents) as TsConfigJson;
} catch (err) {
console.error(err);
return;
}

if (!hasGraphQLSP(tsConfig)) {
return;
}

const foundPlugin = tsConfig.compilerOptions!.plugins!.find(
(plugin) => plugin.name === '@0no-co/graphqlsp'
) as GraphQLSPConfig;

await ensureTadaIntrospection(foundPlugin.schema, foundPlugin.tadaOutputLocation!, cwd);
}

const prog = sade('gql.tada');

prog.version(process.env.npm_package_version || '0.0.0');
Expand All @@ -30,147 +164,28 @@ async function main() {
.example("generate-schema https://example.com --header 'Authorization: Bearer token'")
.example('generate-schema ./introspection.json')
.action(async (target, options) => {
const cwd = process.cwd();
let url: URL | undefined;

try {
url = new URL(target);
} catch (e) {}

let introspection: IntrospectionQuery;
if (url) {
const headers = (Array.isArray(options.header) ? options.header : [options.header]).reduce(
(acc, item) => {
if (!item) return acc;

const parts = item.split(':');
return {
...acc,
[parts[0]]: parts[1],
};
},
{}
);
const response = await fetch(url!.toString(), {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: getIntrospectionQuery({
descriptions: true,
schemaDescription: false,
inputValueDeprecation: false,
directiveIsRepeatable: false,
specifiedByUrl: false,
}),
}),
const parsedHeaders = {};

if (typeof options.header === 'string') {
const [key, value] = options.header.split(':').map((part) => part.trim());
parsedHeaders[key] = value;
} else if (Array.isArray(options.header)) {
options.header.forEach((header) => {
const [key, value] = header.split(':').map((part) => part.trim());
parsedHeaders[key] = value;
});

if (response.ok) {
const text = await response.text();

try {
const result = JSON.parse(text);
if (result.data) {
introspection = (result as { data: IntrospectionQuery }).data;
} else {
console.error(`Got invalid response ${JSON.stringify(result)}`);
return;
}
} catch (e) {
console.error(`Got invalid JSON ${text}`);
return;
}
} else {
console.error(`Got invalid response ${await response.text()}`);
return;
}
} else {
const path = resolve(cwd, target);
const fileContents = await fs.readFile(path, 'utf-8');

try {
introspection = JSON.parse(fileContents);
} catch (e) {
console.error(`Got invalid JSON ${fileContents}`);
return;
}
}

const schema = buildClientSchema(introspection!);

let destination = options.output;
if (!destination) {
const cwd = process.cwd();
const tsconfigpath = path.resolve(cwd, 'tsconfig.json');
const hasTsConfig = existsSync(tsconfigpath);
if (!hasTsConfig) {
console.error(`Could not find a tsconfig in the working-directory.`);
return;
}

const tsconfigContents = await fs.readFile(tsconfigpath, 'utf-8');
let tsConfig: TsConfigJson;
try {
tsConfig = parse(tsconfigContents) as TsConfigJson;
} catch (err) {
console.error(err);
return;
}

if (!hasGraphQLSP(tsConfig)) {
console.error(`Could not find a "@0no-co/graphqlsp" plugin in your tsconfig.`);
return;
}

const foundPlugin = tsConfig.compilerOptions!.plugins!.find(
(plugin) => plugin.name === '@0no-co/graphqlsp'
) as GraphQLSPConfig;

destination = foundPlugin.schema;

if (!foundPlugin.schema.endsWith('.graphql')) {
console.error(`Found "${foundPlugin.schema}" which is not a path to a GraphQL Schema.`);
return;
}
}

await fs.writeFile(resolve(cwd, destination), printSchema(schema), 'utf-8');
generateSchema(target, {
headers: parsedHeaders,
output: options.output,
});
})
.command('generate-output')
.describe(
'Generate the gql.tada types file, this will look for your "tsconfig.json" and use the "@0no-co/graphqlsp" configuration to generate the file.'
)
.action(async () => {
const cwd = process.cwd();
const tsconfigpath = path.resolve(cwd, 'tsconfig.json');
const hasTsConfig = existsSync(tsconfigpath);
if (!hasTsConfig) {
console.error('Missing tsconfig.json');
return;
}

const tsconfigContents = await fs.readFile(tsconfigpath, 'utf-8');
let tsConfig: TsConfigJson;
try {
tsConfig = parse(tsconfigContents) as TsConfigJson;
} catch (err) {
console.error(err);
return;
}

if (!hasGraphQLSP(tsConfig)) {
return;
}

const foundPlugin = tsConfig.compilerOptions!.plugins!.find(
(plugin) => plugin.name === '@0no-co/graphqlsp'
) as GraphQLSPConfig;

await ensureTadaIntrospection(foundPlugin.schema, foundPlugin.tadaOutputLocation!);
});
.action(() => generateTadaTypes());
prog.parse(process.argv);
}

Expand Down
5 changes: 2 additions & 3 deletions packages/cli-utils/src/tada.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@ export { readFragment as useFragment } from 'gql.tada';
*/
export async function ensureTadaIntrospection(
schemaLocation: SchemaOrigin | string,
outputLocation: string
outputLocation: string,
base: string = process.cwd()
) {
const base = process.cwd();

const writeTada = async () => {
try {
const schema = await loadSchema(base, schemaLocation);
Expand Down
2 changes: 1 addition & 1 deletion src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env node

import cli from '@gql.tada/cli-utils';
cli();
(cli as any).default();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are the types erroneously generated now?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed types for gql-data-cli.d.ts are the same as they were previous to this change 👍🙂

Loading