The best way to control Claude Code, Codex and more from any computer or phone

main
ts 169 lines 7.14 KB
Raw
1 /**
2 * Pieces of the `graphqlgen` command shared by a single run and the watch
3 * loop: config loading, diagnostic formatting and writing changed files.
4 *
5 * @internal
6 */
7 import * as Data from "effect/Data"
8 import * as Effect from "effect/Effect"
9 import * as FileSystem from "effect/FileSystem"
10 import * as Path from "effect/Path"
11 import type { PlatformError } from "effect/PlatformError"
12 import * as Runtime from "effect/Runtime"
13 import * as Schema from "effect/Schema"
14 import * as Config from "../Config.ts"
15 import type * as Generator from "../Generator.ts"
16
17 export class ConfigLoadError extends Data.TaggedError("ConfigLoadError")<{
18 readonly message: string
19 }> {
20 override readonly [Runtime.errorExitCode] = 2
21 override readonly [Runtime.errorReported] = false
22 }
23
24 export class GenerateError extends Data.TaggedError("GenerateError")<{
25 readonly message: string
26 }> {
27 override readonly [Runtime.errorExitCode] = 1
28 override readonly [Runtime.errorReported] = false
29 }
30
31 export const toGenerateError = (error: PlatformError): GenerateError =>
32 new GenerateError({ message: `error: ${error.message}` })
33
34 // -----------------------------------------------------------------------------
35 // Config loading
36 // -----------------------------------------------------------------------------
37
38 /**
39 * Imports and decodes the config file. `version`, when given, is added to the
40 * import URL as `?t=<version>` so an edited config is imported again instead
41 * of coming from the module cache.
42 */
43 export const loadConfig = Effect.fnUntraced(function*(configPath: string, version?: number) {
44 const fs = yield* FileSystem.FileSystem
45 const path = yield* Path.Path
46 const display = displayPath(path, configPath)
47 const exists = yield* fs.exists(configPath).pipe(Effect.orElseSucceed(() => false))
48 if (!exists) {
49 return yield* new ConfigLoadError({ message: `error: config file not found: ${display}` })
50 }
51 const url = yield* path.toFileUrl(configPath).pipe(
52 Effect.mapError((error) => new ConfigLoadError({ message: `error: ${display}: ${error.message}` }))
53 )
54 if (version !== undefined) url.searchParams.set("t", String(version))
55 const module = yield* Effect.tryPromise({
56 try: () => import(/* @vite-ignore */ url.href) as Promise<{ readonly default?: unknown }>,
57 catch: (cause) => new ConfigLoadError({ message: importFailure(display, cause) })
58 })
59 if (module.default === undefined) {
60 return yield* new ConfigLoadError({
61 message:
62 `error: ${display}: the config file has no default export. Export the config with \`export default defineConfig({ ... })\`.`
63 })
64 }
65 return yield* Schema.decodeUnknownEffect(Config.Config)(module.default).pipe(
66 Effect.mapError((error) =>
67 new ConfigLoadError({
68 message: `error: ${display}: the default export is not a valid config:\n${error.message}`
69 })
70 )
71 )
72 })
73
74 /** Errors Node raises when it can't import a `.ts` file through type stripping. */
75 const typeStrippingCodes = new Set(["ERR_UNKNOWN_FILE_EXTENSION", "ERR_NO_TYPESCRIPT"])
76
77 /** Errors Node raises for TypeScript syntax that type stripping can't erase. */
78 const strippableSyntaxCodes = new Set([
79 "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX",
80 "ERR_INVALID_TYPESCRIPT_SYNTAX"
81 ])
82
83 const importFailure = (display: string, cause: unknown): string => {
84 const code = typeof cause === "object" && cause !== null && "code" in cause ? String(cause.code) : undefined
85 const detail = cause instanceof Error ? cause.message : String(cause)
86 if (code !== undefined && typeStrippingCodes.has(code) && display.endsWith(".ts")) {
87 return [
88 `error: ${display}: this runtime cannot import a TypeScript config file (${code}).`,
89 `graphqlgen loads the config with import(), which needs Node.js >= 22.18 (where type stripping is on by default), Bun or Deno.`,
90 `Upgrade Node.js, or run graphqlgen with Bun or Deno.`,
91 ` ${detail}`
92 ].join("\n")
93 }
94 if (code === "ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING") {
95 return [
96 `error: ${display}: Node.js does not strip types from files under node_modules (${code}).`,
97 `Move the config out of node_modules, or run graphqlgen with Bun or Deno.`,
98 ` ${detail}`
99 ].join("\n")
100 }
101 if (code !== undefined && strippableSyntaxCodes.has(code)) {
102 return [
103 `error: ${display}: Node.js type stripping cannot load this config (${code}).`,
104 `Type stripping only erases type annotations, so the config can't use enums, namespaces or parameter properties.`,
105 ` ${detail}`
106 ].join("\n")
107 }
108 return `error: ${display}: could not import the config: ${detail}`
109 }
110
111 // -----------------------------------------------------------------------------
112 // Diagnostics
113 // -----------------------------------------------------------------------------
114
115 export const formatDiagnostic = (path: Path.Path, cwd: string, diagnostic: Generator.Diagnostic): string => {
116 let location = displayPath(path, path.resolve(cwd, diagnostic.path))
117 if (diagnostic.line !== undefined) {
118 location += diagnostic.column === undefined ? `:${diagnostic.line}` : `:${diagnostic.line}:${diagnostic.column}`
119 }
120 const message = `${location}: ${diagnostic.severity}: ${diagnostic.message}`
121 return diagnostic.codeFrame === undefined ? message : `${message}\n${diagnostic.codeFrame}`
122 }
123
124 export const errorSummary = (errors: number): string =>
125 `${errors} ${errors === 1 ? "error" : "errors"}; no files were written.`
126
127 /** A path relative to the current directory, with `/` separators. */
128 export const displayPath = (path: Path.Path, absolute: string): string => {
129 const relative = path.relative(path.resolve("."), absolute)
130 return (relative === "" || path.isAbsolute(relative) ? absolute : relative).split(path.sep).join("/")
131 }
132
133 // -----------------------------------------------------------------------------
134 // Writing
135 // -----------------------------------------------------------------------------
136
137 export interface Changes {
138 readonly creates: ReadonlyArray<Generator.GeneratedFile>
139 readonly updates: ReadonlyArray<Generator.GeneratedFile>
140 readonly deletes: ReadonlyArray<string>
141 }
142
143 /** Compares the generated files with what is on disk; unchanged files are left out. */
144 export const planChanges = Effect.fnUntraced(function*(result: Generator.GenerateResult) {
145 const fs = yield* FileSystem.FileSystem
146 const creates: Array<Generator.GeneratedFile> = []
147 const updates: Array<Generator.GeneratedFile> = []
148 for (const file of result.files) {
149 if (!(yield* fs.exists(file.path))) {
150 creates.push(file)
151 } else if ((yield* fs.readFileString(file.path)) !== file.contents) {
152 updates.push(file)
153 }
154 }
155 return { creates, updates, deletes: result.deletes } satisfies Changes
156 }, Effect.mapError(toGenerateError))
157
158 /** Writes the created and updated files, then deletes the stale ones. */
159 export const writeChanges = Effect.fnUntraced(function*(changes: Changes) {
160 const fs = yield* FileSystem.FileSystem
161 const path = yield* Path.Path
162 for (const file of [...changes.creates, ...changes.updates]) {
163 yield* fs.makeDirectory(path.dirname(file.path), { recursive: true })
164 yield* fs.writeFileString(file.path, file.contents)
165 }
166 for (const file of changes.deletes) {
167 yield* fs.remove(file)
168 }
169 }, Effect.mapError(toGenerateError))