@janga/norna 0.7.22 → 0.7.24

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.
Files changed (88) hide show
  1. package/README.md +14 -18
  2. package/astro.config.mjs +15 -0
  3. package/bin/norna-cli.mjs +8 -2
  4. package/package.json +28 -3
  5. package/schemas/category.schema.json +2 -2
  6. package/schemas/config.schema.json +52 -24
  7. package/schemas/content-frontmatter.schema.json +25 -5
  8. package/schemas/page-theme.schema.json +53 -25
  9. package/schemas/sitewide-content.schema.json +19 -18
  10. package/schemas/theme.schema.json +385 -252
  11. package/scripts/build-site.mjs +1 -0
  12. package/scripts/check-config.mjs +36 -5
  13. package/scripts/deploy-site.mjs +0 -1
  14. package/scripts/dev-local.mjs +175 -112
  15. package/scripts/generate-search-index.mjs +57 -0
  16. package/scripts/init-site.mjs +1 -0
  17. package/scripts/lib/code-fence-metadata.mjs +223 -0
  18. package/scripts/lib/content-sync-apply.mjs +34 -0
  19. package/scripts/lib/content-sync-plan.mjs +179 -0
  20. package/scripts/lib/edit-source-link.mjs +49 -0
  21. package/scripts/lib/editor-language-service.mjs +160 -12
  22. package/scripts/lib/heading-ids.mjs +1 -1
  23. package/scripts/lib/image-presentation.mjs +6 -0
  24. package/scripts/lib/markdown-links.mjs +182 -0
  25. package/scripts/lib/navigation-model.mjs +44 -12
  26. package/scripts/lib/navigation-review.mjs +396 -0
  27. package/scripts/lib/norna-markdown-blocks.mjs +74 -26
  28. package/scripts/lib/norna-markdown-render-plugin.mjs +64 -1
  29. package/scripts/lib/page-aliases.mjs +184 -0
  30. package/scripts/lib/page-markdown.mjs +88 -7
  31. package/scripts/lib/page-move-plan.mjs +659 -0
  32. package/scripts/lib/presentation-palette-metadata.mjs +1 -1
  33. package/scripts/lib/presentation.mjs +10 -37
  34. package/scripts/lib/project-config.mjs +146 -19
  35. package/scripts/lib/public-asset-conventions.mjs +36 -2
  36. package/scripts/lib/schema-definitions.mjs +43 -15
  37. package/scripts/lib/schema-editor-metadata.mjs +60 -32
  38. package/scripts/lib/schema-value-definitions.mjs +6 -2
  39. package/scripts/lib/semantic-callouts.mjs +128 -0
  40. package/scripts/lib/site-content.mjs +28 -5
  41. package/scripts/lib/site-link-graph.mjs +357 -0
  42. package/scripts/lib/site-navigation-tree.mjs +85 -0
  43. package/scripts/lib/site-page-urls.mjs +10 -0
  44. package/scripts/lib/sitemap.mjs +34 -0
  45. package/scripts/lib/social-image-assets.mjs +30 -0
  46. package/scripts/lib/theme-presets.mjs +53 -25
  47. package/scripts/lib/theme-profiles.mjs +6 -8
  48. package/scripts/lib/yaml-config.mjs +6 -2
  49. package/scripts/move-site-page.mjs +256 -0
  50. package/scripts/review-navigation.mjs +32 -0
  51. package/scripts/sync-content-sections.mjs +182 -216
  52. package/scripts/sync-site-public.mjs +43 -3
  53. package/src/components/CodeBlockCopyScript.astro +97 -0
  54. package/src/components/DisplaySettings.astro +4 -4
  55. package/src/components/EditSourceLink.astro +17 -0
  56. package/src/components/ImageCarousel.astro +6 -3
  57. package/src/components/NavigationPageTree.astro +81 -86
  58. package/src/components/NavigationTreeControls.astro +77 -0
  59. package/src/components/PageAliasRedirect.astro +49 -0
  60. package/src/components/PageContentsNavigation.astro +21 -0
  61. package/src/components/PageList.astro +33 -0
  62. package/src/components/PageSequenceNavigation.astro +37 -0
  63. package/src/components/SearchPage.astro +151 -0
  64. package/src/components/SectionNavigationScript.astro +62 -6
  65. package/src/components/SiteNavigation.astro +50 -11
  66. package/src/components/SitePage.astro +113 -20
  67. package/src/components/SiteSection.astro +16 -3
  68. package/src/components/SiteTreeNavigation.astro +8 -2
  69. package/src/components/TreeNavigationScript.astro +207 -26
  70. package/src/content.config.ts +5 -2
  71. package/src/layouts/BaseLayout.astro +71 -10
  72. package/src/lib/readerPreferencesScript.mjs +2 -2
  73. package/src/lib/sectionContent.ts +32 -3
  74. package/src/lib/siteNavigation.ts +31 -52
  75. package/src/lib/sitePages.ts +3 -2
  76. package/src/lib/sitePublicAssets.ts +1 -0
  77. package/src/pages/404.astro +110 -0
  78. package/src/pages/[...slug].astro +45 -8
  79. package/src/styles/content.css +718 -0
  80. package/src/styles/foundations.css +284 -0
  81. package/src/styles/global.css +6 -2510
  82. package/src/styles/media.css +518 -0
  83. package/src/styles/navigation.css +526 -0
  84. package/src/styles/page-layout.css +786 -0
  85. package/src/styles/responsive.css +594 -0
  86. package/starters/basic/README.md +6 -19
  87. package/starters/basic/package.json +1 -0
  88. package/starters/basic/site/pages/000-home/content.md +13 -50
