@mulmoclaude/core 0.4.0 → 0.5.1
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/dist/collection/registry/server/index.cjs +1 -1
- package/dist/collection/registry/server/index.js +1 -1
- package/dist/collection/server/index.cjs +2 -1
- package/dist/collection/server/index.js +2 -2
- package/dist/collection/server/io.d.ts +37 -9
- package/dist/collection-watchers/index.cjs +1 -1
- package/dist/collection-watchers/index.js +1 -1
- package/dist/feeds/server/index.cjs +2 -2
- package/dist/feeds/server/index.cjs.map +1 -1
- package/dist/feeds/server/index.js +2 -2
- package/dist/feeds/server/index.js.map +1 -1
- package/dist/graph-2R4HbQAg.cjs +433 -0
- package/dist/graph-2R4HbQAg.cjs.map +1 -0
- package/dist/graph-o5FZZbXf.js +326 -0
- package/dist/graph-o5FZZbXf.js.map +1 -0
- package/dist/{server-DRoqc8dL.js → server-D44bvGjw.js} +51 -17
- package/dist/server-D44bvGjw.js.map +1 -0
- package/dist/{server-DoDXibCq.cjs → server-cmnH6g2O.cjs} +56 -16
- package/dist/server-cmnH6g2O.cjs.map +1 -0
- package/dist/wiki/index.cjs +20 -341
- package/dist/wiki/index.cjs.map +1 -1
- package/dist/wiki/index.js +1 -322
- package/dist/wiki/index.js.map +1 -1
- package/dist/wiki/paths.cjs +42 -0
- package/dist/wiki/paths.cjs.map +1 -0
- package/dist/wiki/paths.js +38 -0
- package/dist/wiki/paths.js.map +1 -0
- package/dist/wiki/server/engine.d.ts +39 -0
- package/dist/wiki/server/frontmatter.d.ts +9 -0
- package/dist/wiki/server/fs.d.ts +5 -0
- package/dist/wiki/server/index.cjs +241 -21
- package/dist/wiki/server/index.cjs.map +1 -1
- package/dist/wiki/server/index.d.ts +4 -1
- package/dist/wiki/server/index.js +230 -22
- package/dist/wiki/server/index.js.map +1 -1
- package/dist/wiki/server/pageIndex.d.ts +13 -0
- package/dist/wiki/server/paths.d.ts +8 -0
- package/package.json +9 -2
- package/dist/server-DRoqc8dL.js.map +0 -1
- package/dist/server-DoDXibCq.cjs.map +0 -1
package/dist/wiki/index.js
CHANGED
|
@@ -1,326 +1,5 @@
|
|
|
1
|
+
import { _ as WIKI_LINK_PATTERN, a as findBrokenLinksInPage, c as findTagDrift, d as BULLET_WIKI_LINK_PATTERN, f as buildTableColumnMap, g as parseTagsCell, h as parseIndexEntries, i as resolveLinkTarget, l as formatLintReport, m as extractSlugFromBulletHref, n as incomingLinks, o as findMissingFiles, p as extractHashTags, r as pageOutgoingSlugs, s as findOrphanPages, t as buildWikiGraph, u as BULLET_LINK_PATTERN, v as parseWikiLink } from "../graph-o5FZZbXf.js";
|
|
1
2
|
import { n as wikiSlugify, t as isSafeSlug } from "../slug-CdN-pQX1.js";
|
|
2
|
-
//#region src/wiki/link.ts
|
|
3
|
-
/** Inline `[[...]]` link pattern. The capture group is the raw
|
|
4
|
-
* text between the brackets — the caller is expected to feed it
|
|
5
|
-
* through `parseWikiLink` to split off any `|display` suffix.
|
|
6
|
-
*
|
|
7
|
-
* Body length is capped at 200 chars to keep the regex linear:
|
|
8
|
-
* catastrophic backtracking isn't possible (no nested
|
|
9
|
-
* alternation), but a malicious page with thousands of
|
|
10
|
-
* unmatched `[[` could still pin the CPU. 200 is well above the
|
|
11
|
-
* longest legitimate title we've seen and matches the cap the
|
|
12
|
-
* server-side `WIKI_LINK_PATTERN` constant has carried since the
|
|
13
|
-
* original implementation in #951. */
|
|
14
|
-
var WIKI_LINK_PATTERN = /\[\[([^\][\r\n]{1,200})\]\]/g;
|
|
15
|
-
/** Split the raw text inside `[[...]]` into target + display.
|
|
16
|
-
*
|
|
17
|
-
* - `[[foo|Bar Baz]]` → `{ target: "foo", display: "Bar Baz" }`
|
|
18
|
-
* - `[[foo]]` → `{ target: "foo", display: "foo" }`
|
|
19
|
-
* - `[[|empty target]]` → `{ target: "", display: "empty target" }`
|
|
20
|
-
* (caller decides whether an empty target is meaningful;
|
|
21
|
-
* typically lint flags it, renderer shows the display text raw)
|
|
22
|
-
* - `[[foo|]]` → `{ target: "foo", display: "" }`
|
|
23
|
-
* (same — caller decides)
|
|
24
|
-
*
|
|
25
|
-
* Whitespace around the pipe is preserved on the display side
|
|
26
|
-
* (so the user can write `[[foo| ある記事 ]]` and get the
|
|
27
|
-
* spacing intentionally) but TRIMMED on the target side, since
|
|
28
|
-
* a slug-comparable target with leading/trailing whitespace is
|
|
29
|
-
* always a typo.
|
|
30
|
-
*
|
|
31
|
-
* Only the FIRST pipe splits. `[[a|b|c]]` becomes
|
|
32
|
-
* `{ target: "a", display: "b|c" }` so display strings can
|
|
33
|
-
* legitimately contain a literal `|`. */
|
|
34
|
-
function parseWikiLink(inner) {
|
|
35
|
-
const pipeIdx = inner.indexOf("|");
|
|
36
|
-
if (pipeIdx === -1) return {
|
|
37
|
-
target: inner,
|
|
38
|
-
display: inner
|
|
39
|
-
};
|
|
40
|
-
return {
|
|
41
|
-
target: inner.slice(0, pipeIdx).trim(),
|
|
42
|
-
display: inner.slice(pipeIdx + 1)
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
//#endregion
|
|
46
|
-
//#region src/wiki/index-parse.ts
|
|
47
|
-
var BULLET_LINK_PATTERN = /^[-*]\s+\[([^\]]+)\]\(([^)]*)\)(?:\s*[—–-]\s*(.*))?/;
|
|
48
|
-
var BULLET_WIKI_LINK_PATTERN = /^[-*]\s+\[\[([^\]]+)\]\](?:\s*[—–-]\s*(.*))?/;
|
|
49
|
-
var TABLE_SEPARATOR_PATTERN = /^\|[\s|:-]+\|$/;
|
|
50
|
-
var HASHTAG_PATTERN = /(?:^|\s)#([\p{L}\p{N}][\p{L}\p{N}_-]*)/gu;
|
|
51
|
-
/** Extract `#tag` tokens from a bullet description, returning the
|
|
52
|
-
* stripped description and a sorted, deduped, lowercased tag list.
|
|
53
|
-
* Only matches at word boundaries so mid-word `#` (e.g. anchor
|
|
54
|
-
* URLs) is left alone. */
|
|
55
|
-
function extractHashTags(text) {
|
|
56
|
-
const tags = [];
|
|
57
|
-
HASHTAG_PATTERN.lastIndex = 0;
|
|
58
|
-
let match;
|
|
59
|
-
while ((match = HASHTAG_PATTERN.exec(text)) !== null) tags.push(match[1].toLowerCase());
|
|
60
|
-
return {
|
|
61
|
-
description: text.replace(HASHTAG_PATTERN, "").replace(/\s+/g, " ").trim(),
|
|
62
|
-
tags: [...new Set(tags)].sort()
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
/** Split a table Tags cell — tolerates comma, whitespace, or `#`
|
|
66
|
-
* prefixes. Empty cell yields an empty list. */
|
|
67
|
-
function parseTagsCell(cell) {
|
|
68
|
-
const tokens = cell.split(/[,\s]+/).map((token) => token.trim().replace(/^#/, "").toLowerCase()).filter((token) => token.length > 0);
|
|
69
|
-
return [...new Set(tokens)].sort();
|
|
70
|
-
}
|
|
71
|
-
/** Map header cell names → column indices, case- and whitespace-
|
|
72
|
-
* tolerant. Used by the row parser to locate the Tags column (and
|
|
73
|
-
* any other named column) without assuming a fixed position, so
|
|
74
|
-
* older 3- and 4-column tables keep working. */
|
|
75
|
-
function buildTableColumnMap(headerRow) {
|
|
76
|
-
const cells = headerRow.split("|").slice(1, -1).map((cell) => cell.trim().replace(/^`|`$/g, "").toLowerCase());
|
|
77
|
-
const map = /* @__PURE__ */ new Map();
|
|
78
|
-
cells.forEach((cell, i) => {
|
|
79
|
-
if (cell) map.set(cell, i);
|
|
80
|
-
});
|
|
81
|
-
return map;
|
|
82
|
-
}
|
|
83
|
-
/** Resolve the per-column indices the row parser needs. Falls back
|
|
84
|
-
* to positional defaults (0/1/2) when the table has no header map.
|
|
85
|
-
* "summary" is the canonical column name; "description" is accepted
|
|
86
|
-
* as a legacy alias used by older fixtures. */
|
|
87
|
-
function resolveTableColumnIndices(columnMap) {
|
|
88
|
-
return {
|
|
89
|
-
slug: columnMap?.get("slug") ?? 0,
|
|
90
|
-
title: columnMap?.get("title") ?? 1,
|
|
91
|
-
summary: columnMap?.get("summary") ?? columnMap?.get("description") ?? 2,
|
|
92
|
-
tags: columnMap?.get("tags")
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
function parseTableRow(trimmed, columnMap) {
|
|
96
|
-
const cols = trimmed.split("|").slice(1, -1).map((column) => column.trim().replace(/^`|`$/g, ""));
|
|
97
|
-
if (cols.length < 2) return null;
|
|
98
|
-
const idx = resolveTableColumnIndices(columnMap);
|
|
99
|
-
const slug = cols[idx.slug] ?? "";
|
|
100
|
-
const title = cols[idx.title] || slug;
|
|
101
|
-
if (!slug || !title) return null;
|
|
102
|
-
return {
|
|
103
|
-
title,
|
|
104
|
-
slug,
|
|
105
|
-
description: cols[idx.summary] ?? "",
|
|
106
|
-
tags: idx.tags !== void 0 ? parseTagsCell(cols[idx.tags] ?? "") : []
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
/** Extract the slug segment from a bullet link's href. Accepts the
|
|
110
|
-
* canonical `pages/<slug>.md`, a bare `<slug>.md`, or just `<slug>`
|
|
111
|
-
* — the three forms produced by different historical writers of
|
|
112
|
-
* index.md. Returns "" for hrefs that don't look like a wiki page
|
|
113
|
-
* reference (e.g. `https://example.com`) so the caller can fall
|
|
114
|
-
* back to title-based slugification. */
|
|
115
|
-
function extractSlugFromBulletHref(rawHref) {
|
|
116
|
-
const href = rawHref.trim();
|
|
117
|
-
if (!href) return "";
|
|
118
|
-
if (/^[a-z]+:\/\//i.test(href)) return "";
|
|
119
|
-
return (href.split("/").pop() ?? href).replace(/\.md$/i, "");
|
|
120
|
-
}
|
|
121
|
-
function parseBulletLinkRow(trimmed) {
|
|
122
|
-
const match = BULLET_LINK_PATTERN.exec(trimmed);
|
|
123
|
-
if (!match) return null;
|
|
124
|
-
const title = match[1].trim();
|
|
125
|
-
const href = match[2] ?? "";
|
|
126
|
-
const { description, tags } = extractHashTags(match[3]?.trim() ?? "");
|
|
127
|
-
return {
|
|
128
|
-
title,
|
|
129
|
-
slug: extractSlugFromBulletHref(href) || wikiSlugify(title),
|
|
130
|
-
description,
|
|
131
|
-
tags
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
function parseBulletWikiLinkRow(trimmed) {
|
|
135
|
-
const match = BULLET_WIKI_LINK_PATTERN.exec(trimmed);
|
|
136
|
-
if (!match) return null;
|
|
137
|
-
const { target, display } = parseWikiLink(match[1]);
|
|
138
|
-
const title = (display || target).trim();
|
|
139
|
-
const slug = target ? wikiSlugify(target) : wikiSlugify(title);
|
|
140
|
-
const { description, tags } = extractHashTags(match[2]?.trim() ?? "");
|
|
141
|
-
return {
|
|
142
|
-
title,
|
|
143
|
-
slug,
|
|
144
|
-
description,
|
|
145
|
-
tags
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
/** Parse entries from index.md. Supports three formats:
|
|
149
|
-
* 1. Table: `| slug | Title | Summary | (Tags) |`
|
|
150
|
-
* 2. Bullet link: `- [Title](pages/slug.md) — description`
|
|
151
|
-
* 3. Wiki link: `- [[Title]] — description`
|
|
152
|
-
*
|
|
153
|
-
* Returns entries in source order. Any unrecognised line is
|
|
154
|
-
* silently skipped — index.md is freeform markdown otherwise. */
|
|
155
|
-
function parseIndexEntries(content) {
|
|
156
|
-
const entries = [];
|
|
157
|
-
let inTable = false;
|
|
158
|
-
let columnMap = null;
|
|
159
|
-
for (const line of content.split("\n")) {
|
|
160
|
-
const trimmed = line.trim();
|
|
161
|
-
if (trimmed.startsWith("|")) {
|
|
162
|
-
if (TABLE_SEPARATOR_PATTERN.test(trimmed)) {
|
|
163
|
-
inTable = true;
|
|
164
|
-
continue;
|
|
165
|
-
}
|
|
166
|
-
if (!inTable) {
|
|
167
|
-
columnMap = buildTableColumnMap(trimmed);
|
|
168
|
-
inTable = true;
|
|
169
|
-
continue;
|
|
170
|
-
}
|
|
171
|
-
const entry = parseTableRow(trimmed, columnMap);
|
|
172
|
-
if (entry) entries.push(entry);
|
|
173
|
-
continue;
|
|
174
|
-
}
|
|
175
|
-
inTable = false;
|
|
176
|
-
columnMap = null;
|
|
177
|
-
const bullet = parseBulletLinkRow(trimmed) ?? parseBulletWikiLinkRow(trimmed);
|
|
178
|
-
if (bullet) entries.push(bullet);
|
|
179
|
-
}
|
|
180
|
-
return entries;
|
|
181
|
-
}
|
|
182
|
-
//#endregion
|
|
183
|
-
//#region src/wiki/lint.ts
|
|
184
|
-
/** Files on disk that aren't referenced by index.md. */
|
|
185
|
-
function findOrphanPages(fileSlugs, indexedSlugs) {
|
|
186
|
-
const issues = [];
|
|
187
|
-
for (const slug of fileSlugs) if (!indexedSlugs.has(slug)) issues.push(`- **Orphan page**: \`${slug}.md\` exists but is missing from index.md`);
|
|
188
|
-
return issues;
|
|
189
|
-
}
|
|
190
|
-
/** Slugs referenced by index.md that have no corresponding file. */
|
|
191
|
-
function findMissingFiles(pageEntries, fileSlugs) {
|
|
192
|
-
const issues = [];
|
|
193
|
-
for (const entry of pageEntries) if (!fileSlugs.has(entry.slug)) issues.push(`- **Missing file**: index.md references \`${entry.slug}\` but the file does not exist`);
|
|
194
|
-
return issues;
|
|
195
|
-
}
|
|
196
|
-
/** Walk a page's body for `[[…]]` links and flag any whose
|
|
197
|
-
* resolved slug doesn't exist in the file set.
|
|
198
|
-
*
|
|
199
|
-
* Critically: this routes through `parseWikiLink` so
|
|
200
|
-
* `[[slug|display]]` is split correctly — the lint slugifies the
|
|
201
|
-
* TARGET, not the full bracket body. Pre-#1297 the lint
|
|
202
|
-
* slugified the entire content (`slug|display`), which collapsed
|
|
203
|
-
* to a slug that always missed and produced ~168 false-positive
|
|
204
|
-
* "broken link" warnings. */
|
|
205
|
-
function findBrokenLinksInPage(fileName, content, fileSlugs) {
|
|
206
|
-
const issues = [];
|
|
207
|
-
const matches = [...content.matchAll(WIKI_LINK_PATTERN)];
|
|
208
|
-
for (const match of matches) {
|
|
209
|
-
const { target } = parseWikiLink(match[1]);
|
|
210
|
-
const linkSlug = wikiSlugify(target);
|
|
211
|
-
if (linkSlug.length === 0) {
|
|
212
|
-
issues.push(`- **Broken link** in \`${fileName}\`: [[${match[1]}]] → empty target`);
|
|
213
|
-
continue;
|
|
214
|
-
}
|
|
215
|
-
if (!fileSlugs.has(linkSlug)) issues.push(`- **Broken link** in \`${fileName}\`: [[${match[1]}]] → \`${linkSlug}.md\` not found`);
|
|
216
|
-
}
|
|
217
|
-
return issues;
|
|
218
|
-
}
|
|
219
|
-
function formatTagList(tags) {
|
|
220
|
-
return `[${[...tags].sort().join(", ")}]`;
|
|
221
|
-
}
|
|
222
|
-
/** Flag any slug whose index.md tags differ from the page's own
|
|
223
|
-
* frontmatter `tags:` field. Comparison is set-based and order-
|
|
224
|
-
* insensitive; both sides are lowercased at parse time. Slugs
|
|
225
|
-
* missing from `frontmatterTagsBySlug` are ignored here — the
|
|
226
|
-
* missing file itself is already reported by `findMissingFiles`. */
|
|
227
|
-
function findTagDrift(pageEntries, frontmatterTagsBySlug) {
|
|
228
|
-
const issues = [];
|
|
229
|
-
for (const entry of pageEntries) {
|
|
230
|
-
const pageTags = frontmatterTagsBySlug.get(entry.slug.toLowerCase());
|
|
231
|
-
if (pageTags === void 0) continue;
|
|
232
|
-
const pageSet = new Set(pageTags);
|
|
233
|
-
const indexSet = new Set(entry.tags);
|
|
234
|
-
if (pageSet.size !== indexSet.size || [...pageSet].some((tag) => !indexSet.has(tag))) issues.push(`- **Tag drift**: \`${entry.slug}.md\` frontmatter has ${formatTagList(pageTags)} but index.md has ${formatTagList(entry.tags)}`);
|
|
235
|
-
}
|
|
236
|
-
return issues;
|
|
237
|
-
}
|
|
238
|
-
/** Render the final markdown report from the accumulated issues
|
|
239
|
-
* list. Empty input yields the "wiki is healthy" sentinel so the
|
|
240
|
-
* caller can write the same file every time without branching on
|
|
241
|
-
* presence. */
|
|
242
|
-
function formatLintReport(issues) {
|
|
243
|
-
if (issues.length === 0) return "# Wiki Lint Report\n\n✓ No issues found. Wiki is healthy.";
|
|
244
|
-
const noun = `issue${issues.length !== 1 ? "s" : ""}`;
|
|
245
|
-
return `# Wiki Lint Report\n\n${issues.length} ${noun} found:\n\n${issues.join("\n")}`;
|
|
246
|
-
}
|
|
247
|
-
//#endregion
|
|
248
|
-
//#region src/wiki/graph.ts
|
|
249
|
-
/** Resolve a raw `[[link]]` target to an existing page slug, or null.
|
|
250
|
-
* Mirrors the route resolver's strategy: slugify first, then fall
|
|
251
|
-
* back to matching an index entry title so non-ASCII targets like
|
|
252
|
-
* `[[さくらインターネット]]` resolve to their ASCII file slug. */
|
|
253
|
-
function resolveLinkTarget(target, fileSlugs, slugByTitle) {
|
|
254
|
-
const slug = wikiSlugify(target);
|
|
255
|
-
if (slug.length > 0 && fileSlugs.has(slug)) return slug;
|
|
256
|
-
const byTitle = slugByTitle.get(target.trim());
|
|
257
|
-
if (byTitle !== void 0 && fileSlugs.has(byTitle)) return byTitle;
|
|
258
|
-
return null;
|
|
259
|
-
}
|
|
260
|
-
/** Resolved, deduped outgoing slugs for one page body. Self-links and
|
|
261
|
-
* links to non-existent pages are dropped (the latter are already a
|
|
262
|
-
* lint "broken link", not a graph edge). */
|
|
263
|
-
function pageOutgoingSlugs(fromSlug, content, fileSlugs, slugByTitle) {
|
|
264
|
-
const out = /* @__PURE__ */ new Set();
|
|
265
|
-
for (const match of content.matchAll(WIKI_LINK_PATTERN)) {
|
|
266
|
-
const { target } = parseWikiLink(match[1]);
|
|
267
|
-
const resolved = resolveLinkTarget(target, fileSlugs, slugByTitle);
|
|
268
|
-
if (resolved !== null && resolved !== fromSlug) out.add(resolved);
|
|
269
|
-
}
|
|
270
|
-
return [...out];
|
|
271
|
-
}
|
|
272
|
-
function buildTitleMaps(entries) {
|
|
273
|
-
const titleBySlug = /* @__PURE__ */ new Map();
|
|
274
|
-
const slugByTitle = /* @__PURE__ */ new Map();
|
|
275
|
-
for (const entry of entries) {
|
|
276
|
-
if (!titleBySlug.has(entry.slug)) titleBySlug.set(entry.slug, entry.title);
|
|
277
|
-
if (entry.title.length > 0 && !slugByTitle.has(entry.title)) slugByTitle.set(entry.title, entry.slug);
|
|
278
|
-
}
|
|
279
|
-
return {
|
|
280
|
-
titleBySlug,
|
|
281
|
-
slugByTitle
|
|
282
|
-
};
|
|
283
|
-
}
|
|
284
|
-
/** Build the full page→page graph. Nodes are the existing page files
|
|
285
|
-
* (titled from index.md, falling back to the slug for un-indexed
|
|
286
|
-
* pages); edges are the resolved `[[links]]`, deduped per (from,to). */
|
|
287
|
-
function buildWikiGraph(pages, entries) {
|
|
288
|
-
const fileSlugs = new Set(pages.map((page) => page.slug));
|
|
289
|
-
const { titleBySlug, slugByTitle } = buildTitleMaps(entries);
|
|
290
|
-
const nodes = pages.map((page) => ({
|
|
291
|
-
slug: page.slug,
|
|
292
|
-
title: titleBySlug.get(page.slug) ?? page.slug
|
|
293
|
-
}));
|
|
294
|
-
const edges = [];
|
|
295
|
-
const seen = /* @__PURE__ */ new Set();
|
|
296
|
-
for (const page of pages) for (const toSlug of pageOutgoingSlugs(page.slug, page.content, fileSlugs, slugByTitle)) {
|
|
297
|
-
const key = [page.slug, toSlug].join("\n");
|
|
298
|
-
if (seen.has(key)) continue;
|
|
299
|
-
seen.add(key);
|
|
300
|
-
edges.push({
|
|
301
|
-
from: page.slug,
|
|
302
|
-
to: toSlug
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
return {
|
|
306
|
-
nodes,
|
|
307
|
-
edges
|
|
308
|
-
};
|
|
309
|
-
}
|
|
310
|
-
/** Pages that link TO `slug` (incoming edges), deduped, as nodes. */
|
|
311
|
-
function incomingLinks(graph, slug) {
|
|
312
|
-
const nodeBySlug = new Map(graph.nodes.map((node) => [node.slug, node]));
|
|
313
|
-
const result = [];
|
|
314
|
-
const seen = /* @__PURE__ */ new Set();
|
|
315
|
-
for (const edge of graph.edges) {
|
|
316
|
-
if (edge.to !== slug || seen.has(edge.from)) continue;
|
|
317
|
-
seen.add(edge.from);
|
|
318
|
-
const node = nodeBySlug.get(edge.from);
|
|
319
|
-
if (node) result.push(node);
|
|
320
|
-
}
|
|
321
|
-
return result;
|
|
322
|
-
}
|
|
323
|
-
//#endregion
|
|
324
3
|
//#region src/wiki/route.ts
|
|
325
4
|
var WIKI_ROUTE_SECTION = {
|
|
326
5
|
pages: "pages",
|
package/dist/wiki/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/wiki/link.ts","../../src/wiki/index-parse.ts","../../src/wiki/lint.ts","../../src/wiki/graph.ts","../../src/wiki/route.ts","../../src/wiki/render.ts"],"sourcesContent":["// Pure helpers for `[[wiki-link]]` syntax. Used by the lint\n// (`server/api/routes/wiki.ts`), the page resolver, and the\n// frontend renderer (`src/plugins/wiki/helpers.ts`) — before this\n// module the three sites each had their own implementation and\n// none of them handled the `[[target|display]]` form, producing\n// false-positive \"broken link\" warnings on slug-aliased links\n// (issue #1297).\n//\n// All functions are pure string operations; safe to import from\n// browser bundles. No `node:*` imports anywhere in this file.\n\n/** Inline `[[...]]` link pattern. The capture group is the raw\n * text between the brackets — the caller is expected to feed it\n * through `parseWikiLink` to split off any `|display` suffix.\n *\n * Body length is capped at 200 chars to keep the regex linear:\n * catastrophic backtracking isn't possible (no nested\n * alternation), but a malicious page with thousands of\n * unmatched `[[` could still pin the CPU. 200 is well above the\n * longest legitimate title we've seen and matches the cap the\n * server-side `WIKI_LINK_PATTERN` constant has carried since the\n * original implementation in #951. */\nexport const WIKI_LINK_PATTERN = /\\[\\[([^\\][\\r\\n]{1,200})\\]\\]/g;\n\n/** The structural shape of an inline `[[target|display]]` link.\n * `target` is what the resolver / lint compares against page\n * slugs; `display` is what the renderer shows to the user.\n * When the user writes `[[foo]]` (no pipe), both fields hold\n * `foo`. */\nexport interface WikiLink {\n target: string;\n display: string;\n}\n\n/** Split the raw text inside `[[...]]` into target + display.\n *\n * - `[[foo|Bar Baz]]` → `{ target: \"foo\", display: \"Bar Baz\" }`\n * - `[[foo]]` → `{ target: \"foo\", display: \"foo\" }`\n * - `[[|empty target]]` → `{ target: \"\", display: \"empty target\" }`\n * (caller decides whether an empty target is meaningful;\n * typically lint flags it, renderer shows the display text raw)\n * - `[[foo|]]` → `{ target: \"foo\", display: \"\" }`\n * (same — caller decides)\n *\n * Whitespace around the pipe is preserved on the display side\n * (so the user can write `[[foo| ある記事 ]]` and get the\n * spacing intentionally) but TRIMMED on the target side, since\n * a slug-comparable target with leading/trailing whitespace is\n * always a typo.\n *\n * Only the FIRST pipe splits. `[[a|b|c]]` becomes\n * `{ target: \"a\", display: \"b|c\" }` so display strings can\n * legitimately contain a literal `|`. */\nexport function parseWikiLink(inner: string): WikiLink {\n const pipeIdx = inner.indexOf(\"|\");\n if (pipeIdx === -1) {\n return { target: inner, display: inner };\n }\n const target = inner.slice(0, pipeIdx).trim();\n const display = inner.slice(pipeIdx + 1);\n return { target, display };\n}\n","// Pure parsers for `data/wiki/index.md` content. Used by:\n// - server/api/routes/wiki.ts — page resolver + lint\n// - frontend lint preview (future) — same parser, no fork\n//\n// All exports here are pure string ops; no `node:*` imports allowed.\n// If a future caller needs to walk the filesystem, that wrapper goes\n// under `@mulmoclaude/core/wiki/server` (today only `server/paths.ts`\n// touches `node:path`; nothing here touches disk).\n\nimport { parseWikiLink } from \"./link.js\";\nimport { wikiSlugify } from \"./slug.js\";\n\nexport interface WikiPageEntry {\n title: string;\n slug: string;\n description: string;\n tags: string[];\n}\n\n// ── Patterns ──────────────────────────────────────────────────\n// Bullet patterns live here (not server/utils/regex.ts) because the\n// index parser is the only consumer and the regexes are part of the\n// public surface that callers may want to reason about in tests.\n// Linear in line length: every `[^x]+` runs over a fixed exclusion\n// set with a hard delimiter; the optional summary group's `(.*)` is\n// a single greedy run with no nested overlap.\n\n// eslint-disable-next-line security/detect-unsafe-regex -- bullet-link parser; bounded captures with hard delimiters\nexport const BULLET_LINK_PATTERN = /^[-*]\\s+\\[([^\\]]+)\\]\\(([^)]*)\\)(?:\\s*[—–-]\\s*(.*))?/;\n// eslint-disable-next-line security/detect-unsafe-regex -- same shape as BULLET_LINK_PATTERN\nexport const BULLET_WIKI_LINK_PATTERN = /^[-*]\\s+\\[\\[([^\\]]+)\\]\\](?:\\s*[—–-]\\s*(.*))?/;\n\nconst TABLE_SEPARATOR_PATTERN = /^\\|[\\s|:-]+\\|$/;\n\n// Unicode-aware tag body: any letter or number in any script (so\n// Japanese / Chinese / Korean tags like `#クラウド` or `#可視化` work),\n// plus `-` and `_` as internal joiners. First char is a letter or\n// number only — no leading punctuation.\nconst HASHTAG_PATTERN = /(?:^|\\s)#([\\p{L}\\p{N}][\\p{L}\\p{N}_-]*)/gu;\n\n// ── Tag extraction ────────────────────────────────────────────\n\n/** Extract `#tag` tokens from a bullet description, returning the\n * stripped description and a sorted, deduped, lowercased tag list.\n * Only matches at word boundaries so mid-word `#` (e.g. anchor\n * URLs) is left alone. */\nexport function extractHashTags(text: string): { description: string; tags: string[] } {\n const tags: string[] = [];\n HASHTAG_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = HASHTAG_PATTERN.exec(text)) !== null) {\n tags.push(match[1].toLowerCase());\n }\n const description = text.replace(HASHTAG_PATTERN, \"\").replace(/\\s+/g, \" \").trim();\n const deduped = [...new Set(tags)].sort();\n return { description, tags: deduped };\n}\n\n/** Split a table Tags cell — tolerates comma, whitespace, or `#`\n * prefixes. Empty cell yields an empty list. */\nexport function parseTagsCell(cell: string): string[] {\n const tokens = cell\n .split(/[,\\s]+/)\n .map((token) => token.trim().replace(/^#/, \"\").toLowerCase())\n .filter((token) => token.length > 0);\n return [...new Set(tokens)].sort();\n}\n\n// ── Table parser ──────────────────────────────────────────────\n\n/** Map header cell names → column indices, case- and whitespace-\n * tolerant. Used by the row parser to locate the Tags column (and\n * any other named column) without assuming a fixed position, so\n * older 3- and 4-column tables keep working. */\nexport function buildTableColumnMap(headerRow: string): Map<string, number> {\n const cells = headerRow\n .split(\"|\")\n .slice(1, -1)\n // Mirror parseTableRow's cell-normalising: strip the surrounding\n // backticks that commonly wrap cell values in wiki tables.\n // Without this, a `| \\`tags\\` |` header maps to the key \"`tags`\"\n // and the subsequent `columnMap.get(\"tags\")` lookup silently\n // misses the column, falling back to `tags: []`.\n .map((cell) => cell.trim().replace(/^`|`$/g, \"\").toLowerCase());\n const map = new Map<string, number>();\n cells.forEach((cell, i) => {\n if (cell) map.set(cell, i);\n });\n return map;\n}\n\ninterface TableColumnIndices {\n slug: number;\n title: number;\n summary: number;\n /** Undefined when the table has no `tags` column — caller skips\n * the tags lookup entirely and the row gets `tags: []`. */\n tags: number | undefined;\n}\n\n/** Resolve the per-column indices the row parser needs. Falls back\n * to positional defaults (0/1/2) when the table has no header map.\n * \"summary\" is the canonical column name; \"description\" is accepted\n * as a legacy alias used by older fixtures. */\nfunction resolveTableColumnIndices(columnMap: Map<string, number> | null): TableColumnIndices {\n return {\n slug: columnMap?.get(\"slug\") ?? 0,\n title: columnMap?.get(\"title\") ?? 1,\n summary: columnMap?.get(\"summary\") ?? columnMap?.get(\"description\") ?? 2,\n tags: columnMap?.get(\"tags\"),\n };\n}\n\nfunction parseTableRow(trimmed: string, columnMap: Map<string, number> | null): WikiPageEntry | null {\n const cols = trimmed\n .split(\"|\")\n .slice(1, -1)\n .map((column) => column.trim().replace(/^`|`$/g, \"\"));\n if (cols.length < 2) return null;\n\n const idx = resolveTableColumnIndices(columnMap);\n const slug = cols[idx.slug] ?? \"\";\n const title = cols[idx.title] || slug;\n if (!slug || !title) return null;\n\n const description = cols[idx.summary] ?? \"\";\n const tags = idx.tags !== undefined ? parseTagsCell(cols[idx.tags] ?? \"\") : [];\n return { title, slug, description, tags };\n}\n\n// ── Bullet-row parsers ────────────────────────────────────────\n\n/** Extract the slug segment from a bullet link's href. Accepts the\n * canonical `pages/<slug>.md`, a bare `<slug>.md`, or just `<slug>`\n * — the three forms produced by different historical writers of\n * index.md. Returns \"\" for hrefs that don't look like a wiki page\n * reference (e.g. `https://example.com`) so the caller can fall\n * back to title-based slugification. */\nexport function extractSlugFromBulletHref(rawHref: string): string {\n const href = rawHref.trim();\n if (!href) return \"\";\n if (/^[a-z]+:\\/\\//i.test(href)) return \"\";\n const lastSegment = href.split(\"/\").pop() ?? href;\n return lastSegment.replace(/\\.md$/i, \"\");\n}\n\nfunction parseBulletLinkRow(trimmed: string): WikiPageEntry | null {\n const match = BULLET_LINK_PATTERN.exec(trimmed);\n if (!match) return null;\n const title = match[1].trim();\n const href = match[2] ?? \"\";\n const raw = match[3]?.trim() ?? \"\";\n const { description, tags } = extractHashTags(raw);\n // Prefer the slug embedded in the href so non-ASCII titles keep\n // a navigable slug. Fall back to slugifying the title only when\n // the href has no recognisable slug (rare — usually means the\n // author put an external URL here).\n const slug = extractSlugFromBulletHref(href) || wikiSlugify(title);\n return { title, slug, description, tags };\n}\n\nfunction parseBulletWikiLinkRow(trimmed: string): WikiPageEntry | null {\n const match = BULLET_WIKI_LINK_PATTERN.exec(trimmed);\n if (!match) return null;\n // Split `[[target|display]]` so the bullet entry's slug derives\n // from the TARGET (which is already a slug-shaped identifier\n // when the author wrote the alias form) and the title shows\n // the DISPLAY half. Pre-#1297 the parser slugified the full\n // `target|display` body, which collapses `|` to \"\" and\n // produces a wrong slug — Codex review on PR #1312.\n const { target, display } = parseWikiLink(match[1]);\n const title = (display || target).trim();\n const slug = target ? wikiSlugify(target) : wikiSlugify(title);\n const raw = match[2]?.trim() ?? \"\";\n const { description, tags } = extractHashTags(raw);\n return { title, slug, description, tags };\n}\n\n// ── Top-level parser ──────────────────────────────────────────\n\n/** Parse entries from index.md. Supports three formats:\n * 1. Table: `| slug | Title | Summary | (Tags) |`\n * 2. Bullet link: `- [Title](pages/slug.md) — description`\n * 3. Wiki link: `- [[Title]] — description`\n *\n * Returns entries in source order. Any unrecognised line is\n * silently skipped — index.md is freeform markdown otherwise. */\nexport function parseIndexEntries(content: string): WikiPageEntry[] {\n const entries: WikiPageEntry[] = [];\n let inTable = false;\n let columnMap: Map<string, number> | null = null;\n\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n\n if (trimmed.startsWith(\"|\")) {\n if (TABLE_SEPARATOR_PATTERN.test(trimmed)) {\n inTable = true;\n continue;\n }\n if (!inTable) {\n // First `|`-line before the separator is the header. Capture\n // the column map so parseTableRow can locate the Tags\n // column (if any) by name rather than position.\n columnMap = buildTableColumnMap(trimmed);\n inTable = true;\n continue;\n }\n const entry = parseTableRow(trimmed, columnMap);\n if (entry) entries.push(entry);\n continue;\n }\n\n inTable = false;\n columnMap = null;\n\n const bullet = parseBulletLinkRow(trimmed) ?? parseBulletWikiLinkRow(trimmed);\n if (bullet) entries.push(bullet);\n }\n return entries;\n}\n","// Pure wiki lint rules.\n//\n// Each rule takes plain inputs (Sets, page-entry arrays, raw file\n// contents) so the whole pipeline can be unit-tested without\n// filesystem fixtures. The Express route at\n// `server/api/routes/wiki.ts` is a thin shell that reads the disk,\n// calls these rules, formats the result. A future frontend \"lint\n// preview before save\" would call the same functions over an\n// in-memory snapshot.\n\nimport type { WikiPageEntry } from \"./index-parse.js\";\nimport { WIKI_LINK_PATTERN, parseWikiLink } from \"./link.js\";\nimport { wikiSlugify } from \"./slug.js\";\n\n/** Files on disk that aren't referenced by index.md. */\nexport function findOrphanPages(fileSlugs: ReadonlySet<string>, indexedSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n for (const slug of fileSlugs) {\n if (!indexedSlugs.has(slug)) {\n issues.push(`- **Orphan page**: \\`${slug}.md\\` exists but is missing from index.md`);\n }\n }\n return issues;\n}\n\n/** Slugs referenced by index.md that have no corresponding file. */\nexport function findMissingFiles(pageEntries: readonly WikiPageEntry[], fileSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n for (const entry of pageEntries) {\n if (!fileSlugs.has(entry.slug)) {\n issues.push(`- **Missing file**: index.md references \\`${entry.slug}\\` but the file does not exist`);\n }\n }\n return issues;\n}\n\n/** Walk a page's body for `[[…]]` links and flag any whose\n * resolved slug doesn't exist in the file set.\n *\n * Critically: this routes through `parseWikiLink` so\n * `[[slug|display]]` is split correctly — the lint slugifies the\n * TARGET, not the full bracket body. Pre-#1297 the lint\n * slugified the entire content (`slug|display`), which collapsed\n * to a slug that always missed and produced ~168 false-positive\n * \"broken link\" warnings. */\nexport function findBrokenLinksInPage(fileName: string, content: string, fileSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n const matches = [...content.matchAll(WIKI_LINK_PATTERN)];\n for (const match of matches) {\n const { target } = parseWikiLink(match[1]);\n const linkSlug = wikiSlugify(target);\n // Empty target is its own diagnostic — `[[|display]]` or\n // `[[]]` slugifies to \"\" and would otherwise be flagged\n // identically to a real broken link. Keep the original raw\n // bracket body in the report so the user can grep their pages\n // for the malformed link.\n if (linkSlug.length === 0) {\n issues.push(`- **Broken link** in \\`${fileName}\\`: [[${match[1]}]] → empty target`);\n continue;\n }\n if (!fileSlugs.has(linkSlug)) {\n issues.push(`- **Broken link** in \\`${fileName}\\`: [[${match[1]}]] → \\`${linkSlug}.md\\` not found`);\n }\n }\n return issues;\n}\n\nfunction formatTagList(tags: readonly string[]): string {\n return `[${[...tags].sort().join(\", \")}]`;\n}\n\n/** Flag any slug whose index.md tags differ from the page's own\n * frontmatter `tags:` field. Comparison is set-based and order-\n * insensitive; both sides are lowercased at parse time. Slugs\n * missing from `frontmatterTagsBySlug` are ignored here — the\n * missing file itself is already reported by `findMissingFiles`. */\nexport function findTagDrift(pageEntries: readonly WikiPageEntry[], frontmatterTagsBySlug: ReadonlyMap<string, readonly string[]>): string[] {\n const issues: string[] = [];\n for (const entry of pageEntries) {\n // Lowercase on lookup — the caller keys the map with\n // lowercased slugs, so a `MyPage.md` filename still matches\n // an `entry.slug` of `mypage` produced by `wikiSlugify` on the\n // wiki-link parser path.\n const pageTags = frontmatterTagsBySlug.get(entry.slug.toLowerCase());\n if (pageTags === undefined) continue;\n const pageSet = new Set(pageTags);\n const indexSet = new Set(entry.tags);\n if (pageSet.size !== indexSet.size || [...pageSet].some((tag) => !indexSet.has(tag))) {\n issues.push(`- **Tag drift**: \\`${entry.slug}.md\\` frontmatter has ${formatTagList(pageTags)} but index.md has ${formatTagList(entry.tags)}`);\n }\n }\n return issues;\n}\n\n/** Render the final markdown report from the accumulated issues\n * list. Empty input yields the \"wiki is healthy\" sentinel so the\n * caller can write the same file every time without branching on\n * presence. */\nexport function formatLintReport(issues: readonly string[]): string {\n if (issues.length === 0) {\n return \"# Wiki Lint Report\\n\\n✓ No issues found. Wiki is healthy.\";\n }\n const noun = `issue${issues.length !== 1 ? \"s\" : \"\"}`;\n return `# Wiki Lint Report\\n\\n${issues.length} ${noun} found:\\n\\n${issues.join(\"\\n\")}`;\n}\n","// Pure builder for the wiki page→page link graph. Used by:\n// - server/api/routes/wiki.ts — the `graph` action endpoint\n// - src/plugins/wiki/View.vue — backlinks (\"linked references\") +\n// the Graph tab\n//\n// All functions are pure string / collection ops; no `node:*` imports,\n// so the frontend bundle can import them directly (same discipline as\n// the sibling `link.ts` / `lint.ts` / `index-parse.ts` modules).\n//\n// NOTE: this is page→page link structure, distinct from the\n// `server/workspace/wiki-backlinks/` module, which appends *session*\n// backlinks (a page → the chat that edited it, #109). Different concept\n// — do not conflate.\n\nimport { WIKI_LINK_PATTERN, parseWikiLink } from \"./link.js\";\nimport { wikiSlugify } from \"./slug.js\";\nimport type { WikiPageEntry } from \"./index-parse.js\";\n\nexport interface WikiGraphNode {\n slug: string;\n title: string;\n}\n\nexport interface WikiGraphEdge {\n from: string;\n to: string;\n}\n\nexport interface WikiGraph {\n nodes: WikiGraphNode[];\n edges: WikiGraphEdge[];\n}\n\n/** One page's raw body plus its canonical (file-derived) slug. */\nexport interface WikiPageContent {\n slug: string;\n content: string;\n}\n\n/** Resolve a raw `[[link]]` target to an existing page slug, or null.\n * Mirrors the route resolver's strategy: slugify first, then fall\n * back to matching an index entry title so non-ASCII targets like\n * `[[さくらインターネット]]` resolve to their ASCII file slug. */\nexport function resolveLinkTarget(target: string, fileSlugs: ReadonlySet<string>, slugByTitle: ReadonlyMap<string, string>): string | null {\n const slug = wikiSlugify(target);\n if (slug.length > 0 && fileSlugs.has(slug)) return slug;\n const byTitle = slugByTitle.get(target.trim());\n if (byTitle !== undefined && fileSlugs.has(byTitle)) return byTitle;\n return null;\n}\n\n/** Resolved, deduped outgoing slugs for one page body. Self-links and\n * links to non-existent pages are dropped (the latter are already a\n * lint \"broken link\", not a graph edge). */\nexport function pageOutgoingSlugs(fromSlug: string, content: string, fileSlugs: ReadonlySet<string>, slugByTitle: ReadonlyMap<string, string>): string[] {\n const out = new Set<string>();\n for (const match of content.matchAll(WIKI_LINK_PATTERN)) {\n const { target } = parseWikiLink(match[1]);\n const resolved = resolveLinkTarget(target, fileSlugs, slugByTitle);\n if (resolved !== null && resolved !== fromSlug) out.add(resolved);\n }\n return [...out];\n}\n\nfunction buildTitleMaps(entries: readonly WikiPageEntry[]): { titleBySlug: Map<string, string>; slugByTitle: Map<string, string> } {\n const titleBySlug = new Map<string, string>();\n const slugByTitle = new Map<string, string>();\n for (const entry of entries) {\n if (!titleBySlug.has(entry.slug)) titleBySlug.set(entry.slug, entry.title);\n if (entry.title.length > 0 && !slugByTitle.has(entry.title)) slugByTitle.set(entry.title, entry.slug);\n }\n return { titleBySlug, slugByTitle };\n}\n\n/** Build the full page→page graph. Nodes are the existing page files\n * (titled from index.md, falling back to the slug for un-indexed\n * pages); edges are the resolved `[[links]]`, deduped per (from,to). */\nexport function buildWikiGraph(pages: readonly WikiPageContent[], entries: readonly WikiPageEntry[]): WikiGraph {\n const fileSlugs = new Set(pages.map((page) => page.slug));\n const { titleBySlug, slugByTitle } = buildTitleMaps(entries);\n const nodes: WikiGraphNode[] = pages.map((page) => ({ slug: page.slug, title: titleBySlug.get(page.slug) ?? page.slug }));\n const edges: WikiGraphEdge[] = [];\n const seen = new Set<string>();\n for (const page of pages) {\n for (const toSlug of pageOutgoingSlugs(page.slug, page.content, fileSlugs, slugByTitle)) {\n // Newline cannot appear in a wiki slug, so it is a safe pair key.\n const key = [page.slug, toSlug].join(\"\\n\");\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({ from: page.slug, to: toSlug });\n }\n }\n return { nodes, edges };\n}\n\n/** Pages that link TO `slug` (incoming edges), deduped, as nodes. */\nexport function incomingLinks(graph: WikiGraph, slug: string): WikiGraphNode[] {\n const nodeBySlug = new Map(graph.nodes.map((node) => [node.slug, node]));\n const result: WikiGraphNode[] = [];\n const seen = new Set<string>();\n for (const edge of graph.edges) {\n if (edge.to !== slug || seen.has(edge.from)) continue;\n seen.add(edge.from);\n const node = nodeBySlug.get(edge.from);\n if (node) result.push(node);\n }\n return result;\n}\n","// Pure helpers for reading, building, and validating wiki route\n// params. Kept free of Vue / vue-router imports so it can be shared\n// across hosts (MulmoClaude + MulmoTerminal) from\n// `@mulmoclaude/core/wiki`:\n//\n// - the host router guard (synchronous validation at navigation time)\n// - the wiki View (watcher + push helpers)\n// - the workspace-link click handler\n// - unit tests\n//\n// Mirrors the \"one file owns the URL ↔ domain mapping\" pattern so the\n// literals don't drift across the router definition, guards, views,\n// and tests.\n\nimport { isSafeSlug } from \"./slug.js\";\n\n// URL segment used in `/wiki/:section/...`. Closed enum — the router\n// regex `(pages|log|lint-report)` rejects anything else.\nexport const WIKI_ROUTE_SECTION = {\n pages: \"pages\",\n log: \"log\",\n lintReport: \"lint-report\",\n graph: \"graph\",\n} as const;\n\nexport type WikiRouteSection = (typeof WIKI_ROUTE_SECTION)[keyof typeof WIKI_ROUTE_SECTION];\n\n// Internal action name sent to the server / shown in the View. Diverges\n// from the URL segment in one place only: `lint-report` (URL) vs\n// `lint_report` (action), because the server API still speaks the\n// underscore form.\nexport const WIKI_ACTION = {\n index: \"index\",\n page: \"page\",\n log: \"log\",\n lintReport: \"lint_report\",\n graph: \"graph\",\n save: \"save\",\n} as const;\n\nexport type WikiAction = (typeof WIKI_ACTION)[keyof typeof WIKI_ACTION];\n\n// Route-level representation. `pushWiki(target)` and\n// `readWikiRouteTarget(params)` both speak this so the watcher, the\n// button handlers, and the router guard agree on the same shape.\nexport type WikiTarget = { kind: \"index\" } | { kind: \"page\"; slug: string } | { kind: \"log\" } | { kind: \"lint_report\" } | { kind: \"graph\" };\n\n// Reject anything that could escape `data/wiki/pages/` or collide\n// with a different page. Vue Router decodes `%2F` back to `/` in\n// `route.params.slug`, so `/wiki/pages/..%2Fsecrets` lands here as\n// `slug === \"../secrets\"` — this check is the last line of defence\n// before the slug is passed to the server's page resolver. Non-\n// ASCII characters (e.g. Japanese page titles) are allowed; only\n// separators and the literal `.` / `..` are blocked.\n//\n// Delegates the actual rule to `isSafeSlug` in\n// `src/lib/wiki-page/slug.ts` (imported at the top of this file)\n// so server and frontend share one implementation (#1297). The\n// wrapper adds the type-guard / non-string-input handling the\n// router needs.\nexport function isSafeWikiSlug(value: unknown): value is string {\n return typeof value === \"string\" && isSafeSlug(value);\n}\n\n// Read `route.params` from the wiki route and normalise to a\n// `WikiTarget`. Returns `null` when the params describe an invalid\n// state (unknown section, missing slug for a page view, unsafe slug)\n// so the caller can decide what to do — the router guard redirects to\n// `/wiki`, the view watcher treats it as \"render the index\".\nexport function readWikiRouteTarget(params: unknown): WikiTarget | null {\n if (!params || typeof params !== \"object\") return null;\n const { section, slug } = params as { section?: unknown; slug?: unknown };\n\n if (section === undefined || section === \"\") return { kind: \"index\" };\n\n if (section === WIKI_ROUTE_SECTION.pages) {\n if (!isSafeWikiSlug(slug)) return null;\n return { kind: \"page\", slug };\n }\n if (section === WIKI_ROUTE_SECTION.log) return { kind: \"log\" };\n if (section === WIKI_ROUTE_SECTION.lintReport) return { kind: \"lint_report\" };\n if (section === WIKI_ROUTE_SECTION.graph) return { kind: \"graph\" };\n\n return null;\n}\n\n// Inverse of `readWikiRouteTarget`: given a target, produce the\n// `{ section, slug }` params object that `router.push({ name: \"wiki\",\n// params })` needs.\n//\n// Optional route params are NOT cleared by named-route navigation\n// unless explicitly set — returning `{}` for `kind: \"index\"` would\n// leak the previous `section`/`slug` into the URL when navigating\n// from `/wiki/pages/foo` back to the index, leaving the user on\n// `/wiki/pages/foo` with the View believing it's the index. Pass\n// empty strings so the router writes out `/wiki` cleanly. The\n// readWikiRouteTarget() branch for `section === \"\"` already\n// normalises those back to `{ kind: \"index\" }`.\nexport function buildWikiRouteParams(target: WikiTarget): Record<string, string> {\n switch (target.kind) {\n case \"index\":\n return { section: \"\", slug: \"\" };\n case \"page\":\n return { section: WIKI_ROUTE_SECTION.pages, slug: target.slug };\n case \"log\":\n return { section: WIKI_ROUTE_SECTION.log, slug: \"\" };\n case \"lint_report\":\n return { section: WIKI_ROUTE_SECTION.lintReport, slug: \"\" };\n case \"graph\":\n return { section: WIKI_ROUTE_SECTION.graph, slug: \"\" };\n default: {\n const exhaustive: never = target;\n throw new Error(`unreachable WikiTarget kind: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n\n// Resolve a target to the action name the server expects. Centralises\n// the one place URL-shape and action-shape diverge (`lint-report` ↔\n// `lint_report`).\nexport function wikiActionFor(target: WikiTarget): WikiAction {\n switch (target.kind) {\n case \"index\":\n return WIKI_ACTION.index;\n case \"page\":\n return WIKI_ACTION.page;\n case \"log\":\n return WIKI_ACTION.log;\n case \"lint_report\":\n return WIKI_ACTION.lintReport;\n case \"graph\":\n return WIKI_ACTION.graph;\n default: {\n const exhaustive: never = target;\n throw new Error(`unreachable WikiTarget kind: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n","// Pure `[[wiki-link]]` → HTML renderer, shared across hosts via\n// `@mulmoclaude/core/wiki`. Extracted from the MulmoClaude host's\n// `src/plugins/wiki/helpers.ts` so MulmoTerminal can render the same\n// internal-link markup without forking the walker.\n//\n// String-only, no `marked` / DOM / Node deps — the host pipeline\n// (image-ref rewrite, marked.parse, task-interactive) wraps this.\n\nimport { parseWikiLink } from \"./link.js\";\n\n/** HTML-escape attribute / text content. Self-contained on purpose:\n * this package can't reach the host's escaper, and the rule is a\n * fixed five-char map. */\nexport function escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => {\n switch (char) {\n case \"&\":\n return \"&\";\n case \"<\":\n return \"<\";\n case \">\":\n return \">\";\n case '\"':\n return \""\";\n default:\n return \"'\";\n }\n });\n}\n\n/**\n * Replace every `[[page name]]` occurrence in `content` with a\n * `<span class=\"wiki-link\" data-page=\"…\">…</span>` element. The\n * page name may not contain `]`; an opening `[[` that is not\n * followed later by `]]` (with no bare `]` in between) is left\n * untouched so malformed text renders as-is — matching the\n * previous regex's non-match behaviour.\n *\n * `[[target|display]]` is split via the shared `parseWikiLink`\n * helper so `data-page` carries only the target slug while the\n * visible text shows the display half (#1297). Both halves are\n * HTML-escaped before interpolation — `parseWikiLink` runs BEFORE\n * the host's `marked.parse`, so escaping has to happen here.\n */\nexport function renderWikiLinks(content: string): string {\n const out: string[] = [];\n let i = 0;\n while (i < content.length) {\n if (content[i] === \"[\" && content[i + 1] === \"[\") {\n const closeStart = findNextCloseBrackets(content, i + 2);\n if (closeStart !== -1) {\n const inner = content.slice(i + 2, closeStart);\n const { target, display } = parseWikiLink(inner);\n out.push(`<span class=\"wiki-link\" data-page=\"${escapeHtml(target)}\">${escapeHtml(display)}</span>`);\n i = closeStart + 2;\n continue;\n }\n }\n out.push(content[i]);\n i++;\n }\n return out.join(\"\");\n}\n\n/**\n * Starting at `from`, scan forward for a `]]` sequence. Returns\n * the index of the first `]` of that pair, or -1 if a bare `]`\n * (one not immediately followed by a second `]`) is encountered\n * first — mirroring the old regex's `[^\\]]+` constraint that the\n * page name must contain no `]` characters. Also returns -1 if\n * nothing matched before the end of input, or if the pair sits\n * immediately after `from` (zero-length page name, which the old\n * regex rejected via the `+` quantifier).\n */\nfunction findNextCloseBrackets(str: string, from: number): number {\n let j = from;\n while (j < str.length) {\n if (str[j] === \"]\") {\n if (str[j + 1] === \"]\" && j > from) return j;\n // Bare `]` inside the page-name span — old regex would not\n // match here, so we bail and let the caller emit the `[[`\n // as literal text.\n return -1;\n }\n j++;\n }\n return -1;\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,IAAa,oBAAoB;;;;;;;;;;;;;;;;;;;;AA+BjC,SAAgB,cAAc,OAAyB;CACrD,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AG;CAEhF;AACF;;;;;;AC5HA,SAAgB,WAAW,OAAuB;CAChD,OAAO,MAAM,QAAQ,aAAa,SAAS;EACzC,QAAQ,MAAR;GACE,KAAK,KACH,OAAO;GACT,KAAK,KACH,OAAO;GACT,KAAK,KACH,OAAO;GACT,KAAK,MACH,OAAO;GACT,SACE,OAAO;EACX;CACF,CAAC;AACH;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,SAAyB;CACvD,MAAM,MAAgB,CAAC;CACvB,IAAI,IAAI;CACR,OAAO,IAAI,QAAQ,QAAQ;EACzB,IAAI,QAAQ,OAAO,OAAO,QAAQ,IAAI,OAAO,KAAK;GAChD,MAAM,aAAa,sBAAsB,SAAS,IAAI,CAAC;GACvD,IAAI,eAAe,IAAI;IAErB,MAAM,EAAE,QAAQ,YAAY,cADd,QAAQ,MAAM,IAAI,GAAG,UACO,CAAK;IAC/C,IAAI,KAAK,sCAAsC,WAAW,MAAM,EAAE,IAAI,WAAW,OAAO,EAAE,QAAQ;IAClG,IAAI,aAAa;IACjB;GACF;EACF;EACA,IAAI,KAAK,QAAQ,EAAE;EACnB;CACF;CACA,OAAO,IAAI,KAAK,EAAE;AACpB;;;;;;;;;;;AAYA,SAAS,sBAAsB,KAAa,MAAsB;CAChE,IAAI,IAAI;CACR,OAAO,IAAI,IAAI,QAAQ;EACrB,IAAI,IAAI,OAAO,KAAK;GAClB,IAAI,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,OAAO;GAI3C,OAAO;EACT;EACA;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/wiki/route.ts","../../src/wiki/render.ts"],"sourcesContent":["// Pure helpers for reading, building, and validating wiki route\n// params. Kept free of Vue / vue-router imports so it can be shared\n// across hosts (MulmoClaude + MulmoTerminal) from\n// `@mulmoclaude/core/wiki`:\n//\n// - the host router guard (synchronous validation at navigation time)\n// - the wiki View (watcher + push helpers)\n// - the workspace-link click handler\n// - unit tests\n//\n// Mirrors the \"one file owns the URL ↔ domain mapping\" pattern so the\n// literals don't drift across the router definition, guards, views,\n// and tests.\n\nimport { isSafeSlug } from \"./slug.js\";\n\n// URL segment used in `/wiki/:section/...`. Closed enum — the router\n// regex `(pages|log|lint-report)` rejects anything else.\nexport const WIKI_ROUTE_SECTION = {\n pages: \"pages\",\n log: \"log\",\n lintReport: \"lint-report\",\n graph: \"graph\",\n} as const;\n\nexport type WikiRouteSection = (typeof WIKI_ROUTE_SECTION)[keyof typeof WIKI_ROUTE_SECTION];\n\n// Internal action name sent to the server / shown in the View. Diverges\n// from the URL segment in one place only: `lint-report` (URL) vs\n// `lint_report` (action), because the server API still speaks the\n// underscore form.\nexport const WIKI_ACTION = {\n index: \"index\",\n page: \"page\",\n log: \"log\",\n lintReport: \"lint_report\",\n graph: \"graph\",\n save: \"save\",\n} as const;\n\nexport type WikiAction = (typeof WIKI_ACTION)[keyof typeof WIKI_ACTION];\n\n// Route-level representation. `pushWiki(target)` and\n// `readWikiRouteTarget(params)` both speak this so the watcher, the\n// button handlers, and the router guard agree on the same shape.\nexport type WikiTarget = { kind: \"index\" } | { kind: \"page\"; slug: string } | { kind: \"log\" } | { kind: \"lint_report\" } | { kind: \"graph\" };\n\n// Reject anything that could escape `data/wiki/pages/` or collide\n// with a different page. Vue Router decodes `%2F` back to `/` in\n// `route.params.slug`, so `/wiki/pages/..%2Fsecrets` lands here as\n// `slug === \"../secrets\"` — this check is the last line of defence\n// before the slug is passed to the server's page resolver. Non-\n// ASCII characters (e.g. Japanese page titles) are allowed; only\n// separators and the literal `.` / `..` are blocked.\n//\n// Delegates the actual rule to `isSafeSlug` in\n// `src/lib/wiki-page/slug.ts` (imported at the top of this file)\n// so server and frontend share one implementation (#1297). The\n// wrapper adds the type-guard / non-string-input handling the\n// router needs.\nexport function isSafeWikiSlug(value: unknown): value is string {\n return typeof value === \"string\" && isSafeSlug(value);\n}\n\n// Read `route.params` from the wiki route and normalise to a\n// `WikiTarget`. Returns `null` when the params describe an invalid\n// state (unknown section, missing slug for a page view, unsafe slug)\n// so the caller can decide what to do — the router guard redirects to\n// `/wiki`, the view watcher treats it as \"render the index\".\nexport function readWikiRouteTarget(params: unknown): WikiTarget | null {\n if (!params || typeof params !== \"object\") return null;\n const { section, slug } = params as { section?: unknown; slug?: unknown };\n\n if (section === undefined || section === \"\") return { kind: \"index\" };\n\n if (section === WIKI_ROUTE_SECTION.pages) {\n if (!isSafeWikiSlug(slug)) return null;\n return { kind: \"page\", slug };\n }\n if (section === WIKI_ROUTE_SECTION.log) return { kind: \"log\" };\n if (section === WIKI_ROUTE_SECTION.lintReport) return { kind: \"lint_report\" };\n if (section === WIKI_ROUTE_SECTION.graph) return { kind: \"graph\" };\n\n return null;\n}\n\n// Inverse of `readWikiRouteTarget`: given a target, produce the\n// `{ section, slug }` params object that `router.push({ name: \"wiki\",\n// params })` needs.\n//\n// Optional route params are NOT cleared by named-route navigation\n// unless explicitly set — returning `{}` for `kind: \"index\"` would\n// leak the previous `section`/`slug` into the URL when navigating\n// from `/wiki/pages/foo` back to the index, leaving the user on\n// `/wiki/pages/foo` with the View believing it's the index. Pass\n// empty strings so the router writes out `/wiki` cleanly. The\n// readWikiRouteTarget() branch for `section === \"\"` already\n// normalises those back to `{ kind: \"index\" }`.\nexport function buildWikiRouteParams(target: WikiTarget): Record<string, string> {\n switch (target.kind) {\n case \"index\":\n return { section: \"\", slug: \"\" };\n case \"page\":\n return { section: WIKI_ROUTE_SECTION.pages, slug: target.slug };\n case \"log\":\n return { section: WIKI_ROUTE_SECTION.log, slug: \"\" };\n case \"lint_report\":\n return { section: WIKI_ROUTE_SECTION.lintReport, slug: \"\" };\n case \"graph\":\n return { section: WIKI_ROUTE_SECTION.graph, slug: \"\" };\n default: {\n const exhaustive: never = target;\n throw new Error(`unreachable WikiTarget kind: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n\n// Resolve a target to the action name the server expects. Centralises\n// the one place URL-shape and action-shape diverge (`lint-report` ↔\n// `lint_report`).\nexport function wikiActionFor(target: WikiTarget): WikiAction {\n switch (target.kind) {\n case \"index\":\n return WIKI_ACTION.index;\n case \"page\":\n return WIKI_ACTION.page;\n case \"log\":\n return WIKI_ACTION.log;\n case \"lint_report\":\n return WIKI_ACTION.lintReport;\n case \"graph\":\n return WIKI_ACTION.graph;\n default: {\n const exhaustive: never = target;\n throw new Error(`unreachable WikiTarget kind: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n","// Pure `[[wiki-link]]` → HTML renderer, shared across hosts via\n// `@mulmoclaude/core/wiki`. Extracted from the MulmoClaude host's\n// `src/plugins/wiki/helpers.ts` so MulmoTerminal can render the same\n// internal-link markup without forking the walker.\n//\n// String-only, no `marked` / DOM / Node deps — the host pipeline\n// (image-ref rewrite, marked.parse, task-interactive) wraps this.\n\nimport { parseWikiLink } from \"./link.js\";\n\n/** HTML-escape attribute / text content. Self-contained on purpose:\n * this package can't reach the host's escaper, and the rule is a\n * fixed five-char map. */\nexport function escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => {\n switch (char) {\n case \"&\":\n return \"&\";\n case \"<\":\n return \"<\";\n case \">\":\n return \">\";\n case '\"':\n return \""\";\n default:\n return \"'\";\n }\n });\n}\n\n/**\n * Replace every `[[page name]]` occurrence in `content` with a\n * `<span class=\"wiki-link\" data-page=\"…\">…</span>` element. The\n * page name may not contain `]`; an opening `[[` that is not\n * followed later by `]]` (with no bare `]` in between) is left\n * untouched so malformed text renders as-is — matching the\n * previous regex's non-match behaviour.\n *\n * `[[target|display]]` is split via the shared `parseWikiLink`\n * helper so `data-page` carries only the target slug while the\n * visible text shows the display half (#1297). Both halves are\n * HTML-escaped before interpolation — `parseWikiLink` runs BEFORE\n * the host's `marked.parse`, so escaping has to happen here.\n */\nexport function renderWikiLinks(content: string): string {\n const out: string[] = [];\n let i = 0;\n while (i < content.length) {\n if (content[i] === \"[\" && content[i + 1] === \"[\") {\n const closeStart = findNextCloseBrackets(content, i + 2);\n if (closeStart !== -1) {\n const inner = content.slice(i + 2, closeStart);\n const { target, display } = parseWikiLink(inner);\n out.push(`<span class=\"wiki-link\" data-page=\"${escapeHtml(target)}\">${escapeHtml(display)}</span>`);\n i = closeStart + 2;\n continue;\n }\n }\n out.push(content[i]);\n i++;\n }\n return out.join(\"\");\n}\n\n/**\n * Starting at `from`, scan forward for a `]]` sequence. Returns\n * the index of the first `]` of that pair, or -1 if a bare `]`\n * (one not immediately followed by a second `]`) is encountered\n * first — mirroring the old regex's `[^\\]]+` constraint that the\n * page name must contain no `]` characters. Also returns -1 if\n * nothing matched before the end of input, or if the pair sits\n * immediately after `from` (zero-length page name, which the old\n * regex rejected via the `+` quantifier).\n */\nfunction findNextCloseBrackets(str: string, from: number): number {\n let j = from;\n while (j < str.length) {\n if (str[j] === \"]\") {\n if (str[j + 1] === \"]\" && j > from) return j;\n // Bare `]` inside the page-name span — old regex would not\n // match here, so we bail and let the caller emit the `[[`\n // as literal text.\n return -1;\n }\n j++;\n }\n return -1;\n}\n"],"mappings":";;;AAkBA,IAAa,qBAAqB;CAChC,OAAO;CACP,KAAK;CACL,YAAY;CACZ,OAAO;AACT;AAQA,IAAa,cAAc;CACzB,OAAO;CACP,MAAM;CACN,KAAK;CACL,YAAY;CACZ,OAAO;CACP,MAAM;AACR;AAsBA,SAAgB,eAAe,OAAiC;CAC9D,OAAO,OAAO,UAAU,YAAY,WAAW,KAAK;AACtD;AAOA,SAAgB,oBAAoB,QAAoC;CACtE,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO;CAClD,MAAM,EAAE,SAAS,SAAS;CAE1B,IAAI,YAAY,KAAA,KAAa,YAAY,IAAI,OAAO,EAAE,MAAM,QAAQ;CAEpE,IAAI,YAAY,mBAAmB,OAAO;EACxC,IAAI,CAAC,eAAe,IAAI,GAAG,OAAO;EAClC,OAAO;GAAE,MAAM;GAAQ;EAAK;CAC9B;CACA,IAAI,YAAY,mBAAmB,KAAK,OAAO,EAAE,MAAM,MAAM;CAC7D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AAM,aAAa,sBAAsB,SAAS,IAAI,CAAC;GACvD,IAAI,eAAe,IAAI;IAErB,MAAM,EAAE,QAAQ,YAAY,cADd,QAAQ,MAAM,IAAI,GAAG,UACO,CAAK;IAC/C,IAAI,KAAK,sCAAsC,WAAW,MAAM,EAAE,IAAI,WAAW,OAAO,EAAE,QAAQ;IAClG,IAAI,aAAa;IACjB;GACF;EACF;EACA,IAAI,KAAK,QAAQ,EAAE;EACnB;CACF;CACA,OAAO,IAAI,KAAK,EAAE;AACpB;;;;;;;;;;;AAYA,SAAS,sBAAsB,KAAa,MAAsB;CAChE,IAAI,IAAI;CACR,OAAO,IAAI,IAAI,QAAQ;EACrB,IAAI,IAAI,OAAO,KAAK;GAClB,IAAI,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,OAAO;GAI3C,OAAO;EACT;EACA;CACF;CACA,OAAO;AACT"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_rolldown_runtime = require("../rolldown-runtime-D6vf50IK.cjs");
|
|
3
|
+
const require_slug = require("../slug-DbwORN9z.cjs");
|
|
4
|
+
let node_path = require("node:path");
|
|
5
|
+
node_path = require_rolldown_runtime.__toESM(node_path, 1);
|
|
6
|
+
//#region src/wiki/server/paths.ts
|
|
7
|
+
/** Canonical on-disk layout of a wiki, derived from the workspace
|
|
8
|
+
* root. Owning this here (not per host) is what keeps MulmoClaude and
|
|
9
|
+
* MulmoTerminal agreeing on where `data/wiki/` lives. */
|
|
10
|
+
function wikiDirs(workspace) {
|
|
11
|
+
const root = node_path.default.join(workspace, "data", "wiki");
|
|
12
|
+
return {
|
|
13
|
+
pagesDir: node_path.default.join(root, "pages"),
|
|
14
|
+
indexFile: node_path.default.join(root, "index.md"),
|
|
15
|
+
logFile: node_path.default.join(root, "log.md")
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Given an absolute path and the absolute `pagesDir`, return the
|
|
19
|
+
* slug if `absPath` is a direct `.md` child of `pagesDir`, else
|
|
20
|
+
* null. Pure path-string math — no fs IO, no symlink resolution.
|
|
21
|
+
*
|
|
22
|
+
* Caller responsibility: pass already-realpath'd values for both
|
|
23
|
+
* arguments. Mixing a realpath'd `absPath` with a symlinked
|
|
24
|
+
* `pagesDir` (or vice versa) silently mismatches because
|
|
25
|
+
* `path.relative` is plain string arithmetic. The trap caused
|
|
26
|
+
* #883 review-iter-1 — a symlinked workspace silently routed
|
|
27
|
+
* wiki writes through the generic writer. */
|
|
28
|
+
function wikiSlugFromAbsPath(absPath, pagesDir) {
|
|
29
|
+
const rel = node_path.default.relative(pagesDir, absPath);
|
|
30
|
+
if (rel.length === 0) return null;
|
|
31
|
+
if (node_path.default.isAbsolute(rel)) return null;
|
|
32
|
+
if (rel.includes(node_path.default.sep)) return null;
|
|
33
|
+
if (!rel.endsWith(".md")) return null;
|
|
34
|
+
const slug = rel.slice(0, -3);
|
|
35
|
+
if (!require_slug.isSafeSlug(slug)) return null;
|
|
36
|
+
return slug;
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
exports.wikiDirs = wikiDirs;
|
|
40
|
+
exports.wikiSlugFromAbsPath = wikiSlugFromAbsPath;
|
|
41
|
+
|
|
42
|
+
//# sourceMappingURL=paths.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.cjs","names":[],"sources":["../../src/wiki/server/paths.ts"],"sourcesContent":["// Node-only wiki-page helpers — anything that needs `node:path`\n// lives here so the rest of `@mulmoclaude/core/wiki` stays pure\n// (string-only, importable from both browser and Node bundles).\n// Frontend code MUST NOT import this file directly; use the pure\n// `@mulmoclaude/core/wiki` modules instead.\n\nimport path from \"node:path\";\nimport { isSafeSlug } from \"../slug.js\";\n\n/** Canonical on-disk layout of a wiki, derived from the workspace\n * root. Owning this here (not per host) is what keeps MulmoClaude and\n * MulmoTerminal agreeing on where `data/wiki/` lives. */\nexport function wikiDirs(workspace: string): { pagesDir: string; indexFile: string; logFile: string } {\n const root = path.join(workspace, \"data\", \"wiki\");\n return {\n pagesDir: path.join(root, \"pages\"),\n indexFile: path.join(root, \"index.md\"),\n logFile: path.join(root, \"log.md\"),\n };\n}\n\n/** Given an absolute path and the absolute `pagesDir`, return the\n * slug if `absPath` is a direct `.md` child of `pagesDir`, else\n * null. Pure path-string math — no fs IO, no symlink resolution.\n *\n * Caller responsibility: pass already-realpath'd values for both\n * arguments. Mixing a realpath'd `absPath` with a symlinked\n * `pagesDir` (or vice versa) silently mismatches because\n * `path.relative` is plain string arithmetic. The trap caused\n * #883 review-iter-1 — a symlinked workspace silently routed\n * wiki writes through the generic writer. */\nexport function wikiSlugFromAbsPath(absPath: string, pagesDir: string): string | null {\n const rel = path.relative(pagesDir, absPath);\n if (rel.length === 0) return null;\n if (path.isAbsolute(rel)) return null;\n // Direct child only — no nested layout today. Any separator\n // means the path either escapes (`../secret.md`) or descends\n // (`subdir/foo.md`). A literal page name like `..foo.md` is a\n // single segment without a separator and is allowed (codex\n // iter-3 #883 — the prior `startsWith(\"..\")` rule wrongly\n // rejected it).\n if (rel.includes(path.sep)) return null;\n if (!rel.endsWith(\".md\")) return null;\n const slug = rel.slice(0, -\".md\".length);\n if (!isSafeSlug(slug)) return null;\n return slug;\n}\n"],"mappings":";;;;;;;;;AAYA,SAAgB,SAAS,WAA6E;CACpG,MAAM,OAAO,UAAA,QAAK,KAAK,WAAW,QAAQ,MAAM;CAChD,OAAO;EACL,UAAU,UAAA,QAAK,KAAK,MAAM,OAAO;EACjC,WAAW,UAAA,QAAK,KAAK,MAAM,UAAU;EACrC,SAAS,UAAA,QAAK,KAAK,MAAM,QAAQ;CACnC;AACF;;;;;;;;;;;AAYA,SAAgB,oBAAoB,SAAiB,UAAiC;CACpF,MAAM,MAAM,UAAA,QAAK,SAAS,UAAU,OAAO;CAC3C,IAAI,IAAI,WAAW,GAAG,OAAO;CAC7B,IAAI,UAAA,QAAK,WAAW,GAAG,GAAG,OAAO;CAOjC,IAAI,IAAI,SAAS,UAAA,QAAK,GAAG,GAAG,OAAO;CACnC,IAAI,CAAC,IAAI,SAAS,KAAK,GAAG,OAAO;CACjC,MAAM,OAAO,IAAI,MAAM,GAAG,EAAa;CACvC,IAAI,CAAC,aAAA,WAAW,IAAI,GAAG,OAAO;CAC9B,OAAO;AACT"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { t as isSafeSlug } from "../slug-CdN-pQX1.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
//#region src/wiki/server/paths.ts
|
|
4
|
+
/** Canonical on-disk layout of a wiki, derived from the workspace
|
|
5
|
+
* root. Owning this here (not per host) is what keeps MulmoClaude and
|
|
6
|
+
* MulmoTerminal agreeing on where `data/wiki/` lives. */
|
|
7
|
+
function wikiDirs(workspace) {
|
|
8
|
+
const root = path.join(workspace, "data", "wiki");
|
|
9
|
+
return {
|
|
10
|
+
pagesDir: path.join(root, "pages"),
|
|
11
|
+
indexFile: path.join(root, "index.md"),
|
|
12
|
+
logFile: path.join(root, "log.md")
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** Given an absolute path and the absolute `pagesDir`, return the
|
|
16
|
+
* slug if `absPath` is a direct `.md` child of `pagesDir`, else
|
|
17
|
+
* null. Pure path-string math — no fs IO, no symlink resolution.
|
|
18
|
+
*
|
|
19
|
+
* Caller responsibility: pass already-realpath'd values for both
|
|
20
|
+
* arguments. Mixing a realpath'd `absPath` with a symlinked
|
|
21
|
+
* `pagesDir` (or vice versa) silently mismatches because
|
|
22
|
+
* `path.relative` is plain string arithmetic. The trap caused
|
|
23
|
+
* #883 review-iter-1 — a symlinked workspace silently routed
|
|
24
|
+
* wiki writes through the generic writer. */
|
|
25
|
+
function wikiSlugFromAbsPath(absPath, pagesDir) {
|
|
26
|
+
const rel = path.relative(pagesDir, absPath);
|
|
27
|
+
if (rel.length === 0) return null;
|
|
28
|
+
if (path.isAbsolute(rel)) return null;
|
|
29
|
+
if (rel.includes(path.sep)) return null;
|
|
30
|
+
if (!rel.endsWith(".md")) return null;
|
|
31
|
+
const slug = rel.slice(0, -3);
|
|
32
|
+
if (!isSafeSlug(slug)) return null;
|
|
33
|
+
return slug;
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
export { wikiDirs, wikiSlugFromAbsPath };
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=paths.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.js","names":[],"sources":["../../src/wiki/server/paths.ts"],"sourcesContent":["// Node-only wiki-page helpers — anything that needs `node:path`\n// lives here so the rest of `@mulmoclaude/core/wiki` stays pure\n// (string-only, importable from both browser and Node bundles).\n// Frontend code MUST NOT import this file directly; use the pure\n// `@mulmoclaude/core/wiki` modules instead.\n\nimport path from \"node:path\";\nimport { isSafeSlug } from \"../slug.js\";\n\n/** Canonical on-disk layout of a wiki, derived from the workspace\n * root. Owning this here (not per host) is what keeps MulmoClaude and\n * MulmoTerminal agreeing on where `data/wiki/` lives. */\nexport function wikiDirs(workspace: string): { pagesDir: string; indexFile: string; logFile: string } {\n const root = path.join(workspace, \"data\", \"wiki\");\n return {\n pagesDir: path.join(root, \"pages\"),\n indexFile: path.join(root, \"index.md\"),\n logFile: path.join(root, \"log.md\"),\n };\n}\n\n/** Given an absolute path and the absolute `pagesDir`, return the\n * slug if `absPath` is a direct `.md` child of `pagesDir`, else\n * null. Pure path-string math — no fs IO, no symlink resolution.\n *\n * Caller responsibility: pass already-realpath'd values for both\n * arguments. Mixing a realpath'd `absPath` with a symlinked\n * `pagesDir` (or vice versa) silently mismatches because\n * `path.relative` is plain string arithmetic. The trap caused\n * #883 review-iter-1 — a symlinked workspace silently routed\n * wiki writes through the generic writer. */\nexport function wikiSlugFromAbsPath(absPath: string, pagesDir: string): string | null {\n const rel = path.relative(pagesDir, absPath);\n if (rel.length === 0) return null;\n if (path.isAbsolute(rel)) return null;\n // Direct child only — no nested layout today. Any separator\n // means the path either escapes (`../secret.md`) or descends\n // (`subdir/foo.md`). A literal page name like `..foo.md` is a\n // single segment without a separator and is allowed (codex\n // iter-3 #883 — the prior `startsWith(\"..\")` rule wrongly\n // rejected it).\n if (rel.includes(path.sep)) return null;\n if (!rel.endsWith(\".md\")) return null;\n const slug = rel.slice(0, -\".md\".length);\n if (!isSafeSlug(slug)) return null;\n return slug;\n}\n"],"mappings":";;;;;;AAYA,SAAgB,SAAS,WAA6E;CACpG,MAAM,OAAO,KAAK,KAAK,WAAW,QAAQ,MAAM;CAChD,OAAO;EACL,UAAU,KAAK,KAAK,MAAM,OAAO;EACjC,WAAW,KAAK,KAAK,MAAM,UAAU;EACrC,SAAS,KAAK,KAAK,MAAM,QAAQ;CACnC;AACF;;;;;;;;;;;AAYA,SAAgB,oBAAoB,SAAiB,UAAiC;CACpF,MAAM,MAAM,KAAK,SAAS,UAAU,OAAO;CAC3C,IAAI,IAAI,WAAW,GAAG,OAAO;CAC7B,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;CAOjC,IAAI,IAAI,SAAS,KAAK,GAAG,GAAG,OAAO;CACnC,IAAI,CAAC,IAAI,SAAS,KAAK,GAAG,OAAO;CACjC,MAAM,OAAO,IAAI,MAAM,GAAG,EAAa;CACvC,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,OAAO;AACT"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { WikiPageEntry } from '../index-parse.js';
|
|
2
|
+
import { WikiGraph } from '../graph.js';
|
|
3
|
+
/** Walk every indexed slug for an `includes`-style match. Returns the
|
|
4
|
+
* single best candidate, or null when the slug is too short OR several
|
|
5
|
+
* candidates tie at the top score (ambiguous → defer to the caller's
|
|
6
|
+
* title-match fallback). Score = min/max length, decoupled from Map
|
|
7
|
+
* iteration order so resolution is deterministic across hosts. */
|
|
8
|
+
export declare function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null;
|
|
9
|
+
/** Resolve a page name to an absolute `.md` path: exact slug → fuzzy →
|
|
10
|
+
* index-title fallback (for non-ASCII names that slugify to empty).
|
|
11
|
+
* `pageName` may carry the `[[target|display]]` form; `parseWikiLink`
|
|
12
|
+
* strips the display half so the lookup uses just the target. */
|
|
13
|
+
export declare function resolvePagePath(workspace: string, pageName: string): Promise<string | null>;
|
|
14
|
+
/** Raw `index.md` content + its parsed entries. */
|
|
15
|
+
export declare function readWikiIndex(workspace: string): {
|
|
16
|
+
content: string;
|
|
17
|
+
entries: WikiPageEntry[];
|
|
18
|
+
};
|
|
19
|
+
/** Raw `log.md` content (empty string if absent). */
|
|
20
|
+
export declare function readWikiLog(workspace: string): string;
|
|
21
|
+
export interface WikiPageRead {
|
|
22
|
+
/** Absolute path of the resolved file, or null when nothing matched. */
|
|
23
|
+
filePath: string | null;
|
|
24
|
+
/** File body (empty when missing OR when the file is an empty placeholder). */
|
|
25
|
+
content: string;
|
|
26
|
+
/** True iff a page file resolved (distinct from empty content). */
|
|
27
|
+
exists: boolean;
|
|
28
|
+
/** Title to display — the resolved filename stem, or the raw pageName. */
|
|
29
|
+
resolvedTitle: string;
|
|
30
|
+
}
|
|
31
|
+
/** Resolve + read a page. Distinguishes missing (`exists: false`) from
|
|
32
|
+
* empty-but-present (`exists: true`, `content: ""`). */
|
|
33
|
+
export declare function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead>;
|
|
34
|
+
/** Read every page + the index and build the page→page link graph.
|
|
35
|
+
* No cache: the graph is requested explicitly and a content edit does
|
|
36
|
+
* not advance the pagesDir mtime the page index caches on. */
|
|
37
|
+
export declare function loadWikiGraph(workspace: string): Promise<WikiGraph>;
|
|
38
|
+
/** Run every lint rule over the on-disk wiki, returning issue strings. */
|
|
39
|
+
export declare function collectLintIssues(workspace: string): Promise<string[]>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Parse `---\n…\n---\n` frontmatter. Never throws; malformed YAML in a
|
|
2
|
+
* well-formed envelope yields `{ meta: {}, hasHeader: false }`. */
|
|
3
|
+
export declare function parseFrontmatter(raw: string): {
|
|
4
|
+
meta: Record<string, unknown>;
|
|
5
|
+
hasHeader: boolean;
|
|
6
|
+
};
|
|
7
|
+
/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list
|
|
8
|
+
* style; anything unparseable returns `[]` (best-effort, never throws). */
|
|
9
|
+
export declare function parseFrontmatterTags(content: string): string[];
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Dirent, Stats } from 'node:fs';
|
|
2
|
+
export declare function readTextSafe(absPath: string): Promise<string | null>;
|
|
3
|
+
export declare function readTextSafeSync(absPath: string): string | null;
|
|
4
|
+
export declare function statSafeAsync(absPath: string): Promise<Stats | null>;
|
|
5
|
+
export declare function readDirSafeAsync(absPath: string): Promise<Dirent[]>;
|