@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 79 lines 2.43 KB
Raw
1 /**
2 * Located diagnostics for the generator. Lexing and parsing stop at the first
3 * error; validation collects multiple errors.
4 *
5 * @internal
6 */
7 import * as Data from "effect/Data"
8 import * as Result from "effect/Result"
9
10 /** A GraphQL document together with the path diagnostics report it under. */
11 export interface Source {
12 readonly path: string
13 readonly body: string
14 }
15
16 /**
17 * A located error in one GraphQL source file.
18 *
19 * Locations are 1-based UTF-16 columns; EOF points past the last character.
20 * `message` excludes the location. `codeFrame` shows the line and its
21 * neighbours with a caret under the offending column.
22 */
23 export class Diagnostic extends Data.TaggedError("Diagnostic")<{
24 readonly path: string
25 readonly line: number
26 readonly column: number
27 readonly message: string
28 readonly codeFrame: string
29 }> {}
30
31 interface Location {
32 readonly line: number
33 readonly column: number
34 }
35
36 const lineTerminator = /\r\n|\r|\n/g
37
38 /** The 1-based line and UTF-16 column of a code-unit offset into `body`. */
39 const locationOf = (body: string, offset: number): Location => {
40 const lines = body.slice(0, offset).split(lineTerminator)
41 return { line: lines.length, column: lines[lines.length - 1]!.length + 1 }
42 }
43
44 const codeFrame = (body: string, location: Location): string => {
45 const lines = body.split(lineTerminator)
46 const first = Math.max(1, location.line - 1)
47 const last = Math.min(lines.length, location.line + 1)
48 const width = String(last).length
49 const out: Array<string> = []
50 for (let n = first; n <= last; n++) {
51 out.push(`${String(n).padStart(width)} | ${lines[n - 1] ?? ""}`)
52 if (n === location.line) {
53 out.push(`${" ".repeat(width)} | ${" ".repeat(location.column - 1)}^`)
54 }
55 }
56 return out.join("\n")
57 }
58
59 /** Builds a diagnostic for `message` at a code-unit offset into the source. */
60 export const make = (source: Source, offset: number, message: string): Diagnostic => {
61 const location = locationOf(source.body, offset)
62 return new Diagnostic({
63 path: source.path,
64 line: location.line,
65 column: location.column,
66 message,
67 codeFrame: codeFrame(source.body, location)
68 })
69 }
70
71 /** Runs `body`, turning a thrown {@link Diagnostic} into a failure. Other errors propagate. */
72 export const catchDiagnostic = <A>(body: () => A): Result.Result<A, Diagnostic> => {
73 try {
74 return Result.succeed(body())
75 } catch (error) {
76 if (error instanceof Diagnostic) return Result.fail(error)
77 throw error
78 }
79 }