@@ -79,7 +79,7 @@ export const getMarkdownHeadings = async (source) => {
79
79
  ),
80
80
  }));
81
81
 
82
- return { headings, source: normalizedSource };
82
+ return { headings, source: normalizedSource, tree };
83
83
  };
84
84
 
85
85
  export const getHeadingIdentifierIssues = (headings) => {
@@ -0,0 +1,6 @@
1
+ export const imagePresentationNames = Object.freeze(['prose-aligned', 'centered-fit']);
2
+ export const defaultImagePresentation = 'prose-aligned';
3
+ export const defaultImageMaxAvailableHeightPercent = Object.freeze({
4
+ desktop: 74,
5
+ mobile: 68,
6
+ });
@@ -0,0 +1,182 @@
1
+ const getNodeRange = (node) => {
2
+ const start = node.position?.start.offset;
3
+ const end = node.position?.end.offset;
4
+ return Number.isInteger(start) && Number.isInteger(end)
5
+ ? { start, end }
6
+ : null;
7
+ };
8
+
9
+ const visitNodes = (node, visit) => {
10
+ if (!node || typeof node !== 'object') return;
11
+ visit(node);
12
+ if (!Array.isArray(node.children)) return;
13
+ for (const child of node.children) visitNodes(child, visit);
14
+ };
15
+
16
+ const scanDestination = (source, start, end) => {
17
+ let cursor = start;
18
+ while (cursor < end && /\s/.test(source[cursor] ?? '')) cursor += 1;
19
+
20
+ if (source[cursor] === '<') {
21
+ const targetStart = cursor + 1;
22
+ for (cursor = targetStart; cursor < end; cursor += 1) {
23
+ if (source[cursor] === '>' && source[cursor - 1] !== '\\') {
24
+ return { start: targetStart, end: cursor };
25
+ }
26
+ }
27
+ return null;
28
+ }
29
+
30
+ const targetStart = cursor;
31
+ let parenthesisDepth = 0;
32
+ let escaped = false;
33
+ for (; cursor < end; cursor += 1) {
34
+ const character = source[cursor] ?? '';
35
+ if (escaped) {
36
+ escaped = false;
37
+ continue;
38
+ }
39
+ if (character === '\\') {
40
+ escaped = true;
41
+ continue;
42
+ }
43
+ if (character === '(') {
44
+ parenthesisDepth += 1;
45
+ continue;
46
+ }
47
+ if (character === ')') {
48
+ if (parenthesisDepth === 0) break;
49
+ parenthesisDepth -= 1;
50
+ continue;
51
+ }
52
+ if (/\s/.test(character) && parenthesisDepth === 0) break;
53
+ }
54
+
55
+ return { start: targetStart, end: cursor };
56
+ };
57
+
58
+ const getInlineLinkTargetRange = (source, node) => {
59
+ const nodeRange = getNodeRange(node);
60
+ if (!nodeRange) return null;
61
+ const childEnd = Array.isArray(node.children)
62
+ ? Math.max(nodeRange.start, ...node.children.map((child) => child.position?.end.offset ?? nodeRange.start))
63
+ : nodeRange.start;
64
+ const delimiter = source.indexOf('](', childEnd);
65
+ if (delimiter < 0 || delimiter >= nodeRange.end) return null;
66
+ return scanDestination(source, delimiter + 2, nodeRange.end);
67
+ };
68
+
69
+ const getDefinitionTargetRange = (source, node) => {
70
+ const nodeRange = getNodeRange(node);
71
+ if (!nodeRange) return null;
72
+ const delimiter = source.indexOf(']:', nodeRange.start);
73
+ if (delimiter < 0 || delimiter >= nodeRange.end) return null;
74
+ return scanDestination(source, delimiter + 2, nodeRange.end);
75
+ };
76
+
77
+ const getSourceTarget = (source, range, fallback) => range
78
+ ? source.slice(range.start, range.end)
79
+ : fallback;
80
+
81
+ export const extractMarkdownLinks = ({ source, tree, lineOffset = 0 }) => {
82
+ const definitions = new Map();
83
+ visitNodes(tree, (node) => {
84
+ if (node.type !== 'definition') return;
85
+ definitions.set(node.identifier, node);
86
+ });
87
+
88
+ const links = [];
89
+ visitNodes(tree, (node) => {
90
+ if (node.type === 'link') {
91
+ const range = getNodeRange(node);
92
+ const targetRange = getInlineLinkTargetRange(source, node);
93
+ links.push({
94
+ kind: 'markdown-link',
95
+ column: node.position?.start.column ?? 1,
96
+ line: lineOffset + (node.position?.start.line ?? 1),
97
+ range,
98
+ target: node.url ?? '',
99
+ targetRange,
100
+ targetSource: getSourceTarget(source, targetRange, node.url ?? ''),
101
+ });
102
+ return;
103
+ }
104
+
105
+ if (node.type !== 'linkReference') return;
106
+ const definition = definitions.get(node.identifier);
107
+ if (!definition) return;
108
+ const targetRange = getDefinitionTargetRange(source, definition);
109
+ links.push({
110
+ kind: 'markdown-reference-link',
111
+ column: node.position?.start.column ?? 1,
112
+ definitionLine: lineOffset + (definition.position?.start.line ?? 1),
113
+ line: lineOffset + (node.position?.start.line ?? 1),
114
+ range: getNodeRange(node),
115
+ target: definition.url ?? '',
116
+ targetRange,
117
+ targetSource: getSourceTarget(source, targetRange, definition.url ?? ''),
118
+ });
119
+ });
120
+
121
+ return links;
122
+ };
123
+
124
+ const getLineOffsets = (source) => {
125
+ const offsets = [0];
126
+ for (let index = 0; index < source.length; index += 1) {
127
+ if (source[index] === '\n') offsets.push(index + 1);
128
+ }
129
+ return offsets;
130
+ };
131
+
132
+ const getCardLinkTargetRange = (source, lineStart) => {
133
+ const lineEnd = source.indexOf('\n', lineStart);
134
+ const end = lineEnd < 0 ? source.length : lineEnd;
135
+ const line = source.slice(lineStart, end);
136
+ const match = line.match(/^\s*link:\s*(.*?)\s*$/);
137
+ if (!match) return null;
138
+
139
+ const value = match[1] ?? '';
140
+ let valueStart = lineStart + (match.index ?? 0) + match[0].indexOf(value);
141
+ let valueEnd = valueStart + value.length;
142
+ if (
143
+ value.length >= 2
144
+ && (value[0] === '"' || value[0] === "'")
145
+ && value.at(-1) === value[0]
146
+ ) {
147
+ valueStart += 1;
148
+ valueEnd -= 1;
149
+ }
150
+
151
+ return { start: valueStart, end: valueEnd };
152
+ };
153
+
154
+ export const extractNornaBlockLinks = ({ source, blocks, lineOffset = 0 }) => {
155
+ const lineOffsets = getLineOffsets(source);
156
+ const links = [];
157
+
158
+ for (const block of blocks) {
159
+ if (block.type !== 'card-list') continue;
160
+ for (const card of block.cards) {
161
+ if (!card.link || !card.linkLine) continue;
162
+ const localLine = card.linkLine - lineOffset;
163
+ const lineStart = lineOffsets[localLine - 1];
164
+ const targetRange = Number.isInteger(lineStart)
165
+ ? getCardLinkTargetRange(source, lineStart)
166
+ : null;
167
+ links.push({
168
+ kind: 'card-link',
169
+ column: targetRange && Number.isInteger(lineStart)
170
+ ? targetRange.start - lineStart + 1
171
+ : 3,
172
+ line: card.linkLine,
173
+ range: targetRange,
174
+ target: card.link,
175
+ targetRange,
176
+ targetSource: getSourceTarget(source, targetRange, card.link),
177
+ });
178
+ }
179
+ }
180
+
181
+ return links;
182
+ };
@@ -15,23 +15,28 @@ const assertNavigationMode = (mode) => {
15
15
 
16
16
  const getListedNodes = (nodes) => nodes.filter((node) => node.isHome || node.listed !== false);
17
17
 
18
- const getNodeNavigationDepth = (node) => {
19
- const nodeDepth = node.depth ?? 1;
20
- return (node.headings ?? []).reduce((maximum, heading) => (
21
- Math.max(maximum, nodeDepth + heading.depth - 1)
22
- ), nodeDepth);
18
+ const getNodeDepth = (node) => node.depth ?? 1;
19
+
20
+ const getTopLevelPagePath = (pagePath) => pagePath?.split('/')[0] ?? '';
21
+
22
+ const getActiveBranchNodes = (nodes, currentPage) => {
23
+ if (!currentPage) return [];
24
+ if (currentPage.isHome) return nodes.filter((node) => node.isHome);
25
+
26
+ const rootPath = getTopLevelPagePath(currentPage.pagePath);
27
+ return nodes.filter((node) => (
28
+ node.pagePath === rootPath
29
+ || node.pagePath?.startsWith(`${rootPath}/`)
30
+ ));
23
31
  };
24
32
 
25
33
  export const getAutomaticNavigationMode = (nodes) => {
26
34
  const listedNodes = getListedNodes(nodes);
27
35
  if (listedNodes.length <= 1) return 'sections';
28
- if (listedNodes.some((node) => node.kind === 'category')) return 'tree';
29
-
30
- const maximumDepth = listedNodes.reduce((maximum, node) => (
31
- Math.max(maximum, getNodeNavigationDepth(node))
32
- ), 1);
33
36
 
34
- return maximumDepth <= 2 ? 'top' : 'tree';
37
+ return listedNodes.some((node) => node.kind === 'category' || getNodeDepth(node) > 1)
38
+ ? 'tree'
39
+ : 'top';
35
40
  };
36
41
 
37
42
  export const resolveNavigationModel = ({ mode = 'automatic', nodes }) => {
@@ -42,8 +47,9 @@ export const resolveNavigationModel = ({ mode = 'automatic', nodes }) => {
42
47
  throw new Error(`Navigation categories require tree navigation. Remove navigation.mode: ${requestedMode}, or set navigation.mode: tree.`);
43
48
  }
44
49
  const maximumDepth = listedNodes.reduce((maximum, node) => (
45
- Math.max(maximum, getNodeNavigationDepth(node))
50
+ Math.max(maximum, getNodeDepth(node))
46
51
  ), 1);
52
+ const hasNestedPages = listedNodes.some((node) => getNodeDepth(node) > 1);
47
53
 
48
54
  return Object.freeze({
49
55
  mode: requestedMode === 'automatic'
@@ -52,6 +58,32 @@ export const resolveNavigationModel = ({ mode = 'automatic', nodes }) => {
52
58
  requestedMode,
53
59
  listedNodeCount: listedNodes.length,
54
60
  hasCategories,
61
+ hasNestedPages,
55
62
  maximumDepth,
56
63
  });
57
64
  };
65
+
66
+ export const resolvePageContentsPlacement = ({
67
+ navigationMode,
68
+ nodes,
69
+ currentPage,
70
+ headingCount,
71
+ }) => {
72
+ const listedNodes = getListedNodes(nodes);
73
+ const activeBranchNodes = getActiveBranchNodes(listedNodes, currentPage);
74
+ const activeBranchDepth = activeBranchNodes.reduce((maximum, node) => (
75
+ Math.max(maximum, getNodeDepth(node))
76
+ ), 0);
77
+ const hasPageContents = headingCount >= 2;
78
+ const placement = navigationMode !== 'tree' || !hasPageContents
79
+ ? 'none'
80
+ : activeBranchDepth <= 2
81
+ ? 'page-tree'
82
+ : 'contents-rail';
83
+
84
+ return Object.freeze({
85
+ activeBranchDepth,
86
+ hasPageContents,
87
+ placement,
88
+ });
89
+ };
@@ -0,0 +1,396 @@
1
+ import { resolveNavigationModel } from './navigation-model.mjs';
2
+ import { getSiteLinkGraph } from './site-link-graph.mjs';
3
+ import { getSiteNodePathname } from './site-page-urls.mjs';
4
+ import {
5
+ flattenSiteNavigationTree,
6
+ getListedSiteNavigationTree,
7
+ getSiteNavigationTree,
8
+ } from './site-navigation-tree.mjs';
9
+ import { getSiteStructure } from './site-structure.mjs';
10
+
11
+ export const navigationReviewFormatNames = Object.freeze(['text', 'json']);
12
+
13
+ export const navigationReviewThresholds = Object.freeze({
14
+ deepBranchLevels: 4,
15
+ sectionCount: 8,
16
+ wideSiblingCount: 10,
17
+ });
18
+
19
+ const plural = (count, singular, pluralForm = `${singular}s`) => (
20
+ `${count} ${count === 1 ? singular : pluralForm}`
21
+ );
22
+
23
+ const logicalPathname = (node) => getSiteNodePathname(node);
24
+
25
+ const getTreeMetrics = (root) => {
26
+ const nodes = flattenSiteNavigationTree([root]);
27
+ const rootDepth = root.node.depth;
28
+ return {
29
+ categoryCount: nodes.filter(({ node }) => node.kind === 'category').length,
30
+ maximumLevels: nodes.reduce((maximum, { node }) => (
31
+ Math.max(maximum, node.depth - rootDepth + 1)
32
+ ), 1),
33
+ nodeCount: nodes.length,
34
+ pageCount: nodes.filter(({ node }) => node.kind === 'page').length,
35
+ };
36
+ };
37
+
38
+ const getSiblingGroups = (roots) => {
39
+ const groups = [];
40
+ const collect = (nodes, parent = null) => {
41
+ if (nodes.length > 0) {
42
+ groups.push({
43
+ count: nodes.length,
44
+ entries: nodes.map(({ node }) => ({
45
+ kind: node.kind,
46
+ path: logicalPathname(node),
47
+ title: node.title,
48
+ })),
49
+ parentPath: parent ? logicalPathname(parent.node) : null,
50
+ parentTitle: parent?.node.title ?? 'Site root',
51
+ });
52
+ }
53
+
54
+ for (const node of nodes) collect(node.children, node);
55
+ };
56
+
57
+ collect(roots);
58
+ return groups;
59
+ };
60
+
61
+ const toGraphError = (diagnostic) => ({
62
+ code: diagnostic.code,
63
+ ...(diagnostic.fix ? { fix: diagnostic.fix } : {}),
64
+ ...(diagnostic.reference?.line ? { line: diagnostic.reference.line } : {}),
65
+ message: diagnostic.message,
66
+ ...(diagnostic.reference?.sourceContentFile?.contentLabel
67
+ ? { source: diagnostic.reference.sourceContentFile.contentLabel }
68
+ : {}),
69
+ });
70
+
71
+ const toStructureObservation = (warning) => ({
72
+ code: warning.code,
73
+ message: warning.message,
74
+ ...(warning.label ? { source: warning.label } : {}),
75
+ });
76
+
77
+ const getResolvedPageReferences = (linkGraph) => linkGraph.references.filter(({ resolution }) => (
78
+ resolution?.kind === 'page' || resolution?.kind === 'page-alias'
79
+ ));
80
+
81
+ const getNavigationEntries = (siteStructure, linkGraph) => {
82
+ const pagesByDirectory = new Map(linkGraph.pages.map((page) => [
83
+ page.contentFile.pageDirectory,
84
+ page,
85
+ ]));
86
+
87
+ return siteStructure.nodes.map((siteNode) => {
88
+ const page = siteNode.kind === 'page'
89
+ ? pagesByDirectory.get(siteNode.pageDirectory)
90
+ : null;
91
+ if (siteNode.kind === 'page' && !page) {
92
+ throw new Error(`Navigation review could not find parsed content for ${siteNode.contentLabel}.`);
93
+ }
94
+
95
+ return {
96
+ headings: page?.document.headings.filter(({ depth }) => depth === 2 || depth === 3) ?? [],
97
+ node: {
98
+ ...siteNode,
99
+ navigation: {
100
+ listed: siteNode.isHome || (page?.navigation.listed ?? true),
101
+ },
102
+ pathname: siteNode.kind === 'page' ? page.pathname : null,
103
+ title: siteNode.kind === 'page' ? page.title : siteNode.label,
104
+ },
105
+ page,
106
+ sections: [],
107
+ };
108
+ });
109
+ };
110
+
111
+ const getNavigationModes = ({ entries, listedEntries, requestedNavigationMode }) => {
112
+ const modelNodes = listedEntries.map(({ headings, node }) => ({
113
+ depth: node.depth,
114
+ headings,
115
+ isHome: node.isHome,
116
+ kind: node.kind,
117
+ listed: true,
118
+ pagePath: node.pagePath,
119
+ }));
120
+ const errors = [];
121
+ const modes = new Map();
122
+ const seenErrors = new Set();
123
+
124
+ for (const entry of entries.filter(({ node }) => node.kind === 'page')) {
125
+ try {
126
+ const model = resolveNavigationModel({
127
+ currentPage: {
128
+ depth: entry.node.depth,
129
+ headings: entry.headings,
130
+ isHome: entry.node.isHome,
131
+ kind: 'page',
132
+ listed: entry.node.navigation.listed,
133
+ pagePath: entry.node.pagePath,
134
+ },
135
+ mode: requestedNavigationMode,
136
+ nodes: modelNodes,
137
+ });
138
+ modes.set(entry.node.pagePath, model.mode);
139
+ } catch (error) {
140
+ const message = error instanceof Error ? error.message : String(error);
141
+ if (!seenErrors.has(message)) {
142
+ seenErrors.add(message);
143
+ errors.push({
144
+ code: 'invalid-navigation-model',
145
+ message,
146
+ });
147
+ }
148
+ modes.set(entry.node.pagePath, null);
149
+ }
150
+ }
151
+
152
+ return { errors, modes };
153
+ };
154
+
155
+ const sortUnique = (values) => [...new Set(values)].sort((left, right) => left.localeCompare(right, 'en'));
156
+
157
+ export const createNavigationReview = ({
158
+ linkGraph,
159
+ requestedNavigationMode = 'automatic',
160
+ siteStructure,
161
+ thresholds = navigationReviewThresholds,
162
+ }) => {
163
+ const entries = getNavigationEntries(siteStructure, linkGraph);
164
+ const completeTree = getSiteNavigationTree(entries);
165
+ const listedTree = getListedSiteNavigationTree(entries);
166
+ const completeEntries = flattenSiteNavigationTree(completeTree);
167
+ const listedEntries = flattenSiteNavigationTree(listedTree);
168
+ const listedPaths = new Set(listedEntries.map(({ node }) => node.pagePath));
169
+ const resolvedPageReferences = getResolvedPageReferences(linkGraph);
170
+ const { errors: navigationErrors, modes } = getNavigationModes({
171
+ entries: completeEntries,
172
+ listedEntries,
173
+ requestedNavigationMode,
174
+ });
175
+
176
+ const pages = completeEntries
177
+ .filter(({ node }) => node.kind === 'page')
178
+ .map(({ headings, node, page }) => {
179
+ const incomingPageLinkCount = resolvedPageReferences.filter(({ resolution }) => (
180
+ resolution.page.pathname === page.pathname
181
+ )).length;
182
+ const outgoingReferences = linkGraph.references.filter(({ sourcePage }) => sourcePage.pathname === page.pathname);
183
+ const outgoingPageLinkCount = outgoingReferences.filter(({ resolution }) => (
184
+ resolution?.kind === 'page' || resolution?.kind === 'page-alias'
185
+ )).length;
186
+
187
+ return {
188
+ contentFile: node.contentLabel,
189
+ depth: node.depth,
190
+ h2Count: headings.filter(({ depth }) => depth === 2).length,
191
+ h3Count: headings.filter(({ depth }) => depth === 3).length,
192
+ incomingPageLinkCount,
193
+ listed: listedPaths.has(node.pagePath),
194
+ navigationMode: modes.get(node.pagePath) ?? null,
195
+ outgoingInternalReferenceCount: outgoingReferences.length,
196
+ outgoingPageLinkCount,
197
+ parentPath: node.parentPagePath === null ? null : `/${node.parentPagePath}/`,
198
+ pathname: page.pathname,
199
+ title: node.title,
200
+ };
201
+ });
202
+
203
+ const categories = completeEntries
204
+ .filter(({ node }) => node.kind === 'category')
205
+ .map(({ children, node }) => ({
206
+ childCount: children.length,
207
+ depth: node.depth,
208
+ listed: listedPaths.has(node.pagePath),
209
+ listedChildCount: listedPaths.has(node.pagePath)
210
+ ? (listedEntries.find(({ node: listedNode }) => listedNode.pagePath === node.pagePath)?.children.length ?? 0)
211
+ : 0,
212
+ parentPath: node.parentPagePath === null ? null : `/${node.parentPagePath}/`,
213
+ path: logicalPathname(node),
214
+ source: node.categorySourceLabel,
215
+ title: node.title,
216
+ }));
217
+
218
+ const branches = listedTree.map((root) => {
219
+ const metrics = getTreeMetrics(root);
220
+ const branchPaths = new Set(flattenSiteNavigationTree([root]).map(({ node }) => node.pagePath));
221
+ const navigationModes = sortUnique(pages
222
+ .filter((page) => branchPaths.has(page.pathname === '/' ? '' : page.pathname.slice(1, -1)))
223
+ .map(({ navigationMode }) => navigationMode)
224
+ .filter(Boolean));
225
+
226
+ return {
227
+ ...metrics,
228
+ kind: root.node.kind,
229
+ navigationModes,
230
+ path: logicalPathname(root.node),
231
+ title: root.node.title,
232
+ };
233
+ });
234
+
235
+ const siblingGroups = getSiblingGroups(listedTree);
236
+ const widestSiblingCount = siblingGroups.reduce((maximum, group) => Math.max(maximum, group.count), 0);
237
+ const observations = [
238
+ ...siteStructure.warnings.map(toStructureObservation),
239
+ ];
240
+ const unlistedPages = pages.filter(({ listed }) => !listed);
241
+ if (unlistedPages.length > 0) {
242
+ observations.push({
243
+ code: 'unlisted-pages',
244
+ message: `${plural(unlistedPages.length, 'page')} and any descendants are outside generated navigation: ${unlistedPages.map(({ pathname }) => pathname).join(', ')}.`,
245
+ });
246
+ }
247
+
248
+ const recommendations = [];
249
+ for (const category of categories.filter(({ listed, listedChildCount }) => listed && listedChildCount === 1)) {
250
+ recommendations.push({
251
+ code: 'single-child-category',
252
+ message: `${category.title} (${category.path}) has one listed child. Keep the category when its label adds useful orientation; otherwise consider moving the child to the category's parent.`,
253
+ path: category.path,
254
+ });
255
+ }
256
+ for (const branch of branches.filter(({ maximumLevels }) => maximumLevels >= thresholds.deepBranchLevels)) {
257
+ recommendations.push({
258
+ code: 'deep-branch',
259
+ message: `${branch.title} (${branch.path}) has ${branch.maximumLevels} visible levels. Review representative navigation tasks before adding another level.`,
260
+ path: branch.path,
261
+ });
262
+ }
263
+ for (const group of siblingGroups.filter(({ count }) => count >= thresholds.wideSiblingCount)) {
264
+ recommendations.push({
265
+ code: 'wide-sibling-group',
266
+ message: `${group.parentTitle} has ${group.count} listed child entries. Review whether stable, meaningful groups would make scanning easier.`,
267
+ ...(group.parentPath ? { path: group.parentPath } : {}),
268
+ });
269
+ }
270
+ for (const page of pages.filter(({ h2Count }) => h2Count >= thresholds.sectionCount)) {
271
+ recommendations.push({
272
+ code: 'section-heavy-page',
273
+ message: `${page.title} (${page.pathname}) has ${page.h2Count} H2 sections. Confirm that they still support one coherent reading task; otherwise consider child pages.`,
274
+ path: page.pathname,
275
+ });
276
+ }
277
+
278
+ const effectiveNavigationModes = sortUnique(pages.map(({ navigationMode }) => navigationMode).filter(Boolean));
279
+
280
+ return {
281
+ command: 'navigation:review',
282
+ schemaVersion: 1,
283
+ thresholds: {
284
+ deepBranchLevels: thresholds.deepBranchLevels,
285
+ sectionCount: thresholds.sectionCount,
286
+ wideSiblingCount: thresholds.wideSiblingCount,
287
+ },
288
+ site: {
289
+ branchCount: branches.length,
290
+ categoryCount: categories.length,
291
+ effectiveNavigationModes,
292
+ internalReferenceCount: linkGraph.references.length,
293
+ listedCategoryCount: categories.filter(({ listed }) => listed).length,
294
+ listedPageCount: pages.filter(({ listed }) => listed).length,
295
+ maximumDepth: listedEntries.reduce((maximum, { node }) => Math.max(maximum, node.depth), 0),
296
+ pageCount: pages.length,
297
+ requestedNavigationMode,
298
+ resolvedPageLinkCount: resolvedPageReferences.length,
299
+ widestSiblingCount,
300
+ },
301
+ branches,
302
+ siblingGroups,
303
+ pages,
304
+ categories,
305
+ errors: [
306
+ ...linkGraph.diagnostics.map(toGraphError),
307
+ ...navigationErrors,
308
+ ],
309
+ observations,
310
+ recommendations,
311
+ };
312
+ };
313
+
314
+ export const getNavigationReview = async ({ requestedNavigationMode = 'automatic' } = {}) => {
315
+ const siteStructure = await getSiteStructure();
316
+ const linkGraph = await getSiteLinkGraph({ siteStructure });
317
+ return createNavigationReview({ linkGraph, requestedNavigationMode, siteStructure });
318
+ };
319
+
320
+ const formatFindingSection = (title, findings) => [
321
+ title,
322
+ ...(findings.length === 0
323
+ ? ['- None.']
324
+ : findings.map((finding) => `- [${finding.code}] ${finding.message}${finding.source ? ` (${finding.source}${finding.line ? `:${finding.line}` : ''})` : ''}${finding.fix ? ` Fix: ${finding.fix}` : ''}`)),
325
+ ];
326
+
327
+ export const formatNavigationReviewText = (review) => {
328
+ const lines = [
329
+ 'Navigation Review',
330
+ '',
331
+ 'Site',
332
+ `- Navigation: ${review.site.requestedNavigationMode} configured; ${review.site.effectiveNavigationModes.join(', ') || 'unresolved'} effective`,
333
+ `- Content: ${plural(review.site.pageCount, 'page')} (${review.site.listedPageCount} listed), ${plural(review.site.categoryCount, 'category', 'categories')} (${review.site.listedCategoryCount} listed)`,
334
+ `- Structure: ${plural(review.site.branchCount, 'top-level branch', 'top-level branches')}, ${review.site.maximumDepth} listed ${review.site.maximumDepth === 1 ? 'level' : 'levels'}, widest sibling group ${review.site.widestSiblingCount}`,
335
+ `- Links: ${plural(review.site.internalReferenceCount, 'internal reference')}, ${review.site.resolvedPageLinkCount} resolved to pages`,
336
+ '',
337
+ 'Branches',
338
+ ...review.branches.map((branch) => (
339
+ `- ${branch.title} (${branch.path}; ${branch.kind}): ${plural(branch.pageCount, 'page')}, ${plural(branch.categoryCount, 'category', 'categories')}, ${plural(branch.maximumLevels, 'visible level')}; navigation ${branch.navigationModes.join(', ') || 'unresolved'}`
340
+ )),
341
+ '',
342
+ 'Pages',
343
+ ...review.pages.map((page) => (
344
+ `- ${page.title} (${page.pathname}; ${page.listed ? 'listed' : 'not listed'}): H2 ${page.h2Count}, H3 ${page.h3Count}; page links ${page.outgoingPageLinkCount} out / ${page.incomingPageLinkCount} in; navigation ${page.navigationMode ?? 'unresolved'}`
345
+ )),
346
+ '',
347
+ 'Categories',
348
+ ...(review.categories.length === 0
349
+ ? ['- None.']
350
+ : review.categories.map((category) => (
351
+ `- ${category.title} (${category.path}; ${category.listed ? 'listed' : 'not listed'}): ${category.listedChildCount} listed of ${plural(category.childCount, 'direct child', 'direct children')}`
352
+ ))),
353
+ '',
354
+ ...formatFindingSection('Errors', review.errors),
355
+ '',
356
+ ...formatFindingSection('Observations', review.observations),
357
+ '',
358
+ ...formatFindingSection('Recommendations', review.recommendations),
359
+ ];
360
+
361
+ return `${lines.join('\n')}\n`;
362
+ };
363
+
364
+ export const parseNavigationReviewArgs = (args) => {
365
+ let format = 'text';
366
+ let formatSeen = false;
367
+ let help = false;
368
+
369
+ for (let index = 0; index < args.length; index += 1) {
370
+ const arg = args[index];
371
+ if (arg === '-h' || arg === '--help') {
372
+ help = true;
373
+ continue;
374
+ }
375
+
376
+ let value = null;
377
+ if (arg === '--format') {
378
+ value = args[index + 1];
379
+ if (!value || value.startsWith('-')) throw new Error('--format requires text or json.');
380
+ index += 1;
381
+ } else if (arg.startsWith('--format=')) {
382
+ value = arg.slice('--format='.length);
383
+ } else {
384
+ throw new Error(`Unknown navigation:review option "${arg}". Use --format text or --format json.`);
385
+ }
386
+
387
+ if (formatSeen) throw new Error('Specify --format only once.');
388
+ if (!navigationReviewFormatNames.includes(value)) {
389
+ throw new Error(`Unknown navigation:review format "${value}". Use one of: ${navigationReviewFormatNames.join(', ')}.`);
390
+ }
391
+ format = value;
392
+ formatSeen = true;
393
+ }
394
+
395
+ return { format, help };
396
+ };