Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Codegen.ts

214 lines6.9 KB

1/**
2 * Barrel file discovery and export generation for Effect development tools.
3 *
4 * This module provides the `BarrelGenerator` service used by the codegen CLI to
5 * find files annotated with `@barrel` comments and rewrite the generated export
6 * section beneath each annotation. The generator resolves matching modules
7 * relative to each annotated barrel file, copies each module's top-level
8 * `@since` tag into a minimal JSDoc block, and normalizes export paths so the
9 * produced TypeScript is stable across platforms.
10 *
11 * @since 4.0.0
12 */
13import * as Context from "effect/Context"
14import * as Data from "effect/Data"
15import * as Effect from "effect/Effect"
16import * as FileSystem from "effect/FileSystem"
17import * as Layer from "effect/Layer"
18import * as Path from "effect/Path"
19import type { PlatformError } from "effect/PlatformError"
20import * as Glob from "./Glob.ts"
21​
22/**
23 * Error raised when barrel export generation cannot read required module metadata.
24 *
25 * @category errors
26 * @since 4.0.0
27 */
28export class BarrelCodegenError extends Data.TaggedError("BarrelCodegenError")<{
29 readonly path: string
30 readonly reason: string
31}> {}
32​
33const findAnnotation = (content: string): { pattern: string; offset: number } | undefined => {
34 const lines = content.split("\n")
35​
36 // Find the line containing the annotation
37 let annotationLine = -1
38 let pattern: string | undefined
39 for (let i = 0; i < lines.length; i++) {
40 pattern = parseAnnotation(lines[i])
41 if (pattern !== undefined) {
42 annotationLine = i
43 break
44 }
45 }
46​
47 if (annotationLine === -1 || pattern === undefined) {
48 return undefined
49 }
50​
51 // Walk forwards to find the end of the comment block
52 let commentEnd = annotationLine
53 while (commentEnd < lines.length - 1 && lines[commentEnd + 1].trimStart().startsWith("//")) {
54 commentEnd++
55 }
56​
57 return { pattern, offset: commentEnd + 1 }
59​
60const parseAnnotation = (line: string): string | undefined => {
61 const match = line.match(/^\/\/\s*@barrel(?:\((.+?)\))?/)
62 if (!match) {
63 return undefined
64 }
65 return match[1] ?? "*.ts"
67​
68const extractModuleSince = (file: string, content: string): Effect.Effect<string, BarrelCodegenError> => {
69 const block = content.match(/^\s*(\/\*\*[\s\S]*?\*\/)/)?.[1]
70 if (block === undefined) {
71 return Effect.fail(
72 new BarrelCodegenError({
73 path: file,
74 reason: "missing top-level module JSDoc"
75 })
76 )
77 }
78 const matches = Array.from(block.matchAll(/^\s*\*\s*@since(?:\s+(.*))?$/gm))
79 if (matches.length !== 1) {
80 return Effect.fail(
81 new BarrelCodegenError({
82 path: file,
83 reason: matches.length === 0
84 ? "missing top-level module @since tag"
85 : "multiple top-level module @since tags"
86 })
87 )
88 }
89 const since = matches[0]?.[1]?.trim() ?? ""
90 if (since.length === 0) {
91 return Effect.fail(
92 new BarrelCodegenError({
93 path: file,
94 reason: "empty top-level module @since tag"
95 })
96 )
97 }
98 return Effect.succeed(since)
100​
101const renderExportJSDoc = (since: string): string =>
102 `/**
103 * @since ${since}
104 */`
105​
106/**
107 * Metadata for a barrel file discovered from a `@barrel` annotation, including the file path, glob pattern, and insertion offset for generated exports.
108 *
109 * @category models
110 * @since 4.0.0
111 */
112export interface BarrelFile {
113 readonly path: string
114 readonly pattern: string
115 readonly offset: number
117​
118/**
119 * Service interface for discovering annotated barrel files and regenerating their export contents.
120 *
121 * @category models
122 * @since 4.0.0
123 */
124export interface BarrelGenerator {
125 readonly discoverFiles: (
126 pattern: string,
127 cwd: string
128 ) => Effect.Effect<Array<BarrelFile>, PlatformError | Glob.GlobError>
129 readonly processFile: (file: BarrelFile) => Effect.Effect<void, PlatformError | Glob.GlobError | BarrelCodegenError>
131​
132/**
133 * Service tag for barrel file generation.
134 *
135 * @category services
136 * @since 4.0.0
137 */
138export const BarrelGenerator: Context.Service<BarrelGenerator, BarrelGenerator> = Context.Service(
139 "@effect/utils/BarrelGenerator"
141​
142/**
143 * Builds the `BarrelGenerator` service, discovering files with `@barrel` annotations and rewriting their generated export sections from matching modules.
144 *
145 * @category layers
146 * @since 4.0.0
147 */
148export const layer: Layer.Layer<BarrelGenerator, never, FileSystem.FileSystem | Path.Path | Glob.Glob> = Effect.gen(
149 function*() {
150 const fs = yield* FileSystem.FileSystem
151 const path = yield* Path.Path
152 const glob = yield* Glob.Glob
153​
154 // Convert native path separators to POSIX (forward slashes) for import/export statements
155 const toPosix = path.sep === "/" ? (file: string) => file : (file: string) => file.split(path.sep).join("/")
156​
157 const fileToModuleName = (posix: string): string => {
158 const withoutExt = posix.slice(0, -path.extname(posix).length)
159 return withoutExt.replace(/\//g, "_")
160 }
161​
162 const processModule = Effect.fn("processModule")(function*(directory: string, file: string) {
163 const fullPath = path.join(directory, file)
164 const posixPath = toPosix(file)
165 const content = yield* fs.readFileString(fullPath)
166 const since = yield* extractModuleSince(fullPath, content)
167 const moduleName = fileToModuleName(posixPath)
168 return `${renderExportJSDoc(since)}\nexport * as ${moduleName} from "./${posixPath}"`
169 })
170​
171 const discoverFile = Effect.fn("discoverFile")(function*(file: string) {
172 const content = yield* fs.readFileString(file)
173 const parsed = findAnnotation(content)
174 return parsed ? { path: file, ...parsed } : undefined
175 })
176​
177 const discoverFiles = Effect.fn("discoverFiles")(function*(pattern: string, cwd: string) {
178 const indexFiles = yield* glob.glob(pattern, {
179 cwd,
180 dot: false,
181 follow: false,
182 nodir: true
183 })
184​
185 const results = yield* Effect.forEach(indexFiles, (file) => discoverFile(path.join(cwd, file)))
186 return results.filter((file) => file !== undefined)
187 })
188​
189 const processFile = Effect.fn("processFile")(function*(file: BarrelFile) {
190 const { offset, pattern } = file
191 const directory = path.dirname(file.path)
192 const self = path.basename(file.path)
193​
194 // Find all matching files relative to the current directory excluding the barrel file itself
195 const matchedFiles = yield* glob.glob(pattern, {
196 cwd: directory,
197 dot: false,
198 follow: false,
199 nodir: true,
200 ignore: [self]
201 }).pipe(Effect.map((files) => files.sort((a, b) => a.localeCompare(b))))
202​
203 const moduleContents = yield* Effect.forEach(matchedFiles, (file) => processModule(directory, file))
204 const content = yield* fs.readFileString(file.path)
205 const lines = content.split("\n")
206 const header = lines.slice(0, offset).join("\n")
207 const generated = moduleContents.join("\n\n")
208​
209 yield* fs.writeFileString(file.path, `${header}\n\n${generated}\n`)
210 })
211​
212 return { discoverFiles, processFile }
213 }
214).pipe(Layer.effect(BarrelGenerator), Layer.provide(Glob.layer))