Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Path from "effect/Path";
6import * as Schema from "effect/Schema";
7
8import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10
11export class WorkspaceRootNotExistsError extends Schema.TaggedError<WorkspaceRootNotExistsError>()(
12 "WorkspaceRootNotExistsError",
13 {
14 workspaceRoot: Schema.String,
15 normalizedWorkspaceRoot: Schema.String,
16 },
17) {
18 override get message(): string {
19 return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`;
20 }
21}
22
23export class WorkspaceRootCreateFailedError extends Schema.TaggedError<WorkspaceRootCreateFailedError>()(
24 "WorkspaceRootCreateFailedError",
25 {
26 workspaceRoot: Schema.String,
27 normalizedWorkspaceRoot: Schema.String,
28 cause: Schema.Defect(),
29 },
30) {
31 override get message(): string {
32 return `Failed to create workspace root: ${this.normalizedWorkspaceRoot}`;
33 }
34}
35
36export class WorkspaceRootStatFailedError extends Schema.TaggedError<WorkspaceRootStatFailedError>()(
37 "WorkspaceRootStatFailedError",
38 {
39 workspaceRoot: Schema.String,
40 normalizedWorkspaceRoot: Schema.String,
41 phase: Schema.Literals(["validate-existing", "verify-created"]),
42 cause: Schema.Defect(),
43 },
44) {
45 override get message(): string {
46 return `Failed to stat workspace root '${this.normalizedWorkspaceRoot}' during '${this.phase}'.`;
47 }
48}
49
50export class WorkspaceRootNotDirectoryError extends Schema.TaggedError<WorkspaceRootNotDirectoryError>()(
51 "WorkspaceRootNotDirectoryError",
52 {
53 workspaceRoot: Schema.String,
54 normalizedWorkspaceRoot: Schema.String,
55 },
56) {
57 override get message(): string {
58 return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`;
59 }
60}
61
62export class WorkspacePathOutsideRootError extends Schema.TaggedError<WorkspacePathOutsideRootError>()(
63 "WorkspacePathOutsideRootError",
64 {
65 workspaceRoot: Schema.String,
66 relativePath: Schema.String,
67 },
68) {
69 override get message(): string {
70 return `Workspace file path must be relative to the project root: ${this.relativePath}`;
71 }
72}
73
74export const WorkspacePathsError = Schema.Union([
75 WorkspaceRootNotExistsError,
76 WorkspaceRootCreateFailedError,
77 WorkspaceRootStatFailedError,
78 WorkspaceRootNotDirectoryError,
79 WorkspacePathOutsideRootError,
80]);
81export type WorkspacePathsError = typeof WorkspacePathsError.Type;
82
83export class WorkspacePaths extends Context.Service<
84 WorkspacePaths,
85 {
86 readonly normalizeWorkspaceRoot: (
87 workspaceRoot: string,
88 options?: { readonly createIfMissing?: boolean },
89 ) => Effect.Effect<
90 string,
91 | WorkspaceRootNotExistsError
92 | WorkspaceRootCreateFailedError
93 | WorkspaceRootStatFailedError
94 | WorkspaceRootNotDirectoryError
95 >;
96 readonly resolveRelativePathWithinRoot: (input: {
97 workspaceRoot: string;
98 relativePath: string;
99 }) => Effect.Effect<
100 { absolutePath: string; relativePath: string },
101 WorkspacePathOutsideRootError
102 >;
103 }
104>()("t3/workspace/WorkspacePaths") {}
105
106function toPosixRelativePath(input: string): string {
107 return input.replaceAll("\\", "/");
108}
109
110export const make = Effect.gen(function* () {
111 const fileSystem = yield* FileSystem.FileSystem;
112 const path = yield* Path.Path;
113
114 const statWorkspaceRoot = Effect.fn("WorkspacePaths.statWorkspaceRoot")(function* (
115 workspaceRoot: string,
116 normalizedWorkspaceRoot: string,
117 phase: WorkspaceRootStatFailedError["phase"],
118 ) {
119 return yield* fileSystem.stat(normalizedWorkspaceRoot).pipe(
120 Effect.matchEffect({
121 onFailure: (cause) =>
122 cause.reason._tag === "NotFound"
123 ? Effect.succeed(null)
124 : Effect.fail(
125 new WorkspaceRootStatFailedError({
126 workspaceRoot,
127 normalizedWorkspaceRoot,
128 phase,
129 cause,
130 }),
131 ),
132 onSuccess: Effect.succeed,
133 }),
134 );
135 });
136
137 const normalizeWorkspaceRoot: WorkspacePaths["Service"]["normalizeWorkspaceRoot"] = Effect.fn(
138 "WorkspacePaths.normalizeWorkspaceRoot",
139 )(function* (workspaceRoot, options) {
140 const normalizedWorkspaceRoot = path.resolve(
141 expandHomePath(workspaceRoot.trim(), yield* HostProcess.HomeDirectory),
142 );
143 let workspaceStat = yield* statWorkspaceRoot(
144 workspaceRoot,
145 normalizedWorkspaceRoot,
146 "validate-existing",
147 );
148 if (!workspaceStat && options?.createIfMissing) {
149 yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(
150 Effect.mapError(
151 (cause) =>
152 new WorkspaceRootCreateFailedError({
153 workspaceRoot,
154 normalizedWorkspaceRoot,
155 cause,
156 }),
157 ),
158 );
159 workspaceStat = yield* statWorkspaceRoot(
160 workspaceRoot,
161 normalizedWorkspaceRoot,
162 "verify-created",
163 );
164 }
165 if (!workspaceStat) {
166 return yield* new WorkspaceRootNotExistsError({
167 workspaceRoot,
168 normalizedWorkspaceRoot,
169 });
170 }
171 if (workspaceStat.type !== "Directory") {
172 return yield* new WorkspaceRootNotDirectoryError({
173 workspaceRoot,
174 normalizedWorkspaceRoot,
175 });
176 }
177 return normalizedWorkspaceRoot;
178 });
179
180 const resolveRelativePathWithinRoot: WorkspacePaths["Service"]["resolveRelativePathWithinRoot"] =
181 Effect.fn("WorkspacePaths.resolveRelativePathWithinRoot")(function* (input) {
182 const normalizedInputPath = input.relativePath.trim();
183 if (path.isAbsolute(normalizedInputPath)) {
184 return yield* new WorkspacePathOutsideRootError({
185 workspaceRoot: input.workspaceRoot,
186 relativePath: input.relativePath,
187 });
188 }
189
190 const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath);
191 const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath));
192 if (
193 relativeToRoot.length === 0 ||
194 relativeToRoot === "." ||
195 relativeToRoot.startsWith("../") ||
196 relativeToRoot === ".." ||
197 path.isAbsolute(relativeToRoot)
198 ) {
199 return yield* new WorkspacePathOutsideRootError({
200 workspaceRoot: input.workspaceRoot,
201 relativePath: input.relativePath,
202 });
203 }
204
205 return {
206 absolutePath,
207 relativePath: relativeToRoot,
208 };
209 });
210
211 return WorkspacePaths.of({ normalizeWorkspaceRoot, resolveRelativePathWithinRoot });
212});
213
214export const layer = Layer.effect(WorkspacePaths, make);