/** CLI tests run scratch projects in process; the bin test uses Node to load the config. */
import * as Generator from "@effect/graphql-generator/Generator"
import * as NodeServices from "@effect/platform-node/NodeServices"
import { assert, describe, it } from "@effect/vitest"
import * as Cause from "effect/Cause"
import { CliOutput } from "effect/cli"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as FileSystem from "effect/FileSystem"
import * as Layer from "effect/Layer"
import * as Option from "effect/Option"
import * as Path from "effect/Path"
import { ChildProcess, ChildProcessSpawner } from "effect/process"
import * as Runtime from "effect/Runtime"
import * as Stdio from "effect/Stdio"
import * as Stream from "effect/Stream"
import { TestConsole } from "effect/testing"
import { fileURLToPath } from "node:url"
const schemaSdl = `type User {
id: ID!
name: String!
}
type Query {
viewer: User!
}
`
const query = (name: string, field = "id"): string => `query ${name} {\n viewer {\n ${field}\n }\n}\n`
const config = {
schema: "./schema.graphql",
documents: ["src/**/*.graphql"]
}
const configSource = (value: unknown): string =>
`import { defineConfig } from "@effect/graphql-generator/Config"\n\nexport default defineConfig(${
JSON.stringify(value, null, 2)
})\n`
const header = (sourceName: string): string =>
`// Generated by @effect/graphql-generator from ${sourceName}. Do not edit.\n`
const tmpRoot = fileURLToPath(new URL("./.tmp", import.meta.url))
const binPath = fileURLToPath(new URL("../src/bin.ts", import.meta.url))
const runBin = Effect.fnUntraced(function*(cwd: string) {
const handle = yield* ChildProcess.make("node", [binPath], { cwd })
return yield* Effect.all({
exitCode: handle.exitCode,
stderr: Stream.mkString(Stream.decodeText(handle.stderr))
}, { concurrency: "unbounded" })
})
/** Writes `files` (relative path to contents) to a fresh scratch directory, removed with the scope. */
const project = Effect.fnUntraced(function*(files: Readonly<Record<string, string>>) {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
yield* fs.makeDirectory(tmpRoot, { recursive: true })
const dir = yield* fs.makeTempDirectoryScoped({ directory: tmpRoot, prefix: "cli-" })
yield* write(dir, files)
return {
dir,
configPath: path.join(dir, "graphql.config.ts"),
file: (relative: string) => path.join(dir, relative)
}
})
const write = Effect.fnUntraced(function*(dir: string, files: Readonly<Record<string, string>>) {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
for (const [relative, body] of Object.entries(files)) {
const file = path.join(dir, relative)
yield* fs.makeDirectory(path.dirname(file), { recursive: true })
yield* fs.writeFileString(file, body)
}
})
const baseProject = (documents: Readonly<Record<string, string>>, value: unknown = config) =>
project({ "graphql.config.ts": configSource(value), "schema.graphql": schemaSdl, ...documents })
const runCli = Effect.fnUntraced(function*(args: ReadonlyArray<string>) {
const module = (yield* Effect.promise(
() => import(new URL("../src/main.ts", import.meta.url).href)
)) as { readonly run: Effect.Effect<void, unknown> }
return yield* Effect.gen(function*() {
const exit = yield* Effect.exit(module.run)
const stdout = (yield* TestConsole.logLines).map(String).join("\n")
const stderr = (yield* TestConsole.errorLines).map(String).join("\n")
return { exitCode: exitCode(exit), stdout, stderr, output: `${stdout}\n${stderr}` } as const
}).pipe(
Effect.provide(Layer.mergeAll(
TestConsole.layer,
CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),
NodeServices.layer,
Stdio.layerTest({ args: Effect.succeed(args) })
))
)
})
/** The process exit code `NodeRuntime.runMain` would use for `exit`. */
const exitCode = (exit: Exit.Exit<void, unknown>): number =>
Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause))
const exists = Effect.fnUntraced(function*(file: string) {
const fs = yield* FileSystem.FileSystem
return yield* fs.exists(file)
})
const read = Effect.fnUntraced(function*(file: string) {
const fs = yield* FileSystem.FileSystem
return yield* fs.readFileString(file)
})
describe("graphqlgen CLI", () => {
it.effect("unknown flags exit 2", () =>
Effect.gen(function*() {
const result = yield* runCli(["--unknown"])
assert.strictEqual(result.exitCode, 2, result.output)
}))
it.effect("--watch --check exits 2", () =>
Effect.gen(function*() {
const result = yield* runCli(["--watch", "--check"])
assert.strictEqual(result.exitCode, 2, result.output)
}))
it.effect("a clean run writes the generated files, deletes stale ones and exits 0; a second run writes nothing", () =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const p = yield* baseProject({ "src/a.graphql": query("A") })
const expected = yield* Generator.generate(config, { cwd: p.dir })
yield* write(p.dir, { "src/stale.graphql.ts": header("stale.graphql") })
const first = yield* runCli(["--config", p.configPath])
assert.strictEqual(first.exitCode, 0, first.output)
assert.isFalse(yield* exists(p.file("src/stale.graphql.ts")))
for (const file of expected.files) {
assert.strictEqual(yield* read(file.path), file.contents, file.path)
yield* fs.utimes(file.path, 0, 0)
}
const second = yield* runCli(["--config", p.configPath])
assert.strictEqual(second.exitCode, 0, second.output)
for (const file of expected.files) {
const info = yield* fs.stat(file.path)
assert.strictEqual(Option.getOrThrow(info.mtime).getTime(), 0, `${file.path} was rewritten`)
}
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
it.effect("a validation error prints file:line:col with a code frame, changes nothing on disk and exits 1", () =>
Effect.gen(function*() {
const p = yield* baseProject({
"src/a.graphql": query("A"),
"src/b.graphql": query("B", "nope"),
"src/stale.graphql.ts": header("stale.graphql")
})
const result = yield* runCli(["--config", p.configPath])
assert.strictEqual(result.exitCode, 1, result.output)
assert.include(result.stderr, `src/b.graphql:3:5: error: Cannot query field "nope" on type "User".`)
assert.include(result.stderr, "3 | nope")
assert.isFalse(yield* exists(p.file("src/a.graphql.ts")))
assert.isFalse(yield* exists(p.file("schema.graphql.ts")))
assert.isTrue(yield* exists(p.file("src/stale.graphql.ts")))
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
it.effect("a config that fails to decode exits 2 naming the issue path", () =>
Effect.gen(function*() {
const p = yield* baseProject(
{ "src/a.graphql": query("A") },
{ schema: "./schema.graphql", documents: "src/**/*.graphql" }
)
const result = yield* runCli(["--config", p.configPath])
assert.strictEqual(result.exitCode, 2, result.output)
assert.include(result.stderr, "documents")
assert.isFalse(yield* exists(p.file("src/a.graphql.ts")))
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
it.effect("--check exits 0 when up to date, otherwise lists every create, change and delete and exits 1", () =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const p = yield* baseProject({ "src/changed.graphql": query("Changed"), "src/removed.graphql": query("Removed") })
yield* runCli(["--config", p.configPath])
const upToDate = yield* runCli(["--config", p.configPath, "--check"])
assert.strictEqual(upToDate.exitCode, 0, upToDate.output)
yield* write(p.dir, { "src/changed.graphql": query("Changed", "name"), "src/created.graphql": query("Created") })
yield* fs.remove(p.file("src/removed.graphql"))
const result = yield* runCli(["--config", p.configPath, "--check"])
assert.strictEqual(result.exitCode, 1, result.output)
assert.match(result.stdout, /would create \S*src\/created\.graphql\.ts/)
assert.match(result.stdout, /would update \S*src\/changed\.graphql\.ts/)
assert.match(result.stdout, /would delete \S*src\/removed\.graphql\.ts/)
assert.isFalse(yield* exists(p.file("src/created.graphql.ts")))
assert.isTrue(yield* exists(p.file("src/removed.graphql.ts")))
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
it.effect("documents skip the schema file, node_modules and dot-directories without a diagnostic", () =>
Effect.gen(function*() {
const p = yield* baseProject(
{ "src/a.graphql": query("A"), "node_modules/pkg/bad.graphql": "query {", ".cache/bad.graphql": "query {" },
{ schema: "./schema.graphql", documents: ["**/*.graphql"] }
)
const result = yield* runCli(["--config", p.configPath])
assert.strictEqual(result.exitCode, 0, result.output)
assert.strictEqual(result.stderr, "")
assert.isTrue(yield* exists(p.file("src/a.graphql.ts")))
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
it.effect("documents patterns rooted in node_modules or a dot-directory match nothing; ../ roots still work", () =>
Effect.gen(function*() {
const orphan = `${header("orphan.graphql")}export const Orphan = 1\n`
const p = yield* project({
"app/graphql.config.ts": configSource({
schema: "./schema.graphql",
documents: ["../shared/**/*.graphql", ".cache/**/*.graphql", "node_modules/pkg/**/*.graphql"]
}),
"app/schema.graphql": schemaSdl,
"shared/a.graphql": query("A"),
"app/.cache/q.graphql": query("CacheQuery"),
"app/.cache/orphan.graphql.ts": orphan,
"app/node_modules/pkg/q.graphql": query("PackageQuery"),
"app/node_modules/pkg/orphan.graphql.ts": orphan
})
const result = yield* runCli(["--config", p.file("app/graphql.config.ts")])
assert.strictEqual(result.exitCode, 0, result.output)
assert.isTrue(yield* exists(p.file("shared/a.graphql.ts")))
assert.isFalse(yield* exists(p.file("app/.cache/q.graphql.ts")))
assert.isFalse(yield* exists(p.file("app/node_modules/pkg/q.graphql.ts")))
assert.isTrue(yield* exists(p.file("app/.cache/orphan.graphql.ts")))
assert.isTrue(yield* exists(p.file("app/node_modules/pkg/orphan.graphql.ts")))
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
it.effect("bin.ts loads graphql.config.ts from the working directory under Node", () =>
Effect.gen(function*() {
const p = yield* baseProject({ "src/a.graphql": query("A") })
const result = yield* runBin(p.dir)
assert.strictEqual(result.exitCode, ChildProcessSpawner.ExitCode(0), result.stderr)
assert.include(yield* read(p.file("src/a.graphql.ts")), header("a.graphql"))
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
})