@mulmoclaude/core 1.14.0 → 1.14.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/atomic-C_7YpMiM.cjs.map +1 -1
- package/dist/atomic-DPpdrJzO.js.map +1 -1
- package/dist/{calendarGrid-DivcNKkX.js → calendarGrid-Csy2rpjp.js} +58 -28
- package/dist/{calendarGrid-DivcNKkX.js.map → calendarGrid-Csy2rpjp.js.map} +1 -1
- package/dist/{calendarGrid-BQYqOCnF.cjs → calendarGrid-p8K-7cuB.cjs} +58 -28
- package/dist/{calendarGrid-BQYqOCnF.cjs.map → calendarGrid-p8K-7cuB.cjs.map} +1 -1
- package/dist/collection/core/actionVisible.d.ts +3 -3
- package/dist/collection/core/completion.d.ts +5 -5
- package/dist/collection/index.cjs +5 -8
- package/dist/collection/index.cjs.map +1 -1
- package/dist/collection/index.js +5 -8
- package/dist/collection/index.js.map +1 -1
- package/dist/collection/registry/registryIndex.d.ts +1 -1
- package/dist/collection/registry/server/index.cjs +14 -12
- package/dist/collection/registry/server/index.cjs.map +1 -1
- package/dist/collection/registry/server/index.js +14 -12
- package/dist/collection/registry/server/index.js.map +1 -1
- package/dist/collection/server/discovery.d.ts +2 -2
- package/dist/collection/server/index.cjs +3 -3
- package/dist/collection/server/index.js +3 -3
- package/dist/collection/server/io.d.ts +3 -3
- package/dist/collection/server/manageTool.d.ts +3 -3
- package/dist/collection/server/store.d.ts +3 -3
- package/dist/collection/server/validate.d.ts +1 -1
- package/dist/collection-watchers/index.cjs +5 -5
- package/dist/collection-watchers/index.js +5 -5
- package/dist/{discovery-D6p4ITNR.js → discovery-BSedPW8A.js} +14 -6
- package/dist/discovery-BSedPW8A.js.map +1 -0
- package/dist/{discovery-CRDx6TS4.cjs → discovery-DSLgRQhN.cjs} +14 -6
- package/dist/discovery-DSLgRQhN.cjs.map +1 -0
- package/dist/feeds/index.cjs +2 -2
- package/dist/feeds/index.js +2 -2
- package/dist/feeds/server/host.d.ts +2 -2
- package/dist/feeds/server/index.cjs +11 -11
- package/dist/feeds/server/index.cjs.map +1 -1
- package/dist/feeds/server/index.js +11 -11
- package/dist/feeds/server/index.js.map +1 -1
- package/dist/feeds/server/refreshResult.d.ts +2 -2
- package/dist/files/index.cjs +3 -2
- package/dist/files/index.cjs.map +1 -1
- package/dist/files/index.js +3 -2
- package/dist/files/index.js.map +1 -1
- package/dist/google/calendar.d.ts +24 -24
- package/dist/google/collectionSync.d.ts +2 -2
- package/dist/google/index.cjs +3 -3
- package/dist/google/index.cjs.map +1 -1
- package/dist/google/index.js +3 -3
- package/dist/google/index.js.map +1 -1
- package/dist/{graph-DjE1Az1C.cjs → graph-BZJxiv1E.cjs} +10 -12
- package/dist/graph-BZJxiv1E.cjs.map +1 -0
- package/dist/{graph-BcwqiSpR.js → graph-Ce7xsDTt.js} +10 -12
- package/dist/graph-Ce7xsDTt.js.map +1 -0
- package/dist/{ingestTypes-C7IJSqv4.cjs → ingestTypes-CPR-h-OZ.cjs} +2 -2
- package/dist/{ingestTypes-C7IJSqv4.cjs.map → ingestTypes-CPR-h-OZ.cjs.map} +1 -1
- package/dist/{ingestTypes-DmtDLRmt.js → ingestTypes-F2IJhOLJ.js} +2 -2
- package/dist/{ingestTypes-DmtDLRmt.js.map → ingestTypes-F2IJhOLJ.js.map} +1 -1
- package/dist/notifier/index.cjs +1 -1
- package/dist/notifier/index.js +1 -1
- package/dist/notifier/types.d.ts +4 -4
- package/dist/{notifier-Wc4M24Bi.cjs → notifier-CKFVVwDP.cjs} +35 -24
- package/dist/notifier-CKFVVwDP.cjs.map +1 -0
- package/dist/{notifier-Dxh8mEFh.js → notifier-CQD8NljP.js} +35 -24
- package/dist/notifier-CQD8NljP.js.map +1 -0
- package/dist/{promptSafety-B52GvaJc.cjs → promptSafety-DUZ5BiW5.cjs} +11 -7
- package/dist/promptSafety-DUZ5BiW5.cjs.map +1 -0
- package/dist/{promptSafety-DJgaDjM4.js → promptSafety-DgHMF4Pz.js} +11 -7
- package/dist/promptSafety-DgHMF4Pz.js.map +1 -0
- package/dist/remote-host/server/hostRunner.d.ts +7 -2
- package/dist/remote-host/server/index.cjs +12 -9
- package/dist/remote-host/server/index.cjs.map +1 -1
- package/dist/remote-host/server/index.js +13 -10
- package/dist/remote-host/server/index.js.map +1 -1
- package/dist/remote-view/index.cjs.map +1 -1
- package/dist/remote-view/index.d.ts +1 -1
- package/dist/remote-view/index.js.map +1 -1
- package/dist/scheduler/adapter.d.ts +4 -4
- package/dist/scheduler/index.cjs +34 -2
- package/dist/scheduler/index.cjs.map +1 -1
- package/dist/scheduler/index.js +34 -2
- package/dist/scheduler/index.js.map +1 -1
- package/dist/scheduler/task-manager.d.ts +2 -2
- package/dist/{server-D7_oRbTJ.cjs → server-1c6gB372.cjs} +12 -8
- package/dist/server-1c6gB372.cjs.map +1 -0
- package/dist/{server-D6EUf3BF.js → server-Dv_L7l0y.js} +12 -8
- package/dist/server-Dv_L7l0y.js.map +1 -0
- package/dist/skill-bridge/index.cjs +3 -4
- package/dist/skill-bridge/index.cjs.map +1 -1
- package/dist/skill-bridge/index.js +3 -4
- package/dist/skill-bridge/index.js.map +1 -1
- package/dist/types-BKVZrtyc.js.map +1 -1
- package/dist/types-CNqkLT4M.cjs.map +1 -1
- package/dist/utils/fetch.cjs.map +1 -1
- package/dist/utils/fetch.d.ts +1 -1
- package/dist/utils/fetch.js.map +1 -1
- package/dist/whisper/client.cjs.map +1 -1
- package/dist/whisper/client.d.ts +3 -3
- package/dist/whisper/client.js.map +1 -1
- package/dist/wiki/index.cjs +2 -2
- package/dist/wiki/index.cjs.map +1 -1
- package/dist/wiki/index.js +2 -2
- package/dist/wiki/index.js.map +1 -1
- package/dist/wiki/server/index.cjs +15 -12
- package/dist/wiki/server/index.cjs.map +1 -1
- package/dist/wiki/server/index.js +15 -12
- package/dist/wiki/server/index.js.map +1 -1
- package/package.json +6 -6
- package/dist/discovery-CRDx6TS4.cjs.map +0 -1
- package/dist/discovery-D6p4ITNR.js.map +0 -1
- package/dist/graph-BcwqiSpR.js.map +0 -1
- package/dist/graph-DjE1Az1C.cjs.map +0 -1
- package/dist/notifier-Dxh8mEFh.js.map +0 -1
- package/dist/notifier-Wc4M24Bi.cjs.map +0 -1
- package/dist/promptSafety-B52GvaJc.cjs.map +0 -1
- package/dist/promptSafety-DJgaDjM4.js.map +0 -1
- package/dist/server-D6EUf3BF.js.map +0 -1
- package/dist/server-D7_oRbTJ.cjs.map +0 -1
package/dist/wiki/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","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 { isRecord } from \"@mulmoclaude/common\";\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 (!isRecord(params)) return null;\n const { section, slug } = params;\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 { escapeHtml } from \"@mulmoclaude/common\";\nimport { parseWikiLink, WIKI_LINK_MAX_LEN } from \"./link.js\";\n\n// `escapeHtml` moved down to the zero-dep leaf `@mulmoclaude/common` (#2483) so\n// `@mulmoclaude/markdown-utils` — a leaf THIS package depends on, hence unable\n// to import back up — can share it. Re-exported here because the wiki\n// consumers (collection-plugin's graph view, the host's wiki embeds and\n// spreadsheet view) already import it from `@mulmoclaude/core/wiki`.\nexport { escapeHtml };\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 `[` or `]`; an opening `[[` that is\n * not followed later by `]]` (with no bare `[` or `]` in between)\n * is left 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 the span isn't\n * a valid wiki-link body — mirroring `WIKI_LINK_PATTERN` exactly so\n * the renderer can't accept a link the graph / backlinks / lint\n * would reject. The pattern's body class is `[^\\][\\r\\n]`, so it\n * rejects `[` as well as `]`. Bails (-1) on:\n * - a bare `]` (regex `[^\\]]`),\n * - a `[` inside the body (regex `[^\\[]` — a nested `[[` opener\n * never belongs in a page name, and the pattern would not match),\n * - a `\\r` or `\\n` (regex `[^\\r\\n]` — a newline-bearing link must\n * not render clickable, and its slug must not reach the URL),\n * - a body longer than WIKI_LINK_MAX_LEN (regex `{1,200}`),\n * - a zero-length body (regex `{1,}` minimum),\n * - reaching end-of-input with no `]]`.\n */\nfunction findNextCloseBrackets(str: string, from: number): number {\n let j = from;\n while (j < str.length) {\n const char = str[j];\n if (char === \"]\") {\n if (str[j + 1] === \"]\" && j > from) return j;\n // Bare `]` inside the page-name span — regex would not match.\n return -1;\n }\n // A `[`, a newline, or a span past the cap: none match the pattern's\n // `[^\\][\\r\\n]{1,200}` body, so bail and let the caller emit `[[` literally.\n if (char === \"[\" || char === \"\\n\" || char === \"\\r\" || j - from >= WIKI_LINK_MAX_LEN) return -1;\n j++;\n }\n return -1;\n}\n"],"mappings":";;;;;AAmBA,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,aAAA,WAAW,KAAK;AACtD;AAOA,SAAgB,oBAAoB,QAAoC;CACtE,IAAI,CAAC,aAAA,SAAS,MAAM,GAAG,OAAO;CAC9B,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,IAAI,YAAY,mBAAmB,YAAY,OAAO,EAAE,MAAM,cAAc;CAC5E,IAAI,YAAY,mBAAmB,OAAO,OAAO,EAAE,MAAM,QAAQ;CAEjE,OAAO;AACT;AAcA,SAAgB,qBAAqB,QAA4C;CAC/E,QAAQ,OAAO,MAAf;EACE,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AAI,IAAI;CACR,OAAO,IAAI,IAAI,QAAQ;EACrB,MAAM,OAAO,IAAI;EACjB,IAAI,SAAS,KAAK;GAChB,IAAI,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,OAAO;GAE3C,OAAO;EACT;EAGA,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS,QAAQ,IAAI,QAAA,KAA2B,OAAO;EAC5F;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.cjs","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 { isRecord } from \"@mulmoclaude/common\";\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 (!isRecord(params)) return null;\n const { section, slug } = params;\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 { escapeHtml } from \"@mulmoclaude/common\";\nimport { parseWikiLink, WIKI_LINK_MAX_LEN } from \"./link.js\";\n\n// `escapeHtml` moved down to the zero-dep leaf `@mulmoclaude/common` (#2483) so\n// `@mulmoclaude/markdown-utils` — a leaf THIS package depends on, hence unable\n// to import back up — can share it. Re-exported here because the wiki\n// consumers (collection-plugin's graph view, the host's wiki embeds and\n// spreadsheet view) already import it from `@mulmoclaude/core/wiki`.\nexport { escapeHtml };\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 `[` or `]`; an opening `[[` that is\n * not followed later by `]]` (with no bare `[` or `]` in between)\n * is left 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.charAt(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 the span isn't\n * a valid wiki-link body — mirroring `WIKI_LINK_PATTERN` exactly so\n * the renderer can't accept a link the graph / backlinks / lint\n * would reject. The pattern's body class is `[^\\][\\r\\n]`, so it\n * rejects `[` as well as `]`. Bails (-1) on:\n * - a bare `]` (regex `[^\\]]`),\n * - a `[` inside the body (regex `[^\\[]` — a nested `[[` opener\n * never belongs in a page name, and the pattern would not match),\n * - a `\\r` or `\\n` (regex `[^\\r\\n]` — a newline-bearing link must\n * not render clickable, and its slug must not reach the URL),\n * - a body longer than WIKI_LINK_MAX_LEN (regex `{1,200}`),\n * - a zero-length body (regex `{1,}` minimum),\n * - reaching end-of-input with no `]]`.\n */\nfunction findNextCloseBrackets(str: string, from: number): number {\n let j = from;\n while (j < str.length) {\n const char = str[j];\n if (char === \"]\") {\n if (str[j + 1] === \"]\" && j > from) return j;\n // Bare `]` inside the page-name span — regex would not match.\n return -1;\n }\n // A `[`, a newline, or a span past the cap: none match the pattern's\n // `[^\\][\\r\\n]{1,200}` body, so bail and let the caller emit `[[` literally.\n if (char === \"[\" || char === \"\\n\" || char === \"\\r\" || j - from >= WIKI_LINK_MAX_LEN) return -1;\n j++;\n }\n return -1;\n}\n"],"mappings":";;;;;AAmBA,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,aAAA,WAAW,KAAK;AACtD;AAOA,SAAgB,oBAAoB,QAAoC;CACtE,IAAI,CAAC,aAAA,SAAS,MAAM,GAAG,OAAO;CAC9B,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,IAAI,YAAY,mBAAmB,YAAY,OAAO,EAAE,MAAM,cAAc;CAC5E,IAAI,YAAY,mBAAmB,OAAO,OAAO,EAAE,MAAM,QAAQ;CAEjE,OAAO;AACT;AAcA,SAAgB,qBAAqB,QAA4C;CAC/E,QAAQ,OAAO,MAAf;EACE,KAAK,SACH,OAAO;GAAE,SAAS;GAAI,MAAM;EAAG;EACjC,KAAK,QACH,OAAO;GAAE,S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;EACjB,IAAI,SAAS,KAAK;GAChB,IAAI,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,OAAO;GAE3C,OAAO;EACT;EAGA,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS,QAAQ,IAAI,QAAA,KAA2B,OAAO;EAC5F;CACF;CACA,OAAO;AACT"}
|
package/dist/wiki/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as escapeHtml, s as isRecord } from "../dist-D8zokgGo.js";
|
|
2
|
-
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-
|
|
2
|
+
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-Ce7xsDTt.js";
|
|
3
3
|
import { n as wikiSlugify, t as isSafeSlug } from "../slug-CdN-pQX1.js";
|
|
4
4
|
//#region src/wiki/route.ts
|
|
5
5
|
var WIKI_ROUTE_SECTION = {
|
|
@@ -99,7 +99,7 @@ function renderWikiLinks(content) {
|
|
|
99
99
|
continue;
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
|
-
out.push(content
|
|
102
|
+
out.push(content.charAt(i));
|
|
103
103
|
i++;
|
|
104
104
|
}
|
|
105
105
|
return out.join("");
|
package/dist/wiki/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 { isRecord } from \"@mulmoclaude/common\";\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 (!isRecord(params)) return null;\n const { section, slug } = params;\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 { escapeHtml } from \"@mulmoclaude/common\";\nimport { parseWikiLink, WIKI_LINK_MAX_LEN } from \"./link.js\";\n\n// `escapeHtml` moved down to the zero-dep leaf `@mulmoclaude/common` (#2483) so\n// `@mulmoclaude/markdown-utils` — a leaf THIS package depends on, hence unable\n// to import back up — can share it. Re-exported here because the wiki\n// consumers (collection-plugin's graph view, the host's wiki embeds and\n// spreadsheet view) already import it from `@mulmoclaude/core/wiki`.\nexport { escapeHtml };\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 `[` or `]`; an opening `[[` that is\n * not followed later by `]]` (with no bare `[` or `]` in between)\n * is left 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 the span isn't\n * a valid wiki-link body — mirroring `WIKI_LINK_PATTERN` exactly so\n * the renderer can't accept a link the graph / backlinks / lint\n * would reject. The pattern's body class is `[^\\][\\r\\n]`, so it\n * rejects `[` as well as `]`. Bails (-1) on:\n * - a bare `]` (regex `[^\\]]`),\n * - a `[` inside the body (regex `[^\\[]` — a nested `[[` opener\n * never belongs in a page name, and the pattern would not match),\n * - a `\\r` or `\\n` (regex `[^\\r\\n]` — a newline-bearing link must\n * not render clickable, and its slug must not reach the URL),\n * - a body longer than WIKI_LINK_MAX_LEN (regex `{1,200}`),\n * - a zero-length body (regex `{1,}` minimum),\n * - reaching end-of-input with no `]]`.\n */\nfunction findNextCloseBrackets(str: string, from: number): number {\n let j = from;\n while (j < str.length) {\n const char = str[j];\n if (char === \"]\") {\n if (str[j + 1] === \"]\" && j > from) return j;\n // Bare `]` inside the page-name span — regex would not match.\n return -1;\n }\n // A `[`, a newline, or a span past the cap: none match the pattern's\n // `[^\\][\\r\\n]{1,200}` body, so bail and let the caller em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ure 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 { isRecord } from \"@mulmoclaude/common\";\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 (!isRecord(params)) return null;\n const { section, slug } = params;\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 { escapeHtml } from \"@mulmoclaude/common\";\nimport { parseWikiLink, WIKI_LINK_MAX_LEN } from \"./link.js\";\n\n// `escapeHtml` moved down to the zero-dep leaf `@mulmoclaude/common` (#2483) so\n// `@mulmoclaude/markdown-utils` — a leaf THIS package depends on, hence unable\n// to import back up — can share it. Re-exported here because the wiki\n// consumers (collection-plugin's graph view, the host's wiki embeds and\n// spreadsheet view) already import it from `@mulmoclaude/core/wiki`.\nexport { escapeHtml };\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 `[` or `]`; an opening `[[` that is\n * not followed later by `]]` (with no bare `[` or `]` in between)\n * is left 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.charAt(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 the span isn't\n * a valid wiki-link body — mirroring `WIKI_LINK_PATTERN` exactly so\n * the renderer can't accept a link the graph / backlinks / lint\n * would reject. The pattern's body class is `[^\\][\\r\\n]`, so it\n * rejects `[` as well as `]`. Bails (-1) on:\n * - a bare `]` (regex `[^\\]]`),\n * - a `[` inside the body (regex `[^\\[]` — a nested `[[` opener\n * never belongs in a page name, and the pattern would not match),\n * - a `\\r` or `\\n` (regex `[^\\r\\n]` — a newline-bearing link must\n * not render clickable, and its slug must not reach the URL),\n * - a body longer than WIKI_LINK_MAX_LEN (regex `{1,200}`),\n * - a zero-length body (regex `{1,}` minimum),\n * - reaching end-of-input with no `]]`.\n */\nfunction findNextCloseBrackets(str: string, from: number): number {\n let j = from;\n while (j < str.length) {\n const char = str[j];\n if (char === \"]\") {\n if (str[j + 1] === \"]\" && j > from) return j;\n // Bare `]` inside the page-name span — regex would not match.\n return -1;\n }\n // A `[`, a newline, or a span past the cap: none match the pattern's\n // `[^\\][\\r\\n]{1,200}` body, so bail and let the caller emit `[[` literally.\n if (char === \"[\" || char === \"\\n\" || char === \"\\r\" || j - from >= WIKI_LINK_MAX_LEN) return -1;\n j++;\n }\n return -1;\n}\n"],"mappings":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O,YAAY;EACrB,KAAK,QACH,OAAO,YAAY;EACrB,KAAK,OACH,OAAO,YAAY;EACrB,KAAK,eACH,OAAO,YAAY;EACrB,KAAK,SACH,OAAO,YAAY;EACrB,SAEE,MAAM,IAAI,MAAM,gCAAgC,KAAK,UAAU,MAAU,GAAG;CAEhF;AACF;;;;;;;;;;;;;;;;;AC1GA,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,OAAO,CAAC,CAAC;EAC1B;CACF;CACA,OAAO,IAAI,KAAK,EAAE;AACpB;;;;;;;;;;;;;;;;;AAkBA,SAAS,sBAAsB,KAAa,MAAsB;CAChE,IAAI,IAAI;CACR,OAAO,IAAI,IAAI,QAAQ;EACrB,MAAM,OAAO,IAAI;EACjB,IAAI,SAAS,KAAK;GAChB,IAAI,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,OAAO;GAE3C,OAAO;EACT;EAGA,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS,QAAQ,IAAI,QAAA,KAA2B,OAAO;EAC5F;CACF;CACA,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_rolldown_runtime = require("../../rolldown-runtime-D6vf50IK.cjs");
|
|
3
|
-
const require_graph = require("../../graph-
|
|
3
|
+
const require_graph = require("../../graph-BZJxiv1E.cjs");
|
|
4
4
|
const require_slug = require("../../slug-DbwORN9z.cjs");
|
|
5
5
|
const require_wiki_paths = require("../paths.cjs");
|
|
6
6
|
let node_fs = require("node:fs");
|
|
@@ -161,18 +161,20 @@ async function readWikiPage(workspace, pageName) {
|
|
|
161
161
|
resolvedTitle
|
|
162
162
|
};
|
|
163
163
|
}
|
|
164
|
+
/** Page body, or "" when the file vanished between indexing and reading. */
|
|
165
|
+
async function readPageBody(pagesDir, fileName) {
|
|
166
|
+
return await readTextSafe(node_path.default.join(pagesDir, fileName)) ?? "";
|
|
167
|
+
}
|
|
164
168
|
/** Read every page + the index and build the page→page link graph.
|
|
165
169
|
* No cache: the graph is requested explicitly and a content edit does
|
|
166
170
|
* not advance the pagesDir mtime the page index caches on. */
|
|
167
171
|
async function loadWikiGraph(workspace) {
|
|
168
172
|
const { pagesDir, indexFile } = require_wiki_paths.wikiDirs(workspace);
|
|
169
173
|
const { slugs } = await getPageIndex(pagesDir);
|
|
170
|
-
|
|
171
|
-
const contents = await Promise.all(fileEntries.map(async ([, fileName]) => await readTextSafe(node_path.default.join(pagesDir, fileName)) ?? ""));
|
|
172
|
-
return require_graph.buildWikiGraph(fileEntries.map(([slug], i) => ({
|
|
174
|
+
return require_graph.buildWikiGraph(await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({
|
|
173
175
|
slug,
|
|
174
|
-
content:
|
|
175
|
-
})), require_graph.parseIndexEntries(readFileOrEmpty(indexFile)));
|
|
176
|
+
content: await readPageBody(pagesDir, fileName)
|
|
177
|
+
}))), require_graph.parseIndexEntries(readFileOrEmpty(indexFile)));
|
|
176
178
|
}
|
|
177
179
|
/** Run every lint rule over the on-disk wiki, returning issue strings. */
|
|
178
180
|
async function collectLintIssues(workspace) {
|
|
@@ -181,17 +183,18 @@ async function collectLintIssues(workspace) {
|
|
|
181
183
|
if (slugs.size === 0) return ["- Wiki `pages/` directory does not exist yet. Start ingesting sources."];
|
|
182
184
|
const pageEntries = require_graph.parseIndexEntries(readFileOrEmpty(indexFile));
|
|
183
185
|
const indexedSlugs = new Set(pageEntries.map((entry) => entry.slug));
|
|
184
|
-
const pageFiles = [...slugs.values()];
|
|
185
186
|
const fileSlugs = new Set(slugs.keys());
|
|
187
|
+
const bodies = await Promise.all([...slugs.values()].map(async (fileName) => ({
|
|
188
|
+
fileName,
|
|
189
|
+
content: await readPageBody(pagesDir, fileName)
|
|
190
|
+
})));
|
|
186
191
|
const issues = [];
|
|
187
192
|
issues.push(...require_graph.findOrphanPages(fileSlugs, indexedSlugs));
|
|
188
193
|
issues.push(...require_graph.findMissingFiles(pageEntries, fileSlugs));
|
|
189
|
-
const contents = await Promise.all(pageFiles.map(async (fileName) => await readTextSafe(node_path.default.join(pagesDir, fileName)) ?? ""));
|
|
190
194
|
const frontmatterTagsBySlug = /* @__PURE__ */ new Map();
|
|
191
|
-
for (
|
|
192
|
-
issues.push(...require_graph.findBrokenLinksInPage(
|
|
193
|
-
|
|
194
|
-
frontmatterTagsBySlug.set(slug, parseFrontmatterTags(contents[i]));
|
|
195
|
+
for (const { fileName, content } of bodies) {
|
|
196
|
+
issues.push(...require_graph.findBrokenLinksInPage(fileName, content, fileSlugs));
|
|
197
|
+
frontmatterTagsBySlug.set(fileName.replace(/\.md$/i, "").toLowerCase(), parseFrontmatterTags(content));
|
|
195
198
|
}
|
|
196
199
|
issues.push(...require_graph.findTagDrift(pageEntries, frontmatterTagsBySlug));
|
|
197
200
|
return issues;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { Dirent, Stats } from \"node:fs\";\nimport { readFileSync } from \"node:fs\";\nimport { readFile, readdir, stat } from \"node:fs/promises\";\n\nexport async function readTextSafe(absPath: string): Promise<string | null> {\n try {\n return await readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport function readTextSafeSync(absPath: string): string | null {\n try {\n return readFileSync(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { wikiDirs } from \"./paths.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string): string {\n return readTextSafeSync(absPath) ?? \"\";\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** Resolve a page name to an absolute `.md` path: exact slug → fuzzy →\n * index-title fallback (for non-ASCII names that slugify to empty).\n * `pageName` may carry the `[[target|display]]` form; `parseWikiLink`\n * strips the display half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const slug = wikiSlugify(target);\n\n if (slug.length > 0) {\n const exact = slugs.get(slug);\n if (exact) return path.join(pagesDir, exact);\n const fuzzy = pickFuzzyMatch(slug, slugs);\n if (fuzzy) return path.join(pagesDir, fuzzy);\n }\n\n const entries = parseIndexEntries(readFileOrEmpty(indexFile));\n const titleMatch = entries.find((entry) => entry.title === target);\n if (titleMatch) {\n const file = slugs.get(titleMatch.slug);\n if (file) return path.join(pagesDir, file);\n }\n return null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const content = readFileOrEmpty(wikiDirs(workspace).indexFile);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n return readFileOrEmpty(wikiDirs(workspace).logFile);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const filePath = await resolvePagePath(workspace, pageName);\n const content = filePath ? readFileOrEmpty(filePath) : \"\";\n const resolvedTitle = filePath ? path.basename(filePath, \".md\") : pageName;\n return { filePath, content, exists: Boolean(filePath), resolvedTitle };\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n const fileEntries = [...slugs.entries()];\n const contents = await Promise.all(fileEntries.map(async ([, fileName]) => (await readTextSafe(path.join(pagesDir, fileName))) ?? \"\"));\n const pages = fileEntries.map(([slug], i) => ({ slug, content: contents[i] }));\n const indexEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n return buildWikiGraph(pages, indexEntries);\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n const indexedSlugs = new Set(pageEntries.map((entry) => entry.slug));\n const pageFiles = [...slugs.values()];\n const fileSlugs = new Set(slugs.keys());\n\n const issues: string[] = [];\n issues.push(...findOrphanPages(fileSlugs, indexedSlugs));\n issues.push(...findMissingFiles(pageEntries, fileSlugs));\n const contents = await Promise.all(pageFiles.map(async (fileName) => (await readTextSafe(path.join(pagesDir, fileName))) ?? \"\"));\n const frontmatterTagsBySlug = new Map<string, string[]>();\n for (let i = 0; i < pageFiles.length; i++) {\n issues.push(...findBrokenLinksInPage(pageFiles[i], contents[i], fileSlugs));\n // Lowercase the key so a `MyPage.md` filename matches an\n // `entry.slug` of `mypage`; `findTagDrift` lowercases the lookup.\n const slug = pageFiles[i].replace(/\\.md$/i, \"\").toLowerCase();\n frontmatterTagsBySlug.set(slug, parseFrontmatterTags(contents[i]));\n }\n issues.push(...findTagDrift(pageEntries, frontmatterTagsBySlug));\n return issues;\n}\n"],"mappings":";;;;;;;;;;;AAUA,eAAsB,aAAa,SAAyC;CAC1E,IAAI;EACF,OAAO,OAAA,GAAA,iBAAA,SAAA,CAAe,SAAS,OAAO;CACxC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,S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iki/server/frontmatter.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { Dirent, Stats } from \"node:fs\";\nimport { readFileSync } from \"node:fs\";\nimport { readFile, readdir, stat } from \"node:fs/promises\";\n\nexport async function readTextSafe(absPath: string): Promise<string | null> {\n try {\n return await readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport function readTextSafeSync(absPath: string): string | null {\n try {\n return readFileSync(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { wikiDirs } from \"./paths.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string): string {\n return readTextSafeSync(absPath) ?? \"\";\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** Resolve a page name to an absolute `.md` path: exact slug → fuzzy →\n * index-title fallback (for non-ASCII names that slugify to empty).\n * `pageName` may carry the `[[target|display]]` form; `parseWikiLink`\n * strips the display half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const slug = wikiSlugify(target);\n\n if (slug.length > 0) {\n const exact = slugs.get(slug);\n if (exact) return path.join(pagesDir, exact);\n const fuzzy = pickFuzzyMatch(slug, slugs);\n if (fuzzy) return path.join(pagesDir, fuzzy);\n }\n\n const entries = parseIndexEntries(readFileOrEmpty(indexFile));\n const titleMatch = entries.find((entry) => entry.title === target);\n if (titleMatch) {\n const file = slugs.get(titleMatch.slug);\n if (file) return path.join(pagesDir, file);\n }\n return null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const content = readFileOrEmpty(wikiDirs(workspace).indexFile);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n return readFileOrEmpty(wikiDirs(workspace).logFile);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const filePath = await resolvePagePath(workspace, pageName);\n const content = filePath ? readFileOrEmpty(filePath) : \"\";\n const resolvedTitle = filePath ? path.basename(filePath, \".md\") : pageName;\n return { filePath, content, exists: Boolean(filePath), resolvedTitle };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(pagesDir: string, fileName: string): Promise<string> {\n return (await readTextSafe(path.join(pagesDir, fileName))) ?? \"\";\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(pagesDir, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n return buildWikiGraph(pages, indexEntries);\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n const indexedSlugs = new Set(pageEntries.map((entry) => entry.slug));\n const fileSlugs = new Set(slugs.keys());\n const bodies = await Promise.all([...slugs.values()].map(async (fileName) => ({ fileName, content: await readPageBody(pagesDir, fileName) })));\n\n const issues: string[] = [];\n issues.push(...findOrphanPages(fileSlugs, indexedSlugs));\n issues.push(...findMissingFiles(pageEntries, fileSlugs));\n const frontmatterTagsBySlug = new Map<string, string[]>();\n for (const { fileName, content } of bodies) {\n issues.push(...findBrokenLinksInPage(fileName, content, fileSlugs));\n // Lowercase the key so a `MyPage.md` filename matches an\n // `entry.slug` of `mypage`; `findTagDrift` lowercases the lookup.\n frontmatterTagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n }\n issues.push(...findTagDr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,qBAAqB,CAAC;CAC/D,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as findBrokenLinksInPage, c as findTagDrift, h as parseIndexEntries, o as findMissingFiles, s as findOrphanPages, t as buildWikiGraph, v as parseWikiLink } from "../../graph-
|
|
1
|
+
import { a as findBrokenLinksInPage, c as findTagDrift, h as parseIndexEntries, o as findMissingFiles, s as findOrphanPages, t as buildWikiGraph, v as parseWikiLink } from "../../graph-Ce7xsDTt.js";
|
|
2
2
|
import { n as wikiSlugify } from "../../slug-CdN-pQX1.js";
|
|
3
3
|
import { wikiDirs, wikiSlugFromAbsPath } from "../paths.js";
|
|
4
4
|
import { readFileSync } from "node:fs";
|
|
@@ -158,18 +158,20 @@ async function readWikiPage(workspace, pageName) {
|
|
|
158
158
|
resolvedTitle
|
|
159
159
|
};
|
|
160
160
|
}
|
|
161
|
+
/** Page body, or "" when the file vanished between indexing and reading. */
|
|
162
|
+
async function readPageBody(pagesDir, fileName) {
|
|
163
|
+
return await readTextSafe(path.join(pagesDir, fileName)) ?? "";
|
|
164
|
+
}
|
|
161
165
|
/** Read every page + the index and build the page→page link graph.
|
|
162
166
|
* No cache: the graph is requested explicitly and a content edit does
|
|
163
167
|
* not advance the pagesDir mtime the page index caches on. */
|
|
164
168
|
async function loadWikiGraph(workspace) {
|
|
165
169
|
const { pagesDir, indexFile } = wikiDirs(workspace);
|
|
166
170
|
const { slugs } = await getPageIndex(pagesDir);
|
|
167
|
-
|
|
168
|
-
const contents = await Promise.all(fileEntries.map(async ([, fileName]) => await readTextSafe(path.join(pagesDir, fileName)) ?? ""));
|
|
169
|
-
return buildWikiGraph(fileEntries.map(([slug], i) => ({
|
|
171
|
+
return buildWikiGraph(await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({
|
|
170
172
|
slug,
|
|
171
|
-
content:
|
|
172
|
-
})), parseIndexEntries(readFileOrEmpty(indexFile)));
|
|
173
|
+
content: await readPageBody(pagesDir, fileName)
|
|
174
|
+
}))), parseIndexEntries(readFileOrEmpty(indexFile)));
|
|
173
175
|
}
|
|
174
176
|
/** Run every lint rule over the on-disk wiki, returning issue strings. */
|
|
175
177
|
async function collectLintIssues(workspace) {
|
|
@@ -178,17 +180,18 @@ async function collectLintIssues(workspace) {
|
|
|
178
180
|
if (slugs.size === 0) return ["- Wiki `pages/` directory does not exist yet. Start ingesting sources."];
|
|
179
181
|
const pageEntries = parseIndexEntries(readFileOrEmpty(indexFile));
|
|
180
182
|
const indexedSlugs = new Set(pageEntries.map((entry) => entry.slug));
|
|
181
|
-
const pageFiles = [...slugs.values()];
|
|
182
183
|
const fileSlugs = new Set(slugs.keys());
|
|
184
|
+
const bodies = await Promise.all([...slugs.values()].map(async (fileName) => ({
|
|
185
|
+
fileName,
|
|
186
|
+
content: await readPageBody(pagesDir, fileName)
|
|
187
|
+
})));
|
|
183
188
|
const issues = [];
|
|
184
189
|
issues.push(...findOrphanPages(fileSlugs, indexedSlugs));
|
|
185
190
|
issues.push(...findMissingFiles(pageEntries, fileSlugs));
|
|
186
|
-
const contents = await Promise.all(pageFiles.map(async (fileName) => await readTextSafe(path.join(pagesDir, fileName)) ?? ""));
|
|
187
191
|
const frontmatterTagsBySlug = /* @__PURE__ */ new Map();
|
|
188
|
-
for (
|
|
189
|
-
issues.push(...findBrokenLinksInPage(
|
|
190
|
-
|
|
191
|
-
frontmatterTagsBySlug.set(slug, parseFrontmatterTags(contents[i]));
|
|
192
|
+
for (const { fileName, content } of bodies) {
|
|
193
|
+
issues.push(...findBrokenLinksInPage(fileName, content, fileSlugs));
|
|
194
|
+
frontmatterTagsBySlug.set(fileName.replace(/\.md$/i, "").toLowerCase(), parseFrontmatterTags(content));
|
|
192
195
|
}
|
|
193
196
|
issues.push(...findTagDrift(pageEntries, frontmatterTagsBySlug));
|
|
194
197
|
return issues;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { Dirent, Stats } from \"node:fs\";\nimport { readFileSync } from \"node:fs\";\nimport { readFile, readdir, stat } from \"node:fs/promises\";\n\nexport async function readTextSafe(absPath: string): Promise<string | null> {\n try {\n return await readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport function readTextSafeSync(absPath: string): string | null {\n try {\n return readFileSync(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { wikiDirs } from \"./paths.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string): string {\n return readTextSafeSync(absPath) ?? \"\";\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** Resolve a page name to an absolute `.md` path: exact slug → fuzzy →\n * index-title fallback (for non-ASCII names that slugify to empty).\n * `pageName` may carry the `[[target|display]]` form; `parseWikiLink`\n * strips the display half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const slug = wikiSlugify(target);\n\n if (slug.length > 0) {\n const exact = slugs.get(slug);\n if (exact) return path.join(pagesDir, exact);\n const fuzzy = pickFuzzyMatch(slug, slugs);\n if (fuzzy) return path.join(pagesDir, fuzzy);\n }\n\n const entries = parseIndexEntries(readFileOrEmpty(indexFile));\n const titleMatch = entries.find((entry) => entry.title === target);\n if (titleMatch) {\n const file = slugs.get(titleMatch.slug);\n if (file) return path.join(pagesDir, file);\n }\n return null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const content = readFileOrEmpty(wikiDirs(workspace).indexFile);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n return readFileOrEmpty(wikiDirs(workspace).logFile);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const filePath = await resolvePagePath(workspace, pageName);\n const content = filePath ? readFileOrEmpty(filePath) : \"\";\n const resolvedTitle = filePath ? path.basename(filePath, \".md\") : pageName;\n return { filePath, content, exists: Boolean(filePath), resolvedTitle };\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n const fileEntries = [...slugs.entries()];\n const contents = await Promise.all(fileEntries.map(async ([, fileName]) => (await readTextSafe(path.join(pagesDir, fileName))) ?? \"\"));\n const pages = fileEntries.map(([slug], i) => ({ slug, content: contents[i] }));\n const indexEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n return buildWikiGraph(pages, indexEntries);\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n const indexedSlugs = new Set(pageEntries.map((entry) => entry.slug));\n const pageFiles = [...slugs.values()];\n const fileSlugs = new Set(slugs.keys());\n\n const issues: string[] = [];\n issues.push(...findOrphanPages(fileSlugs, indexedSlugs));\n issues.push(...findMissingFiles(pageEntries, fileSlugs));\n const contents = await Promise.all(pageFiles.map(async (fileName) => (await readTextSafe(path.join(pagesDir, fileName))) ?? \"\"));\n const frontmatterTagsBySlug = new Map<string, string[]>();\n for (let i = 0; i < pageFiles.length; i++) {\n issues.push(...findBrokenLinksInPage(pageFiles[i], contents[i], fileSlugs));\n // Lowercase the key so a `MyPage.md` filename matches an\n // `entry.slug` of `mypage`; `findTagDrift` lowercases the lookup.\n const slug = pageFiles[i].replace(/\\.md$/i, \"\").toLowerCase();\n frontmatterTagsBySlug.set(slug, parseFrontmatterTags(contents[i]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AAO,eAFO,YAAY,KAAK,CAAC,OAAO,OAAO;EAAE;EAAM,SAAS,SAAS;CAAG,EAErD,GADD,kBAAkB,gBAAgB,SAAS,CACnC,CAAY;AAC3C;;AAGA,eAAsB,kBAAkB,WAAsC;CAC5E,MAAM,EAAE,UAAU,cAAc,SAAS,SAAS;CAClD,MAAM,EAAE,UAAU,MAAM,aAAa,QAAQ;CAC7C,IAAI,MAAM,SAAS,GACjB,OAAO,CAAC,wEAAwE;CAElF,MAAM,cAAc,kBAAkB,gBAAgB,SAAS,CAAC;CAChE,MAAM,eAAe,IAAI,IAAI,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC;CACnE,MAAM,YAAY,CAAC,GAAG,MAAM,OAAO,CAAC;CACpC,MAAM,YAAY,IAAI,IAAI,MAAM,KAAK,CAAC;CAEtC,MAAM,SAAmB,CAAC;CAC1B,OAAO,KAAK,GAAG,gBAAgB,WAAW,YAAY,CAAC;CACvD,OAAO,KAAK,GAAG,iBAAiB,aAAa,SAAS,CAAC;CACvD,MAAM,WAAW,MAAM,QAAQ,IAAI,UAAU,IAAI,OAAO,aAAc,MAAM,aAAa,KAAK,KAAK,UAAU,QAAQ,CAAC,KAAM,EAAE,CAAC;CAC/H,MAAM,wCAAwB,IAAI,IAAsB;CACxD,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;EACzC,OAAO,KAAK,GAAG,sBAAsB,UAAU,IAAI,SAAS,IAAI,SAAS,CAAC;EAG1E,MAAM,OAAO,UAAU,EAAE,CAAC,QAAQ,UAAU,EAAE,CAAC,CAAC,YAAY;EAC5D,sBAAsB,IAAI,MAAM,qBAAqB,SAAS,EAAE,CAAC;CACnE;CACA,OAAO,KAAK,GAAG,aAAa,aAAa,qBAAqB,CAAC;CAC/D,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { Dirent, Stats } from \"node:fs\";\nimport { readFileSync } from \"node:fs\";\nimport { readFile, readdir, stat } from \"node:fs/promises\";\n\nexport async function readTextSafe(absPath: string): Promise<string | null> {\n try {\n return await readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport function readTextSafeSync(absPath: string): string | null {\n try {\n return readFileSync(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { wikiDirs } from \"./paths.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string): string {\n return readTextSafeSync(absPath) ?? \"\";\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** Resolve a page name to an absolute `.md` path: exact slug → fuzzy →\n * index-title fallback (for non-ASCII names that slugify to empty).\n * `pageName` may carry the `[[target|display]]` form; `parseWikiLink`\n * strips the display half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const slug = wikiSlugify(target);\n\n if (slug.length > 0) {\n const exact = slugs.get(slug);\n if (exact) return path.join(pagesDir, exact);\n const fuzzy = pickFuzzyMatch(slug, slugs);\n if (fuzzy) return path.join(pagesDir, fuzzy);\n }\n\n const entries = parseIndexEntries(readFileOrEmpty(indexFile));\n const titleMatch = entries.find((entry) => entry.title === target);\n if (titleMatch) {\n const file = slugs.get(titleMatch.slug);\n if (file) return path.join(pagesDir, file);\n }\n return null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const content = readFileOrEmpty(wikiDirs(workspace).indexFile);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n return readFileOrEmpty(wikiDirs(workspace).logFile);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const filePath = await resolvePagePath(workspace, pageName);\n const content = filePath ? readFileOrEmpty(filePath) : \"\";\n const resolvedTitle = filePath ? path.basename(filePath, \".md\") : pageName;\n return { filePath, content, exists: Boolean(filePath), resolvedTitle };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(pagesDir: string, fileName: string): Promise<string> {\n return (await readTextSafe(path.join(pagesDir, fileName))) ?? \"\";\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(pagesDir, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n return buildWikiGraph(pages, indexEntries);\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n const indexedSlugs = new Set(pageEntries.map((entry) => entry.slug));\n const fileSlugs = new Set(slugs.keys());\n const bodies = await Promise.all([...slugs.values()].map(async (fileName) => ({ fileName, content: await readPageBody(pagesDir, fileName) })));\n\n const issues: string[] = [];\n issues.push(...findOrphanPages(fileSlugs, indexedSlugs));\n issues.push(...findMissingFiles(pageEntries, fileSlugs));\n const frontmatterTagsBySlug = new Map<string, string[]>();\n for (const { fileName, content } of bodies) {\n issues.push(...findBrokenLinksInPage(fileName, content, fileSlugs));\n // Lowercase the key so a `MyPage.md` filename matches an\n // `entry.slug` of `mypage`; `findTagDrift` lowercases the lookup.\n frontmatterTagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n }\n issues.push(...findTagDrift(pageEntries, frontmatterTagsBySlug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,MAAM,aAAa,UAAU,QAAQ;CAAE,EAAE,CAAC,GAC5H,kBAAkB,gBAAgB,SAAS,CACnC,CAAY;AAC3C;;AAGA,eAAsB,kBAAkB,WAAsC;CAC5E,MAAM,EAAE,UAAU,cAAc,SAAS,SAAS;CAClD,MAAM,EAAE,UAAU,MAAM,aAAa,QAAQ;CAC7C,IAAI,MAAM,SAAS,GACjB,OAAO,CAAC,wEAAwE;CAElF,MAAM,cAAc,kBAAkB,gBAAgB,SAAS,CAAC;CAChE,MAAM,eAAe,IAAI,IAAI,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC;CACnE,MAAM,YAAY,IAAI,IAAI,MAAM,KAAK,CAAC;CACtC,MAAM,SAAS,MAAM,QAAQ,IAAI,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,IAAI,OAAO,cAAc;EAAE;EAAU,SAAS,MAAM,aAAa,UAAU,QAAQ;CAAE,EAAE,CAAC;CAE7I,MAAM,SAAmB,CAAC;CAC1B,OAAO,KAAK,GAAG,gBAAgB,WAAW,YAAY,CAAC;CACvD,OAAO,KAAK,GAAG,iBAAiB,aAAa,SAAS,CAAC;CACvD,MAAM,wCAAwB,IAAI,IAAsB;CACxD,KAAK,MAAM,EAAE,UAAU,aAAa,QAAQ;EAC1C,OAAO,KAAK,GAAG,sBAAsB,UAAU,SAAS,SAAS,CAAC;EAGlE,sBAAsB,IAAI,SAAS,QAAQ,UAAU,EAAE,CAAC,CAAC,YAAY,GAAG,qBAAqB,OAAO,CAAC;CACvG;CACA,OAAO,KAAK,GAAG,aAAa,aAAa,qBAAqB,CAAC;CAC/D,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mulmoclaude/core",
|
|
3
|
-
"version": "1.14.
|
|
3
|
+
"version": "1.14.1",
|
|
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 ./artifacts, ./whisper/client, ./workspace-setup/slug, ./translation/client, ./remote-view, ./remote-host and ./plugin-vue entries. All host specifics are injected.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -214,16 +214,16 @@
|
|
|
214
214
|
"dependencies": {
|
|
215
215
|
"@duckdb/node-api": "^1.5.5-r.2",
|
|
216
216
|
"@mulmoclaude/common": "^1.1.1",
|
|
217
|
-
"@mulmoclaude/markdown-utils": "^1.3.
|
|
217
|
+
"@mulmoclaude/markdown-utils": "^1.3.4",
|
|
218
218
|
"dompurify": "^3.4.12",
|
|
219
219
|
"fast-xml-parser": "^5.10.1",
|
|
220
220
|
"google-auth-library": "^10.9.1",
|
|
221
221
|
"iconv-lite": "^0.7.3",
|
|
222
|
-
"js-yaml": "^5.2.
|
|
222
|
+
"js-yaml": "^5.2.3",
|
|
223
223
|
"zod": "^4.4.3"
|
|
224
224
|
},
|
|
225
225
|
"peerDependencies": {
|
|
226
|
-
"@receptron/task-scheduler": "^1.0.
|
|
226
|
+
"@receptron/task-scheduler": "^1.0.3",
|
|
227
227
|
"firebase": "^12.0.0",
|
|
228
228
|
"gui-chat-protocol": "^1.2.0",
|
|
229
229
|
"vue": "^3.5.0",
|
|
@@ -241,10 +241,10 @@
|
|
|
241
241
|
}
|
|
242
242
|
},
|
|
243
243
|
"devDependencies": {
|
|
244
|
-
"@receptron/task-scheduler": "^1.0.
|
|
244
|
+
"@receptron/task-scheduler": "^1.0.3",
|
|
245
245
|
"@types/node": "^26.1.2",
|
|
246
246
|
"gui-chat-protocol": "^1.2.0",
|
|
247
|
-
"tsx": "^4.23.
|
|
247
|
+
"tsx": "^4.23.4",
|
|
248
248
|
"typescript": "^6.0.3",
|
|
249
249
|
"vite": "^8.1.5",
|
|
250
250
|
"vite-plugin-dts": "^5.0.3",
|