memory-test-utils.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import { createFileSystemError, type FileSystemPort } from "@zcode/contracts";
  2. export class MemoryFileSystem implements FileSystemPort {
  3. readonly createdDirectories = new Set<string>();
  4. readonly readRequests: Array<{ maxBytes?: number; path: string }> = [];
  5. readonly searchFileRequests: Array<{ maxResults?: number; path: string; pattern: string }> = [];
  6. constructor(
  7. readonly files: Record<string, string>,
  8. private readonly fileMtimes: Readonly<Record<string, number>> = {},
  9. ) {}
  10. async createDirectory(request: { path: string }) {
  11. this.createdDirectories.add(request.path);
  12. return { path: request.path };
  13. }
  14. async stat(request: { path: string }) {
  15. if (this.createdDirectories.has(request.path)) {
  16. return { kind: "directory" as const, path: request.path, sizeBytes: 0 };
  17. }
  18. const content = this.files[request.path];
  19. if (content === undefined) throw missingFile(request.path);
  20. return {
  21. kind: "file" as const,
  22. path: request.path,
  23. sizeBytes: Buffer.byteLength(content),
  24. mtimeMs: this.fileMtimes[request.path],
  25. };
  26. }
  27. async readTextFile(request: { path: string; encoding?: BufferEncoding; maxBytes?: number }) {
  28. this.readRequests.push({ maxBytes: request.maxBytes, path: request.path });
  29. const content = this.files[request.path];
  30. if (content === undefined) throw missingFile(request.path);
  31. const sizeBytes = Buffer.byteLength(content, "utf8");
  32. const maxBytes = request.maxBytes ?? sizeBytes;
  33. const truncated = sizeBytes > maxBytes;
  34. const returned = truncated ? content.slice(0, maxBytes) : content;
  35. return {
  36. bytesRead: Buffer.byteLength(returned, "utf8"),
  37. content: returned,
  38. encoding: request.encoding ?? "utf8",
  39. path: request.path,
  40. sizeBytes,
  41. truncated,
  42. };
  43. }
  44. async readBinaryFile(request: { path: string; maxBytes?: number }) {
  45. this.readRequests.push({ maxBytes: request.maxBytes, path: request.path });
  46. const content = this.files[request.path];
  47. if (content === undefined) throw missingFile(request.path);
  48. const buffer = Buffer.from(content, "utf8");
  49. if (request.maxBytes !== undefined && buffer.byteLength > request.maxBytes) {
  50. throw createFileSystemError({
  51. code: "too_large",
  52. path: request.path,
  53. message: `File content (${buffer.byteLength}B) exceeds maximum allowed size (${request.maxBytes}B).`,
  54. });
  55. }
  56. return {
  57. bytesRead: buffer.byteLength,
  58. content: buffer,
  59. path: request.path,
  60. sizeBytes: buffer.byteLength,
  61. };
  62. }
  63. async readTextFileRange(request: {
  64. path: string;
  65. encoding?: BufferEncoding;
  66. offsetLine?: number;
  67. limitLines?: number;
  68. maxBytes?: number;
  69. }) {
  70. this.readRequests.push({ maxBytes: request.maxBytes, path: request.path });
  71. const content = this.files[request.path];
  72. if (content === undefined) throw missingFile(request.path);
  73. const sizeBytes = Buffer.byteLength(content, "utf8");
  74. if (request.maxBytes !== undefined && sizeBytes > request.maxBytes) {
  75. throw createFileSystemError({
  76. code: "too_large",
  77. path: request.path,
  78. message: `File content (${sizeBytes}B) exceeds maximum allowed size (${request.maxBytes}B). Use offset and limit parameters to read specific portions of the file, or search for specific content instead of reading the whole file.`,
  79. });
  80. }
  81. const lines = content.length === 0 ? [] : content.split(/\r?\n/);
  82. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  83. const limitLines =
  84. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  85. const selected =
  86. limitLines === undefined
  87. ? lines.slice(offsetLine)
  88. : lines.slice(offsetLine, offsetLine + limitLines);
  89. return {
  90. bytesRead: sizeBytes,
  91. content: selected.join("\n"),
  92. encoding: request.encoding ?? "utf8",
  93. lineCount: selected.length,
  94. path: request.path,
  95. sizeBytes,
  96. startLine: offsetLine + 1,
  97. totalLines: lines.length,
  98. truncated: false,
  99. };
  100. }
  101. async writeTextFile(request: { content: string; path: string }) {
  102. this.files[request.path] = request.content;
  103. return { bytesWritten: Buffer.byteLength(request.content, "utf8"), path: request.path };
  104. }
  105. async removeFile(request: { missingOk?: boolean; path: string }) {
  106. const existed = this.files[request.path] !== undefined;
  107. if (!existed && request.missingOk !== true) throw missingFile(request.path);
  108. delete this.files[request.path];
  109. return { path: request.path, removed: existed };
  110. }
  111. async listDirectory(request: { path: string }) {
  112. const prefix = `${request.path.replace(/\/+$/, "")}/`;
  113. const seen = new Set<string>();
  114. const entries = Object.keys(this.files).flatMap((path) => {
  115. if (!path.startsWith(prefix)) return [];
  116. const rest = path.slice(prefix.length);
  117. const [name] = rest.split("/");
  118. if (!name || seen.has(name)) return [];
  119. seen.add(name);
  120. const isDirectory = rest.includes("/");
  121. return [
  122. {
  123. kind: isDirectory ? ("directory" as const) : ("file" as const),
  124. name,
  125. path: `${prefix}${name}`,
  126. },
  127. ];
  128. });
  129. return {
  130. durationMs: 0,
  131. entries,
  132. numEntries: entries.length,
  133. path: request.path,
  134. };
  135. }
  136. async searchFiles(request: { maxResults?: number; path: string; pattern: string }) {
  137. this.searchFileRequests.push({
  138. maxResults: request.maxResults,
  139. path: request.path,
  140. pattern: request.pattern,
  141. });
  142. const prefix = `${request.path.replace(/\/+$/, "")}/`;
  143. const files = Object.keys(this.files)
  144. .filter((path) => path.startsWith(prefix))
  145. .filter((path) => !path.slice(prefix.length).includes("/"))
  146. .filter((path) => (request.pattern === "*.md" ? path.endsWith(".md") : true))
  147. .slice(0, request.maxResults);
  148. return {
  149. durationMs: 0,
  150. files,
  151. numFiles: files.length,
  152. path: request.path,
  153. pattern: request.pattern,
  154. truncated: false,
  155. };
  156. }
  157. async searchText(request: {
  158. outputMode?: "content" | "files_with_matches" | "count";
  159. path: string;
  160. pattern: string;
  161. }) {
  162. return {
  163. durationMs: 0,
  164. entries: [],
  165. files: [],
  166. mode: request.outputMode ?? "files_with_matches",
  167. numMatches: 0,
  168. path: request.path,
  169. pattern: request.pattern,
  170. truncated: false,
  171. };
  172. }
  173. }
  174. function missingFile(path: string): Error {
  175. return createFileSystemError({ code: "not_found", message: `missing: ${path}`, path });
  176. }