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