|
1 | | -import { Data, Effect } from "effect"; |
| 1 | +import { Effect } from "effect"; |
2 | 2 | import { ModuleKind, ModuleResolutionKind, Project, ScriptTarget } from "ts-morph"; |
| 3 | +import { ProjectError } from "./errors.ts"; |
| 4 | +import type { CreateProjectOptions, CreateProjectReturn } from "./types.ts"; |
3 | 5 |
|
4 | | -export type CreateProjectOptions = { |
5 | | - indexFilePath: string; |
6 | | - cwd: string; |
7 | | -}; |
8 | | - |
9 | | -/** @internal */ |
10 | | -export class ProjectError extends Data.TaggedError("ProjectError")<{ |
11 | | - readonly cause?: unknown; |
12 | | -}> {} |
13 | | - |
14 | | -export const createProject = ({ indexFilePath, cwd }: CreateProjectOptions) => |
15 | | - Effect.try({ |
16 | | - try: () => { |
| 6 | +export function createProject({ indexFilePath, cwd }: CreateProjectOptions) { |
| 7 | + return Effect.try({ |
| 8 | + try: (): CreateProjectReturn => { |
17 | 9 | const project = new Project({ |
18 | 10 | compilerOptions: { |
| 11 | + // Include esnext types. |
19 | 12 | // See https://github.com/dsherret/ts-morph/issues/938 |
20 | 13 | // and https://github.com/microsoft/TypeScript/blob/master/lib/lib.esnext.full.d.ts |
21 | 14 | lib: ["lib.esnext.full.d.ts"], |
| 15 | + |
| 16 | + // Set modern target and module resolutions options. |
22 | 17 | target: ScriptTarget.ESNext, |
23 | 18 | module: ModuleKind.ESNext, |
24 | 19 | moduleResolution: ModuleResolutionKind.Bundler, |
25 | | - // By default, ts-morph creates a project rooted in the current working directory. |
26 | | - // We must change the `typeRoots` directory to the temporary directory |
27 | | - // where the packages are installed, otherwise TypeScript will discover |
28 | | - // `@types` packages from our local `node_modules` directory. |
| 20 | + |
| 21 | + // By default, `ts-morph` creates a project rooted in the current working directory |
| 22 | + // (that is, where this library or an app using it is running). |
| 23 | + // We must change the `typeRoots` directory to the temporary directory where |
| 24 | + // the analyzed package is installed, otherwise TypeScript will discover |
| 25 | + // `@types` packages from our local `node_modules` directory giving |
| 26 | + // inconsistent analysis results due to available type definitions. |
29 | 27 | // See https://www.typescriptlang.org/tsconfig#typeRoots. |
30 | 28 | typeRoots: [cwd], |
31 | 29 | }, |
32 | 30 | }); |
| 31 | + |
| 32 | + // Add index file and resolve module imports. |
33 | 33 | const indexFile = project.addSourceFileAtPath(indexFilePath); |
34 | 34 | project.resolveSourceFileDependencies(); |
| 35 | + |
35 | 36 | return { project, indexFile }; |
36 | 37 | }, |
37 | | - catch: (e) => new ProjectError({ cause: e }), |
| 38 | + catch: (err) => new ProjectError({ cause: err }), |
38 | 39 | }); |
| 40 | +} |
0 commit comments