@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, 04:45 UTC

main
ts 375 lines 10.7 KB
Raw
1 /**
2 * Renders parsed documentation models as Markdown.
3 *
4 * @since 0.6.0
5 */
6 import * as Array from "effect/Array"
7 import * as Effect from "effect/Effect"
8 import { pipe } from "effect/Function"
9 import * as Order from "effect/Order"
10 import * as Record from "effect/Record"
11 import * as String from "effect/String"
12 import * as Prettier from "prettier"
13 import * as Configuration from "./Configuration.ts"
14 import type * as Domain from "./Domain.ts"
15 import * as Parser from "./Parser.ts"
16
17 /** @internal */
18 export type Printable =
19 | Domain.Class
20 | Domain.Constant
21 | Domain.Export
22 | Domain.Function
23 | Domain.Interface
24 | Domain.TypeAlias
25 | Domain.Namespace
26
27 const Markdown = {
28 bold: (content: string) => `**${content}**`,
29 fence: (content: string) => `\`\`\`ts\n${content}\n\`\`\`\n\n`,
30 strikethrough: (content: string) => `~~${content}~~`
31 }
32
33 /**
34 * Replaces the link from a JSDoc link tag with a simple text.
35 *
36 * Given "This is a description containing two links to {@link foo} and {@link bar baz}."
37 * returns "This is a description containing two links to `foo` and `baz`."
38 */
39 function replaceJSDocLinks(text: string): string {
40 return text.replace(/\{@link\s+([^\s}]+)(?:\s+([^}]+))?\}/g, (_, link, label) => {
41 // Use the label if provided; otherwise, use the link target
42 return `\`${(label || link).trim()}\``
43 })
44 }
45
46 /**
47 * Removes all extra metadata from fenced code blocks in a Markdown string.
48 * For each code fence, only the first token (the language identifier) is preserved.
49 */
50 function removeFenceMetadata(markdown: string): string {
51 return markdown.replace(/^(`{3,})([^\n]*)/gm, (_match, fence, info) => {
52 // Trim the info string and split by whitespace into tokens.
53 // The first token (if present) is typically the language identifier.
54 const tokens = info.trim().split(/\s+/)
55 // Rebuild the fence line with just the language (if it exists)
56 return fence + (tokens[0] || "")
57 })
58 }
59
60 const printOptionalDescription = Effect.fnUntraced(function*(description: string | undefined) {
61 if (description === undefined) {
62 return ""
63 }
64 const config = yield* Configuration.Configuration
65 const descriptionWithoutLinks = replaceJSDocLinks(description)
66 const out = config.theme === Configuration.DEFAULT_THEME
67 ? removeFenceMetadata(descriptionWithoutLinks)
68 : descriptionWithoutLinks
69 return `\n\n${out}`
70 })
71
72 const printArray = (title: string, ss?: ReadonlyArray<string>): string => {
73 if (ss === undefined || ss.length === 0) {
74 return ""
75 }
76 return `\n\n${Markdown.bold(title)}\n\n${ss.join("\n")}`
77 }
78
79 const printFence = (code: string): string => {
80 if (code.startsWith("```ts") || code.startsWith("~~~ts")) {
81 return code
82 }
83 return "```ts\n" + code + "\n```"
84 }
85
86 const printOptionalSignature = (signature?: string): string => {
87 if (signature === undefined) {
88 return ""
89 }
90 return `\n\n${Markdown.bold("Signature")}\n\n${printFence(signature)}`
91 }
92
93 const printThrowsArray = (throws?: ReadonlyArray<string>): string => printArray("Throws", throws)
94
95 const printExamplesArray = (examples: ReadonlyArray<string>): string => {
96 if (examples.length === 0) {
97 return ""
98 }
99 return examples.map((ex) => "\n\n**Example**\n\n" + printFence(ex)).join("")
100 }
101
102 const printOptionalSince = (since: ReadonlyArray<string>): string => {
103 if (since.length === 0) {
104 return ""
105 }
106 return `\n\nSince v${since.join(", ")}`
107 }
108
109 const printHeaderByIndentation = (indentation: number) => {
110 switch (indentation) {
111 case 0:
112 return "## "
113 case 1:
114 return "### "
115 default:
116 return "#### "
117 }
118 }
119
120 const printTitle = (s: string, deprecated: ReadonlyArray<string>, postfix?: string): string => {
121 const name = s.trim() === "hasOwnProperty" ? `${s} (function)` : s
122 const title = deprecated.length > 0 ? Markdown.strikethrough(name) : name
123 return postfix === undefined ? title : title + ` ${postfix}`
124 }
125
126 const printSeesArray = (sees?: ReadonlyArray<string>): string => {
127 if (sees === undefined || sees.length === 0) {
128 return ""
129 }
130 return `\n\n${Markdown.bold("See")}\n\n${sees.map((see) => `- ${replaceJSDocLinks(see)}`).join("\n")}`
131 }
132
133 const printOptionalSourceLink = Effect.fnUntraced(function*(position?: Domain.Position) {
134 if (position === undefined) {
135 return ""
136 }
137 const config = yield* Configuration.Configuration
138 const source = yield* Parser.Source
139 const name = source.sourceFile.getBaseName()
140 return `\n\n[Source](${config.srcLink}${name}#L${position.line})`
141 })
142
143 const printModel = Effect.fnUntraced(function*(name: string, doc: Domain.Doc, options: {
144 readonly signature?: string | undefined
145 readonly position?: Domain.Position | undefined
146 readonly indentation?: number | undefined
147 readonly postfix?: string | undefined
148 }) {
149 const sourceLink = yield* printOptionalSourceLink(options.position)
150 const description = yield* printOptionalDescription(doc.description)
151 return printHeaderByIndentation(options.indentation ?? 0) + printTitle(name, doc.deprecated, options.postfix) +
152 description +
153 printThrowsArray(doc.throws) +
154 printExamplesArray(doc.examples) +
155 printSeesArray(doc.sees) +
156 printOptionalSignature(options.signature) +
157 sourceLink +
158 printOptionalSince(doc.since)
159 })
160
161 const printEntry = (model: Domain.DocEntry, options: {
162 readonly indentation?: number | undefined
163 readonly postfix?: string | undefined
164 }) => {
165 return printModel(model.name, model.doc, {
166 signature: model.signature,
167 position: model.position,
168 indentation: options.indentation,
169 postfix: options.postfix
170 })
171 }
172
173 const printStaticMethod = (model: Domain.DocEntry) => {
174 return printEntry(model, {
175 indentation: 1,
176 postfix: "(static method)"
177 })
178 }
179
180 const printMethod = (model: Domain.DocEntry) => {
181 return printEntry(model, {
182 indentation: 1,
183 postfix: "(method)"
184 })
185 }
186
187 const printProperty = (model: Domain.DocEntry) => {
188 return printEntry(model, {
189 indentation: 1,
190 postfix: "(property)"
191 })
192 }
193
194 const printClass = Effect.fnUntraced(function*(model: Domain.Class) {
195 const header = yield* printEntry(model, {
196 postfix: "(class)"
197 })
198 const staticMethods = yield* Effect.forEach(model.staticMethods, (method) => printStaticMethod(method))
199 const methods = yield* Effect.forEach(model.methods, (method) => printMethod(method))
200 const properties = yield* Effect.forEach(model.properties, (property) => printProperty(property))
201 return header +
202 staticMethods.map((s) => "\n\n" + s).join("") +
203 methods.map((s) => "\n\n" + s).join("") +
204 properties.map((s) => "\n\n" + s).join("")
205 })
206
207 const printConstant = (model: Domain.Constant) => {
208 return printEntry(model, {})
209 }
210
211 const printExport = (model: Domain.Export) => {
212 return printEntry(model, {
213 postfix: model.isNamespaceExport ? "(namespace export)" : undefined
214 })
215 }
216
217 const printFunction = (model: Domain.Function) => {
218 return printEntry(model, {})
219 }
220
221 const printInterface = (model: Domain.Interface, indentation: number) => {
222 return printEntry(model, {
223 indentation,
224 postfix: "(interface)"
225 })
226 }
227
228 const printTypeAlias = (model: Domain.TypeAlias, indentation: number) => {
229 return printEntry(model, {
230 indentation,
231 postfix: "(type alias)"
232 })
233 }
234
235 const printNamespace = (
236 model: Domain.Namespace,
237 indentation: number
238 ): Effect.Effect<string, never, Configuration.Configuration | Parser.Source> => {
239 return Effect.gen(function*() {
240 const header = yield* printModel(model.name, model.doc, {
241 position: model.position,
242 indentation,
243 postfix: "(namespace)"
244 })
245 const interfaces = yield* Effect.forEach(model.interfaces, (inter) => printInterface(inter, indentation + 1))
246 const typeAliases = yield* Effect.forEach(
247 model.typeAliases,
248 (typeAlias) => printTypeAlias(typeAlias, indentation + 1)
249 )
250 const namespaces = yield* Effect.forEach(
251 model.namespaces,
252 (namespace) => printNamespace(namespace, indentation + 1)
253 )
254 return header +
255 interfaces.map((s) => "\n\n" + s).join("") +
256 typeAliases.map((s) => "\n\n" + s).join("") +
257 namespaces.map((s) => "\n\n" + s).join("")
258 })
259 }
260
261 /** @internal */
262 export const print = (p: Printable) => {
263 switch (p._tag) {
264 case "Class":
265 return printClass(p)
266 case "Constant":
267 return printConstant(p)
268 case "Export":
269 return printExport(p)
270 case "Function":
271 return printFunction(p)
272 case "Interface":
273 return printInterface(p, 0)
274 case "TypeAlias":
275 return printTypeAlias(p, 0)
276 case "Namespace":
277 return printNamespace(p, 0)
278 }
279 }
280
281 const DEFAULT_CATEGORY = "utils"
282
283 const byCategory = Order.mapInput(
284 String.Order,
285 ([category]: [string, ...Array<unknown>]) => category
286 )
287
288 const getPrintables = (module: Domain.Module): ReadonlyArray<Printable> =>
289 Array.flatten([
290 module.classes,
291 module.constants,
292 module.exports,
293 module.functions,
294 module.interfaces,
295 module.typeAliases,
296 module.namespaces
297 ])
298
299 const sortByName: <A extends { name: string }>(self: Iterable<A>) => Array<A> = Array.sort(
300 pipe(
301 String.Order,
302 Order.mapInput(({ name }: { name: string }) => name)
303 )
304 )
305
306 /**
307 * Renders a parsed module as a Markdown documentation page.
308 *
309 * @category printers
310 * @since 0.6.0
311 */
312 export const printModule = (module: Domain.Module) => {
313 return Effect.gen(function*() {
314 const description = yield* printModel(module.name, module.doc, {
315 postfix: "overview"
316 })
317
318 const printables = pipe(
319 sortByName(getPrintables(module)),
320 Array.groupBy((printable) =>
321 printable.doc.category.length === 0 ? DEFAULT_CATEGORY : printable.doc.category.join(", ")
322 ),
323 Record.toEntries,
324 Array.sort(byCategory)
325 )
326
327 const strings = yield* Effect.forEach(printables, ([category, printables]) =>
328 Effect.gen(function*() {
329 const out = `\n\n# ${category}`
330 const strings = yield* Effect.forEach(sortByName(printables), (printable) => print(printable))
331 return out + strings.map((s) => "\n\n" + s).join("")
332 }))
333
334 const content = strings.join("")
335
336 return `${description}
337
338 <!-- toc -->${content}`
339 }).pipe(Effect.provideService(Parser.Source, module.source))
340 }
341
342 const defaultPrettierOptions: Prettier.Options = {
343 parser: "markdown",
344 semi: false,
345 singleQuote: false,
346 printWidth: 120,
347 trailingComma: "none"
348 }
349
350 /**
351 * Renders the front matter for a generated module page.
352 *
353 * @category printers
354 * @since 0.6.0
355 */
356 export const printFrontMatter = (module: Domain.Module, nav_order: number): string => {
357 return `---
358 title: ${module.name}
359 nav_order: ${nav_order}
360 parent: Modules
361 ---`
362 }
363
364 /**
365 * Formats generated Markdown with the docgen Prettier settings.
366 *
367 * @category printers
368 * @since 0.6.0
369 */
370 export function prettify(s: string) {
371 return Effect.tryPromise({
372 try: () => Prettier.format(s, defaultPrettierOptions),
373 catch: globalThis.String
374 }).pipe(Effect.orDie)
375 }