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

source-file-document.ts

54 lines1.6 KB

1import { buildNativeSourceRows } from "./nativeSourceFileAdapter";
2​
3const MAX_CACHED_DOCUMENTS = 8;
4const MAX_CACHED_CHARACTERS = 4 * 1024 * 1024;
5​
6export interface SourceFileDocument {
7 readonly contents: string;
8 readonly lines: ReadonlyArray<string>;
9 readonly rowsJson: string;
11​
12const documentCache = new Map<string, SourceFileDocument>();
13let cachedCharacterCount = 0;
14​
15function removeOldestCachedDocument(): void {
16 const oldestKey = documentCache.keys().next().value;
17 if (typeof oldestKey !== "string") {
18 return;
19 }
20 const document = documentCache.get(oldestKey);
21 documentCache.delete(oldestKey);
22 cachedCharacterCount -= (document?.contents.length ?? 0) + (document?.rowsJson.length ?? 0);
24​
25export function prepareSourceFileDocument(contents: string): SourceFileDocument {
26 const cached = documentCache.get(contents);
27 if (cached !== undefined) {
28 documentCache.delete(contents);
29 documentCache.set(contents, cached);
30 return cached;
31 }
32​
33 const normalizedContents = contents.replace(/\r\n?/g, "\n");
34 const lines = normalizedContents.split("\n");
35 const document = {
36 contents: normalizedContents,
37 lines,
38 rowsJson: JSON.stringify(buildNativeSourceRows(lines)),
39 } satisfies SourceFileDocument;
40 const characterCount = document.contents.length + document.rowsJson.length;
41​
42 if (characterCount <= MAX_CACHED_CHARACTERS) {
43 while (
44 documentCache.size >= MAX_CACHED_DOCUMENTS ||
45 cachedCharacterCount + characterCount > MAX_CACHED_CHARACTERS
46 ) {
47 removeOldestCachedDocument();
48 }
49 documentCache.set(contents, document);
50 cachedCharacterCount += characterCount;
51 }
52​
53 return document;