merong-docs 0.1.11 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/OVERVIEW.md +19 -19
- package/OVERVIEW.zh-CN.md +19 -22
- package/README.md +77 -77
- package/README.zh-CN.md +81 -81
- package/client/android-file-share.ts +25 -25
- package/client/controls.tsx +163 -163
- package/client/document-panel.tsx +166 -166
- package/client/external-file.tsx +78 -78
- package/client/file-reader.tsx +43 -43
- package/client/markdown-panel.tsx +737 -737
- package/client/markdown-scroll.ts +122 -122
- package/client/messages.ts +224 -224
- package/client/native-contacts.ts +145 -145
- package/client/page-render-queue.ts +12 -12
- package/client/page-selection.tsx +227 -227
- package/client/page-tools.tsx +72 -72
- package/client/pdf-geometry.ts +96 -96
- package/client/pdf-panel.tsx +477 -477
- package/client/reader-find.tsx +190 -190
- package/client/reader-notice.tsx +46 -46
- package/client/settings.tsx +143 -143
- package/client/syntax.tsx +55 -55
- package/client/viewport-geometry.ts +61 -61
- package/client/web.ts +462 -462
- package/client/worksheet-panel.tsx +631 -631
- package/client/zoom-controls.tsx +140 -140
- package/index.client.tsx +36 -36
- package/index.server.ts +73 -73
- package/node_modules/markdown-it/bin/markdown-it.mjs +0 -0
- package/node_modules/yaml/bin.mjs +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/scripts/prepare-office.mjs +20 -20
- package/server/engine.ts +89 -89
- package/server/external-file.ts +42 -42
- package/server/generated/document-worker.ts +1 -1
- package/server/generated/rust-reader_bg.wasm +0 -0
- package/server/markdown-index.ts +305 -305
- package/server/markdown-links.ts +51 -51
- package/server/markdown-page.ts +120 -120
- package/server/office-fonts.cjs +824 -824
- package/server/office-location.ts +41 -41
- package/server/office-preview.ts +186 -186
- package/server/office-worker.cjs +49 -49
- package/server/office-xml.ts +79 -79
- package/server/pdf-engine.ts +168 -168
- package/server/pdf-text-geometry.ts +60 -60
- package/server/rust-reader.ts +40 -40
- package/server/structured-document.ts +69 -69
- package/server/text-search.ts +15 -15
- package/server/worker-entry.ts +42 -42
- package/server/worker-protocol.ts +38 -38
- package/server/worksheet.ts +67 -67
- package/server/workspace-file.ts +63 -63
- package/shared/contracts.ts +187 -187
- package/shared/file-limits.ts +5 -5
- package/shared/markdown-constants.ts +4 -4
- package/shared/markdown-math.ts +198 -198
- package/shared/markdown-references.ts +83 -83
- package/shared/markdown-source-location.ts +8 -8
- package/shared/reader-settings.ts +15 -15
- package/shared/reader-shortcuts.ts +132 -132
- package/vendor/office2pdf/office2pdf_bg.wasm +2 -2
|
Binary file
|
package/server/markdown-index.ts
CHANGED
|
@@ -1,305 +1,305 @@
|
|
|
1
|
-
import type { FileHandle } from "node:fs/promises";
|
|
2
|
-
import type { RpcOutput } from "@getpaseo/plugin";
|
|
3
|
-
import { parseDocument, stringify } from "yaml";
|
|
4
|
-
import type { Fence, MarkdownSearchOptions, TableContinuation, readMarkdownInfo, readMarkdownSource,
|
|
5
|
-
searchMarkdownFile } from "../shared/contracts";
|
|
6
|
-
import { markdownExtensions, markdownSearchPageSize, maxMarkdownTableLine } from "../shared/markdown-constants";
|
|
7
|
-
import { normalizeMarkdownLabel } from "../shared/markdown-references";
|
|
8
|
-
import { withWorkspaceFile } from "./workspace-file";
|
|
9
|
-
import { rebaseMarkdownDestination } from "./markdown-links";
|
|
10
|
-
import { markdownStructure, rustReader } from "./rust-reader";
|
|
11
|
-
import { searchExpression } from "./text-search";
|
|
12
|
-
|
|
13
|
-
const readBytes = 64 * 1024;
|
|
14
|
-
const checkpointLines = 128;
|
|
15
|
-
const maxSourceBytes = 96 * 1024;
|
|
16
|
-
const maxMetadataBytes = 32 * 1024;
|
|
17
|
-
type Info = RpcOutput<typeof readMarkdownInfo>;
|
|
18
|
-
type Source = RpcOutput<typeof readMarkdownSource>;
|
|
19
|
-
type Search = RpcOutput<typeof searchMarkdownFile>;
|
|
20
|
-
type Ending = Source["lines"][number]["ending"];
|
|
21
|
-
type BlockContext = { fence?: Fence; table?: TableContinuation };
|
|
22
|
-
type PreviewPosition = { offset: number; line: number } & BlockContext;
|
|
23
|
-
type MarkdownIndex = { info: Info; offsets: number[]; contexts: BlockContext[]; previewStart: PreviewPosition };
|
|
24
|
-
const indexes = new Map<string, Promise<MarkdownIndex>>();
|
|
25
|
-
|
|
26
|
-
async function* lines(file: FileHandle, size: number, start: number) {
|
|
27
|
-
let parts: Buffer[] = [];
|
|
28
|
-
let offset = start;
|
|
29
|
-
let waitingForLineFeed = false;
|
|
30
|
-
const finish = (nextOffset: number, ending: Ending) => {
|
|
31
|
-
const decoded = parts.length === 0 ? ""
|
|
32
|
-
: parts.length === 1 ? parts[0].toString("utf8")
|
|
33
|
-
: Buffer.concat(parts).toString("utf8");
|
|
34
|
-
const value = { offset, text: offset === 0 ? decoded.replace(/^\uFEFF/, "") : decoded, ending };
|
|
35
|
-
parts = [];
|
|
36
|
-
offset = nextOffset;
|
|
37
|
-
return value;
|
|
38
|
-
};
|
|
39
|
-
const buffer = size > start ? Buffer.allocUnsafe(Math.min(readBytes, size - start)) : undefined;
|
|
40
|
-
for (let position = start; position < size;) {
|
|
41
|
-
const toRead = Math.min(buffer!.length, size - position);
|
|
42
|
-
const { bytesRead } = await file.read(buffer!, 0, toRead, position);
|
|
43
|
-
if (!bytesRead) throw new Error("File ended while reading.");
|
|
44
|
-
let fragmentStart = 0;
|
|
45
|
-
if (waitingForLineFeed) {
|
|
46
|
-
fragmentStart = Number(buffer![0] === 10);
|
|
47
|
-
yield finish(position + fragmentStart, fragmentStart ? "\r\n" : "\r");
|
|
48
|
-
waitingForLineFeed = false;
|
|
49
|
-
}
|
|
50
|
-
for (let cursor = fragmentStart; cursor < bytesRead; cursor++) {
|
|
51
|
-
const byte = buffer![cursor];
|
|
52
|
-
if (byte !== 10 && byte !== 13) continue;
|
|
53
|
-
if (cursor > fragmentStart) parts.push(buffer!.subarray(fragmentStart, cursor));
|
|
54
|
-
if (byte === 13 && cursor + 1 === bytesRead) {
|
|
55
|
-
if (parts.length && parts[parts.length - 1].buffer === buffer!.buffer) {
|
|
56
|
-
parts[parts.length - 1] = Buffer.from(parts[parts.length - 1]);
|
|
57
|
-
}
|
|
58
|
-
waitingForLineFeed = true;
|
|
59
|
-
fragmentStart = bytesRead;
|
|
60
|
-
break;
|
|
61
|
-
}
|
|
62
|
-
const ending = byte === 10 ? "\n" : buffer![cursor + 1] === 10 ? "\r\n" : "\r";
|
|
63
|
-
cursor += ending.length - 1;
|
|
64
|
-
fragmentStart = cursor + 1;
|
|
65
|
-
yield finish(position + fragmentStart, ending);
|
|
66
|
-
}
|
|
67
|
-
if (fragmentStart < bytesRead) parts.push(Buffer.from(buffer!.subarray(fragmentStart, bytesRead)));
|
|
68
|
-
position += bytesRead;
|
|
69
|
-
}
|
|
70
|
-
if (waitingForLineFeed) yield finish(size, "\r");
|
|
71
|
-
yield finish(size, "");
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function yamlRows(source: string): Info["frontMatter"] {
|
|
75
|
-
try {
|
|
76
|
-
const document = parseDocument(source, { schema: "core" });
|
|
77
|
-
if (document.errors.length) return [];
|
|
78
|
-
const data: unknown = document.toJS({ maxAliasCount: 100 });
|
|
79
|
-
if (!data || typeof data !== "object" || Array.isArray(data)) return [];
|
|
80
|
-
const scalar = (value: unknown) => value === null || ["string", "boolean", "number"].includes(typeof value);
|
|
81
|
-
return Object.entries(data).slice(0, 200).map(([key, value]) => ({
|
|
82
|
-
key,
|
|
83
|
-
value: (scalar(value) ? String(value)
|
|
84
|
-
: Array.isArray(value) && value.every(scalar) ? value.map(String).join(", ")
|
|
85
|
-
: stringify(value).trim()).slice(0, 8192),
|
|
86
|
-
}));
|
|
87
|
-
} catch {
|
|
88
|
-
return [];
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export function nextFence(text: string, fence: Fence | undefined): Fence | undefined {
|
|
93
|
-
const match = /^ {0,3}(`{3,256}|~{3,256})(.*)$/.exec(text);
|
|
94
|
-
if (!match) return fence;
|
|
95
|
-
const [, marker, tail] = match;
|
|
96
|
-
if (fence) {
|
|
97
|
-
return marker[0] === fence.marker[0] && marker.length >= fence.marker.length && !tail.trim()
|
|
98
|
-
? undefined : fence;
|
|
99
|
-
}
|
|
100
|
-
if (tail.length > 750 || (marker[0] === "`" && tail.includes("`"))) return;
|
|
101
|
-
return { marker, opening: marker + tail };
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function blockContext(text: string, previous: string, { fence, table }: BlockContext,
|
|
105
|
-
reader: Awaited<ReturnType<typeof rustReader>>): BlockContext {
|
|
106
|
-
const updatedFence = nextFence(text, fence);
|
|
107
|
-
if (fence || updatedFence) return updatedFence ? { fence: updatedFence } : {};
|
|
108
|
-
if (table && text.includes("|") && !/^ {0,3}(?:#{1,6} |>|[-*+] )/.test(text)) return { table };
|
|
109
|
-
if (!previous || !text.includes("|") || !/^ {0,3}[|: -]+\|[|: -]*$/.test(text) ||
|
|
110
|
-
text.length > maxMarkdownTableLine || previous.length > maxMarkdownTableLine) return {};
|
|
111
|
-
return markdownStructure(reader, `${previous}\n${text}`).tables[0]?.[0] === 0
|
|
112
|
-
? { table: { header: previous, separator: text } } : {};
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
async function scanIndex(file: FileHandle, size: number, revision: string): Promise<MarkdownIndex> {
|
|
116
|
-
const reader = await rustReader();
|
|
117
|
-
const info: Info = { revision, lineCount: 0, headings: [], frontMatter: [], frontMatterEnd: 0, references: [] };
|
|
118
|
-
const offsets: number[] = [];
|
|
119
|
-
const usedAnchors = new Set<string>();
|
|
120
|
-
const suffixes = new Map<string, number>();
|
|
121
|
-
let frontMatter: { text: string[]; length: number } | undefined;
|
|
122
|
-
let previous = "";
|
|
123
|
-
let referenceBlock = "";
|
|
124
|
-
let referenceBytes = 0;
|
|
125
|
-
const contexts: BlockContext[] = [];
|
|
126
|
-
let currentBlock: BlockContext = {};
|
|
127
|
-
let previousLine = "";
|
|
128
|
-
let previewStart = { offset: 0, line: 1 };
|
|
129
|
-
let afterFrontMatter = false;
|
|
130
|
-
const references = new Set<string>();
|
|
131
|
-
const addReferences = () => {
|
|
132
|
-
for (const entry of markdownStructure(reader, referenceBlock).references) {
|
|
133
|
-
const identifier = normalizeMarkdownLabel(entry.label);
|
|
134
|
-
const bytes = Buffer.byteLength(entry.label + entry.destination + (entry.title ?? ""));
|
|
135
|
-
if (references.has(identifier) || referenceBytes + bytes > 256 * 1024) continue;
|
|
136
|
-
references.add(identifier);
|
|
137
|
-
referenceBytes += bytes;
|
|
138
|
-
info.references.push(entry);
|
|
139
|
-
}
|
|
140
|
-
referenceBlock = "";
|
|
141
|
-
};
|
|
142
|
-
const addHeading = (label: string, level: number, line: number) => {
|
|
143
|
-
if (info.headings.length >= 6000) return;
|
|
144
|
-
const title = reader.markdownHeading(label.slice(0, 1024));
|
|
145
|
-
if (!title) return;
|
|
146
|
-
const base = title.normalize("NFC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}_ -]/gu, "").replaceAll(" ", "-");
|
|
147
|
-
let suffix = suffixes.get(base) ?? 0;
|
|
148
|
-
let anchor = suffix ? `${base}-${suffix}` : base;
|
|
149
|
-
while (usedAnchors.has(anchor)) anchor = `${base}-${++suffix}`;
|
|
150
|
-
suffixes.set(base, suffix + 1);
|
|
151
|
-
usedAnchors.add(anchor);
|
|
152
|
-
info.headings.push({ title, level, line, anchor });
|
|
153
|
-
};
|
|
154
|
-
const inspectLine = (text: string, line: number) => {
|
|
155
|
-
const wasFenced = !!currentBlock.fence;
|
|
156
|
-
currentBlock = blockContext(text, previousLine, currentBlock, reader);
|
|
157
|
-
previousLine = text;
|
|
158
|
-
if (wasFenced || currentBlock.fence) {
|
|
159
|
-
previous = "";
|
|
160
|
-
if (referenceBlock) addReferences();
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
const heading = /^ {0,3}(#{1,6})(?:[ \t]+|$)(.*)$/.exec(text);
|
|
164
|
-
const underline = /^ {0,3}(=+|-+)[ \t]*$/.exec(text);
|
|
165
|
-
const reference = /^ {0,3}(?:> ?)*\[[^\r\n]+?\]:/.test(text);
|
|
166
|
-
if (reference || (referenceBlock && text.trim() && referenceBlock.length + text.length < maxMetadataBytes)) {
|
|
167
|
-
if (referenceBlock.length + text.length >= maxMetadataBytes) addReferences();
|
|
168
|
-
if (text.length < maxMetadataBytes) referenceBlock += text + "\n";
|
|
169
|
-
} else if (referenceBlock) addReferences();
|
|
170
|
-
if (heading) addHeading(heading[2].replace(/[ \t]+#+[ \t]*$/, ""), heading[1].length, line);
|
|
171
|
-
else if (underline && previous) addHeading(previous, underline[1][0] === "=" ? 1 : 2, line - 1);
|
|
172
|
-
previous = !heading && !underline && !reference && text.trim() && !/^ {4}|\t|[>#]|[-*+] |\d+[.)] /.test(text)
|
|
173
|
-
? text : "";
|
|
174
|
-
};
|
|
175
|
-
for await (const { offset, text } of lines(file, size, 0)) {
|
|
176
|
-
const line = ++info.lineCount;
|
|
177
|
-
if (afterFrontMatter) {
|
|
178
|
-
previewStart = { offset, line };
|
|
179
|
-
afterFrontMatter = false;
|
|
180
|
-
}
|
|
181
|
-
if ((line - 1) % checkpointLines === 0) {
|
|
182
|
-
offsets.push(offset);
|
|
183
|
-
contexts.push(currentBlock);
|
|
184
|
-
}
|
|
185
|
-
if (line === 1 && /^---[ \t]*$/.test(text)) {
|
|
186
|
-
frontMatter = { text: [text], length: text.length };
|
|
187
|
-
continue;
|
|
188
|
-
}
|
|
189
|
-
if (frontMatter) {
|
|
190
|
-
const closing = /^(?:---|\.\.\.)[ \t]*$/.test(text);
|
|
191
|
-
if (closing) {
|
|
192
|
-
info.frontMatter = yamlRows(frontMatter.text.slice(1).join("\n"));
|
|
193
|
-
if (info.frontMatter.length) {
|
|
194
|
-
info.frontMatterEnd = line;
|
|
195
|
-
frontMatter = undefined;
|
|
196
|
-
previewStart = { offset: size, line: line + 1 };
|
|
197
|
-
afterFrontMatter = true;
|
|
198
|
-
continue;
|
|
199
|
-
}
|
|
200
|
-
} else if (frontMatter.length + text.length + 1 <= maxMetadataBytes) {
|
|
201
|
-
frontMatter.length += text.length + 1;
|
|
202
|
-
frontMatter.text.push(text);
|
|
203
|
-
continue;
|
|
204
|
-
}
|
|
205
|
-
frontMatter.text.forEach((value, index) => inspectLine(value, index + 1));
|
|
206
|
-
frontMatter = undefined;
|
|
207
|
-
}
|
|
208
|
-
inspectLine(text, line);
|
|
209
|
-
}
|
|
210
|
-
frontMatter?.text.forEach((value, index) => inspectLine(value, index + 1));
|
|
211
|
-
if (referenceBlock) addReferences();
|
|
212
|
-
return { info, offsets, contexts, previewStart };
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
function getIndex(path: string, file: FileHandle, size: number, revision: string) {
|
|
216
|
-
const key = JSON.stringify([path, revision]);
|
|
217
|
-
const cached = indexes.get(key);
|
|
218
|
-
if (cached) return cached;
|
|
219
|
-
const index = scanIndex(file, size, revision);
|
|
220
|
-
indexes.set(key, index);
|
|
221
|
-
void index.catch(() => { indexes.delete(key); });
|
|
222
|
-
if (indexes.size > 8) {
|
|
223
|
-
const oldest = indexes.keys().next().value;
|
|
224
|
-
if (oldest) indexes.delete(oldest);
|
|
225
|
-
}
|
|
226
|
-
return index;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function checkpoint(index: MarkdownIndex, requested: number) {
|
|
230
|
-
const line = Math.min(requested, index.info.lineCount);
|
|
231
|
-
const bucket = Math.floor((line - 1) / checkpointLines);
|
|
232
|
-
return { offset: index.offsets[bucket], first: bucket * checkpointLines + 1, line };
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
export function loadMarkdownInfo(root: string, path: string) {
|
|
236
|
-
return withWorkspaceFile(root, path, markdownExtensions, async (file, size, revision, actual) => {
|
|
237
|
-
const { info } = await getIndex(actual, file, size, revision);
|
|
238
|
-
return { ...info, references: info.references.map((entry) => ({
|
|
239
|
-
...entry, destination: rebaseMarkdownDestination(entry.destination, root, path),
|
|
240
|
-
})) };
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
export async function markdownPreviewPosition(file: FileHandle, size: number, revision: string, actual: string, requested: number): Promise<PreviewPosition> {
|
|
245
|
-
const [index, reader] = await Promise.all([getIndex(actual, file, size, revision), rustReader()]);
|
|
246
|
-
if (requested <= index.previewStart.line) return index.previewStart;
|
|
247
|
-
const { offset, first } = checkpoint(index, Math.max(index.previewStart.line, requested - 24));
|
|
248
|
-
const target = Math.min(requested, index.info.lineCount);
|
|
249
|
-
let block = index.contexts[Math.floor((first - 1) / checkpointLines)];
|
|
250
|
-
let position: PreviewPosition = first < index.previewStart.line ? index.previewStart : { offset, line: first, ...block };
|
|
251
|
-
let number = first - 1;
|
|
252
|
-
let previous = "";
|
|
253
|
-
for await (const entry of lines(file, size, offset)) {
|
|
254
|
-
if (++number < index.previewStart.line) continue;
|
|
255
|
-
if (!previous.trim() && !block.fence && !block.table && number > position.line) position = { offset: entry.offset, line: number };
|
|
256
|
-
if (number >= target - 12 && number > position.line + 32 && (block.fence || (block.table && entry.text.includes("|")))) {
|
|
257
|
-
position = { offset: entry.offset, line: number, ...block };
|
|
258
|
-
}
|
|
259
|
-
if (number >= target) break;
|
|
260
|
-
block = blockContext(entry.text, previous, block, reader);
|
|
261
|
-
previous = entry.text;
|
|
262
|
-
}
|
|
263
|
-
return position;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
export function loadMarkdownSource(root: string, path: string, requested: number, through?: number) {
|
|
267
|
-
return withWorkspaceFile(root, path, markdownExtensions, async (file, size, revision, actual): Promise<Source> => {
|
|
268
|
-
const { offset, first, line } = requested === 1 ? { offset: 0, first: 1, line: 1 }
|
|
269
|
-
: checkpoint(await getIndex(actual, file, size, revision), requested);
|
|
270
|
-
const limit = Math.min(through ?? line + checkpointLines - 1, line + 255);
|
|
271
|
-
const result: Source = { revision, firstLine: line, lines: [], nextLine: null };
|
|
272
|
-
let bytes = 0;
|
|
273
|
-
let lineNumber = first - 1;
|
|
274
|
-
for await (const value of lines(file, size, offset)) {
|
|
275
|
-
if (++lineNumber < line) continue;
|
|
276
|
-
const remaining = maxSourceBytes - bytes;
|
|
277
|
-
if (lineNumber > limit || (result.lines.length && Buffer.byteLength(value.text) > remaining)) {
|
|
278
|
-
result.nextLine = lineNumber;
|
|
279
|
-
break;
|
|
280
|
-
}
|
|
281
|
-
const text = value.text.length <= remaining / 4 || Buffer.byteLength(value.text) <= remaining
|
|
282
|
-
? value.text : value.text.slice(0, Math.floor(remaining / 4));
|
|
283
|
-
bytes += Buffer.byteLength(text) + value.ending.length;
|
|
284
|
-
result.lines.push({ text, ending: value.ending, truncated: text.length < value.text.length });
|
|
285
|
-
}
|
|
286
|
-
return result;
|
|
287
|
-
});
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
export function findMarkdownLines(root: string, path: string, query: string, options: MarkdownSearchOptions, offset: number) {
|
|
291
|
-
return withWorkspaceFile(root, path, markdownExtensions, async (file, size, revision): Promise<Search> => {
|
|
292
|
-
const result: Search = { revision, hits: [], total: 0, invalidPattern: false };
|
|
293
|
-
const expression = searchExpression(query, options);
|
|
294
|
-
if (!expression) return { ...result, invalidPattern: true };
|
|
295
|
-
let line = 0;
|
|
296
|
-
for await (const { text } of lines(file, size, 0)) {
|
|
297
|
-
line++;
|
|
298
|
-
for (const match of text.matchAll(expression)) {
|
|
299
|
-
if (result.total++ < offset || result.hits.length >= markdownSearchPageSize) continue;
|
|
300
|
-
result.hits.push({ line, column: match.index, length: match[0].length });
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
return result;
|
|
304
|
-
});
|
|
305
|
-
}
|
|
1
|
+
import type { FileHandle } from "node:fs/promises";
|
|
2
|
+
import type { RpcOutput } from "@getpaseo/plugin";
|
|
3
|
+
import { parseDocument, stringify } from "yaml";
|
|
4
|
+
import type { Fence, MarkdownSearchOptions, TableContinuation, readMarkdownInfo, readMarkdownSource,
|
|
5
|
+
searchMarkdownFile } from "../shared/contracts";
|
|
6
|
+
import { markdownExtensions, markdownSearchPageSize, maxMarkdownTableLine } from "../shared/markdown-constants";
|
|
7
|
+
import { normalizeMarkdownLabel } from "../shared/markdown-references";
|
|
8
|
+
import { withWorkspaceFile } from "./workspace-file";
|
|
9
|
+
import { rebaseMarkdownDestination } from "./markdown-links";
|
|
10
|
+
import { markdownStructure, rustReader } from "./rust-reader";
|
|
11
|
+
import { searchExpression } from "./text-search";
|
|
12
|
+
|
|
13
|
+
const readBytes = 64 * 1024;
|
|
14
|
+
const checkpointLines = 128;
|
|
15
|
+
const maxSourceBytes = 96 * 1024;
|
|
16
|
+
const maxMetadataBytes = 32 * 1024;
|
|
17
|
+
type Info = RpcOutput<typeof readMarkdownInfo>;
|
|
18
|
+
type Source = RpcOutput<typeof readMarkdownSource>;
|
|
19
|
+
type Search = RpcOutput<typeof searchMarkdownFile>;
|
|
20
|
+
type Ending = Source["lines"][number]["ending"];
|
|
21
|
+
type BlockContext = { fence?: Fence; table?: TableContinuation };
|
|
22
|
+
type PreviewPosition = { offset: number; line: number } & BlockContext;
|
|
23
|
+
type MarkdownIndex = { info: Info; offsets: number[]; contexts: BlockContext[]; previewStart: PreviewPosition };
|
|
24
|
+
const indexes = new Map<string, Promise<MarkdownIndex>>();
|
|
25
|
+
|
|
26
|
+
async function* lines(file: FileHandle, size: number, start: number) {
|
|
27
|
+
let parts: Buffer[] = [];
|
|
28
|
+
let offset = start;
|
|
29
|
+
let waitingForLineFeed = false;
|
|
30
|
+
const finish = (nextOffset: number, ending: Ending) => {
|
|
31
|
+
const decoded = parts.length === 0 ? ""
|
|
32
|
+
: parts.length === 1 ? parts[0].toString("utf8")
|
|
33
|
+
: Buffer.concat(parts).toString("utf8");
|
|
34
|
+
const value = { offset, text: offset === 0 ? decoded.replace(/^\uFEFF/, "") : decoded, ending };
|
|
35
|
+
parts = [];
|
|
36
|
+
offset = nextOffset;
|
|
37
|
+
return value;
|
|
38
|
+
};
|
|
39
|
+
const buffer = size > start ? Buffer.allocUnsafe(Math.min(readBytes, size - start)) : undefined;
|
|
40
|
+
for (let position = start; position < size;) {
|
|
41
|
+
const toRead = Math.min(buffer!.length, size - position);
|
|
42
|
+
const { bytesRead } = await file.read(buffer!, 0, toRead, position);
|
|
43
|
+
if (!bytesRead) throw new Error("File ended while reading.");
|
|
44
|
+
let fragmentStart = 0;
|
|
45
|
+
if (waitingForLineFeed) {
|
|
46
|
+
fragmentStart = Number(buffer![0] === 10);
|
|
47
|
+
yield finish(position + fragmentStart, fragmentStart ? "\r\n" : "\r");
|
|
48
|
+
waitingForLineFeed = false;
|
|
49
|
+
}
|
|
50
|
+
for (let cursor = fragmentStart; cursor < bytesRead; cursor++) {
|
|
51
|
+
const byte = buffer![cursor];
|
|
52
|
+
if (byte !== 10 && byte !== 13) continue;
|
|
53
|
+
if (cursor > fragmentStart) parts.push(buffer!.subarray(fragmentStart, cursor));
|
|
54
|
+
if (byte === 13 && cursor + 1 === bytesRead) {
|
|
55
|
+
if (parts.length && parts[parts.length - 1].buffer === buffer!.buffer) {
|
|
56
|
+
parts[parts.length - 1] = Buffer.from(parts[parts.length - 1]);
|
|
57
|
+
}
|
|
58
|
+
waitingForLineFeed = true;
|
|
59
|
+
fragmentStart = bytesRead;
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
const ending = byte === 10 ? "\n" : buffer![cursor + 1] === 10 ? "\r\n" : "\r";
|
|
63
|
+
cursor += ending.length - 1;
|
|
64
|
+
fragmentStart = cursor + 1;
|
|
65
|
+
yield finish(position + fragmentStart, ending);
|
|
66
|
+
}
|
|
67
|
+
if (fragmentStart < bytesRead) parts.push(Buffer.from(buffer!.subarray(fragmentStart, bytesRead)));
|
|
68
|
+
position += bytesRead;
|
|
69
|
+
}
|
|
70
|
+
if (waitingForLineFeed) yield finish(size, "\r");
|
|
71
|
+
yield finish(size, "");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function yamlRows(source: string): Info["frontMatter"] {
|
|
75
|
+
try {
|
|
76
|
+
const document = parseDocument(source, { schema: "core" });
|
|
77
|
+
if (document.errors.length) return [];
|
|
78
|
+
const data: unknown = document.toJS({ maxAliasCount: 100 });
|
|
79
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return [];
|
|
80
|
+
const scalar = (value: unknown) => value === null || ["string", "boolean", "number"].includes(typeof value);
|
|
81
|
+
return Object.entries(data).slice(0, 200).map(([key, value]) => ({
|
|
82
|
+
key,
|
|
83
|
+
value: (scalar(value) ? String(value)
|
|
84
|
+
: Array.isArray(value) && value.every(scalar) ? value.map(String).join(", ")
|
|
85
|
+
: stringify(value).trim()).slice(0, 8192),
|
|
86
|
+
}));
|
|
87
|
+
} catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function nextFence(text: string, fence: Fence | undefined): Fence | undefined {
|
|
93
|
+
const match = /^ {0,3}(`{3,256}|~{3,256})(.*)$/.exec(text);
|
|
94
|
+
if (!match) return fence;
|
|
95
|
+
const [, marker, tail] = match;
|
|
96
|
+
if (fence) {
|
|
97
|
+
return marker[0] === fence.marker[0] && marker.length >= fence.marker.length && !tail.trim()
|
|
98
|
+
? undefined : fence;
|
|
99
|
+
}
|
|
100
|
+
if (tail.length > 750 || (marker[0] === "`" && tail.includes("`"))) return;
|
|
101
|
+
return { marker, opening: marker + tail };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function blockContext(text: string, previous: string, { fence, table }: BlockContext,
|
|
105
|
+
reader: Awaited<ReturnType<typeof rustReader>>): BlockContext {
|
|
106
|
+
const updatedFence = nextFence(text, fence);
|
|
107
|
+
if (fence || updatedFence) return updatedFence ? { fence: updatedFence } : {};
|
|
108
|
+
if (table && text.includes("|") && !/^ {0,3}(?:#{1,6} |>|[-*+] )/.test(text)) return { table };
|
|
109
|
+
if (!previous || !text.includes("|") || !/^ {0,3}[|: -]+\|[|: -]*$/.test(text) ||
|
|
110
|
+
text.length > maxMarkdownTableLine || previous.length > maxMarkdownTableLine) return {};
|
|
111
|
+
return markdownStructure(reader, `${previous}\n${text}`).tables[0]?.[0] === 0
|
|
112
|
+
? { table: { header: previous, separator: text } } : {};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function scanIndex(file: FileHandle, size: number, revision: string): Promise<MarkdownIndex> {
|
|
116
|
+
const reader = await rustReader();
|
|
117
|
+
const info: Info = { revision, lineCount: 0, headings: [], frontMatter: [], frontMatterEnd: 0, references: [] };
|
|
118
|
+
const offsets: number[] = [];
|
|
119
|
+
const usedAnchors = new Set<string>();
|
|
120
|
+
const suffixes = new Map<string, number>();
|
|
121
|
+
let frontMatter: { text: string[]; length: number } | undefined;
|
|
122
|
+
let previous = "";
|
|
123
|
+
let referenceBlock = "";
|
|
124
|
+
let referenceBytes = 0;
|
|
125
|
+
const contexts: BlockContext[] = [];
|
|
126
|
+
let currentBlock: BlockContext = {};
|
|
127
|
+
let previousLine = "";
|
|
128
|
+
let previewStart = { offset: 0, line: 1 };
|
|
129
|
+
let afterFrontMatter = false;
|
|
130
|
+
const references = new Set<string>();
|
|
131
|
+
const addReferences = () => {
|
|
132
|
+
for (const entry of markdownStructure(reader, referenceBlock).references) {
|
|
133
|
+
const identifier = normalizeMarkdownLabel(entry.label);
|
|
134
|
+
const bytes = Buffer.byteLength(entry.label + entry.destination + (entry.title ?? ""));
|
|
135
|
+
if (references.has(identifier) || referenceBytes + bytes > 256 * 1024) continue;
|
|
136
|
+
references.add(identifier);
|
|
137
|
+
referenceBytes += bytes;
|
|
138
|
+
info.references.push(entry);
|
|
139
|
+
}
|
|
140
|
+
referenceBlock = "";
|
|
141
|
+
};
|
|
142
|
+
const addHeading = (label: string, level: number, line: number) => {
|
|
143
|
+
if (info.headings.length >= 6000) return;
|
|
144
|
+
const title = reader.markdownHeading(label.slice(0, 1024));
|
|
145
|
+
if (!title) return;
|
|
146
|
+
const base = title.normalize("NFC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}_ -]/gu, "").replaceAll(" ", "-");
|
|
147
|
+
let suffix = suffixes.get(base) ?? 0;
|
|
148
|
+
let anchor = suffix ? `${base}-${suffix}` : base;
|
|
149
|
+
while (usedAnchors.has(anchor)) anchor = `${base}-${++suffix}`;
|
|
150
|
+
suffixes.set(base, suffix + 1);
|
|
151
|
+
usedAnchors.add(anchor);
|
|
152
|
+
info.headings.push({ title, level, line, anchor });
|
|
153
|
+
};
|
|
154
|
+
const inspectLine = (text: string, line: number) => {
|
|
155
|
+
const wasFenced = !!currentBlock.fence;
|
|
156
|
+
currentBlock = blockContext(text, previousLine, currentBlock, reader);
|
|
157
|
+
previousLine = text;
|
|
158
|
+
if (wasFenced || currentBlock.fence) {
|
|
159
|
+
previous = "";
|
|
160
|
+
if (referenceBlock) addReferences();
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const heading = /^ {0,3}(#{1,6})(?:[ \t]+|$)(.*)$/.exec(text);
|
|
164
|
+
const underline = /^ {0,3}(=+|-+)[ \t]*$/.exec(text);
|
|
165
|
+
const reference = /^ {0,3}(?:> ?)*\[[^\r\n]+?\]:/.test(text);
|
|
166
|
+
if (reference || (referenceBlock && text.trim() && referenceBlock.length + text.length < maxMetadataBytes)) {
|
|
167
|
+
if (referenceBlock.length + text.length >= maxMetadataBytes) addReferences();
|
|
168
|
+
if (text.length < maxMetadataBytes) referenceBlock += text + "\n";
|
|
169
|
+
} else if (referenceBlock) addReferences();
|
|
170
|
+
if (heading) addHeading(heading[2].replace(/[ \t]+#+[ \t]*$/, ""), heading[1].length, line);
|
|
171
|
+
else if (underline && previous) addHeading(previous, underline[1][0] === "=" ? 1 : 2, line - 1);
|
|
172
|
+
previous = !heading && !underline && !reference && text.trim() && !/^ {4}|\t|[>#]|[-*+] |\d+[.)] /.test(text)
|
|
173
|
+
? text : "";
|
|
174
|
+
};
|
|
175
|
+
for await (const { offset, text } of lines(file, size, 0)) {
|
|
176
|
+
const line = ++info.lineCount;
|
|
177
|
+
if (afterFrontMatter) {
|
|
178
|
+
previewStart = { offset, line };
|
|
179
|
+
afterFrontMatter = false;
|
|
180
|
+
}
|
|
181
|
+
if ((line - 1) % checkpointLines === 0) {
|
|
182
|
+
offsets.push(offset);
|
|
183
|
+
contexts.push(currentBlock);
|
|
184
|
+
}
|
|
185
|
+
if (line === 1 && /^---[ \t]*$/.test(text)) {
|
|
186
|
+
frontMatter = { text: [text], length: text.length };
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (frontMatter) {
|
|
190
|
+
const closing = /^(?:---|\.\.\.)[ \t]*$/.test(text);
|
|
191
|
+
if (closing) {
|
|
192
|
+
info.frontMatter = yamlRows(frontMatter.text.slice(1).join("\n"));
|
|
193
|
+
if (info.frontMatter.length) {
|
|
194
|
+
info.frontMatterEnd = line;
|
|
195
|
+
frontMatter = undefined;
|
|
196
|
+
previewStart = { offset: size, line: line + 1 };
|
|
197
|
+
afterFrontMatter = true;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
} else if (frontMatter.length + text.length + 1 <= maxMetadataBytes) {
|
|
201
|
+
frontMatter.length += text.length + 1;
|
|
202
|
+
frontMatter.text.push(text);
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
frontMatter.text.forEach((value, index) => inspectLine(value, index + 1));
|
|
206
|
+
frontMatter = undefined;
|
|
207
|
+
}
|
|
208
|
+
inspectLine(text, line);
|
|
209
|
+
}
|
|
210
|
+
frontMatter?.text.forEach((value, index) => inspectLine(value, index + 1));
|
|
211
|
+
if (referenceBlock) addReferences();
|
|
212
|
+
return { info, offsets, contexts, previewStart };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function getIndex(path: string, file: FileHandle, size: number, revision: string) {
|
|
216
|
+
const key = JSON.stringify([path, revision]);
|
|
217
|
+
const cached = indexes.get(key);
|
|
218
|
+
if (cached) return cached;
|
|
219
|
+
const index = scanIndex(file, size, revision);
|
|
220
|
+
indexes.set(key, index);
|
|
221
|
+
void index.catch(() => { indexes.delete(key); });
|
|
222
|
+
if (indexes.size > 8) {
|
|
223
|
+
const oldest = indexes.keys().next().value;
|
|
224
|
+
if (oldest) indexes.delete(oldest);
|
|
225
|
+
}
|
|
226
|
+
return index;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function checkpoint(index: MarkdownIndex, requested: number) {
|
|
230
|
+
const line = Math.min(requested, index.info.lineCount);
|
|
231
|
+
const bucket = Math.floor((line - 1) / checkpointLines);
|
|
232
|
+
return { offset: index.offsets[bucket], first: bucket * checkpointLines + 1, line };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function loadMarkdownInfo(root: string, path: string) {
|
|
236
|
+
return withWorkspaceFile(root, path, markdownExtensions, async (file, size, revision, actual) => {
|
|
237
|
+
const { info } = await getIndex(actual, file, size, revision);
|
|
238
|
+
return { ...info, references: info.references.map((entry) => ({
|
|
239
|
+
...entry, destination: rebaseMarkdownDestination(entry.destination, root, path),
|
|
240
|
+
})) };
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export async function markdownPreviewPosition(file: FileHandle, size: number, revision: string, actual: string, requested: number): Promise<PreviewPosition> {
|
|
245
|
+
const [index, reader] = await Promise.all([getIndex(actual, file, size, revision), rustReader()]);
|
|
246
|
+
if (requested <= index.previewStart.line) return index.previewStart;
|
|
247
|
+
const { offset, first } = checkpoint(index, Math.max(index.previewStart.line, requested - 24));
|
|
248
|
+
const target = Math.min(requested, index.info.lineCount);
|
|
249
|
+
let block = index.contexts[Math.floor((first - 1) / checkpointLines)];
|
|
250
|
+
let position: PreviewPosition = first < index.previewStart.line ? index.previewStart : { offset, line: first, ...block };
|
|
251
|
+
let number = first - 1;
|
|
252
|
+
let previous = "";
|
|
253
|
+
for await (const entry of lines(file, size, offset)) {
|
|
254
|
+
if (++number < index.previewStart.line) continue;
|
|
255
|
+
if (!previous.trim() && !block.fence && !block.table && number > position.line) position = { offset: entry.offset, line: number };
|
|
256
|
+
if (number >= target - 12 && number > position.line + 32 && (block.fence || (block.table && entry.text.includes("|")))) {
|
|
257
|
+
position = { offset: entry.offset, line: number, ...block };
|
|
258
|
+
}
|
|
259
|
+
if (number >= target) break;
|
|
260
|
+
block = blockContext(entry.text, previous, block, reader);
|
|
261
|
+
previous = entry.text;
|
|
262
|
+
}
|
|
263
|
+
return position;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function loadMarkdownSource(root: string, path: string, requested: number, through?: number) {
|
|
267
|
+
return withWorkspaceFile(root, path, markdownExtensions, async (file, size, revision, actual): Promise<Source> => {
|
|
268
|
+
const { offset, first, line } = requested === 1 ? { offset: 0, first: 1, line: 1 }
|
|
269
|
+
: checkpoint(await getIndex(actual, file, size, revision), requested);
|
|
270
|
+
const limit = Math.min(through ?? line + checkpointLines - 1, line + 255);
|
|
271
|
+
const result: Source = { revision, firstLine: line, lines: [], nextLine: null };
|
|
272
|
+
let bytes = 0;
|
|
273
|
+
let lineNumber = first - 1;
|
|
274
|
+
for await (const value of lines(file, size, offset)) {
|
|
275
|
+
if (++lineNumber < line) continue;
|
|
276
|
+
const remaining = maxSourceBytes - bytes;
|
|
277
|
+
if (lineNumber > limit || (result.lines.length && Buffer.byteLength(value.text) > remaining)) {
|
|
278
|
+
result.nextLine = lineNumber;
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
const text = value.text.length <= remaining / 4 || Buffer.byteLength(value.text) <= remaining
|
|
282
|
+
? value.text : value.text.slice(0, Math.floor(remaining / 4));
|
|
283
|
+
bytes += Buffer.byteLength(text) + value.ending.length;
|
|
284
|
+
result.lines.push({ text, ending: value.ending, truncated: text.length < value.text.length });
|
|
285
|
+
}
|
|
286
|
+
return result;
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function findMarkdownLines(root: string, path: string, query: string, options: MarkdownSearchOptions, offset: number) {
|
|
291
|
+
return withWorkspaceFile(root, path, markdownExtensions, async (file, size, revision): Promise<Search> => {
|
|
292
|
+
const result: Search = { revision, hits: [], total: 0, invalidPattern: false };
|
|
293
|
+
const expression = searchExpression(query, options);
|
|
294
|
+
if (!expression) return { ...result, invalidPattern: true };
|
|
295
|
+
let line = 0;
|
|
296
|
+
for await (const { text } of lines(file, size, 0)) {
|
|
297
|
+
line++;
|
|
298
|
+
for (const match of text.matchAll(expression)) {
|
|
299
|
+
if (result.total++ < offset || result.hits.length >= markdownSearchPageSize) continue;
|
|
300
|
+
result.hits.push({ line, column: match.index, length: match[0].length });
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return result;
|
|
304
|
+
});
|
|
305
|
+
}
|