@mulmoclaude/core 0.2.16 → 0.4.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.
@@ -0,0 +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 \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\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;CACr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GAAG;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"}
@@ -0,0 +1,41 @@
1
+ /** Inline `[[...]]` link pattern. The capture group is the raw
2
+ * text between the brackets — the caller is expected to feed it
3
+ * through `parseWikiLink` to split off any `|display` suffix.
4
+ *
5
+ * Body length is capped at 200 chars to keep the regex linear:
6
+ * catastrophic backtracking isn't possible (no nested
7
+ * alternation), but a malicious page with thousands of
8
+ * unmatched `[[` could still pin the CPU. 200 is well above the
9
+ * longest legitimate title we've seen and matches the cap the
10
+ * server-side `WIKI_LINK_PATTERN` constant has carried since the
11
+ * original implementation in #951. */
12
+ export declare const WIKI_LINK_PATTERN: RegExp;
13
+ /** The structural shape of an inline `[[target|display]]` link.
14
+ * `target` is what the resolver / lint compares against page
15
+ * slugs; `display` is what the renderer shows to the user.
16
+ * When the user writes `[[foo]]` (no pipe), both fields hold
17
+ * `foo`. */
18
+ export interface WikiLink {
19
+ target: string;
20
+ display: string;
21
+ }
22
+ /** Split the raw text inside `[[...]]` into target + display.
23
+ *
24
+ * - `[[foo|Bar Baz]]` → `{ target: "foo", display: "Bar Baz" }`
25
+ * - `[[foo]]` → `{ target: "foo", display: "foo" }`
26
+ * - `[[|empty target]]` → `{ target: "", display: "empty target" }`
27
+ * (caller decides whether an empty target is meaningful;
28
+ * typically lint flags it, renderer shows the display text raw)
29
+ * - `[[foo|]]` → `{ target: "foo", display: "" }`
30
+ * (same — caller decides)
31
+ *
32
+ * Whitespace around the pipe is preserved on the display side
33
+ * (so the user can write `[[foo| ある記事 ]]` and get the
34
+ * spacing intentionally) but TRIMMED on the target side, since
35
+ * a slug-comparable target with leading/trailing whitespace is
36
+ * always a typo.
37
+ *
38
+ * Only the FIRST pipe splits. `[[a|b|c]]` becomes
39
+ * `{ target: "a", display: "b|c" }` so display strings can
40
+ * legitimately contain a literal `|`. */
41
+ export declare function parseWikiLink(inner: string): WikiLink;
@@ -0,0 +1,26 @@
1
+ import { WikiPageEntry } from './index-parse.js';
2
+ /** Files on disk that aren't referenced by index.md. */
3
+ export declare function findOrphanPages(fileSlugs: ReadonlySet<string>, indexedSlugs: ReadonlySet<string>): string[];
4
+ /** Slugs referenced by index.md that have no corresponding file. */
5
+ export declare function findMissingFiles(pageEntries: readonly WikiPageEntry[], fileSlugs: ReadonlySet<string>): string[];
6
+ /** Walk a page's body for `[[…]]` links and flag any whose
7
+ * resolved slug doesn't exist in the file set.
8
+ *
9
+ * Critically: this routes through `parseWikiLink` so
10
+ * `[[slug|display]]` is split correctly — the lint slugifies the
11
+ * TARGET, not the full bracket body. Pre-#1297 the lint
12
+ * slugified the entire content (`slug|display`), which collapsed
13
+ * to a slug that always missed and produced ~168 false-positive
14
+ * "broken link" warnings. */
15
+ export declare function findBrokenLinksInPage(fileName: string, content: string, fileSlugs: ReadonlySet<string>): string[];
16
+ /** Flag any slug whose index.md tags differ from the page's own
17
+ * frontmatter `tags:` field. Comparison is set-based and order-
18
+ * insensitive; both sides are lowercased at parse time. Slugs
19
+ * missing from `frontmatterTagsBySlug` are ignored here — the
20
+ * missing file itself is already reported by `findMissingFiles`. */
21
+ export declare function findTagDrift(pageEntries: readonly WikiPageEntry[], frontmatterTagsBySlug: ReadonlyMap<string, readonly string[]>): string[];
22
+ /** Render the final markdown report from the accumulated issues
23
+ * list. Empty input yields the "wiki is healthy" sentinel so the
24
+ * caller can write the same file every time without branching on
25
+ * presence. */
26
+ export declare function formatLintReport(issues: readonly string[]): string;
@@ -0,0 +1,19 @@
1
+ /** HTML-escape attribute / text content. Self-contained on purpose:
2
+ * this package can't reach the host's escaper, and the rule is a
3
+ * fixed five-char map. */
4
+ export declare function escapeHtml(value: string): string;
5
+ /**
6
+ * Replace every `[[page name]]` occurrence in `content` with a
7
+ * `<span class="wiki-link" data-page="…">…</span>` element. The
8
+ * page name may not contain `]`; an opening `[[` that is not
9
+ * followed later by `]]` (with no bare `]` in between) is left
10
+ * untouched so malformed text renders as-is — matching the
11
+ * previous regex's non-match behaviour.
12
+ *
13
+ * `[[target|display]]` is split via the shared `parseWikiLink`
14
+ * helper so `data-page` carries only the target slug while the
15
+ * visible text shows the display half (#1297). Both halves are
16
+ * HTML-escaped before interpolation — `parseWikiLink` runs BEFORE
17
+ * the host's `marked.parse`, so escaping has to happen here.
18
+ */
19
+ export declare function renderWikiLinks(content: string): string;
@@ -0,0 +1,32 @@
1
+ export declare const WIKI_ROUTE_SECTION: {
2
+ readonly pages: "pages";
3
+ readonly log: "log";
4
+ readonly lintReport: "lint-report";
5
+ readonly graph: "graph";
6
+ };
7
+ export type WikiRouteSection = (typeof WIKI_ROUTE_SECTION)[keyof typeof WIKI_ROUTE_SECTION];
8
+ export declare const WIKI_ACTION: {
9
+ readonly index: "index";
10
+ readonly page: "page";
11
+ readonly log: "log";
12
+ readonly lintReport: "lint_report";
13
+ readonly graph: "graph";
14
+ readonly save: "save";
15
+ };
16
+ export type WikiAction = (typeof WIKI_ACTION)[keyof typeof WIKI_ACTION];
17
+ export type WikiTarget = {
18
+ kind: "index";
19
+ } | {
20
+ kind: "page";
21
+ slug: string;
22
+ } | {
23
+ kind: "log";
24
+ } | {
25
+ kind: "lint_report";
26
+ } | {
27
+ kind: "graph";
28
+ };
29
+ export declare function isSafeWikiSlug(value: unknown): value is string;
30
+ export declare function readWikiRouteTarget(params: unknown): WikiTarget | null;
31
+ export declare function buildWikiRouteParams(target: WikiTarget): Record<string, string>;
32
+ export declare function wikiActionFor(target: WikiTarget): WikiAction;
@@ -0,0 +1,30 @@
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
+ /** Given an absolute path and the absolute `pagesDir`, return the
8
+ * slug if `absPath` is a direct `.md` child of `pagesDir`, else
9
+ * null. Pure path-string math — no fs IO, no symlink resolution.
10
+ *
11
+ * Caller responsibility: pass already-realpath'd values for both
12
+ * arguments. Mixing a realpath'd `absPath` with a symlinked
13
+ * `pagesDir` (or vice versa) silently mismatches because
14
+ * `path.relative` is plain string arithmetic. The trap caused
15
+ * #883 review-iter-1 — a symlinked workspace silently routed
16
+ * wiki writes through the generic writer. */
17
+ function wikiSlugFromAbsPath(absPath, pagesDir) {
18
+ const rel = node_path.default.relative(pagesDir, absPath);
19
+ if (rel.length === 0) return null;
20
+ if (node_path.default.isAbsolute(rel)) return null;
21
+ if (rel.includes(node_path.default.sep)) return null;
22
+ if (!rel.endsWith(".md")) return null;
23
+ const slug = rel.slice(0, -3);
24
+ if (!require_slug.isSafeSlug(slug)) return null;
25
+ return slug;
26
+ }
27
+ //#endregion
28
+ exports.wikiSlugFromAbsPath = wikiSlugFromAbsPath;
29
+
30
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.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/** 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":";;;;;;;;;;;;;;;;AAmBA,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 @@
1
+ export { wikiSlugFromAbsPath } from './paths.js';
@@ -0,0 +1,27 @@
1
+ import { t as isSafeSlug } from "../../slug-CdN-pQX1.js";
2
+ import path from "node:path";
3
+ //#region src/wiki/server/paths.ts
4
+ /** Given an absolute path and the absolute `pagesDir`, return the
5
+ * slug if `absPath` is a direct `.md` child of `pagesDir`, else
6
+ * null. Pure path-string math — no fs IO, no symlink resolution.
7
+ *
8
+ * Caller responsibility: pass already-realpath'd values for both
9
+ * arguments. Mixing a realpath'd `absPath` with a symlinked
10
+ * `pagesDir` (or vice versa) silently mismatches because
11
+ * `path.relative` is plain string arithmetic. The trap caused
12
+ * #883 review-iter-1 — a symlinked workspace silently routed
13
+ * wiki writes through the generic writer. */
14
+ function wikiSlugFromAbsPath(absPath, pagesDir) {
15
+ const rel = path.relative(pagesDir, absPath);
16
+ if (rel.length === 0) return null;
17
+ if (path.isAbsolute(rel)) return null;
18
+ if (rel.includes(path.sep)) return null;
19
+ if (!rel.endsWith(".md")) return null;
20
+ const slug = rel.slice(0, -3);
21
+ if (!isSafeSlug(slug)) return null;
22
+ return slug;
23
+ }
24
+ //#endregion
25
+ export { wikiSlugFromAbsPath };
26
+
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.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/** 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":";;;;;;;;;;;;;AAmBA,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,11 @@
1
+ /** Given an absolute path and the absolute `pagesDir`, return the
2
+ * slug if `absPath` is a direct `.md` child of `pagesDir`, else
3
+ * null. Pure path-string math — no fs IO, no symlink resolution.
4
+ *
5
+ * Caller responsibility: pass already-realpath'd values for both
6
+ * arguments. Mixing a realpath'd `absPath` with a symlinked
7
+ * `pagesDir` (or vice versa) silently mismatches because
8
+ * `path.relative` is plain string arithmetic. The trap caused
9
+ * #883 review-iter-1 — a symlinked workspace silently routed
10
+ * wiki writes through the generic writer. */
11
+ export declare function wikiSlugFromAbsPath(absPath: string, pagesDir: string): string | null;
@@ -0,0 +1,24 @@
1
+ /** Reject slugs that would escape `data/wiki/pages/` once
2
+ * joined back into a path, or that are otherwise invalid as
3
+ * page filenames. The chokepoint must defend itself even when
4
+ * callers derive the slug from a trusted source — a typo or
5
+ * future caller mistake should fail loud, not silently write
6
+ * outside the wiki tree.
7
+ *
8
+ * The rule is intentionally narrow — separators / `..` / NUL /
9
+ * empty — so it only rejects unambiguous violations. Aesthetic
10
+ * concerns (e.g. dot-prefixed filenames) are out of scope: a
11
+ * pre-existing `data/wiki/pages/.foo.md` should remain writable
12
+ * through the chokepoint (codex review iter-2 #883). */
13
+ export declare function isSafeSlug(slug: string): boolean;
14
+ /** Slug rules for `[[wiki link]]` text → slug derivation:
15
+ * lowercase, spaces collapsed to hyphens, every non-ASCII /
16
+ * non-alphanumeric / non-hyphen character stripped.
17
+ *
18
+ * Pure: no normalisation, no transliteration — this is the
19
+ * same shape the index parser, page resolver, and frontend
20
+ * renderer all need to agree on. Non-ASCII titles (e.g.
21
+ * Japanese) collapse to an empty string here; callers fall back
22
+ * to other strategies (title-match in the index, or the agent
23
+ * pre-resolving to a slug-form target via `[[slug|display]]`). */
24
+ export declare function wikiSlugify(text: string): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mulmoclaude/core",
3
- "version": "0.2.16",
3
+ "version": "0.4.0",
4
4
  "description": "Shared server-side core for MulmoClaude and MulmoTerminal — the always-shipped-together subsystems consolidated behind subpath exports so the two hosts can't drift. Server-only except the browser-safe ./whisper/client, ./workspace-setup/slug and ./translation/client entries. All host specifics are injected.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -34,6 +34,18 @@
34
34
  "require": "./dist/collection/registry/server/index.cjs",
35
35
  "default": "./dist/collection/registry/server/index.js"
36
36
  },
37
+ "./wiki": {
38
+ "types": "./dist/wiki/index.d.ts",
39
+ "import": "./dist/wiki/index.js",
40
+ "require": "./dist/wiki/index.cjs",
41
+ "default": "./dist/wiki/index.js"
42
+ },
43
+ "./wiki/server": {
44
+ "types": "./dist/wiki/server/index.d.ts",
45
+ "import": "./dist/wiki/server/index.js",
46
+ "require": "./dist/wiki/server/index.cjs",
47
+ "default": "./dist/wiki/server/index.js"
48
+ },
37
49
  "./feeds": {
38
50
  "types": "./dist/feeds/index.d.ts",
39
51
  "import": "./dist/feeds/index.js",