@mulmoclaude/core 5.7.1 → 5.8.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/artifacts/paths.cjs +38 -75
- package/dist/artifacts/paths.cjs.map +1 -1
- package/dist/artifacts/paths.d.ts +2 -59
- package/dist/artifacts/paths.js +2 -69
- package/dist/artifacts/paths.js.map +1 -1
- package/dist/collection/firestore.cjs.map +1 -1
- package/dist/collection/firestore.js.map +1 -1
- package/dist/collection/index.cjs +3 -3
- package/dist/collection/index.cjs.map +1 -1
- package/dist/collection/index.js +3 -3
- package/dist/collection/registry/server/index.cjs +3 -3
- package/dist/collection/registry/server/index.cjs.map +1 -1
- package/dist/collection/registry/server/index.js +3 -3
- package/dist/collection/registry/server/index.js.map +1 -1
- package/dist/collection/server/index.cjs +2 -2
- package/dist/collection/server/index.js +2 -2
- package/dist/collection-watchers/index.cjs +4 -4
- package/dist/collection-watchers/index.cjs.map +1 -1
- package/dist/collection-watchers/index.js +4 -4
- package/dist/collection-watchers/index.js.map +1 -1
- package/dist/{discovery-XoYJI2Ot.js → discovery-CbwHtcwk.js} +3 -3
- package/dist/{discovery-XoYJI2Ot.js.map → discovery-CbwHtcwk.js.map} +1 -1
- package/dist/{discovery-CwBXvtyn.cjs → discovery-DgZRmO7F.cjs} +3 -3
- package/dist/discovery-DgZRmO7F.cjs.map +1 -0
- package/dist/{dist-Gj7ygaW2.cjs → dist-BZ62pKuU.cjs} +11 -1
- package/dist/dist-BZ62pKuU.cjs.map +1 -0
- package/dist/{dist-BzoA9pDR.js → dist-MFUV9FYo.js} +6 -2
- package/dist/dist-MFUV9FYo.js.map +1 -0
- package/dist/errorMessage-OEQzRwsi.cjs +1 -0
- package/dist/errorMessage-VEiXHRnX.js +1 -0
- package/dist/{errors-CdXsfFCF.cjs → errors-B0xloJ3E.cjs} +2 -2
- package/dist/errors-B0xloJ3E.cjs.map +1 -0
- package/dist/{errors-C7TI_t_4.js → errors-zTAsW7dS.js} +2 -2
- package/dist/{errors-C7TI_t_4.js.map → errors-zTAsW7dS.js.map} +1 -1
- package/dist/feeds/paths.cjs.map +1 -1
- package/dist/feeds/server/index.cjs +4 -4
- package/dist/feeds/server/index.cjs.map +1 -1
- package/dist/feeds/server/index.js +4 -4
- package/dist/feeds/server/index.js.map +1 -1
- package/dist/file-change/index.cjs.map +1 -1
- package/dist/files/index.cjs.map +1 -1
- package/dist/files/index.js.map +1 -1
- package/dist/global-config/index.cjs.map +1 -1
- 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-CURotEkH.cjs.map +1 -1
- package/dist/ingestTypes-DS9HiR2I.cjs.map +1 -1
- package/dist/{listen-Dca-NoBi.js → listen-DUlzSOzX.js} +2 -2
- package/dist/{listen-Dca-NoBi.js.map → listen-DUlzSOzX.js.map} +1 -1
- package/dist/{listen-BXthb-9C.cjs → listen-N_8XdKz_.cjs} +2 -2
- package/dist/listen-N_8XdKz_.cjs.map +1 -0
- package/dist/notifier/index.cjs +1 -1
- package/dist/notifier/index.js +1 -1
- package/dist/{notifier-B65Mvngb.cjs → notifier-CiemUClt.cjs} +3 -6
- package/dist/notifier-CiemUClt.cjs.map +1 -0
- package/dist/{notifier-vAp5t6wL.js → notifier-dgkC-h80.js} +2 -5
- package/dist/notifier-dgkC-h80.js.map +1 -0
- package/dist/paths-C8-jxR0s.cjs.map +1 -1
- package/dist/plugin-vue/i18n.cjs.map +1 -1
- package/dist/plugin-vue/index.cjs +82 -16
- package/dist/plugin-vue/index.cjs.map +1 -1
- package/dist/plugin-vue/index.js +82 -16
- package/dist/plugin-vue/index.js.map +1 -1
- package/dist/{promptSafety-BGV1wrE6.cjs → promptSafety-auQEatax.cjs} +2 -2
- package/dist/promptSafety-auQEatax.cjs.map +1 -0
- package/dist/{promptSafety-B5uGroik.js → promptSafety-yG60Vof8.js} +2 -2
- package/dist/promptSafety-yG60Vof8.js.map +1 -0
- package/dist/relPath-CTAjGdCL.cjs.map +1 -1
- package/dist/remote-host/index.cjs +1 -1
- package/dist/remote-host/index.js +1 -1
- package/dist/remote-host/server/index.cjs +4 -4
- package/dist/remote-host/server/index.cjs.map +1 -1
- package/dist/remote-host/server/index.js +4 -4
- package/dist/remote-host/server/index.js.map +1 -1
- package/dist/{remote-host-DhAHBYzN.cjs → remote-host-BMjh_F-6.cjs} +2 -2
- package/dist/remote-host-BMjh_F-6.cjs.map +1 -0
- package/dist/{remote-host-Cjox2F2J.js → remote-host-CoNX9JEC.js} +2 -2
- package/dist/remote-host-CoNX9JEC.js.map +1 -0
- package/dist/remote-view/index.cjs +1 -1
- package/dist/remote-view/index.cjs.map +1 -1
- package/dist/remote-view/index.js +1 -1
- package/dist/root-BvwBUcol.cjs.map +1 -1
- package/dist/scheduler/index.cjs +2 -2
- package/dist/scheduler/index.cjs.map +1 -1
- package/dist/scheduler/index.js +2 -2
- package/dist/scheduler/index.js.map +1 -1
- package/dist/{server-CLhww8NL.cjs → server-RsnFqPt7.cjs} +5 -5
- package/dist/server-RsnFqPt7.cjs.map +1 -0
- package/dist/{server-CTkTHqEL.js → server-iYXYObKb.js} +5 -5
- package/dist/server-iYXYObKb.js.map +1 -0
- package/dist/skill-bridge/index.cjs.map +1 -1
- package/dist/utils/index.cjs +2 -2
- package/dist/utils/index.js +2 -2
- package/dist/whisper/index.cjs +2 -2
- package/dist/whisper/index.cjs.map +1 -1
- package/dist/whisper/index.js +2 -2
- package/dist/whisper/index.js.map +1 -1
- package/dist/wiki/index.cjs +1 -1
- package/dist/wiki/index.cjs.map +1 -1
- package/dist/wiki/index.js +1 -1
- package/dist/wiki/index.js.map +1 -1
- package/dist/wiki/paths.cjs.map +1 -1
- package/dist/wiki/server/index.cjs.map +1 -1
- package/dist/workspace-setup/index.js.map +1 -1
- package/package.json +9 -8
- package/dist/discovery-CwBXvtyn.cjs.map +0 -1
- package/dist/dist-BzoA9pDR.js.map +0 -1
- package/dist/dist-Gj7ygaW2.cjs.map +0 -1
- package/dist/errorMessage-BQNpSYdT.js +0 -1
- package/dist/errorMessage-CT-va_Pv.cjs +0 -1
- package/dist/errors-CdXsfFCF.cjs.map +0 -1
- package/dist/listen-BXthb-9C.cjs.map +0 -1
- package/dist/notifier-B65Mvngb.cjs.map +0 -1
- package/dist/notifier-vAp5t6wL.js.map +0 -1
- package/dist/promptSafety-B5uGroik.js.map +0 -1
- package/dist/promptSafety-BGV1wrE6.cjs.map +0 -1
- package/dist/remote-host-Cjox2F2J.js.map +0 -1
- package/dist/remote-host-DhAHBYzN.cjs.map +0 -1
- package/dist/server-CLhww8NL.cjs.map +0 -1
- package/dist/server-CTkTHqEL.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-CURotEkH.cjs","names":[],"sources":["../src/wiki/link.ts","../src/wiki/resolve.ts","../src/wiki/index-parse.ts","../src/wiki/lint.ts","../src/wiki/graph.ts"],"sourcesContent":["// Pure helpers for `[[wiki-link]]` syntax. Used by the lint\n// (`server/api/routes/wiki.ts`), the page resolver, and the\n// frontend renderer (`src/plugins/wiki/helpers.ts`) — before this\n// module the three sites each had their own implementation and\n// none of them handled the `[[target|display]]` form, producing\n// false-positive \"broken link\" warnings on slug-aliased links\n// (issue #1297).\n//\n// All functions are pure string operations; safe to import from\n// browser bundles. No `node:*` imports anywhere in this file.\n\n/** Inline `[[...]]` link pattern. The capture group is the raw\n * text between the brackets — the caller is expected to feed it\n * through `parseWikiLink` to split off any `|display` suffix.\n *\n * Body length is capped at 200 chars to keep the regex linear:\n * catastrophic backtracking isn't possible (no nested\n * alternation), but a malicious page with thousands of\n * unmatched `[[` could still pin the CPU. 200 is well above the\n * longest legitimate title we've seen and matches the cap the\n * server-side `WIKI_LINK_PATTERN` constant has carried since the\n * original implementation in #951.\n *\n * Shared with the renderer's hand-rolled scanner so the two can't\n * drift: the renderer must reject the same newline-bearing and\n * over-length bodies, or a link would render clickable while the\n * graph / backlinks / lint (which use this pattern) never see it. */\nexport const WIKI_LINK_MAX_LEN = 200;\nexport const WIKI_LINK_PATTERN = new RegExp(`\\\\[\\\\[([^\\\\][\\\\r\\\\n]{1,${WIKI_LINK_MAX_LEN}})\\\\]\\\\]`, \"g\");\n\n/** The structural shape of an inline `[[target|display]]` link.\n * `target` is what the resolver / lint compares against page\n * slugs; `display` is what the renderer shows to the user.\n * When the user writes `[[foo]]` (no pipe), both fields hold\n * `foo`. */\nexport interface WikiLink {\n target: string;\n display: string;\n}\n\n/** Split the raw text inside `[[...]]` into target + display.\n *\n * - `[[foo|Bar Baz]]` → `{ target: \"foo\", display: \"Bar Baz\" }`\n * - `[[foo]]` → `{ target: \"foo\", display: \"foo\" }`\n * - `[[|empty target]]` → `{ target: \"\", display: \"empty target\" }`\n * (caller decides whether an empty target is meaningful;\n * typically lint flags it, renderer shows the display text raw)\n * - `[[foo|]]` → `{ target: \"foo\", display: \"\" }`\n * (same — caller decides)\n *\n * Whitespace around the pipe is preserved on the display side\n * (so the user can write `[[foo| ある記事 ]]` and get the\n * spacing intentionally) but TRIMMED on the target side, since\n * a slug-comparable target with leading/trailing whitespace is\n * always a typo.\n *\n * Only the FIRST pipe splits. `[[a|b|c]]` becomes\n * `{ target: \"a\", display: \"b|c\" }` so display strings can\n * legitimately contain a literal `|`. */\nexport function parseWikiLink(inner: string): WikiLink {\n const pipeIdx = inner.indexOf(\"|\");\n if (pipeIdx === -1) {\n return { target: inner, display: inner };\n }\n const target = inner.slice(0, pipeIdx).trim();\n const display = inner.slice(pipeIdx + 1);\n return { target, display };\n}\n","// The one rule for \"does this `[[link]]` target name an existing page?\".\n// Shared by the page resolver, the lint, and the graph so the three\n// cannot disagree on which files a target can reach.\n//\n// Pure string + lookup work; safe to import from browser bundles.\n\nimport type { WikiPageEntry } from \"./index-parse.js\";\nimport { wikiSlugify } from \"./slug.js\";\n\n/** Anything that can answer \"do you hold this slug?\" — the page index\n * (`Map<slug, filename>`) and the lint's `Set<slug>` both qualify. */\nexport interface SlugLookup {\n has: (slug: string) => boolean;\n}\n\n/** Match a raw link target against known page slugs, returning the\n * matched slug or null.\n *\n * Literal first: page slugs ARE filename stems, so a non-ASCII page\n * only ever matches its own untouched name — `wikiSlugify` strips\n * every non-ASCII character and would reduce `不耕起栽培-カバークロップ4年計画`\n * to `-4` (#2940). The slugified form still runs second so\n * `[[Sakura Internet]]` keeps resolving to `sakura-internet.md`. */\nexport function matchWikiSlug(target: string, known: SlugLookup): string | null {\n const literal = target.trim();\n if (literal.length === 0) return null;\n if (known.has(literal)) return literal;\n const slug = wikiSlugify(literal);\n if (slug.length > 0 && known.has(slug)) return slug;\n return null;\n}\n\n/** index.md title → slug, first entry wins. The fallback for links\n * written as the display title rather than the page's own name. */\nexport function slugByIndexTitle(entries: readonly WikiPageEntry[]): Map<string, string> {\n const map = new Map<string, string>();\n entries.forEach((entry) => {\n if (entry.title.length > 0 && !map.has(entry.title)) map.set(entry.title, entry.slug);\n });\n return map;\n}\n\n/** Resolve a raw `[[link]]` target to an existing page slug, or null:\n * known slug first, then an index entry's title. Every consumer that\n * judges whether a link points at a real page — the graph and the\n * lint — shares this, so a link cannot be an edge in one and a broken\n * link in the other. */\nexport function resolveLinkTarget(target: string, fileSlugs: SlugLookup, slugByTitle: ReadonlyMap<string, string>): string | null {\n const matched = matchWikiSlug(target, fileSlugs);\n if (matched !== null) return matched;\n const byTitle = slugByTitle.get(target.trim());\n return byTitle !== undefined && fileSlugs.has(byTitle) ? byTitle : null;\n}\n","// Pure parsers for `data/wiki/index.md` content. Used by:\n// - server/api/routes/wiki.ts — page resolver + lint\n// - frontend lint preview (future) — same parser, no fork\n//\n// All exports here are pure string ops; no `node:*` imports allowed.\n// If a future caller needs to walk the filesystem, that wrapper goes\n// under `@mulmoclaude/core/wiki/server` (today only `server/paths.ts`\n// touches `node:path`; nothing here touches disk).\n\nimport { parseWikiLink } from \"./link.js\";\nimport { wikiPageStem, wikiSlugify } from \"./slug.js\";\n\nexport interface WikiPageEntry {\n title: string;\n slug: string;\n description: string;\n tags: string[];\n}\n\n// ── Patterns ──────────────────────────────────────────────────\n// Bullet patterns live here (not server/utils/regex.ts) because the\n// index parser is the only consumer and the regexes are part of the\n// public surface that callers may want to reason about in tests.\n// Linear in line length: every `[^x]+` runs over a fixed exclusion\n// set with a hard delimiter; the optional summary group's `(.*)` is\n// a single greedy run with no nested overlap.\n\n// eslint-disable-next-line security/detect-unsafe-regex -- bullet-link parser; bounded captures with hard delimiters\nexport const BULLET_LINK_PATTERN = /^[-*]\\s+\\[([^\\]]+)\\]\\(([^)]*)\\)(?:\\s*[—–-]\\s*(.*))?/;\n// eslint-disable-next-line security/detect-unsafe-regex -- same shape as BULLET_LINK_PATTERN\nexport const BULLET_WIKI_LINK_PATTERN = /^[-*]\\s+\\[\\[([^\\]]+)\\]\\](?:\\s*[—–-]\\s*(.*))?/;\n\nconst TABLE_SEPARATOR_PATTERN = /^\\|[\\s|:-]+\\|$/;\n\n// Unicode-aware tag body: any letter or number in any script (so\n// Japanese / Chinese / Korean tags like `#クラウド` or `#可視化` work),\n// plus `-` and `_` as internal joiners. First char is a letter or\n// number only — no leading punctuation.\nconst HASHTAG_PATTERN = /(?:^|\\s)#([\\p{L}\\p{N}][\\p{L}\\p{N}_-]*)/gu;\n\n// ── Tag extraction ────────────────────────────────────────────\n\n/** Extract `#tag` tokens from a bullet description, returning the\n * stripped description and a sorted, deduped, lowercased tag list.\n * Only matches at word boundaries so mid-word `#` (e.g. anchor\n * URLs) is left alone. */\nexport function extractHashTags(text: string): { description: string; tags: string[] } {\n HASHTAG_PATTERN.lastIndex = 0;\n const tags = [...text.matchAll(HASHTAG_PATTERN)].flatMap(([, tag]) => (tag ? [tag.toLowerCase()] : []));\n const description = text.replace(HASHTAG_PATTERN, \"\").replace(/\\s+/g, \" \").trim();\n const deduped = [...new Set(tags)].sort();\n return { description, tags: deduped };\n}\n\n/** Split a table Tags cell — tolerates comma, whitespace, or `#`\n * prefixes. Empty cell yields an empty list. */\nexport function parseTagsCell(cell: string): string[] {\n const tokens = cell\n .split(/[,\\s]+/)\n .map((token) => token.trim().replace(/^#/, \"\").toLowerCase())\n .filter((token) => token.length > 0);\n return [...new Set(tokens)].sort();\n}\n\n// ── Table parser ──────────────────────────────────────────────\n\n/** Map header cell names → column indices, case- and whitespace-\n * tolerant. Used by the row parser to locate the Tags column (and\n * any other named column) without assuming a fixed position, so\n * older 3- and 4-column tables keep working. */\nexport function buildTableColumnMap(headerRow: string): Map<string, number> {\n const cells = headerRow\n .split(\"|\")\n .slice(1, -1)\n // Mirror parseTableRow's cell-normalising: strip the surrounding\n // backticks that commonly wrap cell values in wiki tables.\n // Without this, a `| \\`tags\\` |` header maps to the key \"`tags`\"\n // and the subsequent `columnMap.get(\"tags\")` lookup silently\n // misses the column, falling back to `tags: []`.\n .map((cell) => cell.trim().replace(/^`|`$/g, \"\").toLowerCase());\n const map = new Map<string, number>();\n cells.forEach((cell, i) => {\n if (cell) map.set(cell, i);\n });\n return map;\n}\n\ninterface TableColumnIndices {\n slug: number;\n title: number;\n summary: number;\n /** Undefined when the table has no `tags` column — caller skips\n * the tags lookup entirely and the row gets `tags: []`. */\n tags: number | undefined;\n}\n\n/** Resolve the per-column indices the row parser needs. Falls back\n * to positional defaults (0/1/2) when the table has no header map.\n * \"summary\" is the canonical column name; \"description\" is accepted\n * as a legacy alias used by older fixtures. */\nfunction resolveTableColumnIndices(columnMap: Map<string, number> | null): TableColumnIndices {\n return {\n slug: columnMap?.get(\"slug\") ?? 0,\n title: columnMap?.get(\"title\") ?? 1,\n summary: columnMap?.get(\"summary\") ?? columnMap?.get(\"description\") ?? 2,\n tags: columnMap?.get(\"tags\"),\n };\n}\n\nfunction parseTableRow(trimmed: string, columnMap: Map<string, number> | null): WikiPageEntry | null {\n const cols = trimmed\n .split(\"|\")\n .slice(1, -1)\n .map((column) => column.trim().replace(/^`|`$/g, \"\"));\n if (cols.length < 2) return null;\n\n const idx = resolveTableColumnIndices(columnMap);\n const slug = cols[idx.slug] ?? \"\";\n const title = cols[idx.title] || slug;\n if (!slug || !title) return null;\n\n const description = cols[idx.summary] ?? \"\";\n const tags = idx.tags !== undefined ? parseTagsCell(cols[idx.tags] ?? \"\") : [];\n return { title, slug, description, tags };\n}\n\n// ── Bullet-row parsers ────────────────────────────────────────\n\n/** Extract the slug segment from a bullet link's href. Accepts the\n * canonical `pages/<slug>.md`, a bare `<slug>.md`, or just `<slug>`\n * — the three forms produced by different historical writers of\n * index.md. Returns \"\" for hrefs that don't look like a wiki page\n * reference (e.g. `https://example.com`) so the caller can fall\n * back to title-based slugification. */\nexport function extractSlugFromBulletHref(rawHref: string): string {\n const href = rawHref.trim();\n if (!href) return \"\";\n if (/^[a-z]+:\\/\\//i.test(href)) return \"\";\n const lastSegment = href.split(\"/\").pop() ?? href;\n return lastSegment.replace(/\\.md$/i, \"\");\n}\n\n/** Slug for an entry whose only identifier is human-written text.\n * A page file may be named in Japanese, and its slug IS that filename\n * stem — slugifying would index `-4` and leave the real file reported\n * as both missing and orphaned (#2944). `wikiPageStem` keeps the\n * hyphenated convention for ASCII and returns null for a name no file\n * could carry, where the old slug is still the best guess. */\nfunction entrySlugFor(name: string): string {\n return wikiPageStem(name) ?? wikiSlugify(name);\n}\n\nfunction parseBulletLinkRow(trimmed: string): WikiPageEntry | null {\n const match = BULLET_LINK_PATTERN.exec(trimmed);\n if (!match) return null;\n const title = match[1]?.trim() ?? \"\";\n const href = match[2] ?? \"\";\n const raw = match[3]?.trim() ?? \"\";\n const { description, tags } = extractHashTags(raw);\n // Prefer the slug embedded in the href so non-ASCII titles keep\n // a navigable slug. Fall back to the title only when the href has\n // no recognisable slug (rare — usually means the author put an\n // external URL here).\n const slug = extractSlugFromBulletHref(href) || entrySlugFor(title);\n return { title, slug, description, tags };\n}\n\nfunction parseBulletWikiLinkRow(trimmed: string): WikiPageEntry | null {\n const match = BULLET_WIKI_LINK_PATTERN.exec(trimmed);\n if (!match) return null;\n // Split `[[target|display]]` so the bullet entry's slug derives\n // from the TARGET (which is already a slug-shaped identifier\n // when the author wrote the alias form) and the title shows\n // the DISPLAY half. Pre-#1297 the parser slugified the full\n // `target|display` body, which collapses `|` to \"\" and\n // produces a wrong slug — Codex review on PR #1312.\n const { target, display } = parseWikiLink(match[1] ?? \"\");\n const title = (display || target).trim();\n // No title fallback: an explicitly empty target (`- [[|display]]`) is\n // malformed, and borrowing the display half would let it name a real\n // page — silently accepting the typo instead of reporting it. An\n // empty slug reaches `findMissingFiles`, which says so (#2944).\n const slug = entrySlugFor(target);\n const raw = match[2]?.trim() ?? \"\";\n const { description, tags } = extractHashTags(raw);\n return { title, slug, description, tags };\n}\n\n// ── Top-level parser ──────────────────────────────────────────\n\n/** Parse entries from index.md. Supports three formats:\n * 1. Table: `| slug | Title | Summary | (Tags) |`\n * 2. Bullet link: `- [Title](pages/slug.md) — description`\n * 3. Wiki link: `- [[Title]] — description`\n *\n * Returns entries in source order. Any unrecognised line is\n * silently skipped — index.md is freeform markdown otherwise. */\nexport function parseIndexEntries(content: string): WikiPageEntry[] {\n const entries: WikiPageEntry[] = [];\n let inTable = false;\n let columnMap: Map<string, number> | null = null;\n\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n\n if (trimmed.startsWith(\"|\")) {\n if (TABLE_SEPARATOR_PATTERN.test(trimmed)) {\n inTable = true;\n continue;\n }\n if (!inTable) {\n // First `|`-line before the separator is the header. Capture\n // the column map so parseTableRow can locate the Tags\n // column (if any) by name rather than position.\n columnMap = buildTableColumnMap(trimmed);\n inTable = true;\n continue;\n }\n const entry = parseTableRow(trimmed, columnMap);\n if (entry) entries.push(entry);\n continue;\n }\n\n inTable = false;\n columnMap = null;\n\n const bullet = parseBulletLinkRow(trimmed) ?? parseBulletWikiLinkRow(trimmed);\n if (bullet) entries.push(bullet);\n }\n return entries;\n}\n","// Pure wiki lint rules.\n//\n// Each rule takes plain inputs (Sets, page-entry arrays, raw file\n// contents) so the whole pipeline can be unit-tested without\n// filesystem fixtures. The Express route at\n// `server/api/routes/wiki.ts` is a thin shell that reads the disk,\n// calls these rules, formats the result. A future frontend \"lint\n// preview before save\" would call the same functions over an\n// in-memory snapshot.\n\nimport type { WikiPageEntry } from \"./index-parse.js\";\nimport { WIKI_LINK_PATTERN, parseWikiLink } from \"./link.js\";\nimport { resolveLinkTarget } from \"./resolve.js\";\nimport { wikiPageStem } from \"./slug.js\";\n\n/** Files on disk that aren't referenced by index.md. */\nexport function findOrphanPages(fileSlugs: ReadonlySet<string>, indexedSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n for (const slug of fileSlugs) {\n if (!indexedSlugs.has(slug)) {\n issues.push(`- **Orphan page**: \\`${slug}.md\\` exists but is missing from index.md`);\n }\n }\n return issues;\n}\n\n/** Slugs referenced by index.md that have no corresponding file. */\nexport function findMissingFiles(pageEntries: readonly WikiPageEntry[], fileSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n for (const entry of pageEntries) {\n if (entry.slug.length === 0) {\n issues.push(`- **Malformed entry**: index.md lists \\`${entry.title}\\` with no page name`);\n } else if (!fileSlugs.has(entry.slug)) {\n issues.push(`- **Missing file**: index.md references \\`${entry.slug}\\` but the file does not exist`);\n }\n }\n return issues;\n}\n\n/** One `[[…]]` body's diagnostic, or null when the link resolves.\n *\n * Critically: this routes through `parseWikiLink` so\n * `[[slug|display]]` is split correctly — the lint resolves the\n * TARGET, not the full bracket body. Pre-#1297 the lint\n * slugified the entire content (`slug|display`), which collapsed\n * to a slug that always missed and produced ~168 false-positive\n * \"broken link\" warnings. */\nfunction brokenLinkIssue(fileName: string, body: string, fileSlugs: ReadonlySet<string>, slugByTitle: ReadonlyMap<string, string>): string | null {\n const { target } = parseWikiLink(body);\n // Empty target is its own diagnostic — `[[|display]]` has nothing to\n // resolve and would otherwise be flagged identically to a real broken\n // link. Keep the original raw bracket body in the report so the user\n // can grep their pages for the malformed link. (`[[]]` never reaches\n // here: a zero-length body matches neither `WIKI_LINK_PATTERN` nor the\n // renderer's scanner, so it stays literal text everywhere.)\n if (target.trim().length === 0) return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → empty target`;\n if (resolveLinkTarget(target, fileSlugs, slugByTitle) !== null) return null;\n const stem = wikiPageStem(target);\n // A target the write guard would reject has no file to suggest —\n // saying `../secrets.md not found` invites creating what cannot\n // exist (CodeRabbit review).\n if (stem === null) return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → \\`${target.trim()}\\` cannot be a page filename`;\n return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → \\`${stem}.md\\` not found`;\n}\n\n/** Walk a page's body for `[[…]]` links and flag any whose target\n * doesn't resolve to a file.\n *\n * `slugByTitle` (from `slugByIndexTitle`) is what lets a link written\n * as an index.md display title count as resolved — without it the\n * lint calls broken exactly the links the page resolver and the graph\n * follow happily. It defaults to empty so a caller linting an\n * in-memory snapshot with no index still works. */\nexport function findBrokenLinksInPage(\n fileName: string,\n content: string,\n fileSlugs: ReadonlySet<string>,\n slugByTitle: ReadonlyMap<string, string> = new Map(),\n): string[] {\n return [...content.matchAll(WIKI_LINK_PATTERN)]\n .map(([, body = \"\"]) => brokenLinkIssue(fileName, body, fileSlugs, slugByTitle))\n .filter((issue): issue is string => issue !== null);\n}\n\nfunction formatTagList(tags: readonly string[]): string {\n return `[${[...tags].sort().join(\", \")}]`;\n}\n\n/** Flag any slug whose index.md tags differ from the page's own\n * frontmatter `tags:` field. Comparison is set-based and order-\n * insensitive; both sides are lowercased at parse time. Slugs\n * missing from `frontmatterTagsBySlug` are ignored here — the\n * missing file itself is already reported by `findMissingFiles`. */\nexport function findTagDrift(pageEntries: readonly WikiPageEntry[], frontmatterTagsBySlug: ReadonlyMap<string, readonly string[]>): string[] {\n const issues: string[] = [];\n for (const entry of pageEntries) {\n // Lowercase on lookup — the caller keys the map with\n // lowercased slugs, so a `MyPage.md` filename still matches\n // an `entry.slug` of `mypage` produced by `wikiSlugify` on the\n // wiki-link parser path.\n const pageTags = frontmatterTagsBySlug.get(entry.slug.toLowerCase());\n if (pageTags === undefined) continue;\n const pageSet = new Set(pageTags);\n const indexSet = new Set(entry.tags);\n if (pageSet.size !== indexSet.size || [...pageSet].some((tag) => !indexSet.has(tag))) {\n issues.push(`- **Tag drift**: \\`${entry.slug}.md\\` frontmatter has ${formatTagList(pageTags)} but index.md has ${formatTagList(entry.tags)}`);\n }\n }\n return issues;\n}\n\n/** Render the final markdown report from the accumulated issues\n * list. Empty input yields the \"wiki is healthy\" sentinel so the\n * caller can write the same file every time without branching on\n * presence. */\nexport function formatLintReport(issues: readonly string[]): string {\n if (issues.length === 0) {\n return \"# Wiki Lint Report\\n\\n✓ No issues found. Wiki is healthy.\";\n }\n const noun = `issue${issues.length !== 1 ? \"s\" : \"\"}`;\n return `# Wiki Lint Report\\n\\n${issues.length} ${noun} found:\\n\\n${issues.join(\"\\n\")}`;\n}\n","// Pure builder for the wiki page→page link graph. Used by:\n// - server/api/routes/wiki.ts — the `graph` action endpoint\n// - src/plugins/wiki/View.vue — backlinks (\"linked references\") +\n// the Graph tab\n//\n// All functions are pure string / collection ops; no `node:*` imports,\n// so the frontend bundle can import them directly (same discipline as\n// the sibling `link.ts` / `lint.ts` / `index-parse.ts` modules).\n//\n// NOTE: this is page→page link structure, distinct from the\n// `server/workspace/wiki-backlinks/` module, which appends *session*\n// backlinks (a page → the chat that edited it, #109). Different concept\n// — do not conflate.\n\nimport { WIKI_LINK_PATTERN, parseWikiLink } from \"./link.js\";\nimport { resolveLinkTarget, slugByIndexTitle } from \"./resolve.js\";\nimport type { WikiPageEntry } from \"./index-parse.js\";\n\nexport interface WikiGraphNode {\n slug: string;\n title: string;\n}\n\nexport interface WikiGraphEdge {\n from: string;\n to: string;\n}\n\nexport interface WikiGraph {\n nodes: WikiGraphNode[];\n edges: WikiGraphEdge[];\n}\n\n/** One page's raw body plus its canonical (file-derived) slug. */\nexport interface WikiPageContent {\n slug: string;\n content: string;\n}\n\n/** Resolved, deduped outgoing slugs for one page body. Self-links and\n * links to non-existent pages are dropped (the latter are already a\n * lint \"broken link\", not a graph edge). */\nexport function pageOutgoingSlugs(fromSlug: string, content: string, fileSlugs: ReadonlySet<string>, slugByTitle: ReadonlyMap<string, string>): string[] {\n const out = new Set<string>();\n for (const [, body = \"\"] of content.matchAll(WIKI_LINK_PATTERN)) {\n const { target } = parseWikiLink(body);\n const resolved = resolveLinkTarget(target, fileSlugs, slugByTitle);\n if (resolved !== null && resolved !== fromSlug) out.add(resolved);\n }\n return [...out];\n}\n\nfunction buildTitleMaps(entries: readonly WikiPageEntry[]): { titleBySlug: Map<string, string>; slugByTitle: Map<string, string> } {\n const titleBySlug = new Map<string, string>();\n entries.forEach((entry) => {\n if (!titleBySlug.has(entry.slug)) titleBySlug.set(entry.slug, entry.title);\n });\n return { titleBySlug, slugByTitle: slugByIndexTitle(entries) };\n}\n\n/** Build the full page→page graph. Nodes are the existing page files\n * (titled from index.md, falling back to the slug for un-indexed\n * pages); edges are the resolved `[[links]]`, deduped per (from,to). */\nexport function buildWikiGraph(pages: readonly WikiPageContent[], entries: readonly WikiPageEntry[]): WikiGraph {\n const fileSlugs = new Set(pages.map((page) => page.slug));\n const { titleBySlug, slugByTitle } = buildTitleMaps(entries);\n const nodes: WikiGraphNode[] = pages.map((page) => ({ slug: page.slug, title: titleBySlug.get(page.slug) ?? page.slug }));\n const edges: WikiGraphEdge[] = [];\n const seen = new Set<string>();\n for (const page of pages) {\n for (const toSlug of pageOutgoingSlugs(page.slug, page.content, fileSlugs, slugByTitle)) {\n // Newline cannot appear in a wiki slug, so it is a safe pair key.\n const key = [page.slug, toSlug].join(\"\\n\");\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({ from: page.slug, to: toSlug });\n }\n }\n return { nodes, edges };\n}\n\n/** Pages that link TO `slug` (incoming edges), deduped, as nodes. */\nexport function incomingLinks(graph: WikiGraph, slug: string): WikiGraphNode[] {\n const nodeBySlug = new Map(graph.nodes.map((node) => [node.slug, node]));\n const result: WikiGraphNode[] = [];\n const seen = new Set<string>();\n for (const edge of graph.edges) {\n if (edge.to !== slug || seen.has(edge.from)) continue;\n seen.add(edge.from);\n const node = nodeBySlug.get(edge.from);\n if (node) result.push(node);\n }\n return result;\n}\n"],"mappings":";AA4BA,IAAa,oBAAoB,IAAI,OAAO,sCAAuD,GAAG;;;;;;;;;;;;;;;;;;;;AA+BtG,SAAgB,cAAc,OAAyB;CACrD,MAAM,UAAU,MAAM,QAAQ,GAAG;CACjC,IAAI,YAAY,IACd,OAAO;EAAE,QAAQ;EAAO,SAAS;CAAM;CAIzC,OAAO;EAAE,QAFM,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,KAE9B;EAAQ,SADD,MAAM,MAAM,UAAU,CACrB;CAAQ;AAC3B;;;;;;;;;;;AC5CA,SAAgB,cAAc,QAAgB,OAAkC;CAC9E,MAAM,UAAU,OAAO,KAAK;CAC5B,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,IAAI,MAAM,IAAI,OAAO,GAAG,OAAO;CAC/B,MAAM,OAAO,aAAA,YAAY,OAAO;CAChC,IAAI,KAAK,SAAS,KAAK,MAAM,IAAI,IAAI,GAAG,OAAO;CAC/C,OAAO;AACT;;;AAIA,SAAgB,iBAAiB,SAAwD;CACvF,MAAM,sBAAM,IAAI,IAAoB;CACpC,QAAQ,SAAS,UAAU;EACzB,IAAI,MAAM,MAAM,SAAS,KAAK,CAAC,IAAI,IAAI,MAAM,KAAK,GAAG,IAAI,IAAI,MAAM,OAAO,MAAM,IAAI;CACtF,CAAC;CACD,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAkB,QAAgB,WAAuB,aAAyD;CAChI,MAAM,UAAU,cAAc,QAAQ,SAAS;CAC/C,IAAI,YAAY,MAAM,OAAO;CAC7B,MAAM,UAAU,YAAY,IAAI,OAAO,KAAK,CAAC;CAC7C,OAAO,YAAY,KAAA,KAAa,UAAU,IAAI,OAAO,IAAI,UAAU;AACrE;;;ACxBA,IAAa,sBAAsB;AAEnC,IAAa,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AI,IAAY;CAC7B,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,UAAU,kBAAkB,KAAK,MAAM,KAAK,SAAS,WAAW,WAAW,GAAG;EAEvF,MAAM,MAAM,CAAC,KAAK,MAAM,MAAM,CAAC,CAAC,KAAK,IAAI;EACzC,IAAI,KAAK,IAAI,GAAG,GAAG;EACnB,KAAK,IAAI,GAAG;EACZ,MAAM,KAAK;GAAE,MAAM,KAAK;GAAM,IAAI;EAAO,CAAC;CAC5C;CAEF,OAAO;EAAE;EAAO;CAAM;AACxB;;AAGA,SAAgB,cAAc,OAAkB,MAA+B;CAC7E,MAAM,aAAa,IAAI,IAAI,MAAM,MAAM,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;CACvE,MAAM,SAA0B,CAAC;CACjC,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,QAAQ,MAAM,OAAO;EAC9B,IAAI,KAAK,OAAO,QAAQ,KAAK,IAAI,KAAK,IAAI,GAAG;EAC7C,KAAK,IAAI,KAAK,IAAI;EAClB,MAAM,OAAO,WAAW,IAAI,KAAK,IAAI;EACrC,IAAI,MAAM,OAAO,KAAK,IAAI;CAC5B;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"graph-CURotEkH.cjs","names":["wikiSlugify","wikiPageStem","wikiSlugify","wikiPageStem"],"sources":["../src/wiki/link.ts","../src/wiki/resolve.ts","../src/wiki/index-parse.ts","../src/wiki/lint.ts","../src/wiki/graph.ts"],"sourcesContent":["// Pure helpers for `[[wiki-link]]` syntax. Used by the lint\n// (`server/api/routes/wiki.ts`), the page resolver, and the\n// frontend renderer (`src/plugins/wiki/helpers.ts`) — before this\n// module the three sites each had their own implementation and\n// none of them handled the `[[target|display]]` form, producing\n// false-positive \"broken link\" warnings on slug-aliased links\n// (issue #1297).\n//\n// All functions are pure string operations; safe to import from\n// browser bundles. No `node:*` imports anywhere in this file.\n\n/** Inline `[[...]]` link pattern. The capture group is the raw\n * text between the brackets — the caller is expected to feed it\n * through `parseWikiLink` to split off any `|display` suffix.\n *\n * Body length is capped at 200 chars to keep the regex linear:\n * catastrophic backtracking isn't possible (no nested\n * alternation), but a malicious page with thousands of\n * unmatched `[[` could still pin the CPU. 200 is well above the\n * longest legitimate title we've seen and matches the cap the\n * server-side `WIKI_LINK_PATTERN` constant has carried since the\n * original implementation in #951.\n *\n * Shared with the renderer's hand-rolled scanner so the two can't\n * drift: the renderer must reject the same newline-bearing and\n * over-length bodies, or a link would render clickable while the\n * graph / backlinks / lint (which use this pattern) never see it. */\nexport const WIKI_LINK_MAX_LEN = 200;\nexport const WIKI_LINK_PATTERN = new RegExp(`\\\\[\\\\[([^\\\\][\\\\r\\\\n]{1,${WIKI_LINK_MAX_LEN}})\\\\]\\\\]`, \"g\");\n\n/** The structural shape of an inline `[[target|display]]` link.\n * `target` is what the resolver / lint compares against page\n * slugs; `display` is what the renderer shows to the user.\n * When the user writes `[[foo]]` (no pipe), both fields hold\n * `foo`. */\nexport interface WikiLink {\n target: string;\n display: string;\n}\n\n/** Split the raw text inside `[[...]]` into target + display.\n *\n * - `[[foo|Bar Baz]]` → `{ target: \"foo\", display: \"Bar Baz\" }`\n * - `[[foo]]` → `{ target: \"foo\", display: \"foo\" }`\n * - `[[|empty target]]` → `{ target: \"\", display: \"empty target\" }`\n * (caller decides whether an empty target is meaningful;\n * typically lint flags it, renderer shows the display text raw)\n * - `[[foo|]]` → `{ target: \"foo\", display: \"\" }`\n * (same — caller decides)\n *\n * Whitespace around the pipe is preserved on the display side\n * (so the user can write `[[foo| ある記事 ]]` and get the\n * spacing intentionally) but TRIMMED on the target side, since\n * a slug-comparable target with leading/trailing whitespace is\n * always a typo.\n *\n * Only the FIRST pipe splits. `[[a|b|c]]` becomes\n * `{ target: \"a\", display: \"b|c\" }` so display strings can\n * legitimately contain a literal `|`. */\nexport function parseWikiLink(inner: string): WikiLink {\n const pipeIdx = inner.indexOf(\"|\");\n if (pipeIdx === -1) {\n return { target: inner, display: inner };\n }\n const target = inner.slice(0, pipeIdx).trim();\n const display = inner.slice(pipeIdx + 1);\n return { target, display };\n}\n","// The one rule for \"does this `[[link]]` target name an existing page?\".\n// Shared by the page resolver, the lint, and the graph so the three\n// cannot disagree on which files a target can reach.\n//\n// Pure string + lookup work; safe to import from browser bundles.\n\nimport type { WikiPageEntry } from \"./index-parse.js\";\nimport { wikiSlugify } from \"./slug.js\";\n\n/** Anything that can answer \"do you hold this slug?\" — the page index\n * (`Map<slug, filename>`) and the lint's `Set<slug>` both qualify. */\nexport interface SlugLookup {\n has: (slug: string) => boolean;\n}\n\n/** Match a raw link target against known page slugs, returning the\n * matched slug or null.\n *\n * Literal first: page slugs ARE filename stems, so a non-ASCII page\n * only ever matches its own untouched name — `wikiSlugify` strips\n * every non-ASCII character and would reduce `不耕起栽培-カバークロップ4年計画`\n * to `-4` (#2940). The slugified form still runs second so\n * `[[Sakura Internet]]` keeps resolving to `sakura-internet.md`. */\nexport function matchWikiSlug(target: string, known: SlugLookup): string | null {\n const literal = target.trim();\n if (literal.length === 0) return null;\n if (known.has(literal)) return literal;\n const slug = wikiSlugify(literal);\n if (slug.length > 0 && known.has(slug)) return slug;\n return null;\n}\n\n/** index.md title → slug, first entry wins. The fallback for links\n * written as the display title rather than the page's own name. */\nexport function slugByIndexTitle(entries: readonly WikiPageEntry[]): Map<string, string> {\n const map = new Map<string, string>();\n entries.forEach((entry) => {\n if (entry.title.length > 0 && !map.has(entry.title)) map.set(entry.title, entry.slug);\n });\n return map;\n}\n\n/** Resolve a raw `[[link]]` target to an existing page slug, or null:\n * known slug first, then an index entry's title. Every consumer that\n * judges whether a link points at a real page — the graph and the\n * lint — shares this, so a link cannot be an edge in one and a broken\n * link in the other. */\nexport function resolveLinkTarget(target: string, fileSlugs: SlugLookup, slugByTitle: ReadonlyMap<string, string>): string | null {\n const matched = matchWikiSlug(target, fileSlugs);\n if (matched !== null) return matched;\n const byTitle = slugByTitle.get(target.trim());\n return byTitle !== undefined && fileSlugs.has(byTitle) ? byTitle : null;\n}\n","// Pure parsers for `data/wiki/index.md` content. Used by:\n// - server/api/routes/wiki.ts — page resolver + lint\n// - frontend lint preview (future) — same parser, no fork\n//\n// All exports here are pure string ops; no `node:*` imports allowed.\n// If a future caller needs to walk the filesystem, that wrapper goes\n// under `@mulmoclaude/core/wiki/server` (today only `server/paths.ts`\n// touches `node:path`; nothing here touches disk).\n\nimport { parseWikiLink } from \"./link.js\";\nimport { wikiPageStem, wikiSlugify } from \"./slug.js\";\n\nexport interface WikiPageEntry {\n title: string;\n slug: string;\n description: string;\n tags: string[];\n}\n\n// ── Patterns ──────────────────────────────────────────────────\n// Bullet patterns live here (not server/utils/regex.ts) because the\n// index parser is the only consumer and the regexes are part of the\n// public surface that callers may want to reason about in tests.\n// Linear in line length: every `[^x]+` runs over a fixed exclusion\n// set with a hard delimiter; the optional summary group's `(.*)` is\n// a single greedy run with no nested overlap.\n\n// eslint-disable-next-line security/detect-unsafe-regex -- bullet-link parser; bounded captures with hard delimiters\nexport const BULLET_LINK_PATTERN = /^[-*]\\s+\\[([^\\]]+)\\]\\(([^)]*)\\)(?:\\s*[—–-]\\s*(.*))?/;\n// eslint-disable-next-line security/detect-unsafe-regex -- same shape as BULLET_LINK_PATTERN\nexport const BULLET_WIKI_LINK_PATTERN = /^[-*]\\s+\\[\\[([^\\]]+)\\]\\](?:\\s*[—–-]\\s*(.*))?/;\n\nconst TABLE_SEPARATOR_PATTERN = /^\\|[\\s|:-]+\\|$/;\n\n// Unicode-aware tag body: any letter or number in any script (so\n// Japanese / Chinese / Korean tags like `#クラウド` or `#可視化` work),\n// plus `-` and `_` as internal joiners. First char is a letter or\n// number only — no leading punctuation.\nconst HASHTAG_PATTERN = /(?:^|\\s)#([\\p{L}\\p{N}][\\p{L}\\p{N}_-]*)/gu;\n\n// ── Tag extraction ────────────────────────────────────────────\n\n/** Extract `#tag` tokens from a bullet description, returning the\n * stripped description and a sorted, deduped, lowercased tag list.\n * Only matches at word boundaries so mid-word `#` (e.g. anchor\n * URLs) is left alone. */\nexport function extractHashTags(text: string): { description: string; tags: string[] } {\n HASHTAG_PATTERN.lastIndex = 0;\n const tags = [...text.matchAll(HASHTAG_PATTERN)].flatMap(([, tag]) => (tag ? [tag.toLowerCase()] : []));\n const description = text.replace(HASHTAG_PATTERN, \"\").replace(/\\s+/g, \" \").trim();\n const deduped = [...new Set(tags)].sort();\n return { description, tags: deduped };\n}\n\n/** Split a table Tags cell — tolerates comma, whitespace, or `#`\n * prefixes. Empty cell yields an empty list. */\nexport function parseTagsCell(cell: string): string[] {\n const tokens = cell\n .split(/[,\\s]+/)\n .map((token) => token.trim().replace(/^#/, \"\").toLowerCase())\n .filter((token) => token.length > 0);\n return [...new Set(tokens)].sort();\n}\n\n// ── Table parser ──────────────────────────────────────────────\n\n/** Map header cell names → column indices, case- and whitespace-\n * tolerant. Used by the row parser to locate the Tags column (and\n * any other named column) without assuming a fixed position, so\n * older 3- and 4-column tables keep working. */\nexport function buildTableColumnMap(headerRow: string): Map<string, number> {\n const cells = headerRow\n .split(\"|\")\n .slice(1, -1)\n // Mirror parseTableRow's cell-normalising: strip the surrounding\n // backticks that commonly wrap cell values in wiki tables.\n // Without this, a `| \\`tags\\` |` header maps to the key \"`tags`\"\n // and the subsequent `columnMap.get(\"tags\")` lookup silently\n // misses the column, falling back to `tags: []`.\n .map((cell) => cell.trim().replace(/^`|`$/g, \"\").toLowerCase());\n const map = new Map<string, number>();\n cells.forEach((cell, i) => {\n if (cell) map.set(cell, i);\n });\n return map;\n}\n\ninterface TableColumnIndices {\n slug: number;\n title: number;\n summary: number;\n /** Undefined when the table has no `tags` column — caller skips\n * the tags lookup entirely and the row gets `tags: []`. */\n tags: number | undefined;\n}\n\n/** Resolve the per-column indices the row parser needs. Falls back\n * to positional defaults (0/1/2) when the table has no header map.\n * \"summary\" is the canonical column name; \"description\" is accepted\n * as a legacy alias used by older fixtures. */\nfunction resolveTableColumnIndices(columnMap: Map<string, number> | null): TableColumnIndices {\n return {\n slug: columnMap?.get(\"slug\") ?? 0,\n title: columnMap?.get(\"title\") ?? 1,\n summary: columnMap?.get(\"summary\") ?? columnMap?.get(\"description\") ?? 2,\n tags: columnMap?.get(\"tags\"),\n };\n}\n\nfunction parseTableRow(trimmed: string, columnMap: Map<string, number> | null): WikiPageEntry | null {\n const cols = trimmed\n .split(\"|\")\n .slice(1, -1)\n .map((column) => column.trim().replace(/^`|`$/g, \"\"));\n if (cols.length < 2) return null;\n\n const idx = resolveTableColumnIndices(columnMap);\n const slug = cols[idx.slug] ?? \"\";\n const title = cols[idx.title] || slug;\n if (!slug || !title) return null;\n\n const description = cols[idx.summary] ?? \"\";\n const tags = idx.tags !== undefined ? parseTagsCell(cols[idx.tags] ?? \"\") : [];\n return { title, slug, description, tags };\n}\n\n// ── Bullet-row parsers ────────────────────────────────────────\n\n/** Extract the slug segment from a bullet link's href. Accepts the\n * canonical `pages/<slug>.md`, a bare `<slug>.md`, or just `<slug>`\n * — the three forms produced by different historical writers of\n * index.md. Returns \"\" for hrefs that don't look like a wiki page\n * reference (e.g. `https://example.com`) so the caller can fall\n * back to title-based slugification. */\nexport function extractSlugFromBulletHref(rawHref: string): string {\n const href = rawHref.trim();\n if (!href) return \"\";\n if (/^[a-z]+:\\/\\//i.test(href)) return \"\";\n const lastSegment = href.split(\"/\").pop() ?? href;\n return lastSegment.replace(/\\.md$/i, \"\");\n}\n\n/** Slug for an entry whose only identifier is human-written text.\n * A page file may be named in Japanese, and its slug IS that filename\n * stem — slugifying would index `-4` and leave the real file reported\n * as both missing and orphaned (#2944). `wikiPageStem` keeps the\n * hyphenated convention for ASCII and returns null for a name no file\n * could carry, where the old slug is still the best guess. */\nfunction entrySlugFor(name: string): string {\n return wikiPageStem(name) ?? wikiSlugify(name);\n}\n\nfunction parseBulletLinkRow(trimmed: string): WikiPageEntry | null {\n const match = BULLET_LINK_PATTERN.exec(trimmed);\n if (!match) return null;\n const title = match[1]?.trim() ?? \"\";\n const href = match[2] ?? \"\";\n const raw = match[3]?.trim() ?? \"\";\n const { description, tags } = extractHashTags(raw);\n // Prefer the slug embedded in the href so non-ASCII titles keep\n // a navigable slug. Fall back to the title only when the href has\n // no recognisable slug (rare — usually means the author put an\n // external URL here).\n const slug = extractSlugFromBulletHref(href) || entrySlugFor(title);\n return { title, slug, description, tags };\n}\n\nfunction parseBulletWikiLinkRow(trimmed: string): WikiPageEntry | null {\n const match = BULLET_WIKI_LINK_PATTERN.exec(trimmed);\n if (!match) return null;\n // Split `[[target|display]]` so the bullet entry's slug derives\n // from the TARGET (which is already a slug-shaped identifier\n // when the author wrote the alias form) and the title shows\n // the DISPLAY half. Pre-#1297 the parser slugified the full\n // `target|display` body, which collapses `|` to \"\" and\n // produces a wrong slug — Codex review on PR #1312.\n const { target, display } = parseWikiLink(match[1] ?? \"\");\n const title = (display || target).trim();\n // No title fallback: an explicitly empty target (`- [[|display]]`) is\n // malformed, and borrowing the display half would let it name a real\n // page — silently accepting the typo instead of reporting it. An\n // empty slug reaches `findMissingFiles`, which says so (#2944).\n const slug = entrySlugFor(target);\n const raw = match[2]?.trim() ?? \"\";\n const { description, tags } = extractHashTags(raw);\n return { title, slug, description, tags };\n}\n\n// ── Top-level parser ──────────────────────────────────────────\n\n/** Parse entries from index.md. Supports three formats:\n * 1. Table: `| slug | Title | Summary | (Tags) |`\n * 2. Bullet link: `- [Title](pages/slug.md) — description`\n * 3. Wiki link: `- [[Title]] — description`\n *\n * Returns entries in source order. Any unrecognised line is\n * silently skipped — index.md is freeform markdown otherwise. */\nexport function parseIndexEntries(content: string): WikiPageEntry[] {\n const entries: WikiPageEntry[] = [];\n let inTable = false;\n let columnMap: Map<string, number> | null = null;\n\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n\n if (trimmed.startsWith(\"|\")) {\n if (TABLE_SEPARATOR_PATTERN.test(trimmed)) {\n inTable = true;\n continue;\n }\n if (!inTable) {\n // First `|`-line before the separator is the header. Capture\n // the column map so parseTableRow can locate the Tags\n // column (if any) by name rather than position.\n columnMap = buildTableColumnMap(trimmed);\n inTable = true;\n continue;\n }\n const entry = parseTableRow(trimmed, columnMap);\n if (entry) entries.push(entry);\n continue;\n }\n\n inTable = false;\n columnMap = null;\n\n const bullet = parseBulletLinkRow(trimmed) ?? parseBulletWikiLinkRow(trimmed);\n if (bullet) entries.push(bullet);\n }\n return entries;\n}\n","// Pure wiki lint rules.\n//\n// Each rule takes plain inputs (Sets, page-entry arrays, raw file\n// contents) so the whole pipeline can be unit-tested without\n// filesystem fixtures. The Express route at\n// `server/api/routes/wiki.ts` is a thin shell that reads the disk,\n// calls these rules, formats the result. A future frontend \"lint\n// preview before save\" would call the same functions over an\n// in-memory snapshot.\n\nimport type { WikiPageEntry } from \"./index-parse.js\";\nimport { WIKI_LINK_PATTERN, parseWikiLink } from \"./link.js\";\nimport { resolveLinkTarget } from \"./resolve.js\";\nimport { wikiPageStem } from \"./slug.js\";\n\n/** Files on disk that aren't referenced by index.md. */\nexport function findOrphanPages(fileSlugs: ReadonlySet<string>, indexedSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n for (const slug of fileSlugs) {\n if (!indexedSlugs.has(slug)) {\n issues.push(`- **Orphan page**: \\`${slug}.md\\` exists but is missing from index.md`);\n }\n }\n return issues;\n}\n\n/** Slugs referenced by index.md that have no corresponding file. */\nexport function findMissingFiles(pageEntries: readonly WikiPageEntry[], fileSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n for (const entry of pageEntries) {\n if (entry.slug.length === 0) {\n issues.push(`- **Malformed entry**: index.md lists \\`${entry.title}\\` with no page name`);\n } else if (!fileSlugs.has(entry.slug)) {\n issues.push(`- **Missing file**: index.md references \\`${entry.slug}\\` but the file does not exist`);\n }\n }\n return issues;\n}\n\n/** One `[[…]]` body's diagnostic, or null when the link resolves.\n *\n * Critically: this routes through `parseWikiLink` so\n * `[[slug|display]]` is split correctly — the lint resolves the\n * TARGET, not the full bracket body. Pre-#1297 the lint\n * slugified the entire content (`slug|display`), which collapsed\n * to a slug that always missed and produced ~168 false-positive\n * \"broken link\" warnings. */\nfunction brokenLinkIssue(fileName: string, body: string, fileSlugs: ReadonlySet<string>, slugByTitle: ReadonlyMap<string, string>): string | null {\n const { target } = parseWikiLink(body);\n // Empty target is its own diagnostic — `[[|display]]` has nothing to\n // resolve and would otherwise be flagged identically to a real broken\n // link. Keep the original raw bracket body in the report so the user\n // can grep their pages for the malformed link. (`[[]]` never reaches\n // here: a zero-length body matches neither `WIKI_LINK_PATTERN` nor the\n // renderer's scanner, so it stays literal text everywhere.)\n if (target.trim().length === 0) return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → empty target`;\n if (resolveLinkTarget(target, fileSlugs, slugByTitle) !== null) return null;\n const stem = wikiPageStem(target);\n // A target the write guard would reject has no file to suggest —\n // saying `../secrets.md not found` invites creating what cannot\n // exist (CodeRabbit review).\n if (stem === null) return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → \\`${target.trim()}\\` cannot be a page filename`;\n return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → \\`${stem}.md\\` not found`;\n}\n\n/** Walk a page's body for `[[…]]` links and flag any whose target\n * doesn't resolve to a file.\n *\n * `slugByTitle` (from `slugByIndexTitle`) is what lets a link written\n * as an index.md display title count as resolved — without it the\n * lint calls broken exactly the links the page resolver and the graph\n * follow happily. It defaults to empty so a caller linting an\n * in-memory snapshot with no index still works. */\nexport function findBrokenLinksInPage(\n fileName: string,\n content: string,\n fileSlugs: ReadonlySet<string>,\n slugByTitle: ReadonlyMap<string, string> = new Map(),\n): string[] {\n return [...content.matchAll(WIKI_LINK_PATTERN)]\n .map(([, body = \"\"]) => brokenLinkIssue(fileName, body, fileSlugs, slugByTitle))\n .filter((issue): issue is string => issue !== null);\n}\n\nfunction formatTagList(tags: readonly string[]): string {\n return `[${[...tags].sort().join(\", \")}]`;\n}\n\n/** Flag any slug whose index.md tags differ from the page's own\n * frontmatter `tags:` field. Comparison is set-based and order-\n * insensitive; both sides are lowercased at parse time. Slugs\n * missing from `frontmatterTagsBySlug` are ignored here — the\n * missing file itself is already reported by `findMissingFiles`. */\nexport function findTagDrift(pageEntries: readonly WikiPageEntry[], frontmatterTagsBySlug: ReadonlyMap<string, readonly string[]>): string[] {\n const issues: string[] = [];\n for (const entry of pageEntries) {\n // Lowercase on lookup — the caller keys the map with\n // lowercased slugs, so a `MyPage.md` filename still matches\n // an `entry.slug` of `mypage` produced by `wikiSlugify` on the\n // wiki-link parser path.\n const pageTags = frontmatterTagsBySlug.get(entry.slug.toLowerCase());\n if (pageTags === undefined) continue;\n const pageSet = new Set(pageTags);\n const indexSet = new Set(entry.tags);\n if (pageSet.size !== indexSet.size || [...pageSet].some((tag) => !indexSet.has(tag))) {\n issues.push(`- **Tag drift**: \\`${entry.slug}.md\\` frontmatter has ${formatTagList(pageTags)} but index.md has ${formatTagList(entry.tags)}`);\n }\n }\n return issues;\n}\n\n/** Render the final markdown report from the accumulated issues\n * list. Empty input yields the \"wiki is healthy\" sentinel so the\n * caller can write the same file every time without branching on\n * presence. */\nexport function formatLintReport(issues: readonly string[]): string {\n if (issues.length === 0) {\n return \"# Wiki Lint Report\\n\\n✓ No issues found. Wiki is healthy.\";\n }\n const noun = `issue${issues.length !== 1 ? \"s\" : \"\"}`;\n return `# Wiki Lint Report\\n\\n${issues.length} ${noun} found:\\n\\n${issues.join(\"\\n\")}`;\n}\n","// Pure builder for the wiki page→page link graph. Used by:\n// - server/api/routes/wiki.ts — the `graph` action endpoint\n// - src/plugins/wiki/View.vue — backlinks (\"linked references\") +\n// the Graph tab\n//\n// All functions are pure string / collection ops; no `node:*` imports,\n// so the frontend bundle can import them directly (same discipline as\n// the sibling `link.ts` / `lint.ts` / `index-parse.ts` modules).\n//\n// NOTE: this is page→page link structure, distinct from the\n// `server/workspace/wiki-backlinks/` module, which appends *session*\n// backlinks (a page → the chat that edited it, #109). Different concept\n// — do not conflate.\n\nimport { WIKI_LINK_PATTERN, parseWikiLink } from \"./link.js\";\nimport { resolveLinkTarget, slugByIndexTitle } from \"./resolve.js\";\nimport type { WikiPageEntry } from \"./index-parse.js\";\n\nexport interface WikiGraphNode {\n slug: string;\n title: string;\n}\n\nexport interface WikiGraphEdge {\n from: string;\n to: string;\n}\n\nexport interface WikiGraph {\n nodes: WikiGraphNode[];\n edges: WikiGraphEdge[];\n}\n\n/** One page's raw body plus its canonical (file-derived) slug. */\nexport interface WikiPageContent {\n slug: string;\n content: string;\n}\n\n/** Resolved, deduped outgoing slugs for one page body. Self-links and\n * links to non-existent pages are dropped (the latter are already a\n * lint \"broken link\", not a graph edge). */\nexport function pageOutgoingSlugs(fromSlug: string, content: string, fileSlugs: ReadonlySet<string>, slugByTitle: ReadonlyMap<string, string>): string[] {\n const out = new Set<string>();\n for (const [, body = \"\"] of content.matchAll(WIKI_LINK_PATTERN)) {\n const { target } = parseWikiLink(body);\n const resolved = resolveLinkTarget(target, fileSlugs, slugByTitle);\n if (resolved !== null && resolved !== fromSlug) out.add(resolved);\n }\n return [...out];\n}\n\nfunction buildTitleMaps(entries: readonly WikiPageEntry[]): { titleBySlug: Map<string, string>; slugByTitle: Map<string, string> } {\n const titleBySlug = new Map<string, string>();\n entries.forEach((entry) => {\n if (!titleBySlug.has(entry.slug)) titleBySlug.set(entry.slug, entry.title);\n });\n return { titleBySlug, slugByTitle: slugByIndexTitle(entries) };\n}\n\n/** Build the full page→page graph. Nodes are the existing page files\n * (titled from index.md, falling back to the slug for un-indexed\n * pages); edges are the resolved `[[links]]`, deduped per (from,to). */\nexport function buildWikiGraph(pages: readonly WikiPageContent[], entries: readonly WikiPageEntry[]): WikiGraph {\n const fileSlugs = new Set(pages.map((page) => page.slug));\n const { titleBySlug, slugByTitle } = buildTitleMaps(entries);\n const nodes: WikiGraphNode[] = pages.map((page) => ({ slug: page.slug, title: titleBySlug.get(page.slug) ?? page.slug }));\n const edges: WikiGraphEdge[] = [];\n const seen = new Set<string>();\n for (const page of pages) {\n for (const toSlug of pageOutgoingSlugs(page.slug, page.content, fileSlugs, slugByTitle)) {\n // Newline cannot appear in a wiki slug, so it is a safe pair key.\n const key = [page.slug, toSlug].join(\"\\n\");\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({ from: page.slug, to: toSlug });\n }\n }\n return { nodes, edges };\n}\n\n/** Pages that link TO `slug` (incoming edges), deduped, as nodes. */\nexport function incomingLinks(graph: WikiGraph, slug: string): WikiGraphNode[] {\n const nodeBySlug = new Map(graph.nodes.map((node) => [node.slug, node]));\n const result: WikiGraphNode[] = [];\n const seen = new Set<string>();\n for (const edge of graph.edges) {\n if (edge.to !== slug || seen.has(edge.from)) continue;\n seen.add(edge.from);\n const node = nodeBySlug.get(edge.from);\n if (node) result.push(node);\n }\n return result;\n}\n"],"mappings":";AA4BA,IAAa,oBAAoB,IAAI,OAAO,sCAAuD,GAAG;;;;;;;;;;;;;;;;;;;;AA+BtG,SAAgB,cAAc,OAAyB;CACrD,MAAM,UAAU,MAAM,QAAQ,GAAG;CACjC,IAAI,YAAY,IACd,OAAO;EAAE,QAAQ;EAAO,SAAS;CAAM;CAIzC,OAAO;EAAE,QAFM,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,KAE9B;EAAQ,SADD,MAAM,MAAM,UAAU,CACrB;CAAQ;AAC3B;;;;;;;;;;;AC5CA,SAAgB,cAAc,QAAgB,OAAkC;CAC9E,MAAM,UAAU,OAAO,KAAK;CAC5B,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,IAAI,MAAM,IAAI,OAAO,GAAG,OAAO;CAC/B,MAAM,OAAOA,aAAAA,YAAY,OAAO;CAChC,IAAI,KAAK,SAAS,KAAK,MAAM,IAAI,IAAI,GAAG,OAAO;CAC/C,OAAO;AACT;;;AAIA,SAAgB,iBAAiB,SAAwD;CACvF,MAAM,sBAAM,IAAI,IAAoB;CACpC,QAAQ,SAAS,UAAU;EACzB,IAAI,MAAM,MAAM,SAAS,KAAK,CAAC,IAAI,IAAI,MAAM,KAAK,GAAG,IAAI,IA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mechanism. A Feed is a\n// CollectionSchema plus this `ingest` block, registered as data (NOT as\n// a skill) under `<workspace>/feeds/<slug>/schema.json`. The host's\n// retrieval engine reads it to periodically refill the collection's\n// records via the shared collections io layer.\n//\n// The ingest vocab (INGEST_KINDS / FEED_SCHEDULES + their literal-union types)\n// lives in the sibling `../collection` subpath alongside the schema contract, so\n// the package's schema validator can enforce it. Re-exported here so the feeds\n// engine's existing importers resolve them unchanged.\nimport { INGEST_KINDS, FEED_SCHEDULES, type IngestKind, type FeedSchedule } from \"../collection/index.js\";\n// Type-only: keeps zod out of this module's runtime graph (the feeds engine\n// imports it browser-free through `../collection`'s type surface).\nimport type { z } from \"zod\";\nimport type { AgentIngestZ, DeclarativeIngestZ } from \"../collection/core/schemaZ\";\n//\n// Two flavours: the declarative kinds (`rss`/`atom`/`http-json`) fetch-and-map,\n// and `agent` dispatches a hidden worker. The `code` kind (LLM-generated\n// deterministic transform) is still reserved for a future retriever.\n\n// The agent ingest kind. Defined HERE (not imported from `../collection`) on\n// purpose: the engine only needs the literal to branch, and re-importing it as a\n// VALUE keeps this module free of a value dependency on the collection vocab.\n// Core owns its own copy for the schema validator; this matches the same literal.\nexport const AGENT_INGEST_KIND = \"agent\" as const;\nexport type AgentIngestKind = typeof AGENT_INGEST_KIND;\n\nexport { INGEST_KINDS, FEED_SCHEDULES, type IngestKind, type FeedSchedule };\n\nconst FEED_SCHEDULE_SET: ReadonlySet<string> = new Set(FEED_SCHEDULES);\n\nexport function isFeedSchedule(value: unknown): value is FeedSchedule {\n return typeof value === \"string\" && FEED_SCHEDULE_SET.has(value);\n}\n\n/** Default cap on stored records per feed when `ingest.maxItems` is\n * omitted. Keeps high-volume feeds (news / podcasts) bounded. */\nexport const DEFAULT_FEED_MAX_ITEMS = 100;\n\n/** Declarative field map: target collection field name → source path\n * into the raw item (dot/bracket path, e.g. `\"title\"` or\n * `\"data.name\"`). */\nexport type IngestFieldMap = Record<string, string>;\n\n/** Declarative retrieval (`rss`/`atom`/`http-json`): the host fetches `url`\n * and projects each item through `map` (target field → source path; a\n * `http-json` feed may add `itemsAt`, a dot/bracket path to the items\n * array; `idFrom` derives the primaryKey; `maxItems` caps stored records,\n * default {@link DEFAULT_FEED_MAX_ITEMS}, `0` = keep everything). The\n * canonical loose contract stays the minimal `CollectionIngest`; this\n * feeds subtype is derived from the zod source of truth\n * (`collection/core/schemaZ` `DeclarativeIngestZ`), so the engine and the\n * schema validator can never drift. */\nexport type DeclarativeIngestSpec = z.infer<typeof DeclarativeIngestZ>;\n\n/** Agent-performed retrieval (`kind: \"agent\"`). No `url`/`map`: the host seeds\n * a hidden background worker (origin `system`) in `role` with `template` + a\n * summary of every record, and the worker edits the records itself via the\n * collections io layer. Valid on any collection (primarily skill-backed).\n * Derived from `AgentIngestZ` in `collection/core/schemaZ`. */\nexport type AgentIngestSpec = z.infer<typeof AgentIngestZ>;\n\n/** The `ingest` block carried on a `CollectionSchema`, discriminated on `kind`. */\nexport type IngestSpec = DeclarativeIngestSpec | AgentIngestSpec;\n"],"mappings":";;;AAwBA,IAAa,oBAAoB;AAKjC,IAAM,oBAAyC,IAAI,
|
|
1
|
+
{"version":3,"file":"ingestTypes-DS9HiR2I.cjs","names":["FEED_SCHEDULES"],"sources":["../src/feeds/ingestTypes.ts"],"sourcesContent":["// Declarative retrieval config for the \"Feeds\" mechanism. A Feed is a\n// CollectionSchema plus this `ingest` block, registered as data (NOT as\n// a skill) under `<workspace>/feeds/<slug>/schema.json`. The host's\n// retrieval engine reads it to periodically refill the collection's\n// records via the shared collections io layer.\n//\n// The ingest vocab (INGEST_KINDS / FEED_SCHEDULES + their literal-union types)\n// lives in the sibling `../collection` subpath alongside the schema contract, so\n// the package's schema validator can enforce it. Re-exported here so the feeds\n// engine's existing importers resolve them unchanged.\nimport { INGEST_KINDS, FEED_SCHEDULES, type IngestKind, type FeedSchedule } from \"../collection/index.js\";\n// Type-only: keeps zod out of this module's runtime graph (the feeds engine\n// imports it browser-free through `../collection`'s type surface).\nimport type { z } from \"zod\";\nimport type { AgentIngestZ, DeclarativeIngestZ } from \"../collection/core/schemaZ\";\n//\n// Two flavours: the declarative kinds (`rss`/`atom`/`http-json`) fetch-and-map,\n// and `agent` dispatches a hidden worker. The `code` kind (LLM-generated\n// deterministic transform) is still reserved for a future retriever.\n\n// The agent ingest kind. Defined HERE (not imported from `../collection`) on\n// purpose: the engine only needs the literal to branch, and re-importing it as a\n// VALUE keeps this module free of a value dependency on the collection vocab.\n// Core owns its own copy for the schema validator; this matches the same literal.\nexport const AGENT_INGEST_KIND = \"agent\" as const;\nexport type AgentIngestKind = typeof AGENT_INGEST_KIND;\n\nexport { INGEST_KINDS, FEED_SCHEDULES, type IngestKind, type FeedSchedule };\n\nconst FEED_SCHEDULE_SET: ReadonlySet<string> = new Set(FEED_SCHEDULES);\n\nexport function isFeedSchedule(value: unknown): value is FeedSchedule {\n return typeof value === \"string\" && FEED_SCHEDULE_SET.has(value);\n}\n\n/** Default cap on stored records per feed when `ingest.maxItems` is\n * omitted. Keeps high-volume feeds (news / podcasts) bounded. */\nexport const DEFAULT_FEED_MAX_ITEMS = 100;\n\n/** Declarative field map: target collection field name → source path\n * into the raw item (dot/bracket path, e.g. `\"title\"` or\n * `\"data.name\"`). */\nexport type IngestFieldMap = Record<string, string>;\n\n/** Declarative retrieval (`rss`/`atom`/`http-json`): the host fetches `url`\n * and projects each item through `map` (target field → source path; a\n * `http-json` feed may add `itemsAt`, a dot/bracket path to the items\n * array; `idFrom` derives the primaryKey; `maxItems` caps stored records,\n * default {@link DEFAULT_FEED_MAX_ITEMS}, `0` = keep everything). The\n * canonical loose contract stays the minimal `CollectionIngest`; this\n * feeds subtype is derived from the zod source of truth\n * (`collection/core/schemaZ` `DeclarativeIngestZ`), so the engine and the\n * schema validator can never drift. */\nexport type DeclarativeIngestSpec = z.infer<typeof DeclarativeIngestZ>;\n\n/** Agent-performed retrieval (`kind: \"agent\"`). No `url`/`map`: the host seeds\n * a hidden background worker (origin `system`) in `role` with `template` + a\n * summary of every record, and the worker edits the records itself via the\n * collections io layer. Valid on any collection (primarily skill-backed).\n * Derived from `AgentIngestZ` in `collection/core/schemaZ`. */\nexport type AgentIngestSpec = z.infer<typeof AgentIngestZ>;\n\n/** The `ingest` block carried on a `CollectionSchema`, discriminated on `kind`. */\nexport type IngestSpec = DeclarativeIngestSpec | AgentIngestSpec;\n"],"mappings":";;;AAwBA,IAAa,oBAAoB;AAKjC,IAAM,oBAAyC,IAAI,IAAIA,eAAAA,cAAc;AAErE,SAAgB,eAAe,OAAuC;CACpE,OAAO,OAAO,UAAU,YAAY,kBAAkB,IAAI,KAAK;AACjE;;;AAIA,IAAa,yBAAyB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as isRecord } from "./dist-MFUV9FYo.js";
|
|
2
2
|
//#region src/firestore/listen.ts
|
|
3
3
|
var TRANSIENT_LISTEN_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
4
4
|
"aborted",
|
|
@@ -19,4 +19,4 @@ var backoffDelayMs = (attempt) => Math.min(MAX_LISTEN_RETRY_MS, BASE_LISTEN_RETR
|
|
|
19
19
|
//#endregion
|
|
20
20
|
export { shouldGiveUpListening as i, backoffDelayMs as n, classifyListenerError as r, LISTEN_RETRY_WINDOW_MS as t };
|
|
21
21
|
|
|
22
|
-
//# sourceMappingURL=listen-
|
|
22
|
+
//# sourceMappingURL=listen-DUlzSOzX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listen-
|
|
1
|
+
{"version":3,"file":"listen-DUlzSOzX.js","names":[],"sources":["../src/firestore/listen.ts"],"sourcesContent":["// What is true of a Firestore LISTENER, whatever it is listening to.\n//\n// A `onSnapshot` error terminates that listener and never recovers on its own,\n// so every long-lived listener in this package needs the same three answers:\n// is this error worth re-subscribing for, how long to wait before trying, and\n// when to stop trying. Those answers are about Firestore, not about the feature\n// on top of it.\n//\n// Extracted from `remote-host/server/hostRunner.ts` when the shared-collection\n// store grew a listener of its own. Kept in ONE place deliberately: the two\n// would drift, and drift here is silent — one subsystem would keep retrying a\n// revoked grant forever while the other gave up on a network blip. `hostRunner`\n// re-exports these under their original names, so its published surface (which\n// MulmoTerminal imports) is unchanged.\n\nimport { isRecord } from \"@mulmoclaude/common\";\n\n// Firestore listen errors worth re-subscribing for: network / backend blips, plus\n// `unauthenticated` — the SDK refreshes tokens on its own, so an expired one is\n// fixed by trying again, and stopping the host at the first expiry was far too\n// strong (#2633). Everything else — permission-denied and any unrecognized code —\n// is fatal: re-listening can't restore a revoked grant, and an open-ended retry on\n// an unknown code would loop forever. Retrying is bounded by LISTEN_RETRY_WINDOW_MS\n// either way, so even a doomed retry ends in an escalation rather than a spin.\nconst TRANSIENT_LISTEN_ERROR_CODES = new Set([\"aborted\", \"cancelled\", \"deadline-exceeded\", \"internal\", \"resource-exhausted\", \"unauthenticated\", \"unavailable\"]);\n\nconst listenErrorCode = (error: unknown): string => (isRecord(error) && typeof error.code === \"string\" ? error.code : \"\");\n\nexport const classifyListenerError = (error: unknown): \"transient\" | \"fatal\" =>\n TRANSIENT_LISTEN_ERROR_CODES.has(listenErrorCode(error)) ? \"transient\" : \"fatal\";\n\nconst BASE_LISTEN_RETRY_MS = 1_000;\nconst MAX_LISTEN_RETRY_MS = 30_000;\n// How long a listener may keep failing before its owner stops retrying in place\n// and escalates (re-auth, re-mount). Bounding this by a RETRY COUNT instead made\n// it ~31s of wall clock — shorter than any laptop sleep or network move, after\n// which the host never re-subscribed (#2633).\nexport const LISTEN_RETRY_WINDOW_MS = 5 * 60_000;\n\n// The outage is measured from its first failure, not from the last attempt: a\n// backoff ladder that keeps failing must not extend its own deadline.\nexport const shouldGiveUpListening = (downSinceMs: number, now: number, windowMs: number = LISTEN_RETRY_WINDOW_MS): boolean => now - downSinceMs >= windowMs;\n\n// Exponential backoff, capped: attempt 0 → 1s, 1 → 2s, … saturating at 30s.\nexport const backoffDelayMs = (attempt: number): number => Math.min(MAX_LISTEN_RETRY_MS, BASE_LISTEN_RETRY_MS * 2 ** attempt);\n"],"mappings":";;AAwBA,IAAM,+CAA+B,IAAI,IAAI;CAAC;CAAW;CAAa;CAAqB;CAAY;CAAsB;CAAmB;AAAa,CAAC;AAE9J,IAAM,mBAAmB,UAA4B,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;AAEtH,IAAa,yBAAyB,UACpC,6BAA6B,IAAI,gBAAgB,KAAK,CAAC,IAAI,cAAc;AAE3E,IAAM,uBAAuB;AAC7B,IAAM,sBAAsB;AAK5B,IAAa,yBAAyB;AAItC,IAAa,yBAAyB,aAAqB,KAAa,WAAmB,2BAAoC,MAAM,eAAe;AAGpJ,IAAa,kBAAkB,YAA4B,KAAK,IAAI,qBAAqB,uBAAuB,KAAK,OAAO"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_dist = require("./dist-
|
|
1
|
+
const require_dist = require("./dist-BZ62pKuU.cjs");
|
|
2
2
|
//#region src/firestore/listen.ts
|
|
3
3
|
var TRANSIENT_LISTEN_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
4
4
|
"aborted",
|
|
@@ -42,4 +42,4 @@ Object.defineProperty(exports, "shouldGiveUpListening", {
|
|
|
42
42
|
}
|
|
43
43
|
});
|
|
44
44
|
|
|
45
|
-
//# sourceMappingURL=listen-
|
|
45
|
+
//# sourceMappingURL=listen-N_8XdKz_.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"listen-N_8XdKz_.cjs","names":["isRecord"],"sources":["../src/firestore/listen.ts"],"sourcesContent":["// What is true of a Firestore LISTENER, whatever it is listening to.\n//\n// A `onSnapshot` error terminates that listener and never recovers on its own,\n// so every long-lived listener in this package needs the same three answers:\n// is this error worth re-subscribing for, how long to wait before trying, and\n// when to stop trying. Those answers are about Firestore, not about the feature\n// on top of it.\n//\n// Extracted from `remote-host/server/hostRunner.ts` when the shared-collection\n// store grew a listener of its own. Kept in ONE place deliberately: the two\n// would drift, and drift here is silent — one subsystem would keep retrying a\n// revoked grant forever while the other gave up on a network blip. `hostRunner`\n// re-exports these under their original names, so its published surface (which\n// MulmoTerminal imports) is unchanged.\n\nimport { isRecord } from \"@mulmoclaude/common\";\n\n// Firestore listen errors worth re-subscribing for: network / backend blips, plus\n// `unauthenticated` — the SDK refreshes tokens on its own, so an expired one is\n// fixed by trying again, and stopping the host at the first expiry was far too\n// strong (#2633). Everything else — permission-denied and any unrecognized code —\n// is fatal: re-listening can't restore a revoked grant, and an open-ended retry on\n// an unknown code would loop forever. Retrying is bounded by LISTEN_RETRY_WINDOW_MS\n// either way, so even a doomed retry ends in an escalation rather than a spin.\nconst TRANSIENT_LISTEN_ERROR_CODES = new Set([\"aborted\", \"cancelled\", \"deadline-exceeded\", \"internal\", \"resource-exhausted\", \"unauthenticated\", \"unavailable\"]);\n\nconst listenErrorCode = (error: unknown): string => (isRecord(error) && typeof error.code === \"string\" ? error.code : \"\");\n\nexport const classifyListenerError = (error: unknown): \"transient\" | \"fatal\" =>\n TRANSIENT_LISTEN_ERROR_CODES.has(listenErrorCode(error)) ? \"transient\" : \"fatal\";\n\nconst BASE_LISTEN_RETRY_MS = 1_000;\nconst MAX_LISTEN_RETRY_MS = 30_000;\n// How long a listener may keep failing before its owner stops retrying in place\n// and escalates (re-auth, re-mount). Bounding this by a RETRY COUNT instead made\n// it ~31s of wall clock — shorter than any laptop sleep or network move, after\n// which the host never re-subscribed (#2633).\nexport const LISTEN_RETRY_WINDOW_MS = 5 * 60_000;\n\n// The outage is measured from its first failure, not from the last attempt: a\n// backoff ladder that keeps failing must not extend its own deadline.\nexport const shouldGiveUpListening = (downSinceMs: number, now: number, windowMs: number = LISTEN_RETRY_WINDOW_MS): boolean => now - downSinceMs >= windowMs;\n\n// Exponential backoff, capped: attempt 0 → 1s, 1 → 2s, … saturating at 30s.\nexport const backoffDelayMs = (attempt: number): number => Math.min(MAX_LISTEN_RETRY_MS, BASE_LISTEN_RETRY_MS * 2 ** attempt);\n"],"mappings":";;AAwBA,IAAM,+CAA+B,IAAI,IAAI;CAAC;CAAW;CAAa;CAAqB;CAAY;CAAsB;CAAmB;AAAa,CAAC;AAE9J,IAAM,mBAAmB,UAA4BA,aAAAA,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;AAEtH,IAAa,yBAAyB,UACpC,6BAA6B,IAAI,gBAAgB,KAAK,CAAC,IAAI,cAAc;AAE3E,IAAM,uBAAuB;AAC7B,IAAM,sBAAsB;AAK5B,IAAa,yBAAyB;AAItC,IAAa,yBAAyB,aAAqB,KAAa,WAAmB,2BAAoC,MAAM,eAAe;AAGpJ,IAAa,kBAAkB,YAA4B,KAAK,IAAI,qBAAqB,uBAAuB,KAAK,OAAO"}
|
package/dist/notifier/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_notifier = require("../notifier-
|
|
2
|
+
const require_notifier = require("../notifier-CiemUClt.cjs");
|
|
3
3
|
exports.HISTORY_CAP = require_notifier.HISTORY_CAP;
|
|
4
4
|
exports.NOTIFIER_LIFECYCLES = require_notifier.NOTIFIER_LIFECYCLES;
|
|
5
5
|
exports.NOTIFIER_LIMITS = require_notifier.NOTIFIER_LIMITS;
|
package/dist/notifier/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as HISTORY_CAP, a as get, c as listFor, d as publish, f as resetNotifier, g as validatePublishInput, h as NOTIFIER_LIMITS, i as configureNotifier, l as listHistory, m as updateForPlugin, n as clear, o as getForPlugin, p as setNotifierFilePaths, r as clearForPlugin, s as listAll, t as cancel, u as onEvent, v as NOTIFIER_LIFECYCLES, y as NOTIFIER_SEVERITIES } from "../notifier-
|
|
1
|
+
import { _ as HISTORY_CAP, a as get, c as listFor, d as publish, f as resetNotifier, g as validatePublishInput, h as NOTIFIER_LIMITS, i as configureNotifier, l as listHistory, m as updateForPlugin, n as clear, o as getForPlugin, p as setNotifierFilePaths, r as clearForPlugin, s as listAll, t as cancel, u as onEvent, v as NOTIFIER_LIFECYCLES, y as NOTIFIER_SEVERITIES } from "../notifier-dgkC-h80.js";
|
|
2
2
|
export { HISTORY_CAP, NOTIFIER_LIFECYCLES, NOTIFIER_LIMITS, NOTIFIER_SEVERITIES, cancel, clear, clearForPlugin, configureNotifier, get, getForPlugin, listAll, listFor, listHistory, onEvent, publish, resetNotifier, setNotifierFilePaths, updateForPlugin, validatePublishInput };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_dist = require("./dist-
|
|
1
|
+
const require_dist = require("./dist-BZ62pKuU.cjs");
|
|
2
2
|
let node_fs = require("node:fs");
|
|
3
3
|
let node_crypto = require("node:crypto");
|
|
4
4
|
//#region src/notifier/types.ts
|
|
@@ -48,11 +48,8 @@ var TERMINAL_TYPES = ["cleared", "cancelled"];
|
|
|
48
48
|
function isOneOf(allowed, value) {
|
|
49
49
|
return allowed.some((candidate) => candidate === value);
|
|
50
50
|
}
|
|
51
|
-
function isOptionalString(value) {
|
|
52
|
-
return value === void 0 || typeof value === "string";
|
|
53
|
-
}
|
|
54
51
|
function isNotifierEntry(value) {
|
|
55
|
-
return require_dist.hasStringProp(value, "id") && require_dist.hasStringProp(value, "pluginPkg") && require_dist.hasStringProp(value, "title") && require_dist.hasStringProp(value, "createdAt") && isOneOf(NOTIFIER_SEVERITIES, value.severity) && (value.lifecycle === void 0 || isOneOf(NOTIFIER_LIFECYCLES, value.lifecycle)) && isOptionalString(value.body) && isOptionalString(value.navigateTarget);
|
|
52
|
+
return require_dist.hasStringProp(value, "id") && require_dist.hasStringProp(value, "pluginPkg") && require_dist.hasStringProp(value, "title") && require_dist.hasStringProp(value, "createdAt") && isOneOf(NOTIFIER_SEVERITIES, value.severity) && (value.lifecycle === void 0 || isOneOf(NOTIFIER_LIFECYCLES, value.lifecycle)) && require_dist.isOptionalString(value.body) && require_dist.isOptionalString(value.navigateTarget);
|
|
56
53
|
}
|
|
57
54
|
function isNotifierHistoryEntry(value) {
|
|
58
55
|
return isNotifierEntry(value) && require_dist.hasStringProp(value, "terminalAt") && isOneOf(TERMINAL_TYPES, value.terminalType);
|
|
@@ -602,4 +599,4 @@ Object.defineProperty(exports, "validatePublishInput", {
|
|
|
602
599
|
}
|
|
603
600
|
});
|
|
604
601
|
|
|
605
|
-
//# sourceMappingURL=notifier-
|
|
602
|
+
//# sourceMappingURL=notifier-CiemUClt.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"notifier-CiemUClt.cjs","names":["hasStringProp","isOptionalString","isRecord","isUnknownArray","fsPromises","isErrorWithCode","randomUUID"],"sources":["../src/notifier/types.ts","../src/notifier/store.ts","../src/notifier/validate.ts","../src/notifier/engine.ts"],"sourcesContent":["// Notifier value types. Kept dependency-free (no node, no fs, no\n// pubsub) so the host's API-route layer and any future browser\n// consumer can validate inbound payloads against the same enum\n// constants the engine accepts without pulling in the engine's I/O.\n\n/** Two notification shapes, distinguished by who fires the close call:\n *\n * `fyi` — informational. The host (bell panel) clears it when the\n * user dismisses the row. MAY carry a `navigateTarget`\n * (the legacy wrapper publishes fyi entries with one);\n * the row then navigates and clears.\n * `action` — pending obligation. The plugin clears it when the\n * underlying domain state changes (the user paid the tax,\n * viewed the digest, etc.). The bell row navigates to\n * `navigateTarget` on click.\n *\n * The engine reads `lifecycle` only to enforce two publish-time rules\n * (everything downstream — pubsub fan-out, persistence, history — is\n * lifecycle-blind):\n *\n * 1. `action` requires a non-empty `navigateTarget`. Without one,\n * clicking the row does nothing and the entry is a degraded fyi.\n * 2. `action` cannot use `info` severity. A low-priority obligation\n * is incoherent — fyi if it's a ping, `nudge`/`urgent` if it's a\n * real obligation worth a landing page.\n *\n * Both rules live in `validate.ts`, which `publish` and\n * `updateForPlugin` share — there is no HTTP publish path for them to\n * be mirrored into (see `server/api/routes/notifier.ts`). */\nexport const NOTIFIER_LIFECYCLES = [\"fyi\", \"action\"] as const;\nexport type NotifierLifecycle = (typeof NOTIFIER_LIFECYCLES)[number];\n\n/** Severity drives badge color (gray / amber / red, worst-wins) and\n * in a future iteration channel routing. Mostly stored verbatim by\n * the engine; the one engine-visible interaction is the rule that\n * `action` lifecycle cannot pair with `info` severity (see\n * `NotifierLifecycle` above). */\nexport const NOTIFIER_SEVERITIES = [\"info\", \"nudge\", \"urgent\"] as const;\nexport type NotifierSeverity = (typeof NOTIFIER_SEVERITIES)[number];\n\nexport interface NotifierEntry<TPluginData = unknown> {\n /** Engine-assigned UUID. Generated synchronously inside `publish()`\n * so the caller can use it before persistence completes. */\n id: string;\n /** Plugin namespace (e.g. `\"encore\"`, `\"debug__system\"`), and the\n * key the per-plugin isolation is built on: `updateForPlugin`,\n * `getForPlugin` and `clearForPlugin` each compare it and no-op on\n * a mismatch, so one plugin cannot touch another's entries.\n * `listFor` filters on it, and the UI groups by it. */\n pluginPkg: string;\n severity: NotifierSeverity;\n lifecycle?: NotifierLifecycle;\n title: string;\n body?: string;\n /** Optional in-app deep-link target (relative URL). The bell popup\n * routes here on row click, splicing in `notificationId=<id>` so the\n * landing page can identify which entry to clear — with `?` or `&`\n * as the target requires, and before any `#fragment`\n * (`appendNotificationId` in `NotificationBell.vue`). The engine\n * doesn't read this — it's a UI hint stored on the entry. */\n navigateTarget?: string;\n /** Opaque to the engine. Round-trips through JSON unchanged; only\n * the originating plugin's UI knows the shape. */\n pluginData?: TPluginData;\n /** ISO-8601 timestamp set at `publish()` time. */\n createdAt: string;\n}\n\n/** A history entry — a `NotifierEntry` after it has been cleared or\n * cancelled, with the terminal type and timestamp recorded. The\n * bell popup's \"History\" section renders these read-only. */\nexport interface NotifierHistoryEntry<TPluginData = unknown> extends NotifierEntry<TPluginData> {\n terminalType: \"cleared\" | \"cancelled\";\n terminalAt: string;\n}\n\n/** Caller-supplied input for `publish()`. The engine fills in `id`\n * and `createdAt`; everything else flows through verbatim.\n *\n * Two publish-time rules apply to `action` lifecycle (see\n * `NotifierLifecycle`):\n *\n * - `navigateTarget` MUST be a non-empty string.\n * - `severity` MUST NOT be `\"info\"`.\n *\n * Violations cause `publish()` to throw. Currently expressed as\n * runtime validation rather than a discriminated-union type, so the\n * fields below are all individually optional / loose at the\n * type-level. */\nexport interface PublishInput<TPluginData = unknown> {\n pluginPkg: string;\n severity: NotifierSeverity;\n title: string;\n body?: string | undefined;\n lifecycle?: NotifierLifecycle | undefined;\n navigateTarget?: string | undefined;\n pluginData?: TPluginData | undefined;\n}\n\n/** On-disk shape of `~/mulmoclaude/data/notifier/active.json`. Holds\n * only entries that haven't been cleared or cancelled — the file is\n * a snapshot, not an event log. */\nexport interface NotifierFile {\n entries: Record<string, NotifierEntry>;\n}\n\n/** On-disk shape of `~/mulmoclaude/data/notifier/history.json`. Array\n * of terminated entries newest-first, capped at `HISTORY_CAP` with\n * FIFO eviction (push at index 0, slice from the tail). */\nexport interface NotifierHistoryFile {\n entries: NotifierHistoryEntry[];\n}\n\n/** History size cap — how many terminated entries the FILE keeps, not\n * how many the UI shows: older ones fall off when new terminations\n * land. The bell popup renders `HISTORY_INITIAL_VISIBLE` of them and\n * reveals the rest behind \"Show more\" (`NotificationBell.vue`). */\nexport const HISTORY_CAP = 50;\n\n/** Pub-sub event published on the host's notifier channel after every\n * successful state change. Discriminated union — subscribers switch\n * on `type` to keep TypeScript narrowing the rest of the payload.\n *\n * `updated` carries the post-mutation entry — the receiver swaps\n * the matching `id` in their local active set. Reserved for in-\n * place edits via `updateForPlugin`; no history record is written\n * because the entry is still active, just with refreshed content. */\nexport type NotifierEvent =\n { type: \"published\"; entry: NotifierEntry } | { type: \"cleared\"; id: string } | { type: \"cancelled\"; id: string } | { type: \"updated\"; entry: NotifierEntry };\n","// Low-level file I/O for the notifier. Reads use node:fs directly;\n// writes go through an injected atomic-JSON writer (the host owns the\n// rename-based atomic write so it stays single-sourced with its other\n// writers). Kept separate from `engine.ts` so the path can be\n// overridden in tests without monkey-patching.\n\nimport { hasStringProp, isErrorWithCode, isOptionalString, isRecord, isUnknownArray } from \"@mulmoclaude/common\";\nimport { promises as fsPromises } from \"node:fs\";\nimport {\n NOTIFIER_LIFECYCLES,\n NOTIFIER_SEVERITIES,\n type NotifierEntry,\n type NotifierFile,\n type NotifierHistoryEntry,\n type NotifierHistoryFile,\n} from \"./types.js\";\n\n/** Injected atomic JSON writer — the host's `writeJsonAtomic`. */\nexport type WriteJson = (filePath: string, data: unknown) => Promise<void>;\n\nconst TERMINAL_TYPES = [\"cleared\", \"cancelled\"] as const;\n\nfunction isOneOf<T extends string>(allowed: readonly T[], value: unknown): value is T {\n return allowed.some((candidate) => candidate === value);\n}\n\n// Checks every field `NotifierEntry` declares — `pluginData` is `unknown`,\n// so nothing is left unverified. A partial check would be an assertion\n// wearing a predicate's clothes.\nfunction isNotifierEntry(value: unknown): value is NotifierEntry {\n return (\n hasStringProp(value, \"id\") &&\n hasStringProp(value, \"pluginPkg\") &&\n hasStringProp(value, \"title\") &&\n hasStringProp(value, \"createdAt\") &&\n isOneOf(NOTIFIER_SEVERITIES, value.severity) &&\n (value.lifecycle === undefined || isOneOf(NOTIFIER_LIFECYCLES, value.lifecycle)) &&\n isOptionalString(value.body) &&\n isOptionalString(value.navigateTarget)\n );\n}\n\nfunction isNotifierHistoryEntry(value: unknown): value is NotifierHistoryEntry {\n return isNotifierEntry(value) && hasStringProp(value, \"terminalAt\") && isOneOf(TERMINAL_TYPES, value.terminalType);\n}\n\n// `isRecord` rejects `null` and arrays, so `{ entries: [] }` and\n// `{ entries: null }` stay malformed instead of reading as \"no entries\" —\n// downstream `engine.get` / `list*` mutations assume a plain object.\nfunction isNotifierFile(value: unknown): value is NotifierFile {\n return isRecord(value) && isRecord(value.entries) && Object.values(value.entries).every(isNotifierEntry);\n}\n\nfunction isNotifierHistoryFile(value: unknown): value is NotifierHistoryFile {\n return isRecord(value) && isUnknownArray(value.entries) && value.entries.every(isNotifierHistoryEntry);\n}\n\n/** Parsed JSON, or `undefined` when the file doesn't exist yet (first\n * ever call on a fresh workspace) — unambiguous as a sentinel because\n * no JSON document parses to `undefined`. */\nasync function readJsonIfPresent(filePath: string): Promise<unknown> {\n try {\n return JSON.parse(await fsPromises.readFile(filePath, \"utf-8\"));\n } catch (err) {\n if (isErrorWithCode(err) && err.code === \"ENOENT\") return undefined;\n throw err;\n }\n}\n\n/** Read the active-entries file. Returns an empty store when the file\n * doesn't exist yet. Any other read or parse failure throws — the\n * caller has to decide whether to surface or recover, since silently\n * treating \"malformed file\" as \"no entries\" would lose data. A rejected\n * file is never rewritten, so it stays on disk intact for repair. */\nexport async function loadActive(filePath: string): Promise<NotifierFile> {\n const parsed = await readJsonIfPresent(filePath);\n if (parsed === undefined) return { entries: {} };\n if (!isNotifierFile(parsed)) throw new Error(`notifier: malformed active.json at ${filePath}`);\n return parsed;\n}\n\n/** Write the active-entries file via the injected atomic writer so a\n * half-written file is never visible to readers. The caller serialises\n * writes (engine.ts queues mutations) — this function makes no\n * concurrency guarantees of its own. */\nexport async function saveActive(writeJson: WriteJson, filePath: string, state: NotifierFile): Promise<void> {\n await writeJson(filePath, state);\n}\n\n/** Read the history file. Empty array on first run. Same parse-error\n * policy as `loadActive`. */\nexport async function loadHistory(filePath: string): Promise<NotifierHistoryFile> {\n const parsed = await readJsonIfPresent(filePath);\n if (parsed === undefined) return { entries: [] };\n if (!isNotifierHistoryFile(parsed)) throw new Error(`notifier: malformed history.json at ${filePath}`);\n return parsed;\n}\n\nexport async function saveHistory(writeJson: WriteJson, filePath: string, state: NotifierHistoryFile): Promise<void> {\n await writeJson(filePath, state);\n}\n","// Publish-input validation — pure, dependency-free, so every caller\n// can share one rule set. Today that is `engine.publish`, which throws,\n// and `updateForPlugin`, which re-validates the MERGED entry and skips\n// the update with a warning rather than throwing — an update must not\n// be able to degrade an entry below publish-time invariants, but it is\n// also not the caller's error to handle. Publish is deliberately absent\n// from the HTTP surface (see `server/api/routes/notifier.ts`), so the\n// route layer this comment once also named no longer exists.\n\nimport type { PublishInput } from \"./types.js\";\n\n/** Hard caps on publish-input fields. The engine reads each entry on\n * every list/get call (no in-memory cache), so unbounded fields hurt\n * every reader. Caps chosen to be generous for legitimate UX copy\n * while bounding active.json growth: a notification fundamentally is\n * a short blurb, not a document. */\nexport const NOTIFIER_LIMITS = {\n titleMax: 200,\n bodyMax: 4000,\n navigateTargetMax: 1000,\n pluginDataMaxBytes: 16 * 1024,\n} as const;\n\nfunction validateTitle(title: string): string | null {\n if (typeof title !== \"string\" || title.length === 0) return \"title must be a non-empty string\";\n if (title.length > NOTIFIER_LIMITS.titleMax) return `title exceeds max length of ${NOTIFIER_LIMITS.titleMax} chars`;\n return null;\n}\n\nfunction validateBody(body: string | undefined): string | null {\n if (body === undefined) return null;\n if (body.length > NOTIFIER_LIMITS.bodyMax) return `body exceeds max length of ${NOTIFIER_LIMITS.bodyMax} chars`;\n return null;\n}\n\nfunction validateNavigateTarget(target: string | undefined): string | null {\n if (target === undefined) return null;\n if (target.length === 0) return \"navigateTarget must be a non-empty relative path when set\";\n if (target.length > NOTIFIER_LIMITS.navigateTargetMax) {\n return `navigateTarget exceeds max length of ${NOTIFIER_LIMITS.navigateTargetMax} chars`;\n }\n // Must be a same-origin relative path. Reject schemes\n // (`javascript:`, `https://...`) and scheme-relative URLs\n // (`//evil.com/...`, which an `<a href>` would resolve to the\n // attacker's origin). One leading \"/\" only.\n if (!target.startsWith(\"/\") || target.startsWith(\"//\")) {\n return \"navigateTarget must be a relative path beginning with a single '/' (no scheme, no '//')\";\n }\n return null;\n}\n\nfunction validatePluginData(pluginData: unknown): string | null {\n if (pluginData === undefined) return null;\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(pluginData);\n } catch (err) {\n return `pluginData is not JSON-serialisable: ${String(err)}`;\n }\n // `JSON.stringify` returns `undefined` for non-serialisable roots\n // (e.g. a bare function or symbol). Treat that as a serialisation\n // failure so it doesn't slip through as an empty-string size.\n if (typeof serialized !== \"string\") return \"pluginData is not JSON-serialisable\";\n if (serialized.length > NOTIFIER_LIMITS.pluginDataMaxBytes) {\n return `pluginData JSON exceeds ${NOTIFIER_LIMITS.pluginDataMaxBytes} bytes`;\n }\n return null;\n}\n\nfunction validateActionCoherence(input: PublishInput): string | null {\n if (input.lifecycle !== \"action\") return null;\n if (input.severity === \"info\") {\n return \"action lifecycle is incompatible with info severity (use fyi for low-priority pings)\";\n }\n if (typeof input.navigateTarget !== \"string\" || input.navigateTarget.length === 0) {\n return \"action lifecycle requires a non-empty navigateTarget\";\n }\n return null;\n}\n\n/** Validate a `PublishInput`. Returns `null` if OK, or a\n * human-readable error string. Order matters — shape/size errors are\n * reported before lifecycle/severity coherence errors so the message\n * the caller sees points at the most fundamental problem first. */\nexport function validatePublishInput(input: PublishInput): string | null {\n return (\n validateTitle(input.title) ??\n validateBody(input.body) ??\n validateNavigateTarget(input.navigateTarget) ??\n validatePluginData(input.pluginData) ??\n validateActionCoherence(input)\n );\n}\n","// Notifier engine — single-process, two-file (active + history),\n// single-channel. Host-agnostic: file paths, the atomic JSON writer,\n// the pub-sub event sink, and the logger are all injected via\n// `configureNotifier` + `setNotifierFilePaths` so MulmoClaude and\n// MulmoTerminal share one notification engine over their own\n// workspaces and pub-sub fabrics.\n//\n// API surface: publish / clear / cancel / get / listFor / listAll /\n// listHistory (+ plugin-scoped variants). Mutations queue through a\n// writing-flag + waiter-queue coordinator so concurrent callers can't\n// race on the atomic write's rename. Reads bypass the queue (rename\n// atomicity makes half-reads impossible) and trade strict\n// linearisability for simpler code: the contract is \"after\n// `await publish(x)` resolves, subsequent reads see x\" — which holds\n// because `publish` awaits the persist before returning.\n//\n// `clear` / `cancel` push to history *before* removing from active.\n// History persistence is best-effort: if it fails, the active write\n// still wins and the failure is logged. Active is the source of\n// truth; history is an audit aid.\n\nimport type { MinimalLogger } from \"@mulmoclaude/common\";\nimport { randomUUID } from \"node:crypto\";\nimport { loadActive, loadHistory, saveActive, saveHistory, type WriteJson } from \"./store.js\";\nimport { validatePublishInput } from \"./validate.js\";\nimport {\n HISTORY_CAP,\n type NotifierEntry,\n type NotifierEvent,\n type NotifierFile,\n type NotifierHistoryEntry,\n type NotifierSeverity,\n type PublishInput,\n} from \"./types.js\";\n\nexport { NOTIFIER_LIMITS, validatePublishInput } from \"./validate.js\";\n\n// ── Dependency injection ──────────────────────────────────────────\n\n/** Minimal logger the engine needs. The host passes its structured\n * logger; absent one, failures are swallowed (the engine never throws\n * on a fan-out/persist-best-effort path). */\nexport type NotifierLogger = Pick<MinimalLogger, \"warn\" | \"error\">;\n\nexport interface NotifierConfig {\n /** Atomic JSON writer (the host's `writeJsonAtomic`). */\n writeJson: WriteJson;\n /** Fan-out sink — the host binds this to `pubsub.publish(channel, event)`. */\n publishEvent: (event: NotifierEvent) => void;\n /** Optional logger. */\n log?: NotifierLogger;\n}\n\nconst NOOP_LOG: NotifierLogger = { warn: () => {}, error: () => {} };\n\nlet config: NotifierConfig | null = null;\nlet activeFilePath = \"\";\nlet historyFilePath = \"\";\n\nfunction logger(): NotifierLogger {\n return config?.log ?? NOOP_LOG;\n}\n\n/** Wire the engine's I/O deps. Call once at startup, before the first\n * mutation. Does NOT set file paths — those are set independently via\n * `setNotifierFilePaths` so a host can bind production paths at module\n * load and a test can override them without re-supplying the deps. */\nexport function configureNotifier(injected: NotifierConfig): void {\n config = injected;\n}\n\n// ── In-process event listeners ────────────────────────────────────\n//\n// Separate from the socket.io pubsub so server-side adapters (macOS\n// push, future Encore) can react to state changes without going\n// through a websocket round-trip. The host's pubsub is fan-out-only\n// with no server-side subscribe, so this listener registry is the\n// in-process equivalent. Listeners run synchronously inside `emit`,\n// before the pubsub fan-out.\n\ntype NotifierEventListener = (event: NotifierEvent) => void;\nconst listeners: NotifierEventListener[] = [];\n\n/** Register an in-process listener for engine events. Returns an\n * unsubscribe function the caller can use during teardown. */\nexport function onEvent(listener: NotifierEventListener): () => void {\n listeners.push(listener);\n return () => {\n const idx = listeners.indexOf(listener);\n if (idx >= 0) listeners.splice(idx, 1);\n };\n}\n\nfunction emit(event: NotifierEvent): void {\n // In-process fan-out first. Each listener is wrapped: a throwing\n // listener must not poison the rest, and must not propagate out of\n // `processBatch` and strand the still-unsettled waiters (their\n // resolve/reject is called *after* this emit loop). Fan-out is\n // best-effort by contract — losing one subscriber must not lose\n // the write that already committed.\n for (const listener of listeners) {\n try {\n listener(event);\n } catch (err) {\n logger().error(\"in-process listener failed\", { type: event.type, error: String(err) });\n }\n }\n if (!config) {\n logger().warn(\"emit before init\", { type: event.type });\n return;\n }\n try {\n config.publishEvent(event);\n } catch (err) {\n logger().error(\"emit failed\", { type: event.type, error: String(err) });\n }\n}\n\n// ── Write coordinator ─────────────────────────────────────────────\n\n/** A mutation function applied to the in-memory state object during\n * drain. Returns either:\n *\n * - `null` — no state change (e.g., `clear` on an unknown id).\n * The drainer skips the disk write and the emit if every\n * mutation in a batch returned `null`.\n * - `{ event, historyEntry? }` — state changed. The drainer emits\n * the event after the active write succeeds, and prepends\n * `historyEntry` to history (best-effort) when present.\n *\n * Mutations MUST NOT modify state when returning `null`. Violating\n * this invariant produces a write skip with stale on-disk state. */\ntype MutationOutcome = { event: NotifierEvent; historyEntry?: NotifierHistoryEntry } | null;\ntype Mutation = (state: NotifierFile) => MutationOutcome;\n\ninterface Waiter {\n mutate: Mutation;\n resolve: () => void;\n reject: (err: unknown) => void;\n}\n\ntype MutationResult = { ok: true; outcome: MutationOutcome } | { ok: false; error: unknown };\n\nlet writing = false;\nlet waiters: Waiter[] = [];\n\n/** Point the engine at its active/history files. Resets the write\n * queue, so callers must not have in-flight mutations. The host calls\n * this once with the workspace paths; tests call it per-case with temp\n * files. */\nexport function setNotifierFilePaths(paths: { active: string; history: string }): void {\n activeFilePath = paths.active;\n historyFilePath = paths.history;\n writing = false;\n waiters = [];\n}\n\n/** Test-only: clear config + queue so each suite starts clean. */\nexport function resetNotifier(): void {\n config = null;\n activeFilePath = \"\";\n historyFilePath = \"\";\n writing = false;\n waiters = [];\n listeners.length = 0;\n}\n\nfunction requireWriteJson(): WriteJson {\n if (!config) throw new Error(\"notifier: configureNotifier() not called\");\n return config.writeJson;\n}\n\n/** A waiter carried alongside the outcome of its own mutation, so settling can\n * never pair a result with the wrong caller's promise. */\ninterface SettledMutation {\n waiter: Waiter;\n result: MutationResult;\n}\n\nfunction applyBatchMutations(batch: Waiter[], state: NotifierFile): SettledMutation[] {\n return batch.map((waiter) => {\n try {\n return { waiter, result: { ok: true, outcome: waiter.mutate(state) } };\n } catch (err) {\n return { waiter, result: { ok: false, error: err } };\n }\n });\n}\n\nfunction collectEvents(settled: SettledMutation[]): NotifierEvent[] {\n const events: NotifierEvent[] = [];\n for (const { result } of settled) {\n if (result.ok && result.outcome !== null) events.push(result.outcome.event);\n }\n return events;\n}\n\nfunction collectHistoryEntries(settled: SettledMutation[]): NotifierHistoryEntry[] {\n const entries: NotifierHistoryEntry[] = [];\n for (const { result } of settled) {\n if (result.ok && result.outcome !== null && result.outcome.historyEntry) {\n entries.push(result.outcome.historyEntry);\n }\n }\n return entries;\n}\n\nfunction settleBatch(settled: SettledMutation[]): void {\n // Resolves come AFTER any emits so subscribers see the event\n // before the caller's `await` returns.\n for (const { waiter, result } of settled) {\n if (result.ok) waiter.resolve();\n else waiter.reject(result.error);\n }\n}\n\nfunction rejectBatch(batch: Waiter[], err: unknown): void {\n for (const waiter of batch) waiter.reject(err);\n}\n\nasync function persistHistory(newEntries: NotifierHistoryEntry[]): Promise<void> {\n const existing = await loadHistory(historyFilePath);\n // Newest-first ordering: a batch contains terminations in arrival\n // order; we want the last one to land at index 0 of history.\n const merged = [...newEntries.slice().reverse(), ...existing.entries].slice(0, HISTORY_CAP);\n await saveHistory(requireWriteJson(), historyFilePath, { entries: merged });\n}\n\nasync function processBatch(batch: Waiter[]): Promise<void> {\n let state: NotifierFile;\n try {\n state = await loadActive(activeFilePath);\n } catch (err) {\n logger().error(\"load failed\", { error: String(err) });\n rejectBatch(batch, err);\n return;\n }\n const settled = applyBatchMutations(batch, state);\n const events = collectEvents(settled);\n const historyEntries = collectHistoryEntries(settled);\n\n if (events.length > 0) {\n try {\n await saveActive(requireWriteJson(), activeFilePath, state);\n } catch (err) {\n logger().error(\"active write failed\", { error: String(err) });\n rejectBatch(batch, err);\n return;\n }\n if (historyEntries.length > 0) {\n // Best-effort: active is the source of truth, history is an\n // audit aid. A failed history write is logged but doesn't\n // unwind the active commit.\n try {\n await persistHistory(historyEntries);\n } catch (err) {\n logger().error(\"history write failed\", { error: String(err) });\n }\n }\n for (const event of events) emit(event);\n }\n settleBatch(settled);\n}\n\nasync function drain(): Promise<void> {\n writing = true;\n try {\n while (waiters.length > 0) {\n const batch = waiters;\n waiters = [];\n await processBatch(batch);\n }\n } finally {\n writing = false;\n }\n}\n\nfunction enqueue(mutate: Mutation): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n waiters.push({ mutate, resolve, reject });\n if (!writing) void drain();\n });\n}\n\nfunction removeEntry(state: NotifierFile, entryId: string): NotifierFile[\"entries\"] {\n // Object-rest excludes the key without invoking `delete`.\n const { [entryId]: __removed, ...remaining } = state.entries;\n return remaining;\n}\n\nfunction buildHistoryEntry(entry: NotifierEntry, terminalType: \"cleared\" | \"cancelled\"): NotifierHistoryEntry {\n return { ...entry, terminalType, terminalAt: new Date().toISOString() };\n}\n\n// ── Public API ────────────────────────────────────────────────────\n\n/** The optional half of a publish input, with unset keys left OUT rather than\n * written as `undefined` — an entry is persisted and re-read through JSON,\n * where an unset field carries no key at all. */\nfunction optionalPublishFields<TPluginData>(input: PublishInput<TPluginData>): Partial<NotifierEntry<TPluginData>> {\n return {\n ...(input.lifecycle !== undefined ? { lifecycle: input.lifecycle } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.navigateTarget !== undefined ? { navigateTarget: input.navigateTarget } : {}),\n ...(input.pluginData !== undefined ? { pluginData: input.pluginData } : {}),\n };\n}\n\nexport async function publish<TPluginData = unknown>(input: PublishInput<TPluginData>): Promise<{ id: string }> {\n // Validate at the engine boundary, so every caller shares one wall —\n // plugin runtime, legacy wrapper, host module. Publish has no HTTP\n // surface to validate separately (`server/api/routes/notifier.ts`).\n const validationError = validatePublishInput(input);\n if (validationError) {\n throw new Error(`notifier.publish: ${validationError}`);\n }\n const entryId = randomUUID();\n const entry: NotifierEntry<TPluginData> = {\n id: entryId,\n pluginPkg: input.pluginPkg,\n severity: input.severity,\n title: input.title,\n createdAt: new Date().toISOString(),\n ...optionalPublishFields(input),\n };\n await enqueue((state) => {\n state.entries[entryId] = entry;\n return { event: { type: \"published\", entry } };\n });\n return { id: entryId };\n}\n\n/** Remove an active entry and record its terminal history. `clear`\n * (user dismissed) and `cancel` (producer withdrew) differ only in the\n * emitted event / history reason. No-op when the id is unknown. */\nasync function terminateEntry(entryId: string, reason: \"cleared\" | \"cancelled\"): Promise<void> {\n await enqueue((state) => {\n const entry = state.entries[entryId];\n if (!entry) return null;\n state.entries = removeEntry(state, entryId);\n return {\n event: reason === \"cleared\" ? { type: \"cleared\", id: entryId } : { type: \"cancelled\", id: entryId },\n historyEntry: buildHistoryEntry(entry, reason),\n };\n });\n}\n\nexport async function clear(entryId: string): Promise<void> {\n await terminateEntry(entryId, \"cleared\");\n}\n\nexport async function cancel(entryId: string): Promise<void> {\n await terminateEntry(entryId, \"cancelled\");\n}\n\n/** In-place update for an active entry. Only the fields present on\n * `patch` are rewritten; `id`, `pluginPkg`, `lifecycle`, and\n * `createdAt` stay fixed. Emits a single `\"updated\"` event with the\n * post-mutation entry — no history record is written because the\n * entry is still active, just with refreshed content.\n *\n * No-ops (no throw) when the id is unknown, the entry belongs to a\n * different plugin, or the merged shape would violate\n * `validatePublishInput`. The silent skip matches `clearForPlugin`'s\n * isolation semantics; validation failures are logged for diagnosis. */\nexport async function updateForPlugin<TPluginData = unknown>(\n pluginPkg: string,\n entryId: string,\n patch: {\n severity?: NotifierSeverity;\n title?: string;\n body?: string;\n navigateTarget?: string;\n pluginData?: TPluginData;\n },\n): Promise<void> {\n await enqueue((state) => {\n const entry = state.entries[entryId];\n if (!entry) return null;\n if (entry.pluginPkg !== pluginPkg) return null;\n const next: NotifierEntry = {\n ...entry,\n ...(patch.severity !== undefined ? { severity: patch.severity } : {}),\n ...(patch.title !== undefined ? { title: patch.title } : {}),\n ...(patch.body !== undefined ? { body: patch.body } : {}),\n ...(patch.navigateTarget !== undefined ? { navigateTarget: patch.navigateTarget } : {}),\n ...(patch.pluginData !== undefined ? { pluginData: patch.pluginData } : {}),\n };\n // Re-validate the merged shape so an update can't degrade the\n // entry below publish-time invariants.\n const validationError = validatePublishInput({\n pluginPkg: next.pluginPkg,\n severity: next.severity,\n title: next.title,\n body: next.body,\n lifecycle: next.lifecycle,\n navigateTarget: next.navigateTarget,\n pluginData: next.pluginData,\n });\n if (validationError) {\n logger().warn(\"update rejected by validation\", { entryId, pluginPkg, error: validationError });\n return null;\n }\n state.entries[entryId] = next;\n return { event: { type: \"updated\", entry: next } };\n });\n}\n\n/** Plugin-scoped point lookup. Returns the entry by id, but only if it\n * belongs to the caller's plugin; otherwise undefined. Cross-plugin\n * reads return undefined for isolation — same property as\n * `clearForPlugin` / `updateForPlugin`. */\nexport async function getForPlugin(pluginPkg: string, entryId: string): Promise<NotifierEntry | undefined> {\n const state = await loadActive(activeFilePath);\n const entry = state.entries[entryId];\n if (!entry) return undefined;\n if (entry.pluginPkg !== pluginPkg) return undefined;\n return entry;\n}\n\n/** Plugin-scoped clear. Same as `clear` but no-ops if the entry's\n * `pluginPkg` doesn't match the caller's, so a plugin can't dismiss\n * another plugin's notification by guessing or scraping its id. */\nexport async function clearForPlugin(pluginPkg: string, entryId: string): Promise<void> {\n await enqueue((state) => {\n const entry = state.entries[entryId];\n if (!entry) return null;\n if (entry.pluginPkg !== pluginPkg) return null;\n state.entries = removeEntry(state, entryId);\n return {\n event: { type: \"cleared\", id: entryId },\n historyEntry: buildHistoryEntry(entry, \"cleared\"),\n };\n });\n}\n\nexport async function get(entryId: string): Promise<NotifierEntry | undefined> {\n const state = await loadActive(activeFilePath);\n return state.entries[entryId];\n}\n\nexport async function listFor(pluginPkg: string): Promise<NotifierEntry[]> {\n const state = await loadActive(activeFilePath);\n return Object.values(state.entries).filter((entry) => entry.pluginPkg === pluginPkg);\n}\n\nexport async function listAll(): Promise<NotifierEntry[]> {\n const state = await loadActive(activeFilePath);\n return Object.values(state.entries);\n}\n\nexport async function listHistory(): Promise<NotifierHistoryEntry[]> {\n const state = await loadHistory(historyFilePath);\n return state.entries;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,sBAAsB,CAAC,OAAO,QAAQ;;;;;;AAQnD,IAAa,sBAAsB;CAAC;CAAQ;CAAS;AAAQ;;;;;AAgF7D,IAAa,cAAc;;;ACjG3B,IAAM,iBAAiB,CAAC,WAAW,WAAW;AAE9C,SAAS,QAA0B,SAAuB,OAA4B;CACpF,OAAO,QAAQ,MAAM,cAAc,cAAc,KAAK;AACxD;AAKA,SAAS,gBAAgB,OAAwC;CAC/D,OACEA,aAAAA,cAAc,OAAO,IAAI,KACzBA,aAAAA,cAAc,OAAO,WAAW,KAChCA,aAAAA,cAAc,OAAO,OAAO,KAC5BA,aAAAA,cAAc,OAAO,WAAW,KAChC,QAAQ,qBAAqB,MAAM,QAAQ,MAC1C,MAAM,cAAc,KAAA,KAAa,QAAQ,qBAAqB,MAAM,SAAS,MAC9EC,aAAAA,iBAAiB,MAAM,IAAI,KAC3BA,aAAAA,iBAAiB,MAAM,cAAc;AAEzC;AAEA,SAAS,uBAAuB,OAA+C;CAC7E,OAAO,gBAAgB,KAAK,KAAKD,aAAAA,cAAc,OAAO,YAAY,KAAK,QAAQ,gBAAgB,MAAM,YAAY;AACnH;AAKA,SAAS,eAAe,OAAuC;CAC7D,OAAOE,aAAAA,SAAS,KAAK,KAAKA,aAAAA,SAAS,MAAM,OAAO,KAAK,OAAO,OAAO,MAAM,OAAO,CAAC,CAAC,MAAM,eAAe;AACzG;AAEA,SAAS,sBAAsB,OAA8C;CAC3E,OAAOA,aAAAA,SAAS,KAA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B,IAAI,SAAqD;CAE7E,QAAO,MADa,WAAW,cAAc,EAAA,CAChC,QAAQ;AACvB;AAEA,eAAsB,QAAQ,WAA6C;CACzE,MAAM,QAAQ,MAAM,WAAW,cAAc;CAC7C,OAAO,OAAO,OAAO,MAAM,OAAO,CAAC,CAAC,QAAQ,UAAU,MAAM,cAAc,SAAS;AACrF;AAEA,eAAsB,UAAoC;CACxD,MAAM,QAAQ,MAAM,WAAW,cAAc;CAC7C,OAAO,OAAO,OAAO,MAAM,OAAO;AACpC;AAEA,eAAsB,cAA+C;CAEnE,QAAO,MADa,YAAY,eAAe,EAAA,CAClC;AACf"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as isErrorWithCode, i as hasStringProp,
|
|
1
|
+
import { a as isErrorWithCode, c as isRecord, i as hasStringProp, s as isOptionalString, u as isUnknownArray } from "./dist-MFUV9FYo.js";
|
|
2
2
|
import { promises } from "node:fs";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
//#region src/notifier/types.ts
|
|
@@ -48,9 +48,6 @@ var TERMINAL_TYPES = ["cleared", "cancelled"];
|
|
|
48
48
|
function isOneOf(allowed, value) {
|
|
49
49
|
return allowed.some((candidate) => candidate === value);
|
|
50
50
|
}
|
|
51
|
-
function isOptionalString(value) {
|
|
52
|
-
return value === void 0 || typeof value === "string";
|
|
53
|
-
}
|
|
54
51
|
function isNotifierEntry(value) {
|
|
55
52
|
return hasStringProp(value, "id") && hasStringProp(value, "pluginPkg") && hasStringProp(value, "title") && hasStringProp(value, "createdAt") && isOneOf(NOTIFIER_SEVERITIES, value.severity) && (value.lifecycle === void 0 || isOneOf(NOTIFIER_LIFECYCLES, value.lifecycle)) && isOptionalString(value.body) && isOptionalString(value.navigateTarget);
|
|
56
53
|
}
|
|
@@ -489,4 +486,4 @@ async function listHistory() {
|
|
|
489
486
|
//#endregion
|
|
490
487
|
export { HISTORY_CAP as _, get as a, listFor as c, publish as d, resetNotifier as f, validatePublishInput as g, NOTIFIER_LIMITS as h, configureNotifier as i, listHistory as l, updateForPlugin as m, clear as n, getForPlugin as o, setNotifierFilePaths as p, clearForPlugin as r, listAll as s, cancel as t, onEvent as u, NOTIFIER_LIFECYCLES as v, NOTIFIER_SEVERITIES as y };
|
|
491
488
|
|
|
492
|
-
//# sourceMappingURL=notifier-
|
|
489
|
+
//# sourceMappingURL=notifier-dgkC-h80.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"notifier-dgkC-h80.js","names":["fsPromises"],"sources":["../src/notifier/types.ts","../src/notifier/store.ts","../src/notifier/validate.ts","../src/notifier/engine.ts"],"sourcesContent":["// Notifier value types. Kept dependency-free (no node, no fs, no\n// pubsub) so the host's API-route layer and any future browser\n// consumer can validate inbound payloads against the same enum\n// constants the engine accepts without pulling in the engine's I/O.\n\n/** Two notification shapes, distinguished by who fires the close call:\n *\n * `fyi` — informational. The host (bell panel) clears it when the\n * user dismisses the row. MAY carry a `navigateTarget`\n * (the legacy wrapper publishes fyi entries with one);\n * the row then navigates and clears.\n * `action` — pending obligation. The plugin clears it when the\n * underlying domain state changes (the user paid the tax,\n * viewed the digest, etc.). The bell row navigates to\n * `navigateTarget` on click.\n *\n * The engine reads `lifecycle` only to enforce two publish-time rules\n * (everything downstream — pubsub fan-out, persistence, history — is\n * lifecycle-blind):\n *\n * 1. `action` requires a non-empty `navigateTarget`. Without one,\n * clicking the row does nothing and the entry is a degraded fyi.\n * 2. `action` cannot use `info` severity. A low-priority obligation\n * is incoherent — fyi if it's a ping, `nudge`/`urgent` if it's a\n * real obligation worth a landing page.\n *\n * Both rules live in `validate.ts`, which `publish` and\n * `updateForPlugin` share — there is no HTTP publish path for them to\n * be mirrored into (see `server/api/routes/notifier.ts`). */\nexport const NOTIFIER_LIFECYCLES = [\"fyi\", \"action\"] as const;\nexport type NotifierLifecycle = (typeof NOTIFIER_LIFECYCLES)[number];\n\n/** Severity drives badge color (gray / amber / red, worst-wins) and\n * in a future iteration channel routing. Mostly stored verbatim by\n * the engine; the one engine-visible interaction is the rule that\n * `action` lifecycle cannot pair with `info` severity (see\n * `NotifierLifecycle` above). */\nexport const NOTIFIER_SEVERITIES = [\"info\", \"nudge\", \"urgent\"] as const;\nexport type NotifierSeverity = (typeof NOTIFIER_SEVERITIES)[number];\n\nexport interface NotifierEntry<TPluginData = unknown> {\n /** Engine-assigned UUID. Generated synchronously inside `publish()`\n * so the caller can use it before persistence completes. */\n id: string;\n /** Plugin namespace (e.g. `\"encore\"`, `\"debug__system\"`), and the\n * key the per-plugin isolation is built on: `updateForPlugin`,\n * `getForPlugin` and `clearForPlugin` each compare it and no-op on\n * a mismatch, so one plugin cannot touch another's entries.\n * `listFor` filters on it, and the UI groups by it. */\n pluginPkg: string;\n severity: NotifierSeverity;\n lifecycle?: NotifierLifecycle;\n title: string;\n body?: string;\n /** Optional in-app deep-link target (relative URL). The bell popup\n * routes here on row click, splicing in `notificationId=<id>` so the\n * landing page can identify which entry to clear — with `?` or `&`\n * as the target requires, and before any `#fragment`\n * (`appendNotificationId` in `NotificationBell.vue`). The engine\n * doesn't read this — it's a UI hint stored on the entry. */\n navigateTarget?: string;\n /** Opaque to the engine. Round-trips through JSON unchanged; only\n * the originating plugin's UI knows the shape. */\n pluginData?: TPluginData;\n /** ISO-8601 timestamp set at `publish()` time. */\n createdAt: string;\n}\n\n/** A history entry — a `NotifierEntry` after it has been cleared or\n * cancelled, with the terminal type and timestamp recorded. The\n * bell popup's \"History\" section renders these read-only. */\nexport interface NotifierHistoryEntry<TPluginData = unknown> extends NotifierEntry<TPluginData> {\n terminalType: \"cleared\" | \"cancelled\";\n terminalAt: string;\n}\n\n/** Caller-supplied input for `publish()`. The engine fills in `id`\n * and `createdAt`; everything else flows through verbatim.\n *\n * Two publish-time rules apply to `action` lifecycle (see\n * `NotifierLifecycle`):\n *\n * - `navigateTarget` MUST be a non-empty string.\n * - `severity` MUST NOT be `\"info\"`.\n *\n * Violations cause `publish()` to throw. Currently expressed as\n * runtime validation rather than a discriminated-union type, so the\n * fields below are all individually optional / loose at the\n * type-level. */\nexport interface PublishInput<TPluginData = unknown> {\n pluginPkg: string;\n severity: NotifierSeverity;\n title: string;\n body?: string | undefined;\n lifecycle?: NotifierLifecycle | undefined;\n navigateTarget?: string | undefined;\n pluginData?: TPluginData | undefined;\n}\n\n/** On-disk shape of `~/mulmoclaude/data/notifier/active.json`. Holds\n * only entries that haven't been cleared or cancelled — the file is\n * a snapshot, not an event log. */\nexport interface NotifierFile {\n entries: Record<string, NotifierEntry>;\n}\n\n/** On-disk shape of `~/mulmoclaude/data/notifier/history.json`. Array\n * of terminated entries newest-first, capped at `HISTORY_CAP` with\n * FIFO eviction (push at index 0, slice from the tail). */\nexport interface NotifierHistoryFile {\n entries: NotifierHistoryEntry[];\n}\n\n/** History size cap — how many terminated entries the FILE keeps, not\n * how many the UI shows: older ones fall off when new terminations\n * land. The bell popup renders `HISTORY_INITIAL_VISIBLE` of them and\n * reveals the rest behind \"Show more\" (`NotificationBell.vue`). */\nexport const HISTORY_CAP = 50;\n\n/** Pub-sub event published on the host's notifier channel after every\n * successful state change. Discriminated union — subscribers switch\n * on `type` to keep TypeScript narrowing the rest of the payload.\n *\n * `updated` carries the post-mutation entry — the receiver swaps\n * the matching `id` in their local active set. Reserved for in-\n * place edits via `updateForPlugin`; no history record is written\n * because the entry is still active, just with refreshed content. */\nexport type NotifierEvent =\n { type: \"published\"; entry: NotifierEntry } | { type: \"cleared\"; id: string } | { type: \"cancelled\"; id: string } | { type: \"updated\"; entry: NotifierEntry };\n","// Low-level file I/O for the notifier. Reads use node:fs directly;\n// writes go through an injected atomic-JSON writer (the host owns the\n// rename-based atomic write so it stays single-sourced with its other\n// writers). Kept separate from `engine.ts` so the path can be\n// overridden in tests without monkey-patching.\n\nimport { hasStringProp, isErrorWithCode, isOptionalString, isRecord, isUnknownArray } from \"@mulmoclaude/common\";\nimport { promises as fsPromises } from \"node:fs\";\nimport {\n NOTIFIER_LIFECYCLES,\n NOTIFIER_SEVERITIES,\n type NotifierEntry,\n type NotifierFile,\n type NotifierHistoryEntry,\n type NotifierHistoryFile,\n} from \"./types.js\";\n\n/** Injected atomic JSON writer — the host's `writeJsonAtomic`. */\nexport type WriteJson = (filePath: string, data: unknown) => Promise<void>;\n\nconst TERMINAL_TYPES = [\"cleared\", \"cancelled\"] as const;\n\nfunction isOneOf<T extends string>(allowed: readonly T[], value: unknown): value is T {\n return allowed.some((candidate) => candidate === value);\n}\n\n// Checks every field `NotifierEntry` declares — `pluginData` is `unknown`,\n// so nothing is left unverified. A partial check would be an assertion\n// wearing a predicate's clothes.\nfunction isNotifierEntry(value: unknown): value is NotifierEntry {\n return (\n hasStringProp(value, \"id\") &&\n hasStringProp(value, \"pluginPkg\") &&\n hasStringProp(value, \"title\") &&\n hasStringProp(value, \"createdAt\") &&\n isOneOf(NOTIFIER_SEVERITIES, value.severity) &&\n (value.lifecycle === undefined || isOneOf(NOTIFIER_LIFECYCLES, value.lifecycle)) &&\n isOptionalString(value.body) &&\n isOptionalString(value.navigateTarget)\n );\n}\n\nfunction isNotifierHistoryEntry(value: unknown): value is NotifierHistoryEntry {\n return isNotifierEntry(value) && hasStringProp(value, \"terminalAt\") && isOneOf(TERMINAL_TYPES, value.terminalType);\n}\n\n// `isRecord` rejects `null` and arrays, so `{ entries: [] }` and\n// `{ entries: null }` stay malformed instead of reading as \"no entries\" —\n// downstream `engine.get` / `list*` mutations assume a plain object.\nfunction isNotifierFile(value: unknown): value is NotifierFile {\n return isRecord(value) && isRecord(value.entries) && Object.values(value.entries).every(isNotifierEntry);\n}\n\nfunction isNotifierHistoryFile(value: unknown): value is NotifierHistoryFile {\n return isRecord(value) && isUnknownArray(value.entries) && value.entries.every(isNotifierHistoryEntry);\n}\n\n/** Parsed JSON, or `undefined` when the file doesn't exist yet (first\n * ever call on a fresh workspace) — unambiguous as a sentinel because\n * no JSON document parses to `undefined`. */\nasync function readJsonIfPresent(filePath: string): Promise<unknown> {\n try {\n return JSON.parse(await fsPromises.readFile(filePath, \"utf-8\"));\n } catch (err) {\n if (isErrorWithCode(err) && err.code === \"ENOENT\") return undefined;\n throw err;\n }\n}\n\n/** Read the active-entries file. Returns an empty store when the file\n * doesn't exist yet. Any other read or parse failure throws — the\n * caller has to decide whether to surface or recover, since silently\n * treating \"malformed file\" as \"no entries\" would lose data. A rejected\n * file is never rewritten, so it stays on disk intact for repair. */\nexport async function loadActive(filePath: string): Promise<NotifierFile> {\n const parsed = await readJsonIfPresent(filePath);\n if (parsed === undefined) return { entries: {} };\n if (!isNotifierFile(parsed)) throw new Error(`notifier: malformed active.json at ${filePath}`);\n return parsed;\n}\n\n/** Write the active-entries file via the injected atomic writer so a\n * half-written file is never visible to readers. The caller serialises\n * writes (engine.ts queues mutations) — this function makes no\n * concurrency guarantees of its own. */\nexport async function saveActive(writeJson: WriteJson, filePath: string, state: NotifierFile): Promise<void> {\n await writeJson(filePath, state);\n}\n\n/** Read the history file. Empty array on first run. Same parse-error\n * policy as `loadActive`. */\nexport async function loadHistory(filePath: string): Promise<NotifierHistoryFile> {\n const parsed = await readJsonIfPresent(filePath);\n if (parsed === undefined) return { entries: [] };\n if (!isNotifierHistoryFile(parsed)) throw new Error(`notifier: malformed history.json at ${filePath}`);\n return parsed;\n}\n\nexport async function saveHistory(writeJson: WriteJson, filePath: string, state: NotifierHistoryFile): Promise<void> {\n await writeJson(filePath, state);\n}\n","// Publish-input validation — pure, dependency-free, so every caller\n// can share one rule set. Today that is `engine.publish`, which throws,\n// and `updateForPlugin`, which re-validates the MERGED entry and skips\n// the update with a warning rather than throwing — an update must not\n// be able to degrade an entry below publish-time invariants, but it is\n// also not the caller's error to handle. Publish is deliberately absent\n// from the HTTP surface (see `server/api/routes/notifier.ts`), so the\n// route layer this comment once also named no longer exists.\n\nimport type { PublishInput } from \"./types.js\";\n\n/** Hard caps on publish-input fields. The engine reads each entry on\n * every list/get call (no in-memory cache), so unbounded fields hurt\n * every reader. Caps chosen to be generous for legitimate UX copy\n * while bounding active.json growth: a notification fundamentally is\n * a short blurb, not a document. */\nexport const NOTIFIER_LIMITS = {\n titleMax: 200,\n bodyMax: 4000,\n navigateTargetMax: 1000,\n pluginDataMaxBytes: 16 * 1024,\n} as const;\n\nfunction validateTitle(title: string): string | null {\n if (typeof title !== \"string\" || title.length === 0) return \"title must be a non-empty string\";\n if (title.length > NOTIFIER_LIMITS.titleMax) return `title exceeds max length of ${NOTIFIER_LIMITS.titleMax} chars`;\n return null;\n}\n\nfunction validateBody(body: string | undefined): string | null {\n if (body === undefined) return null;\n if (body.length > NOTIFIER_LIMITS.bodyMax) return `body exceeds max length of ${NOTIFIER_LIMITS.bodyMax} chars`;\n return null;\n}\n\nfunction validateNavigateTarget(target: string | undefined): string | null {\n if (target === undefined) return null;\n if (target.length === 0) return \"navigateTarget must be a non-empty relative path when set\";\n if (target.length > NOTIFIER_LIMITS.navigateTargetMax) {\n return `navigateTarget exceeds max length of ${NOTIFIER_LIMITS.navigateTargetMax} chars`;\n }\n // Must be a same-origin relative path. Reject schemes\n // (`javascript:`, `https://...`) and scheme-relative URLs\n // (`//evil.com/...`, which an `<a href>` would resolve to the\n // attacker's origin). One leading \"/\" only.\n if (!target.startsWith(\"/\") || target.startsWith(\"//\")) {\n return \"navigateTarget must be a relative path beginning with a single '/' (no scheme, no '//')\";\n }\n return null;\n}\n\nfunction validatePluginData(pluginData: unknown): string | null {\n if (pluginData === undefined) return null;\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(pluginData);\n } catch (err) {\n return `pluginData is not JSON-serialisable: ${String(err)}`;\n }\n // `JSON.stringify` returns `undefined` for non-serialisable roots\n // (e.g. a bare function or symbol). Treat that as a serialisation\n // failure so it doesn't slip through as an empty-string size.\n if (typeof serialized !== \"string\") return \"pluginData is not JSON-serialisable\";\n if (serialized.length > NOTIFIER_LIMITS.pluginDataMaxBytes) {\n return `pluginData JSON exceeds ${NOTIFIER_LIMITS.pluginDataMaxBytes} bytes`;\n }\n return null;\n}\n\nfunction validateActionCoherence(input: PublishInput): string | null {\n if (input.lifecycle !== \"action\") return null;\n if (input.severity === \"info\") {\n return \"action lifecycle is incompatible with info severity (use fyi for low-priority pings)\";\n }\n if (typeof input.navigateTarget !== \"string\" || input.navigateTarget.length === 0) {\n return \"action lifecycle requires a non-empty navigateTarget\";\n }\n return null;\n}\n\n/** Validate a `PublishInput`. Returns `null` if OK, or a\n * human-readable error string. Order matters — shape/size errors are\n * reported before lifecycle/severity coherence errors so the message\n * the caller sees points at the most fundamental problem first. */\nexport function validatePublishInput(input: PublishInput): string | null {\n return (\n validateTitle(input.title) ??\n validateBody(input.body) ??\n validateNavigateTarget(input.navigateTarget) ??\n validatePluginData(input.pluginData) ??\n validateActionCoherence(input)\n );\n}\n","// Notifier engine — single-process, two-file (active + history),\n// single-channel. Host-agnostic: file paths, the atomic JSON writer,\n// the pub-sub event sink, and the logger are all injected via\n// `configureNotifier` + `setNotifierFilePaths` so MulmoClaude and\n// MulmoTerminal share one notification engine over their own\n// workspaces and pub-sub fabrics.\n//\n// API surface: publish / clear / cancel / get / listFor / listAll /\n// listHistory (+ plugin-scoped variants). Mutations queue through a\n// writing-flag + waiter-queue coordinator so concurrent callers can't\n// race on the atomic write's rename. Reads bypass the queue (rename\n// atomicity makes half-reads impossible) and trade strict\n// linearisability for simpler code: the contract is \"after\n// `await publish(x)` resolves, subsequent reads see x\" — which holds\n// because `publish` awaits the persist before returning.\n//\n// `clear` / `cancel` push to history *before* removing from active.\n// History persistence is best-effort: if it fails, the active write\n// still wins and the failure is logged. Active is the source of\n// truth; history is an audit aid.\n\nimport type { MinimalLogger } from \"@mulmoclaude/common\";\nimport { randomUUID } from \"node:crypto\";\nimport { loadActive, loadHistory, saveActive, saveHistory, type WriteJson } from \"./store.js\";\nimport { validatePublishInput } from \"./validate.js\";\nimport {\n HISTORY_CAP,\n type NotifierEntry,\n type NotifierEvent,\n type NotifierFile,\n type NotifierHistoryEntry,\n type NotifierSeverity,\n type PublishInput,\n} from \"./types.js\";\n\nexport { NOTIFIER_LIMITS, validatePublishInput } from \"./validate.js\";\n\n// ── Dependency injection ──────────────────────────────────────────\n\n/** Minimal logger the engine needs. The host passes its structured\n * logger; absent one, failures are swallowed (the engine never throws\n * on a fan-out/persist-best-effort path). */\nexport type NotifierLogger = Pick<MinimalLogger, \"warn\" | \"error\">;\n\nexport interface NotifierConfig {\n /** Atomic JSON writer (the host's `writeJsonAtomic`). */\n writeJson: WriteJson;\n /** Fan-out sink — the host binds this to `pubsub.publish(channel, event)`. */\n publishEvent: (event: NotifierEvent) => void;\n /** Optional logger. */\n log?: NotifierLogger;\n}\n\nconst NOOP_LOG: NotifierLogger = { warn: () => {}, error: () => {} };\n\nlet config: NotifierConfig | null = null;\nlet activeFilePath = \"\";\nlet historyFilePath = \"\";\n\nfunction logger(): NotifierLogger {\n return config?.log ?? NOOP_LOG;\n}\n\n/** Wire the engine's I/O deps. Call once at startup, before the first\n * mutation. Does NOT set file paths — those are set independently via\n * `setNotifierFilePaths` so a host can bind production paths at module\n * load and a test can override them without re-supplying the deps. */\nexport function configureNotifier(injected: NotifierConfig): void {\n config = injected;\n}\n\n// ── In-process event listeners ────────────────────────────────────\n//\n// Separate from the socket.io pubsub so server-side adapters (macOS\n// push, future Encore) can react to state changes without going\n// through a websocket round-trip. The host's pubsub is fan-out-only\n// with no server-side subscribe, so this listener registry is the\n// in-process equivalent. Listeners run synchronously inside `emit`,\n// before the pubsub fan-out.\n\ntype NotifierEventListener = (event: NotifierEvent) => void;\nconst listeners: NotifierEventListener[] = [];\n\n/** Register an in-process listener for engine events. Returns an\n * unsubscribe function the caller can use during teardown. */\nexport function onEvent(listener: NotifierEventListener): () => void {\n listeners.push(listener);\n return () => {\n const idx = listeners.indexOf(listener);\n if (idx >= 0) listeners.splice(idx, 1);\n };\n}\n\nfunction emit(event: NotifierEvent): void {\n // In-process fan-out first. Each listener is wrapped: a throwing\n // listener must not poison the rest, and must not propagate out of\n // `processBatch` and strand the still-unsettled waiters (their\n // resolve/reject is called *after* this emit loop). Fan-out is\n // best-effort by contract — losing one subscriber must not lose\n // the write that already committed.\n for (const listener of listeners) {\n try {\n listener(event);\n } catch (err) {\n logger().error(\"in-process listener failed\", { type: event.type, error: String(err) });\n }\n }\n if (!config) {\n logger().warn(\"emit before init\", { type: event.type });\n return;\n }\n try {\n config.publishEvent(event);\n } catch (err) {\n logger().error(\"emit failed\", { type: event.type, error: String(err) });\n }\n}\n\n// ── Write coordinator ─────────────────────────────────────────────\n\n/** A mutation function applied to the in-memory state object during\n * drain. Returns either:\n *\n * - `null` — no state change (e.g., `clear` on an unknown id).\n * The drainer skips the disk write and the emit if every\n * mutation in a batch returned `null`.\n * - `{ event, historyEntry? }` — state changed. The drainer emits\n * the event after the active write succeeds, and prepends\n * `historyEntry` to history (best-effort) when present.\n *\n * Mutations MUST NOT modify state when returning `null`. Violating\n * this invariant produces a write skip with stale on-disk state. */\ntype MutationOutcome = { event: NotifierEvent; historyEntry?: NotifierHistoryEntry } | null;\ntype Mutation = (state: NotifierFile) => MutationOutcome;\n\ninterface Waiter {\n mutate: Mutation;\n resolve: () => void;\n reject: (err: unknown) => void;\n}\n\ntype MutationResult = { ok: true; outcome: MutationOutcome } | { ok: false; error: unknown };\n\nlet writing = false;\nlet waiters: Waiter[] = [];\n\n/** Point the engine at its active/history files. Resets the write\n * queue, so callers must not have in-flight mutations. The host calls\n * this once with the workspace paths; tests call it per-case with temp\n * files. */\nexport function setNotifierFilePaths(paths: { active: string; history: string }): void {\n activeFilePath = paths.active;\n historyFilePath = paths.history;\n writing = false;\n waiters = [];\n}\n\n/** Test-only: clear config + queue so each suite starts clean. */\nexport function resetNotifier(): void {\n config = null;\n activeFilePath = \"\";\n historyFilePath = \"\";\n writing = false;\n waiters = [];\n listeners.length = 0;\n}\n\nfunction requireWriteJson(): WriteJson {\n if (!config) throw new Error(\"notifier: configureNotifier() not called\");\n return config.writeJson;\n}\n\n/** A waiter carried alongside the outcome of its own mutation, so settling can\n * never pair a result with the wrong caller's promise. */\ninterface SettledMutation {\n waiter: Waiter;\n result: MutationResult;\n}\n\nfunction applyBatchMutations(batch: Waiter[], state: NotifierFile): SettledMutation[] {\n return batch.map((waiter) => {\n try {\n return { waiter, result: { ok: true, outcome: waiter.mutate(state) } };\n } catch (err) {\n return { waiter, result: { ok: false, error: err } };\n }\n });\n}\n\nfunction collectEvents(settled: SettledMutation[]): NotifierEvent[] {\n const events: NotifierEvent[] = [];\n for (const { result } of settled) {\n if (result.ok && result.outcome !== null) events.push(result.outcome.event);\n }\n return events;\n}\n\nfunction collectHistoryEntries(settled: SettledMutation[]): NotifierHistoryEntry[] {\n const entries: NotifierHistoryEntry[] = [];\n for (const { result } of settled) {\n if (result.ok && result.outcome !== null && result.outcome.historyEntry) {\n entries.push(result.outcome.historyEntry);\n }\n }\n return entries;\n}\n\nfunction settleBatch(settled: SettledMutation[]): void {\n // Resolves come AFTER any emits so subscribers see the event\n // before the caller's `await` returns.\n for (const { waiter, result } of settled) {\n if (result.ok) waiter.resolve();\n else waiter.reject(result.error);\n }\n}\n\nfunction rejectBatch(batch: Waiter[], err: unknown): void {\n for (const waiter of batch) waiter.reject(err);\n}\n\nasync function persistHistory(newEntries: NotifierHistoryEntry[]): Promise<void> {\n const existing = await loadHistory(historyFilePath);\n // Newest-first ordering: a batch contains terminations in arrival\n // order; we want the last one to land at index 0 of history.\n const merged = [...newEntries.slice().reverse(), ...existing.entries].slice(0, HISTORY_CAP);\n await saveHistory(requireWriteJson(), historyFilePath, { entries: merged });\n}\n\nasync function processBatch(batch: Waiter[]): Promise<void> {\n let state: NotifierFile;\n try {\n state = await loadActive(activeFilePath);\n } catch (err) {\n logger().error(\"load failed\", { error: String(err) });\n rejectBatch(batch, err);\n return;\n }\n const settled = applyBatchMutations(batch, state);\n const events = collectEvents(settled);\n const historyEntries = collectHistoryEntries(settled);\n\n if (events.length > 0) {\n try {\n await saveActive(requireWriteJson(), activeFilePath, state);\n } catch (err) {\n logger().error(\"active write failed\", { error: String(err) });\n rejectBatch(batch, err);\n return;\n }\n if (historyEntries.length > 0) {\n // Best-effort: active is the source of truth, history is an\n // audit aid. A failed history write is logged but doesn't\n // unwind the active commit.\n try {\n await persistHistory(historyEntries);\n } catch (err) {\n logger().error(\"history write failed\", { error: String(err) });\n }\n }\n for (const event of events) emit(event);\n }\n settleBatch(settled);\n}\n\nasync function drain(): Promise<void> {\n writing = true;\n try {\n while (waiters.length > 0) {\n const batch = waiters;\n waiters = [];\n await processBatch(batch);\n }\n } finally {\n writing = false;\n }\n}\n\nfunction enqueue(mutate: Mutation): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n waiters.push({ mutate, resolve, reject });\n if (!writing) void drain();\n });\n}\n\nfunction removeEntry(state: NotifierFile, entryId: string): NotifierFile[\"entries\"] {\n // Object-rest excludes the key without invoking `delete`.\n const { [entryId]: __removed, ...remaining } = state.entries;\n return remaining;\n}\n\nfunction buildHistoryEntry(entry: NotifierEntry, terminalType: \"cleared\" | \"cancelled\"): NotifierHistoryEntry {\n return { ...entry, terminalType, terminalAt: new Date().toISOString() };\n}\n\n// ── Public API ────────────────────────────────────────────────────\n\n/** The optional half of a publish input, with unset keys left OUT rather than\n * written as `undefined` — an entry is persisted and re-read through JSON,\n * where an unset field carries no key at all. */\nfunction optionalPublishFields<TPluginData>(input: PublishInput<TPluginData>): Partial<NotifierEntry<TPluginData>> {\n return {\n ...(input.lifecycle !== undefined ? { lifecycle: input.lifecycle } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.navigateTarget !== undefined ? { navigateTarget: input.navigateTarget } : {}),\n ...(input.pluginData !== undefined ? { pluginData: input.pluginData } : {}),\n };\n}\n\nexport async function publish<TPluginData = unknown>(input: PublishInput<TPluginData>): Promise<{ id: string }> {\n // Validate at the engine boundary, so every caller shares one wall —\n // plugin runtime, legacy wrapper, host module. Publish has no HTTP\n // surface to validate separately (`server/api/routes/notifier.ts`).\n const validationError = validatePublishInput(input);\n if (validationError) {\n throw new Error(`notifier.publish: ${validationError}`);\n }\n const entryId = randomUUID();\n const entry: NotifierEntry<TPluginData> = {\n id: entryId,\n pluginPkg: input.pluginPkg,\n severity: input.severity,\n title: input.title,\n createdAt: new Date().toISOString(),\n ...optionalPublishFields(input),\n };\n await enqueue((state) => {\n state.entries[entryId] = entry;\n return { event: { type: \"published\", entry } };\n });\n return { id: entryId };\n}\n\n/** Remove an active entry and record its terminal history. `clear`\n * (user dismissed) and `cancel` (producer withdrew) differ only in the\n * emitted event / history reason. No-op when the id is unknown. */\nasync function terminateEntry(entryId: string, reason: \"cleared\" | \"cancelled\"): Promise<void> {\n await enqueue((state) => {\n const entry = state.entries[entryId];\n if (!entry) return null;\n state.entries = removeEntry(state, entryId);\n return {\n event: reason === \"cleared\" ? { type: \"cleared\", id: entryId } : { type: \"cancelled\", id: entryId },\n historyEntry: buildHistoryEntry(entry, reason),\n };\n });\n}\n\nexport async function clear(entryId: string): Promise<void> {\n await terminateEntry(entryId, \"cleared\");\n}\n\nexport async function cancel(entryId: string): Promise<void> {\n await terminateEntry(entryId, \"cancelled\");\n}\n\n/** In-place update for an active entry. Only the fields present on\n * `patch` are rewritten; `id`, `pluginPkg`, `lifecycle`, and\n * `createdAt` stay fixed. Emits a single `\"updated\"` event with the\n * post-mutation entry — no history record is written because the\n * entry is still active, just with refreshed content.\n *\n * No-ops (no throw) when the id is unknown, the entry belongs to a\n * different plugin, or the merged shape would violate\n * `validatePublishInput`. The silent skip matches `clearForPlugin`'s\n * isolation semantics; validation failures are logged for diagnosis. */\nexport async function updateForPlugin<TPluginData = unknown>(\n pluginPkg: string,\n entryId: string,\n patch: {\n severity?: NotifierSeverity;\n title?: string;\n body?: string;\n navigateTarget?: string;\n pluginData?: TPluginData;\n },\n): Promise<void> {\n await enqueue((state) => {\n const entry = state.entries[entryId];\n if (!entry) return null;\n if (entry.pluginPkg !== pluginPkg) return null;\n const next: NotifierEntry = {\n ...entry,\n ...(patch.severity !== undefined ? { severity: patch.severity } : {}),\n ...(patch.title !== undefined ? { title: patch.title } : {}),\n ...(patch.body !== undefined ? { body: patch.body } : {}),\n ...(patch.navigateTarget !== undefined ? { navigateTarget: patch.navigateTarget } : {}),\n ...(patch.pluginData !== undefined ? { pluginData: patch.pluginData } : {}),\n };\n // Re-validate the merged shape so an update can't degrade the\n // entry below publish-time invariants.\n const validationError = validatePublishInput({\n pluginPkg: next.pluginPkg,\n severity: next.severity,\n title: next.title,\n body: next.body,\n lifecycle: next.lifecycle,\n navigateTarget: next.navigateTarget,\n pluginData: next.pluginData,\n });\n if (validationError) {\n logger().warn(\"update rejected by validation\", { entryId, pluginPkg, error: validationError });\n return null;\n }\n state.entries[entryId] = next;\n return { event: { type: \"updated\", entry: next } };\n });\n}\n\n/** Plugin-scoped point lookup. Returns the entry by id, but only if it\n * belongs to the caller's plugin; otherwise undefined. Cross-plugin\n * reads return undefined for isolation — same property as\n * `clearForPlugin` / `updateForPlugin`. */\nexport async function getForPlugin(pluginPkg: string, entryId: string): Promise<NotifierEntry | undefined> {\n const state = await loadActive(activeFilePath);\n const entry = state.entries[entryId];\n if (!entry) return undefined;\n if (entry.pluginPkg !== pluginPkg) return undefined;\n return entry;\n}\n\n/** Plugin-scoped clear. Same as `clear` but no-ops if the entry's\n * `pluginPkg` doesn't match the caller's, so a plugin can't dismiss\n * another plugin's notification by guessing or scraping its id. */\nexport async function clearForPlugin(pluginPkg: string, entryId: string): Promise<void> {\n await enqueue((state) => {\n const entry = state.entries[entryId];\n if (!entry) return null;\n if (entry.pluginPkg !== pluginPkg) return null;\n state.entries = removeEntry(state, entryId);\n return {\n event: { type: \"cleared\", id: entryId },\n historyEntry: buildHistoryEntry(entry, \"cleared\"),\n };\n });\n}\n\nexport async function get(entryId: string): Promise<NotifierEntry | undefined> {\n const state = await loadActive(activeFilePath);\n return state.entries[entryId];\n}\n\nexport async function listFor(pluginPkg: string): Promise<NotifierEntry[]> {\n const state = await loadActive(activeFilePath);\n return Object.values(state.entries).filter((entry) => entry.pluginPkg === pluginPkg);\n}\n\nexport async function listAll(): Promise<NotifierEntry[]> {\n const state = await loadActive(activeFilePath);\n return Object.values(state.entries);\n}\n\nexport async function listHistory(): Promise<NotifierHistoryEntry[]> {\n const state = await loadHistory(historyFilePath);\n return state.entries;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,sBAAsB,CAAC,OAAO,QAAQ;;;;;;AAQnD,IAAa,sBAAsB;CAAC;CAAQ;CAAS;AAAQ;;;;;AAgF7D,IAAa,cAAc;;;ACjG3B,IAAM,iBAAiB,CAAC,WAAW,WAAW;AAE9C,SAAS,QAA0B,SAAuB,OAA4B;CACpF,OAAO,QAAQ,MAAM,cAAc,cAAc,KAAK;AACxD;AAKA,SAAS,gBAAgB,OAAwC;CAC/D,OACE,cAAc,OAAO,IAAI,KACzB,cAAc,OAAO,WAAW,KAChC,cAAc,OAAO,OAAO,KAC5B,cAAc,OAAO,WAAW,KAChC,QAAQ,qBAAqB,MAAM,QAAQ,MAC1C,MAAM,cAAc,KAAA,KAAa,QAAQ,qBAAqB,MAAM,SAAS,MAC9E,iBAAiB,MAAM,IAAI,KAC3B,iBAAiB,MAAM,cAAc;AAEzC;AAEA,SAAS,uBAAuB,OAA+C;CAC7E,OAAO,gBAAgB,KAAK,KAAK,cAAc,OAAO,YAAY,KAAK,QAAQ,gBAAgB,MAAM,YAAY;AACnH;AAKA,SAAS,eAAe,OAAuC;CAC7D,OAAO,SAAS,KAAK,KAAK,SAAS,MAAM,OAAO,KAAK,OAAO,OAAO,MAAM,OAAO,CAAC,CAAC,MAAM,eAAe;AACzG;AAEA,SAAS,sBAAsB,OAA8C;CAC3E,OAAO,SAAS,KAAK,KAAK,eAAe,MAAM,OAAO,KAAK,MAAM,QAAQ,MAAM,sBAAsB;AACvG;;;;AAKA,eAAe,kBAAkB,UAAoC;CACnE,IAAI;EACF,OAAO,KAAK,MAAM,MAAMA,SAAW,SAAS,UAAU,OAAO,CAAC;CAChE,SAAS,KAAK;EACZ,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oC;CACxD,MAAM,QAAQ,MAAM,WAAW,cAAc;CAC7C,OAAO,OAAO,OAAO,MAAM,OAAO;AACpC;AAEA,eAAsB,cAA+C;CAEnE,QAAO,MADa,YAAY,eAAe,EAAA,CAClC;AACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paths-C8-jxR0s.cjs","names":[],"sources":["../src/global-config/paths.ts"],"sourcesContent":["// The host-NEUTRAL per-user config file shared by MulmoClaude and\n// MulmoTerminal. It lives OUTSIDE any workspace, in the same `~/.config/mulmo`\n// directory the Google grant already uses (`../google/paths.ts`), for the same\n// reason: one machine, one set of cross-app preferences, surviving workspace\n// resets and never synced.\n//\n// Deliberately NOT `~/mulmoclaude/config/settings.json` (that is per-workspace\n// and MulmoClaude-owned) and NOT `~/.mulmoterminal/config.json` (that is the\n// terminal's own file). Neither app owns this one.\n//\n// The `home` parameter exists so tests can thread a fake home.\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport function mulmoConfigDir(home?: string): string {\n return join(home ?? homedir(), \".config\", \"mulmo\");\n}\n\nexport function mulmoGlobalConfigPath(home?: string): string {\n return join(mulmoConfigDir(home), \"config.json\");\n}\n"],"mappings":";;;AAcA,SAAgB,eAAe,MAAuB;CACpD,QAAA,
|
|
1
|
+
{"version":3,"file":"paths-C8-jxR0s.cjs","names":["join","homedir"],"sources":["../src/global-config/paths.ts"],"sourcesContent":["// The host-NEUTRAL per-user config file shared by MulmoClaude and\n// MulmoTerminal. It lives OUTSIDE any workspace, in the same `~/.config/mulmo`\n// directory the Google grant already uses (`../google/paths.ts`), for the same\n// reason: one machine, one set of cross-app preferences, surviving workspace\n// resets and never synced.\n//\n// Deliberately NOT `~/mulmoclaude/config/settings.json` (that is per-workspace\n// and MulmoClaude-owned) and NOT `~/.mulmoterminal/config.json` (that is the\n// terminal's own file). Neither app owns this one.\n//\n// The `home` parameter exists so tests can thread a fake home.\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport function mulmoConfigDir(home?: string): string {\n return join(home ?? homedir(), \".config\", \"mulmo\");\n}\n\nexport function mulmoGlobalConfigPath(home?: string): string {\n return join(mulmoConfigDir(home), \"config.json\");\n}\n"],"mappings":";;;AAcA,SAAgB,eAAe,MAAuB;CACpD,QAAA,GAAOA,UAAAA,KAAAA,CAAK,SAAA,GAAQC,QAAAA,QAAAA,CAAQ,GAAG,WAAW,OAAO;AACnD;AAEA,SAAgB,sBAAsB,MAAuB;CAC3D,QAAA,GAAOD,UAAAA,KAAAA,CAAK,eAAe,IAAI,GAAG,aAAa;AACjD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n.cjs","names":[],"sources":["../../src/plugin-vue/pluginI18n.ts"],"sourcesContent":["// Factory for a plugin's OWN vue-i18n instance — fully self-contained, sharing no\n// i18n resources with the host. A plugin can't import another plugin, so the\n// construction the accounting + collection plugins used to duplicate lives here;\n// each plugin keeps only its message maps, its locale binding, and its public\n// composable name. NOT convertible to gui-chat-protocol/vue's `createUseT`: these\n// instances are driven by host bindings, not the PLUGIN_RUNTIME_KEY runtime.\n\nimport { createI18n } from \"vue-i18n\";\nimport { effectScope, watchEffect } from \"vue\";\n\n// A single-signature builder so `typeof buildPluginI18n<M>` is a legal type query:\n// `typeof createI18n<[M], string, false>` itself is rejected — tsc checks explicit\n// type args against createI18n's FIRST overload (`Legacy extends boolean` comes\n// first there) instead of skipping to the schema-first overload a value call picks.\nconst buildPluginI18n = <M>(messages: Record<string, M>) =>\n createI18n<[M], string, false>({\n legacy: false,\n locale: \"en\",\n fallbackLocale: \"en\",\n messages,\n });\n\ntype PluginI18nGlobal<M> = ReturnType<typeof buildPluginI18n<M>>[\"global\"];\n\n/** What the composable returns — a drop-in for vue-i18n's `useI18n()`,\n * destructured at the call site: `t` reads the plugin's keys, `locale` is the\n * reactive tag for date/number formatting. */\nexport interface PluginI18n<M> {\n t: PluginI18nGlobal<M>[\"t\"];\n locale: PluginI18nGlobal<M>[\"locale\"];\n}\n\nconst onceRetryable = (wire: () => void): (() => void) => {\n const state = { wired: false };\n return () => {\n if (state.wired) return;\n wire();\n // Flip the flag only after the wiring succeeds — if the first locale read\n // throws (e.g. the binding isn't configured yet), a later call can retry\n // rather than being locked out forever.\n state.wired = true;\n };\n};\n\n/** Build a plugin's self-contained vue-i18n instance and return its composable.\n * The locale mirror runs in a detached effect scope so it lives for the app's\n * lifetime rather than a single component's, and is wired lazily on the\n * composable's first call — by then the host has configured the binding, so\n * `localeSource()` resolves. */\nexport function createPluginI18n<M>(messages: Record<string, M>, localeSource: () => string): () => PluginI18n<M> {\n const i18n = buildPluginI18n(messages);\n const syncScope = effectScope(true);\n const ensureLocaleSync = onceRetryable(() => {\n syncScope.run(() => {\n watchEffect(() => {\n i18n.global.locale.value = localeSource();\n });\n });\n });\n return () => {\n ensureLocaleSync();\n return { t: i18n.global.t, locale: i18n.global.locale };\n };\n}\n"],"mappings":";;;;AAcA,IAAM,mBAAsB,cAAA,
|
|
1
|
+
{"version":3,"file":"i18n.cjs","names":["createI18n","effectScope"],"sources":["../../src/plugin-vue/pluginI18n.ts"],"sourcesContent":["// Factory for a plugin's OWN vue-i18n instance — fully self-contained, sharing no\n// i18n resources with the host. A plugin can't import another plugin, so the\n// construction the accounting + collection plugins used to duplicate lives here;\n// each plugin keeps only its message maps, its locale binding, and its public\n// composable name. NOT convertible to gui-chat-protocol/vue's `createUseT`: these\n// instances are driven by host bindings, not the PLUGIN_RUNTIME_KEY runtime.\n\nimport { createI18n } from \"vue-i18n\";\nimport { effectScope, watchEffect } from \"vue\";\n\n// A single-signature builder so `typeof buildPluginI18n<M>` is a legal type query:\n// `typeof createI18n<[M], string, false>` itself is rejected — tsc checks explicit\n// type args against createI18n's FIRST overload (`Legacy extends boolean` comes\n// first there) instead of skipping to the schema-first overload a value call picks.\nconst buildPluginI18n = <M>(messages: Record<string, M>) =>\n createI18n<[M], string, false>({\n legacy: false,\n locale: \"en\",\n fallbackLocale: \"en\",\n messages,\n });\n\ntype PluginI18nGlobal<M> = ReturnType<typeof buildPluginI18n<M>>[\"global\"];\n\n/** What the composable returns — a drop-in for vue-i18n's `useI18n()`,\n * destructured at the call site: `t` reads the plugin's keys, `locale` is the\n * reactive tag for date/number formatting. */\nexport interface PluginI18n<M> {\n t: PluginI18nGlobal<M>[\"t\"];\n locale: PluginI18nGlobal<M>[\"locale\"];\n}\n\nconst onceRetryable = (wire: () => void): (() => void) => {\n const state = { wired: false };\n return () => {\n if (state.wired) return;\n wire();\n // Flip the flag only after the wiring succeeds — if the first locale read\n // throws (e.g. the binding isn't configured yet), a later call can retry\n // rather than being locked out forever.\n state.wired = true;\n };\n};\n\n/** Build a plugin's self-contained vue-i18n instance and return its composable.\n * The locale mirror runs in a detached effect scope so it lives for the app's\n * lifetime rather than a single component's, and is wired lazily on the\n * composable's first call — by then the host has configured the binding, so\n * `localeSource()` resolves. */\nexport function createPluginI18n<M>(messages: Record<string, M>, localeSource: () => string): () => PluginI18n<M> {\n const i18n = buildPluginI18n(messages);\n const syncScope = effectScope(true);\n const ensureLocaleSync = onceRetryable(() => {\n syncScope.run(() => {\n watchEffect(() => {\n i18n.global.locale.value = localeSource();\n });\n });\n });\n return () => {\n ensureLocaleSync();\n return { t: i18n.global.t, locale: i18n.global.locale };\n };\n}\n"],"mappings":";;;;AAcA,IAAM,mBAAsB,cAAA,GAC1BA,SAAAA,WAAAA,CAA+B;CAC7B,QAAQ;CACR,QAAQ;CACR,gBAAgB;CAChB;AACF,CAAC;AAYH,IAAM,iBAAiB,SAAmC;CACxD,MAAM,QAAQ,EAAE,OAAO,MAAM;CAC7B,aAAa;EACX,IAAI,MAAM,OAAO;EACjB,KAAK;EAIL,MAAM,QAAQ;CAChB;AACF;;;;;;AAOA,SAAgB,iBAAoB,UAA6B,cAAiD;CAChH,MAAM,OAAO,gBAAgB,QAAQ;CACrC,MAAM,aAAA,GAAYC,IAAAA,YAAAA,CAAY,IAAI;CAClC,MAAM,mBAAmB,oBAAoB;EAC3C,UAAU,UAAU;GAClB,CAAA,GAAA,IAAA,YAAA,OAAkB;IAChB,KAAK,OAAO,OAAO,QAAQ,aAAa;GAC1C,CAAC;EACH,CAAC;CACH,CAAC;CACD,aAAa;EACX,iBAAiB;EACjB,OAAO;GAAE,GAAG,KAAK,OAAO;GAAG,QAAQ,KAAK,OAAO;EAAO;CACxD;AACF"}
|