Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

refactor(app): FileTree pure-helper extraction and row lookup map (#2733)

Andrew Mikofalvya96761211225
diff --git a/knip.config.ts b/knip.config.ts
index 16d637b4b..9633755a0 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -119,7 +119,9 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts'],
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index a5a401d1a..9ef72868b 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -43,8 +43,6 @@ import {
TriangleAlert,
UnfoldVertical,
} from 'lucide-react';
-import { __iconNode as botIcon } from 'lucide-react/dist/esm/icons/bot';
-import { __iconNode as link2Icon } from 'lucide-react/dist/esm/icons/link-2';
import { useTheme } from 'next-themes';
import {
type DragEvent as ReactDragEvent,
@@ -61,10 +59,7 @@ import {
import { toast } from 'sonner';
import { DeleteConfirmationDialog } from '@/components/DeleteConfirmationDialog';
import { FileTreeFilteredToZeroNotice } from '@/components/FileTreeFilteredToZeroNotice';
-import {
- MARKDOWN_FILE_ICON_PATH_D,
- MARKDOWN_FILE_ICON_VIEWBOX,
-} from '@/components/file-entry-icon';
+import { MARKDOWN_FILE_ICON_VIEWBOX } from '@/components/file-entry-icon';
import {
appendSidebarUploadFields,
collectTreeFolderPathsFromDocuments,
@@ -101,6 +96,12 @@ import {
applyExtensionBadges,
FILE_TREE_EXT_BADGE_CSS,
} from '@/components/file-tree-extension-badge';
+import {
+ AGENT_DECORATION_ICON_ID,
+ FILE_TREE_DECORATION_SPRITE_SHEET,
+ LINK_DECORATION_ICON_ID,
+ MARKDOWN_FILE_ICON_ID,
+} from '@/components/file-tree-icon-sprite';
import { buildOkignorePatternFromTarget } from '@/components/file-tree-okignore';
import {
applyDeleteToDocuments,
@@ -116,6 +117,20 @@ import {
type RenamedFolderMapping,
remapActiveDocName,
} from '@/components/file-tree-operations';
+import {
+ alternateMarkdownTreePath,
+ buildRowDecorationIndex,
+ collectTabsToCloseForDelete,
+ deleteTargetCoversPendingCreate,
+ hasSameStemMarkdownSiblingTreePath,
+ isAgentTreePath,
+ isEditableKeyboardTarget,
+ markdownTreeExtension,
+ parseAlreadyExistsRenamePath,
+ resolveDuplicableKeyboardTarget,
+ resolveKeyboardDeleteTargets,
+ selectedTreePathsToDeleteTargets,
+} from '@/components/file-tree-path-helpers';
import {
applyRenameInputAffordance,
FILE_TREE_RENAME_INPUT_CSS,
@@ -135,7 +150,6 @@ import {
classifyEmptyTree,
type DocumentEntry,
type FileEntry,
- type FolderEntry,
filterVisibleEntries,
hasOkPathSegment,
isAssetEntry,
@@ -228,18 +242,6 @@ import { useInstalledAgents } from './handoff/useInstalledAgents';
import { cancelHoverPrewarm, scheduleHoverPrewarm } from './sidebar-hover-prewarm';
import { useSidebar } from './ui/sidebar';
-const MARKDOWN_TREE_EXTENSION_PATTERN = /\.(md|mdx)$/i;
-
-function parseAlreadyExistsRenamePath(message: string): string | null {
- const match = message.match(/^"(.+)" already exists\.$/);
- return match ? match[1] : null;
-}
-
-function markdownTreeExtension(path: string): string | null {
- const match = path.match(MARKDOWN_TREE_EXTENSION_PATTERN);
- return match ? match[0] : null;
-}
-
function focusEditorAfterRename(docName: string): void {
window.requestAnimationFrame(() => {
const editor = getEditorForDoc(docName);
@@ -300,43 +302,6 @@ async function copyToClipboard(text: string, kind: 'full' | 'relative'): Promise
}
}
-const AGENT_FILE_NAMES = new Set(['agents', 'agent', 'claude', 'skill']);
-const LINK_DECORATION_ICON_ID = 'ok-file-tree-link-decoration';
-const AGENT_DECORATION_ICON_ID = 'ok-file-tree-agent-decoration';
-const MARKDOWN_FILE_ICON_ID = 'ok-file-tree-markdown';
-// Custom Markdown file glyph (document with an "MD" label) overriding Pierre's
-// built-in `complete`-set markdown glyph. `fill="currentColor"` lets
-// `--trees-file-icon-color-markdown` (set in createFileTreeStyle, see
-// file-tree-density.ts) color it.
-const MARKDOWN_FILE_ICON_SYMBOL = `<symbol id="${MARKDOWN_FILE_ICON_ID}" viewBox="${MARKDOWN_FILE_ICON_VIEWBOX}" fill="currentColor"><path d="${MARKDOWN_FILE_ICON_PATH_D}"/></symbol>`;
-
-type IconNode = [string, Record<string, string>][];
-
-function iconNodeToSvg(iconNode: IconNode): string {
- return (
- iconNode
- // remove React key
- .map(([tag, { key: _, ...attrs }]) => {
- const attrString = Object.entries(attrs)
- .map(([k, v]) => `${k}="${v}"`)
- .join(' ');
- return `<${tag} ${attrString} />`;
- })
- .join('')
- );
-}
-
-function createLucideSpriteSymbol(id: string, iconNode: IconNode): string {
- const symbolContent = iconNodeToSvg(iconNode);
- return `<symbol id="${id}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${symbolContent}</symbol>`;
-}
-
-const FILE_TREE_DECORATION_SPRITE_SHEET = `<svg data-icon-sprite aria-hidden="true" width="0" height="0">
- ${createLucideSpriteSymbol(LINK_DECORATION_ICON_ID, link2Icon)}
- ${createLucideSpriteSymbol(AGENT_DECORATION_ICON_ID, botIcon)}
- ${MARKDOWN_FILE_ICON_SYMBOL}
-</svg>`;
-
// Drop-to-root affordance. The patched `@pierre/trees` sets
// `data-file-tree-root-drag-target="true"` on the virtualized root while an
// in-tree drag hovers empty content area (or a top-level file) — i.e. when the
@@ -432,11 +397,6 @@ const FILE_TREE_CREATION_CLEARED_CSS = `
// CSS + DOM-mutation contract stays in one place.
const FILE_TREE_UNSAFE_CSS = `${FILE_TREE_EXT_BADGE_CSS}\n${FILE_TREE_RENAME_INPUT_CSS}\n${FILE_TREE_ROOT_DROP_CSS}\n${FILE_TREE_EXTERNAL_FILE_DROP_CSS}\n${FILE_TREE_CREATION_CLEARED_CSS}\n${FILE_TREE_INDENT_GUIDE_CSS}\n${FILE_TREE_STICKY_HEADER_CSS}`;
-function isAgentTreePath(treePath: string): boolean {
- const name = treePath.split('/').pop()?.replace(/\.md$/i, '').toLowerCase();
- return !!name && AGENT_FILE_NAMES.has(name);
-}
-
interface PendingCreate {
kind: 'file' | 'folder';
renamePath: string;
@@ -592,161 +552,6 @@ interface FileTreeMenuProps {
documents: readonly FileEntry[];
}
-function treePathToTarget(treePath: string, documents: readonly FileEntry[]): FileTreeTarget {
- return treeItemToTarget(
- {
- kind: treePath.endsWith('/') ? 'directory' : 'file',
- name: treePath,
- path: treePath,
- },
- documents,
- );
-}
-
-function alternateMarkdownTreePath(treePath: string): string | null {
- const match = treePath.match(/\.(md|mdx)$/i);
- if (!match) return null;
- const ext = match[0].toLowerCase();
- const alternateExt = ext === '.md' ? '.mdx' : '.md';
- return `${treePath.slice(0, -match[0].length)}${alternateExt}`;
-}
-
-function hasSameStemMarkdownSiblingTreePath(
- treePath: string,
- treePaths: readonly string[],
-): boolean {
- const alternate = alternateMarkdownTreePath(treePath);
- if (!alternate) return false;
- return treePaths.includes(alternate);
-}
-
-function isTreePathInsideFolder(treePath: string, folderTreePath: string): boolean {
- return treePath !== folderTreePath && treePath.startsWith(folderTreePath);
-}
-
-function selectedTreePathsToDeleteTargets(
- selectedTreePaths: readonly string[],
- documents: readonly FileEntry[],
-): FileTreeTarget[] {
- // Revealed `.ok` rows are read-only OK-managed state — they never become
- // delete targets, even when swept into a multi-selection beside deletable
- // rows (this also keeps the confirm dialog's item count honest).
- const uniqueDeletablePaths = [...new Set(selectedTreePaths)].filter(
- (treePath) => !hasOkPathSegment(treePath),
- );
- const selectedFolderPaths = uniqueDeletablePaths.filter((treePath) => treePath.endsWith('/'));
- return uniqueDeletablePaths
- .filter(
- (treePath) =>
- !selectedFolderPaths.some((folderPath) => isTreePathInsideFolder(treePath, folderPath)),
- )
- .map((treePath) => treePathToTarget(treePath, documents));
-}
-
-function normalizeTreePathFromModel(model: PierreFileTreeModel, treePath: string): string {
- const selectedItem =
- model.getItem(treePath) ?? model.getItem(folderPathToTreeDirectoryPath(treePath));
- return selectedItem?.isDirectory()
- ? folderPathToTreeDirectoryPath(treeDirectoryPathToFolderPath(selectedItem.getPath()))
- : treePath;
-}
-
-function focusedOrFirstSelectedTreePath(model: PierreFileTreeModel): string | null {
- const selectedPath = model.getFocusedPath() ?? model.getSelectedPaths()[0] ?? null;
- return selectedPath ? normalizeTreePathFromModel(model, selectedPath) : null;
-}
-
-function resolveDuplicableKeyboardTarget(
- model: PierreFileTreeModel,
- documents: readonly FileEntry[],
- assetTreePaths: ReadonlySet<string>,
-): FileTreeTarget | null {
- const selectedPath = focusedOrFirstSelectedTreePath(model);
- // Revealed `.ok` rows are read-only OK-managed state — no keyboard
- // copy/paste/duplicate, matching their menu's suppressed affordances.
- if (!selectedPath || assetTreePaths.has(selectedPath) || hasOkPathSegment(selectedPath)) {
- return null;
- }
- return treePathToTarget(selectedPath, documents);
-}
-
-function resolveKeyboardDeleteTargets(
- model: PierreFileTreeModel,
- documents: readonly FileEntry[],
-): FileTreeTarget[] {
- const selectedPaths = model.getSelectedPaths();
- const focusedPath = focusedOrFirstSelectedTreePath(model);
- const paths =
- selectedPaths.length > 0
- ? selectedPaths.map((treePath) => normalizeTreePathFromModel(model, treePath))
- : focusedPath
- ? [focusedPath]
- : [];
- return selectedTreePathsToDeleteTargets(paths, documents);
-}
-
-function isPathAtOrInsideFolder(path: string, folderPath: string): boolean {
- return path === folderPath || path.startsWith(`${folderPath}/`);
-}
-
-function isEditableKeyboardTarget(target: EventTarget | null): boolean {
- if (!(target instanceof HTMLElement)) return false;
- const tagName = target.tagName;
- return (
- tagName === 'INPUT' ||
- tagName === 'TEXTAREA' ||
- tagName === 'SELECT' ||
- target.isContentEditable ||
- target.closest('[contenteditable="true"]') !== null
- );
-}
-
-function collectTabsToCloseForDelete(
- targets: readonly FileTreeTarget[],
- documents: readonly FileEntry[],
- folderTreePaths: readonly string[],
-): { docNames: Set<string>; folderPaths: Set<string>; assetPaths: Set<string> } {
- const docNames = new Set<string>();
- const folderPaths = new Set<string>();
- const assetPaths = new Set<string>();
-
- for (const target of targets) {
- if (target.kind === 'file') {
- docNames.add(target.path);
- continue;
- }
- if (target.kind === 'asset') {
- assetPaths.add(target.path);
- continue;
- }
-
- folderPaths.add(target.path);
- for (const entry of documents) {
- if (isDocumentEntry(entry) && entry.docName.startsWith(`${target.path}/`)) {
- docNames.add(entry.docName);
- } else if (isAssetEntry(entry) && entry.path.startsWith(`${target.path}/`)) {
- assetPaths.add(entry.path);
- }
- }
- for (const treePath of folderTreePaths) {
- const folderPath = treeDirectoryPathToFolderPath(treePath);
- if (isPathAtOrInsideFolder(folderPath, target.path)) {
- folderPaths.add(folderPath);
- }
- }
- }
-
- return { docNames, folderPaths, assetPaths };
-}
-
-function deleteTargetCoversPendingCreate(target: FileTreeTarget, pending: PendingCreate): boolean {
- if (target.kind === 'file') {
- return pending.kind === 'file' && target.path === pending.createdPath;
- }
- if (target.kind === 'asset') return false;
- return isPathAtOrInsideFolder(pending.createdPath, target.path);
-}
-
function FileTreeMenu({
item,
context,
@@ -1386,25 +1191,6 @@ export function FileTree({
}
);
}
- function navigateToWithPulse(
- targetPath: string,
- size?: number,
- options?: { registerPage?: boolean },
- ) {
- if (options?.registerPage) addPage(targetPath);
- openTarget(navigationTargetForDocument(targetPath, size), { tabBehavior: 'replace-active' });
- replaceHashWithoutNavigation(hashFromDocName(targetPath));
- notifySidebarFileSelected();
- }
- function navigateToFolderWithPulse(folderPath: string) {
- const nextHash = hashFromFolderPath(folderPath);
- openTarget(
- { kind: 'folder', target: folderPath, folderPath },
- { tabBehavior: 'replace-active' },
- );
- replaceHashWithoutNavigation(nextHash);
- notifySidebarFileSelected();
- }
const [documents, setDocuments] = useState<FileEntry[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -1467,6 +1253,45 @@ export function FileTree({
const documentsRef = useRef(documents);
const pageMetaRef = useRef(pageMeta);
const pendingExactFileSelectionRef = useRef<string | null>(null);
+ // Single navigation path for tree-initiated opens: resolve the target per
+ // kind, open it in the active tab, sync the hash, and pulse the sidebar.
+ function navigateWithPulse(
+ target:
+ | { kind: 'doc'; docName: string; size?: number; registerPage?: boolean }
+ | { kind: 'folder'; folderPath: string }
+ | { kind: 'asset'; assetPath: string; entries?: readonly FileEntry[] },
+ ) {
+ if (target.kind === 'doc') {
+ if (target.registerPage) addPage(target.docName);
+ openTarget(navigationTargetForDocument(target.docName, target.size), {
+ tabBehavior: 'replace-active',
+ });
+ replaceHashWithoutNavigation(hashFromDocName(target.docName));
+ } else if (target.kind === 'folder') {
+ openTarget(
+ { kind: 'folder', target: target.folderPath, folderPath: target.folderPath },
+ { tabBehavior: 'replace-active' },
+ );
+ replaceHashWithoutNavigation(hashFromFolderPath(target.folderPath));
+ } else {
+ const currentEntries = target.entries ?? documentsRef.current;
+ const entry = currentEntries.find(
+ (item): item is Extract<FileEntry, { kind: 'asset' }> =>
+ isAssetEntry(item) && item.path === target.assetPath,
+ );
+ openTarget(
+ {
+ kind: 'asset',
+ target: target.assetPath,
+ assetPath: target.assetPath,
+ mediaKind: entry?.mediaKind ?? null,
+ },
+ { tabBehavior: 'replace-active' },
+ );
+ replaceHashWithoutNavigation(hashFromAssetPath(target.assetPath));
+ }
+ notifySidebarFileSelected();
+ }
function activateTreePath(treePath: string, entries: readonly FileEntry[] = documents) {
const action = resolveFileTreeSelectionAction(treePath, entries);
if (action.kind === 'none') {
@@ -1491,7 +1316,7 @@ export function FileTree({
return;
}
if (action.kind === 'folder') {
- navigateToFolderWithPulse(action.path);
+ navigateWithPulse({ kind: 'folder', folderPath: action.path });
return;
}
const docEntry = entries.find(
@@ -1513,36 +1338,23 @@ export function FileTree({
return;
}
if (okTarget?.kind === 'doc') {
- navigateToWithPulse(okTarget.docName);
+ navigateWithPulse({ kind: 'doc', docName: okTarget.docName });
return;
}
- navigateToWithPulse(action.path, docEntry?.size, {
+ navigateWithPulse({
+ kind: 'doc',
+ docName: action.path,
+ size: docEntry?.size,
registerPage: hasSupportedDocumentExtension(action.path),
});
}
- function navigateToAssetWithPulse(assetPath: string, entries?: readonly FileEntry[]) {
- const currentEntries = entries ?? documentsRef.current;
- const entry = currentEntries.find(
- (item): item is Extract<FileEntry, { kind: 'asset' }> =>
- isAssetEntry(item) && item.path === assetPath,
- );
- openTarget(
- {
- kind: 'asset',
- target: assetPath,
- assetPath,
- mediaKind: entry?.mediaKind ?? null,
- },
- { tabBehavior: 'replace-active' },
- );
- replaceHashWithoutNavigation(hashFromAssetPath(assetPath));
- notifySidebarFileSelected();
- }
const activeDocNameRef = useRef(activeDocName);
const assetTreePaths = new Set(
documents.filter(isAssetEntry).map((entry) => fileEntryToTreePath(entry)),
);
const assetTreePathsRef = useRef(assetTreePaths);
+ const rowDecorationIndex = buildRowDecorationIndex(documents);
+ const rowDecorationIndexRef = useRef(rowDecorationIndex);
const activeAncestorTreePathsRef = useRef<string[]>([]);
const pendingCreateRef = useRef<PendingCreate | null>(null);
const cleanupPendingCreateRef = useRef<
@@ -1854,10 +1666,7 @@ export function FileTree({
onSelectionChange: (selectedPaths) => handleSelectionChangeRef.current(selectedPaths),
renderRowDecoration: ({ item }) => {
if (item.kind === 'file') {
- const doc = documentsRef.current.find(
- (entry): entry is DocumentEntry =>
- isDocumentEntry(entry) && docNameToTreePath(entry.docName, entry.docExt) === item.path,
- );
+ const doc = rowDecorationIndexRef.current.docsByTreePath.get(item.path);
if (doc?.isSymlink) {
const targetPath = doc.targetPath;
return {
@@ -1876,10 +1685,8 @@ export function FileTree({
// Symlinked directories carry isSymlink on their FolderEntry. Badge the
// alias folder itself (Finder-style — its contents are not separately
// marked, since they live behind the one symlink).
- const folder = documentsRef.current.find(
- (entry): entry is FolderEntry =>
- isFolderEntry(entry) &&
- folderPathToTreeDirectoryPath(entry.path) === folderPathToTreeDirectoryPath(item.path),
+ const folder = rowDecorationIndexRef.current.foldersByTreeDirectoryPath.get(
+ folderPathToTreeDirectoryPath(item.path),
);
if (folder?.isSymlink) {
const targetPath = folder.targetPath;
@@ -2162,9 +1969,9 @@ export function FileTree({
if (success.path !== target.path) {
if (success.kind === 'folder') {
- navigateToFolderWithPulse(success.path);
+ navigateWithPulse({ kind: 'folder', folderPath: success.path });
} else {
- navigateToWithPulse(success.path);
+ navigateWithPulse({ kind: 'doc', docName: success.path });
}
}
toast.success(success.kind === 'folder' ? t`Folder duplicated` : t`File duplicated`, {
@@ -2830,15 +2637,19 @@ export function FileTree({
nextActiveFolderPath &&
nextActiveFolderPath !== currentActiveFolderPath
) {
- navigateToFolderWithPulse(nextActiveFolderPath);
+ navigateWithPulse({ kind: 'folder', folderPath: nextActiveFolderPath });
} else if (nextActiveDocName && nextActiveDocName !== currentActiveDocName) {
- navigateToWithPulse(nextActiveDocName);
+ navigateWithPulse({ kind: 'doc', docName: nextActiveDocName });
focusEditorAfterRename(nextActiveDocName);
} else if (
nextActiveAssetPath &&
(activeDocToAssetPath || nextActiveAssetPath !== currentActiveAssetPath)
) {
- navigateToAssetWithPulse(nextActiveAssetPath, nextDocumentsForRename ?? documentsRef.current);
+ navigateWithPulse({
+ kind: 'asset',
+ assetPath: nextActiveAssetPath,
+ entries: nextDocumentsForRename ?? documentsRef.current,
+ });
}
emitDocumentsChanged(['files', 'backlinks', 'graph']);
};
@@ -3279,7 +3090,7 @@ export function FileTree({
return next;
});
emitDocumentsChanged(['files', 'backlinks', 'graph']);
- navigateToWithPulse(docName);
+ navigateWithPulse({ kind: 'doc', docName });
} else {
const folderPath = treeDirectoryPathToFolderPath(placeholder.addPath);
const res = await fetch('/api/create-folder', {
@@ -3319,7 +3130,7 @@ export function FileTree({
return next;
});
emitDocumentsChanged(['files']);
- navigateToFolderWithPulse(createdPath);
+ navigateWithPulse({ kind: 'folder', folderPath: createdPath });
}
let disposed = false;
@@ -3403,6 +3214,7 @@ export function FileTree({
useLayoutEffect(() => {
documentsRef.current = documents;
+ rowDecorationIndexRef.current = rowDecorationIndex;
pageMetaRef.current = pageMeta;
activeDocNameRef.current = activeDocName;
activeTargetRef.current = activeTarget;
@@ -4350,7 +4162,7 @@ export function FileTree({
event.preventDefault();
event.stopPropagation();
if (folderItem && !folderItem.isExpanded()) folderItem.expand();
- queueMicrotask(() => navigateToFolderWithPulse(folderPath));
+ queueMicrotask(() => navigateWithPulse({ kind: 'folder', folderPath }));
return;
}
if (model.getSelectedPaths().length !== 1) return;
@@ -4358,7 +4170,7 @@ export function FileTree({
event.preventDefault();
event.stopPropagation();
if (folderItem && !folderItem.isExpanded()) folderItem.expand();
- queueMicrotask(() => navigateToFolderWithPulse(folderPath));
+ queueMicrotask(() => navigateWithPulse({ kind: 'folder', folderPath }));
return;
}
@@ -4372,7 +4184,7 @@ export function FileTree({
pendingExactFileSelectionRef.current = path;
// Let handleSelectionChange's microtask consume the exact file selection
// before navigation commits the extension-qualified URL.
- setTimeout(() => navigateToWithPulse(path, undefined, { registerPage: true }), 0);
+ setTimeout(() => navigateWithPulse({ kind: 'doc', docName: path, registerPage: true }), 0);
return;
}
queueMicrotask(() => activateTreePath(path));
diff --git a/packages/app/src/components/file-tree-icon-sprite.ts b/packages/app/src/components/file-tree-icon-sprite.ts
new file mode 100644
index 000000000..d3f72644d
--- /dev/null
+++ b/packages/app/src/components/file-tree-icon-sprite.ts
@@ -0,0 +1,50 @@
+/**
+ * Inline SVG sprite sheet fed to the @pierre/trees `icons.spriteSheet` option:
+ * row-decoration glyphs (symlink, agent file) plus the custom Markdown file
+ * icon. Lucide icons are imported as raw `__iconNode` data (not React
+ * components) so they can be serialized into `<symbol>` markup once at module
+ * load.
+ */
+
+import { __iconNode as botIcon } from 'lucide-react/dist/esm/icons/bot';
+import { __iconNode as link2Icon } from 'lucide-react/dist/esm/icons/link-2';
+import {
+ MARKDOWN_FILE_ICON_PATH_D,
+ MARKDOWN_FILE_ICON_VIEWBOX,
+} from '@/components/file-entry-icon';
+
+export const LINK_DECORATION_ICON_ID = 'ok-file-tree-link-decoration';
+export const AGENT_DECORATION_ICON_ID = 'ok-file-tree-agent-decoration';
+export const MARKDOWN_FILE_ICON_ID = 'ok-file-tree-markdown';
+// Custom Markdown file glyph (document with an "MD" label) overriding Pierre's
+// built-in `complete`-set markdown glyph. `fill="currentColor"` lets
+// `--trees-file-icon-color-markdown` (set in createFileTreeStyle, see
+// file-tree-density.ts) color it.
+const MARKDOWN_FILE_ICON_SYMBOL = `<symbol id="${MARKDOWN_FILE_ICON_ID}" viewBox="${MARKDOWN_FILE_ICON_VIEWBOX}" fill="currentColor"><path d="${MARKDOWN_FILE_ICON_PATH_D}"/></symbol>`;
+
+type IconNode = [string, Record<string, string>][];
+
+function iconNodeToSvg(iconNode: IconNode): string {
+ return (
+ iconNode
+ // remove React key
+ .map(([tag, { key: _, ...attrs }]) => {
+ const attrString = Object.entries(attrs)
+ .map(([k, v]) => `${k}="${v}"`)
+ .join(' ');
+ return `<${tag} ${attrString} />`;
+ })
+ .join('')
+ );
+}
+
+function createLucideSpriteSymbol(id: string, iconNode: IconNode): string {
+ const symbolContent = iconNodeToSvg(iconNode);
+ return `<symbol id="${id}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${symbolContent}</symbol>`;
+}
+
+export const FILE_TREE_DECORATION_SPRITE_SHEET = `<svg data-icon-sprite aria-hidden="true" width="0" height="0">
+ ${createLucideSpriteSymbol(LINK_DECORATION_ICON_ID, link2Icon)}
+ ${createLucideSpriteSymbol(AGENT_DECORATION_ICON_ID, botIcon)}
+ ${MARKDOWN_FILE_ICON_SYMBOL}
+</svg>`;
diff --git a/packages/app/src/components/file-tree-path-helpers.test.ts b/packages/app/src/components/file-tree-path-helpers.test.ts
new file mode 100644
index 000000000..65714cab0
--- /dev/null
+++ b/packages/app/src/components/file-tree-path-helpers.test.ts
@@ -0,0 +1,189 @@
+import { describe, expect, test } from 'bun:test';
+import type { FileTreeTarget } from './file-tree-operations';
+import {
+ alternateMarkdownTreePath,
+ buildRowDecorationIndex,
+ deleteTargetCoversPendingCreate,
+ hasSameStemMarkdownSiblingTreePath,
+ isAgentTreePath,
+ markdownTreeExtension,
+ parseAlreadyExistsRenamePath,
+ selectedTreePathsToDeleteTargets,
+} from './file-tree-path-helpers';
+import type { FileEntry } from './file-tree-utils';
+
+const doc = (docName: string, docExt?: string): FileEntry => ({
+ kind: 'document',
+ docName,
+ docExt,
+ size: 1,
+ modified: '2026-04-13T00:00:00.000Z',
+});
+
+const folder = (path: string): FileEntry => ({
+ kind: 'folder',
+ path,
+ size: 0,
+ modified: '2026-04-13T00:00:00.000Z',
+});
+
+const asset = (path: string): FileEntry => ({
+ kind: 'asset',
+ path,
+ assetExt: '.png',
+ mediaKind: 'image',
+ size: 1,
+ modified: '2026-04-13T00:00:00.000Z',
+});
+
+describe('file-tree-path-helpers', () => {
+ test('parseAlreadyExistsRenamePath extracts the quoted path', () => {
+ expect(parseAlreadyExistsRenamePath('"docs/notes.md" already exists.')).toBe('docs/notes.md');
+ expect(parseAlreadyExistsRenamePath('some other error')).toBeNull();
+ });
+
+ test('markdownTreeExtension returns the matched extension or null', () => {
+ expect(markdownTreeExtension('docs/notes.md')).toBe('.md');
+ expect(markdownTreeExtension('docs/notes.MDX')).toBe('.MDX');
+ expect(markdownTreeExtension('docs/image.png')).toBeNull();
+ });
+
+ test('isAgentTreePath flags agent/skill filenames case-insensitively', () => {
+ expect(isAgentTreePath('AGENTS.md')).toBe(true);
+ expect(isAgentTreePath('nested/claude.md')).toBe(true);
+ expect(isAgentTreePath('skill')).toBe(true);
+ expect(isAgentTreePath('docs/notes.md')).toBe(false);
+ });
+
+ test('alternateMarkdownTreePath swaps .md <-> .mdx and preserves the stem', () => {
+ expect(alternateMarkdownTreePath('docs/notes.md')).toBe('docs/notes.mdx');
+ expect(alternateMarkdownTreePath('docs/notes.mdx')).toBe('docs/notes.md');
+ expect(alternateMarkdownTreePath('docs/image.png')).toBeNull();
+ });
+
+ test('hasSameStemMarkdownSiblingTreePath detects the alternate-extension sibling', () => {
+ const paths = ['docs/notes.mdx', 'docs/other.md'];
+ expect(hasSameStemMarkdownSiblingTreePath('docs/notes.md', paths)).toBe(true);
+ expect(hasSameStemMarkdownSiblingTreePath('docs/other.md', paths)).toBe(false);
+ });
+
+ describe('selectedTreePathsToDeleteTargets', () => {
+ const documents: FileEntry[] = [doc('docs/notes'), folder('docs'), doc('docs/nested/page')];
+
+ test('deduplicates repeated selections', () => {
+ const targets = selectedTreePathsToDeleteTargets(
+ ['docs/notes.md', 'docs/notes.md'],
+ documents,
+ );
+ expect(targets).toHaveLength(1);
+ expect(targets[0].path).toBe('docs/notes');
+ });
+
+ test('excludes read-only .ok rows', () => {
+ const targets = selectedTreePathsToDeleteTargets(
+ ['docs/notes.md', 'docs/.ok/templates/trip.md'],
+ documents,
+ );
+ expect(targets.map((t) => t.path)).toEqual(['docs/notes']);
+ });
+
+ test('drops paths already covered by a selected ancestor folder', () => {
+ const targets = selectedTreePathsToDeleteTargets(['docs/', 'docs/notes.md'], documents);
+ // The folder subsumes the file inside it — only the folder survives.
+ expect(targets).toHaveLength(1);
+ expect(targets[0].kind).toBe('folder');
+ expect(targets[0].path).toBe('docs');
+ });
+ });
+
+ describe('deleteTargetCoversPendingCreate', () => {
+ const fileTarget = (path: string): FileTreeTarget => ({ kind: 'file', name: path, path });
+ const folderTarget = (path: string): FileTreeTarget => ({ kind: 'folder', name: path, path });
+ const assetTarget = (path: string): FileTreeTarget => ({ kind: 'asset', name: path, path });
+
+ test('file target covers a pending file at the same path only', () => {
+ expect(
+ deleteTargetCoversPendingCreate(fileTarget('docs/new'), {
+ kind: 'file',
+ createdPath: 'docs/new',
+ }),
+ ).toBe(true);
+ expect(
+ deleteTargetCoversPendingCreate(fileTarget('docs/new'), {
+ kind: 'file',
+ createdPath: 'docs/other',
+ }),
+ ).toBe(false);
+ // A file target never covers a pending folder.
+ expect(
+ deleteTargetCoversPendingCreate(fileTarget('docs/new'), {
+ kind: 'folder',
+ createdPath: 'docs/new',
+ }),
+ ).toBe(false);
+ });
+
+ test('asset target never covers a pending create', () => {
+ expect(
+ deleteTargetCoversPendingCreate(assetTarget('docs/img.png'), {
+ kind: 'file',
+ createdPath: 'docs/img.png',
+ }),
+ ).toBe(false);
+ });
+
+ test('folder target covers a pending create at or inside the folder', () => {
+ expect(
+ deleteTargetCoversPendingCreate(folderTarget('docs'), {
+ kind: 'file',
+ createdPath: 'docs/new',
+ }),
+ ).toBe(true);
+ expect(
+ deleteTargetCoversPendingCreate(folderTarget('docs'), {
+ kind: 'folder',
+ createdPath: 'docs',
+ }),
+ ).toBe(true);
+ // A sibling folder that only shares a name prefix is not inside it.
+ expect(
+ deleteTargetCoversPendingCreate(folderTarget('docs'), {
+ kind: 'folder',
+ createdPath: 'docs-archive/new',
+ }),
+ ).toBe(false);
+ });
+ });
+
+ describe('buildRowDecorationIndex', () => {
+ test('keys documents by tree path and folders by directory path; skips assets', () => {
+ const index = buildRowDecorationIndex([
+ doc('docs/notes', '.md'),
+ doc('README'),
+ folder('docs/empty'),
+ asset('docs/image.png'),
+ ]);
+
+ expect(index.docsByTreePath.get('docs/notes.md')?.kind).toBe('document');
+ expect(index.docsByTreePath.get('README.md')?.kind).toBe('document');
+ expect(index.foldersByTreeDirectoryPath.get('docs/empty/')?.kind).toBe('folder');
+ // Assets are not indexed by either map.
+ expect(index.docsByTreePath.has('docs/image.png')).toBe(false);
+ expect(index.foldersByTreeDirectoryPath.has('docs/image.png')).toBe(false);
+ });
+
+ test('first entry wins on document key collision, matching Array.find', () => {
+ const first = doc('dup', '.md');
+ const second = doc('dup', '.md');
+ const index = buildRowDecorationIndex([first, second]);
+ expect(index.docsByTreePath.get('dup.md')).toBe(first);
+ });
+
+ test('first entry wins on folder key collision, matching Array.find', () => {
+ const first = folder('dup');
+ const second = folder('dup');
+ const index = buildRowDecorationIndex([first, second]);
+ expect(index.foldersByTreeDirectoryPath.get('dup/')).toBe(first);
+ });
+ });
+});
diff --git a/packages/app/src/components/file-tree-path-helpers.ts b/packages/app/src/components/file-tree-path-helpers.ts
new file mode 100644
index 000000000..560e4f985
--- /dev/null
+++ b/packages/app/src/components/file-tree-path-helpers.ts
@@ -0,0 +1,239 @@
+/**
+ * Pure tree-path helpers for the file sidebar: keyboard/selection target
+ * resolution, delete-target planning, markdown-sibling checks, and the
+ * row-decoration lookup index. Everything here is a pure function of its
+ * inputs — no React, no DOM mutation, no network — except
+ * `isEditableKeyboardTarget`, which performs a DOM read.
+ */
+
+import type { FileTree as PierreFileTreeModel } from '@pierre/trees';
+import {
+ docNameToTreePath,
+ folderPathToTreeDirectoryPath,
+ treeDirectoryPathToFolderPath,
+ treeItemToTarget,
+} from '@/components/file-tree-adapter';
+import type { FileTreeTarget } from '@/components/file-tree-operations';
+import {
+ type DocumentEntry,
+ type FileEntry,
+ type FolderEntry,
+ hasOkPathSegment,
+ isAssetEntry,
+ isDocumentEntry,
+ isFolderEntry,
+} from '@/components/file-tree-utils';
+
+const MARKDOWN_TREE_EXTENSION_PATTERN = /\.(md|mdx)$/i;
+
+export function parseAlreadyExistsRenamePath(message: string): string | null {
+ const match = message.match(/^"(.+)" already exists\.$/);
+ return match ? match[1] : null;
+}
+
+export function markdownTreeExtension(path: string): string | null {
+ const match = path.match(MARKDOWN_TREE_EXTENSION_PATTERN);
+ return match ? match[0] : null;
+}
+
+const AGENT_FILE_NAMES = new Set(['agents', 'agent', 'claude', 'skill']);
+
+export function isAgentTreePath(treePath: string): boolean {
+ const name = treePath.split('/').pop()?.replace(/\.md$/i, '').toLowerCase();
+ return !!name && AGENT_FILE_NAMES.has(name);
+}
+
+function treePathToTarget(treePath: string, documents: readonly FileEntry[]): FileTreeTarget {
+ return treeItemToTarget(
+ {
+ kind: treePath.endsWith('/') ? 'directory' : 'file',
+ name: treePath,
+ path: treePath,
+ },
+ documents,
+ );
+}
+
+export function alternateMarkdownTreePath(treePath: string): string | null {
+ const match = treePath.match(/\.(md|mdx)$/i);
+ if (!match) return null;
+ const ext = match[0].toLowerCase();
+ const alternateExt = ext === '.md' ? '.mdx' : '.md';
+ return `${treePath.slice(0, -match[0].length)}${alternateExt}`;
+}
+
+export function hasSameStemMarkdownSiblingTreePath(
+ treePath: string,
+ treePaths: readonly string[],
+): boolean {
+ const alternate = alternateMarkdownTreePath(treePath);
+ if (!alternate) return false;
+ return treePaths.includes(alternate);
+}
+
+function isTreePathInsideFolder(treePath: string, folderTreePath: string): boolean {
+ return treePath !== folderTreePath && treePath.startsWith(folderTreePath);
+}
+
+export function selectedTreePathsToDeleteTargets(
+ selectedTreePaths: readonly string[],
+ documents: readonly FileEntry[],
+): FileTreeTarget[] {
+ // Revealed `.ok` rows are read-only OK-managed state — they never become
+ // delete targets, even when swept into a multi-selection beside deletable
+ // rows (this also keeps the confirm dialog's item count honest).
+ const uniqueDeletablePaths = [...new Set(selectedTreePaths)].filter(
+ (treePath) => !hasOkPathSegment(treePath),
+ );
+ const selectedFolderPaths = uniqueDeletablePaths.filter((treePath) => treePath.endsWith('/'));
+ return uniqueDeletablePaths
+ .filter(
+ (treePath) =>
+ !selectedFolderPaths.some((folderPath) => isTreePathInsideFolder(treePath, folderPath)),
+ )
+ .map((treePath) => treePathToTarget(treePath, documents));
+}
+
+function normalizeTreePathFromModel(model: PierreFileTreeModel, treePath: string): string {
+ const selectedItem =
+ model.getItem(treePath) ?? model.getItem(folderPathToTreeDirectoryPath(treePath));
+ return selectedItem?.isDirectory()
+ ? folderPathToTreeDirectoryPath(treeDirectoryPathToFolderPath(selectedItem.getPath()))
+ : treePath;
+}
+
+function focusedOrFirstSelectedTreePath(model: PierreFileTreeModel): string | null {
+ const selectedPath = model.getFocusedPath() ?? model.getSelectedPaths()[0] ?? null;
+ return selectedPath ? normalizeTreePathFromModel(model, selectedPath) : null;
+}
+
+export function resolveDuplicableKeyboardTarget(
+ model: PierreFileTreeModel,
+ documents: readonly FileEntry[],
+ assetTreePaths: ReadonlySet<string>,
+): FileTreeTarget | null {
+ const selectedPath = focusedOrFirstSelectedTreePath(model);
+ // Revealed `.ok` rows are read-only OK-managed state — no keyboard
+ // copy/paste/duplicate, matching their menu's suppressed affordances.
+ if (!selectedPath || assetTreePaths.has(selectedPath) || hasOkPathSegment(selectedPath)) {
+ return null;
+ }
+ return treePathToTarget(selectedPath, documents);
+}
+
+export function resolveKeyboardDeleteTargets(
+ model: PierreFileTreeModel,
+ documents: readonly FileEntry[],
+): FileTreeTarget[] {
+ const selectedPaths = model.getSelectedPaths();
+ const focusedPath = focusedOrFirstSelectedTreePath(model);
+ const paths =
+ selectedPaths.length > 0
+ ? selectedPaths.map((treePath) => normalizeTreePathFromModel(model, treePath))
+ : focusedPath
+ ? [focusedPath]
+ : [];
+ return selectedTreePathsToDeleteTargets(paths, documents);
+}
+
+function isPathAtOrInsideFolder(path: string, folderPath: string): boolean {
+ return path === folderPath || path.startsWith(`${folderPath}/`);
+}
+
+export function isEditableKeyboardTarget(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ const tagName = target.tagName;
+ return (
+ tagName === 'INPUT' ||
+ tagName === 'TEXTAREA' ||
+ tagName === 'SELECT' ||
+ target.isContentEditable ||
+ target.closest('[contenteditable="true"]') !== null
+ );
+}
+
+export function collectTabsToCloseForDelete(
+ targets: readonly FileTreeTarget[],
+ documents: readonly FileEntry[],
+ folderTreePaths: readonly string[],
+): { docNames: Set<string>; folderPaths: Set<string>; assetPaths: Set<string> } {
+ const docNames = new Set<string>();
+ const folderPaths = new Set<string>();
+ const assetPaths = new Set<string>();
+
+ for (const target of targets) {
+ if (target.kind === 'file') {
+ docNames.add(target.path);
+ continue;
+ }
+ if (target.kind === 'asset') {
+ assetPaths.add(target.path);
+ continue;
+ }
+
+ folderPaths.add(target.path);
+ for (const entry of documents) {
+ if (isDocumentEntry(entry) && entry.docName.startsWith(`${target.path}/`)) {
+ docNames.add(entry.docName);
+ } else if (isAssetEntry(entry) && entry.path.startsWith(`${target.path}/`)) {
+ assetPaths.add(entry.path);
+ }
+ }
+ for (const treePath of folderTreePaths) {
+ const folderPath = treeDirectoryPathToFolderPath(treePath);
+ if (isPathAtOrInsideFolder(folderPath, target.path)) {
+ folderPaths.add(folderPath);
+ }
+ }
+ }
+
+ return { docNames, folderPaths, assetPaths };
+}
+
+/**
+ * The slice of FileTree's pending-create state this module needs — kept
+ * structural so the component's richer lifecycle record stays local to it.
+ */
+export interface PendingCreateTarget {
+ kind: 'file' | 'folder';
+ createdPath: string;
+}
+
+export function deleteTargetCoversPendingCreate(
+ target: FileTreeTarget,
+ pending: PendingCreateTarget,
+): boolean {
+ if (target.kind === 'file') {
+ return pending.kind === 'file' && target.path === pending.createdPath;
+ }
+ if (target.kind === 'asset') return false;
+ return isPathAtOrInsideFolder(pending.createdPath, target.path);
+}
+
+export interface RowDecorationIndex {
+ docsByTreePath: ReadonlyMap<string, DocumentEntry>;
+ foldersByTreeDirectoryPath: ReadonlyMap<string, FolderEntry>;
+}
+
+/**
+ * O(1) lookup index for `renderRowDecoration`, which the tree invokes per
+ * visible row on every redraw — a linear scan of the document list there is
+ * O(rows × entries). First entry wins on key collision, matching the
+ * front-to-back `Array.find` this replaces.
+ */
+export function buildRowDecorationIndex(entries: readonly FileEntry[]): RowDecorationIndex {
+ const docsByTreePath = new Map<string, DocumentEntry>();
+ const foldersByTreeDirectoryPath = new Map<string, FolderEntry>();
+ for (const entry of entries) {
+ if (isDocumentEntry(entry)) {
+ const treePath = docNameToTreePath(entry.docName, entry.docExt);
+ if (!docsByTreePath.has(treePath)) docsByTreePath.set(treePath, entry);
+ } else if (isFolderEntry(entry)) {
+ const directoryPath = folderPathToTreeDirectoryPath(entry.path);
+ if (!foldersByTreeDirectoryPath.has(directoryPath)) {
+ foldersByTreeDirectoryPath.set(directoryPath, entry);
+ }
+ }
+ }
+ return { docsByTreePath, foldersByTreeDirectoryPath };
+}
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index c014b1413..8f9d95287 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,3 +1,4 @@
+
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 005627195..8bfdb40cd 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,3 +1,4 @@
+
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8890f6739..c18c086d5 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 9d9c244b0..463e89595 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,3 +1,4 @@
+
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 3ab9cc6ef..3c927eb47 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -38,6 +38,7 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: string
return parts.join('\n');
}
+
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 4b8890476..3f0880aa5 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,3 +1,4 @@
+
const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;
const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 754dc5cc2..0be5203e4 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
+
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
+
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
+
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index af20de1e2..dca644141 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,3 +1,4 @@
+
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index 83d47404a..a363dfd54 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,3 +1,4 @@
+
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 193e286b0..47f0d07e4 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index ece5c02a1..b6299a948 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,3 +1,4 @@
+
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index 54774764a..acd398aa6 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index c7518d614..fb5ac8e8a 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,3 +1,4 @@
+
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 00f5771ee..6931623c7 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
+
interface GfmExample {
section: string;
markdown: string;
@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
+
interface MdxCrashEntry {
id: string;
input: string;
@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
+
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
+
export interface NgPinnedCase {
id: string;
name: string;
@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
+
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..daa3ef82b 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
+
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
+
const WORDS = [
'lorem',
'ipsum',
@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
+
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
+
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 420dc0fe5..32c055c5b 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,6 +7,7 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
+
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 2653473da..283913255 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,3 +1,4 @@
+
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index f55912407..6319f264f 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 78fdfeb02..2f082e6d0 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,3 +1,4 @@
+
import type { Root as HastRoot } from 'hast';
import type { Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -75,7 +76,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified().use(rehypeParse, { fragment: true });
+ const processor = unified()
+ .use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 706fa9afb..994eb6917 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 8b36807fd..fc30bda02 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -196,6 +197,7 @@ export class MarkdownManager {
}
}
+
const registry = createRegistry();
function destructureAttrs(
@@ -244,6 +246,7 @@ function destructureAttrs(
return result;
}
+
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -263,6 +266,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
+
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -331,6 +335,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
+
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -577,6 +582,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -657,6 +663,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -935,6 +942,7 @@ function buildMdastToPmHandlers(
};
}
+
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1060,6 +1068,7 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
+
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index e78a1381d..207cd95c2 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -29,6 +29,7 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
+
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index d48eea5e4..a51f2ffb0 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
+
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index d1a5ab4dc..3baacdeb7 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,3 +1,4 @@
+
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 1cd40ef3a..65a1b564c 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,3 +1,4 @@
+
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';
@@ -8,6 +9,7 @@ import {
type MarkdownlintSlice,
} from './types.ts';
+
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 617f6e5b9..3651bd7eb 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,3 +1,4 @@
+
export const LINT_PLUGIN_IDS = ['markdownlint'] as const;
export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];
@@ -41,6 +42,7 @@ export interface MarkdownlintSlice {
rules: Record<string, MarkdownlintRuleSetting>;
}
+
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index a5b511f25..bd79424c7 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index 679c72ef7..f84967798 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 8ce2b2492..df788a80d 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 1a897fca8..17ed2b829 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 9864b3b60..7e4a9a48b 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,6 +168,7 @@ export function parseRecursive(
}
}
+
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
+
interface Region {
start: number;
end: number;
@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
+
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
+
interface SourceBlock {
src: string;
start: number;
@@ -452,6 +456,7 @@ function tryPerBlockFallback(
};
}
+
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index e6ab4fd57..43d420187 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,3 +1,4 @@
+
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 7f2d5adca..e9e507469 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 5a5e4c42a..f8f5e8530 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,3 +1,4 @@
+
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 0f399d34c..e5b4c9eba 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- } else if (first === '[') {
+ }
+ else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index db10fa54b..ca225ce9b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 34068d103..3a2524a9a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 93151d43b..2279a0189 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index 188f02d83..a0f467c42 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4ba2c3418..4e8542a21 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index 1a74b1272..a3c96b24a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index de35e7b79..e95cf43d6 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index b4be1b2ea..ffdb4d5b5 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index 3c8d88b7c..e2a96d1a7 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index cf2c9da8e..0389575ac 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,3 +1,4 @@
+
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 46cc6a074..542204403 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,3 +1,4 @@
+
import type { Node as PmNode } from '@tiptap/pm/model';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { PropDef, SerializeContext } from '../registry/types.ts';
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index be97d4d62..fe73659e6 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 8f4e9a41c..7bce04302 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index cd245c38c..c5bfd2386 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,3 +1,4 @@
+
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index d578476a7..ac9f5239b 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,3 +1,4 @@
+
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index 6dad26200..afd9936fe 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {
}
}
+
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {
};
}
+
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
+
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {