@tangen/ext-seo 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/package.json +55 -4
  2. package/src/client.ts +48 -0
  3. package/src/components/SeoPanel.tsx +489 -0
  4. package/src/contract.ts +269 -0
  5. package/src/hooks.ts +74 -0
  6. package/src/index.ts +41 -0
  7. package/src/lib/alt-text.ts +59 -0
  8. package/src/lib/analytics.ts +236 -0
  9. package/src/lib/canonical.ts +87 -0
  10. package/src/lib/deployment-role.ts +18 -0
  11. package/src/lib/health-report.ts +93 -0
  12. package/src/lib/llms.ts +55 -0
  13. package/src/lib/metadata.ts +268 -0
  14. package/src/lib/not-found.ts +83 -0
  15. package/src/lib/object-url.ts +83 -0
  16. package/src/lib/optimize.ts +77 -0
  17. package/src/lib/redirects-csv.ts +84 -0
  18. package/src/lib/redirects.ts +178 -0
  19. package/src/lib/resolve.ts +157 -0
  20. package/src/lib/robots.ts +76 -0
  21. package/src/lib/schema-map.ts +66 -0
  22. package/src/lib/schemas.ts +114 -0
  23. package/src/lib/seo-analysis.ts +185 -0
  24. package/src/lib/seo-manager-nav.ts +72 -0
  25. package/src/lib/settings.ts +167 -0
  26. package/src/lib/sitemap-report.ts +38 -0
  27. package/src/lib/sitemap.ts +109 -0
  28. package/src/lib/structured-data.ts +93 -0
  29. package/src/lib/titles.ts +109 -0
  30. package/src/nextjs.ts +70 -0
  31. package/src/pages/AiGeoTab.tsx +78 -0
  32. package/src/pages/AnalyticsTab.tsx +192 -0
  33. package/src/pages/GeoTab.tsx +76 -0
  34. package/src/pages/NotFoundTab.tsx +120 -0
  35. package/src/pages/SchemasTab.tsx +134 -0
  36. package/src/pages/SeoManagerPage.tsx +329 -0
  37. package/src/pages/SettingsTab.tsx +298 -0
  38. package/src/pages/SitemapTab.tsx +51 -0
  39. package/src/pages/TitlesTab.tsx +326 -0
  40. package/src/pages/ToolsTab.tsx +142 -0
  41. package/src/pages/manager-pages.tsx +46 -0
  42. package/src/pages/redirects.tsx +411 -0
  43. package/src/server/analytics-read.ts +51 -0
  44. package/src/server/analytics-sync.ts +182 -0
  45. package/src/server/artifacts.ts +305 -0
  46. package/src/server/health.ts +97 -0
  47. package/src/server/not-found-store.ts +71 -0
  48. package/src/server/optimize.ts +75 -0
  49. package/src/server/redirect-store.ts +128 -0
  50. package/src/server/routes.ts +604 -0
  51. package/src/server/search-console.ts +148 -0
  52. package/src/server/sitemap-source.ts +153 -0
  53. package/src/server/titles.ts +88 -0
  54. package/src/server.ts +47 -0
  55. package/tangen.extension.ts +153 -0
  56. package/README.md +0 -3
@@ -0,0 +1,66 @@
1
+ /**
2
+ * File Name: schema-map.ts
3
+ * Purpose: The per-content-type JSON-LD mapping (plan-seo-next Phase 2). One
4
+ * validated store shape binding a content type to a schema kind and a
5
+ * field mapping (schema property -> content field name), plus the list
6
+ * of selectable kinds. Pure, so the Schemas tab and the resolve layer
7
+ * read the same trusted shape and a bad map never reaches /meta. The
8
+ * builder that turns a config into a node lives in schemas.ts.
9
+ *
10
+ * Author: Raghunath J
11
+ * License: MIT
12
+ */
13
+
14
+ /** Per-content-type kinds. Organization/WebSite are site-level (from settings). */
15
+ export type SchemaKind = 'Article' | 'BlogPosting' | 'WebPage' | 'Product' | 'Person'
16
+
17
+ /** The kinds a type may be mapped to. `none` and site-level entities excluded. */
18
+ export const SCHEMA_KINDS: SchemaKind[] = ['Article', 'BlogPosting', 'WebPage', 'Product', 'Person']
19
+
20
+ export interface TypeSchemaConfig {
21
+ kind: SchemaKind
22
+ /** schema property -> content field name (e.g. { headline: 'title' }). */
23
+ fieldMap: Record<string, string>
24
+ }
25
+
26
+ /** type name -> its schema config. A type absent here emits no per-type node. */
27
+ export type SchemaMap = Record<string, TypeSchemaConfig>
28
+
29
+ export const SEO_SCHEMA_MAP_KEY = 'schema-map'
30
+ export const DEFAULT_SCHEMA_MAP: SchemaMap = {}
31
+
32
+ /**
33
+ * The schema properties a kind can map to a content field. The label property
34
+ * (headline / name) comes first. Shared by the builder and the Schemas tab so
35
+ * both agree on what is mappable.
36
+ */
37
+ export function schemaPropsFor(kind: SchemaKind | 'none'): string[] {
38
+ switch (kind) {
39
+ case 'Article':
40
+ case 'BlogPosting': return ['headline', 'description', 'image', 'datePublished', 'dateModified', 'author']
41
+ case 'WebPage': return ['name', 'description', 'image']
42
+ case 'Product': return ['name', 'description', 'image', 'sku', 'brand']
43
+ case 'Person': return ['name', 'description', 'image']
44
+ default: return []
45
+ }
46
+ }
47
+
48
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
49
+
50
+ /** The one validated read path: unknown kinds, `none`, and junk fields dropped. */
51
+ export function normalizeSchemaMap(raw: unknown): SchemaMap {
52
+ const src = isRecord(raw) ? raw : {}
53
+ const out: SchemaMap = {}
54
+ for (const [type, cfg] of Object.entries(src)) {
55
+ if (!isRecord(cfg)) continue
56
+ if (!SCHEMA_KINDS.includes(cfg.kind as SchemaKind)) continue // drops 'none' and unknown
57
+ const fieldMap: Record<string, string> = {}
58
+ if (isRecord(cfg.fieldMap)) {
59
+ for (const [prop, field] of Object.entries(cfg.fieldMap)) {
60
+ if (typeof field === 'string' && field.trim() !== '') fieldMap[prop] = field.trim()
61
+ }
62
+ }
63
+ out[type] = { kind: cfg.kind as SchemaKind, fieldMap }
64
+ }
65
+ return out
66
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * File Name: schemas.ts
3
+ * Purpose: JSON-LD builders (plan-seo-next Phase 2). Pure functions that turn
4
+ * settings and content into schema.org nodes. This file starts with
5
+ * the SITE-level entity graph (Organization + WebSite) that every page
6
+ * carries - the same nodes that answer an AI engine's "who is this"
7
+ * (GEO). Per-content-type builders (Article, Product, FAQPage, ...)
8
+ * layer on top in a later slice. Structure only: an empty input never
9
+ * emits a node, and absent optionals are omitted rather than blanked.
10
+ *
11
+ * Author: Raghunath J
12
+ * License: MIT
13
+ */
14
+ import type { JsonLdNode } from '../contract'
15
+ import type { SeoSettings } from './settings'
16
+ import type { SchemaKind } from './schema-map'
17
+
18
+ const clean = (v: unknown): string | undefined => {
19
+ if (typeof v !== 'string') return undefined
20
+ const t = v.trim()
21
+ return t === '' ? undefined : t
22
+ }
23
+
24
+ /** The Organization entity: null unless there is at least a name to assert. */
25
+ export function buildOrganization(input: { name?: string; url?: string; logoUrl?: string; sameAs?: string[] }): JsonLdNode | null {
26
+ const name = clean(input.name)
27
+ if (!name) return null
28
+ const node: JsonLdNode = { '@type': 'Organization', name }
29
+ const url = clean(input.url); if (url) node.url = url
30
+ const logo = clean(input.logoUrl); if (logo) node.logo = logo
31
+ const sameAs = (input.sameAs ?? []).map(clean).filter((s): s is string => !!s)
32
+ if (sameAs.length) node.sameAs = sameAs
33
+ return node
34
+ }
35
+
36
+ /** The WebSite entity: null without a url (the one thing it exists to state). */
37
+ export function buildWebSite(input: { name?: string; url?: string }): JsonLdNode | null {
38
+ const url = clean(input.url)
39
+ if (!url) return null
40
+ const node: JsonLdNode = { '@type': 'WebSite', url }
41
+ const name = clean(input.name); if (name) node.name = name
42
+ // Put name before url to read naturally, matching the test's object shape.
43
+ return name ? { '@type': 'WebSite', name, url } : node
44
+ }
45
+
46
+ /**
47
+ * The site-level nodes derived from settings, carried on every page: the
48
+ * organization identity and the website. `siteUrl` and `logoUrl` are resolved
49
+ * by the caller (the app owns URLs); absent ones simply drop their node/field.
50
+ */
51
+ export function buildSiteSchema(settings: SeoSettings, resolved: { siteUrl?: string; logoUrl?: string }): JsonLdNode[] {
52
+ const out: JsonLdNode[] = []
53
+ const org = buildOrganization({
54
+ name: settings.organization.name,
55
+ url: resolved.siteUrl,
56
+ logoUrl: resolved.logoUrl,
57
+ sameAs: settings.organization.sameAs,
58
+ })
59
+ if (org) out.push(org)
60
+ const site = buildWebSite({ name: settings.general.siteName, url: resolved.siteUrl })
61
+ if (site) out.push(site)
62
+ return out
63
+ }
64
+
65
+ const HEADLINE_KINDS = new Set<SchemaKind>(['Article', 'BlogPosting'])
66
+
67
+ /**
68
+ * One content object -> its per-type JSON-LD node, from a type's schema config.
69
+ * The label (headline for Article/BlogPosting, name for the rest) falls back to
70
+ * the resolved page title; description falls back to the resolved description;
71
+ * everything else is read from the mapped content field. Null when the kind is
72
+ * `none` or there is not even a label to assert. The app owns the page url.
73
+ */
74
+ export function buildTypeSchema(
75
+ config: { kind: SchemaKind | 'none'; fieldMap: Record<string, string> },
76
+ ctx: { object: Record<string, unknown>; title?: string; description?: string; url?: string; organizationName?: string },
77
+ ): JsonLdNode | null {
78
+ if (config.kind === 'none') return null
79
+ const get = (prop: string): string | undefined => {
80
+ const field = config.fieldMap[prop]
81
+ return field ? clean(ctx.object[field]) : undefined
82
+ }
83
+ const isHeadline = HEADLINE_KINDS.has(config.kind)
84
+ const labelKey = isHeadline ? 'headline' : 'name'
85
+ const label = get(labelKey) ?? clean(ctx.title)
86
+ if (!label) return null
87
+
88
+ const node: JsonLdNode = { '@type': config.kind }
89
+ node[labelKey] = label
90
+ const description = get('description') ?? clean(ctx.description); if (description) node.description = description
91
+ const image = get('image'); if (image) node.image = image
92
+
93
+ if (isHeadline) {
94
+ const datePublished = get('datePublished'); if (datePublished) node.datePublished = datePublished
95
+ const dateModified = get('dateModified'); if (dateModified) node.dateModified = dateModified
96
+ const author = get('author'); if (author) node.author = { '@type': 'Person', name: author }
97
+ const publisher = clean(ctx.organizationName); if (publisher) node.publisher = { '@type': 'Organization', name: publisher }
98
+ }
99
+ if (config.kind === 'Product') {
100
+ const sku = get('sku'); if (sku) node.sku = sku
101
+ const brand = get('brand'); if (brand) node.brand = { '@type': 'Brand', name: brand }
102
+ }
103
+ const url = clean(ctx.url); if (url) node.url = url
104
+ return node
105
+ }
106
+
107
+ /** A FAQPage node from Q/A pairs, or null when there is no complete pair. */
108
+ export function buildFaqSchema(pairs: { question?: string; answer?: string }[]): JsonLdNode | null {
109
+ const entities = (pairs ?? [])
110
+ .map((p) => ({ q: clean(p.question), a: clean(p.answer) }))
111
+ .filter((p) => p.q && p.a)
112
+ .map((p) => ({ '@type': 'Question', name: p.q, acceptedAnswer: { '@type': 'Answer', text: p.a } }))
113
+ return entities.length ? { '@type': 'FAQPage', mainEntity: entities } : null
114
+ }
@@ -0,0 +1,185 @@
1
+ export type SeoScore = 'good' | 'ok' | 'poor'
2
+
3
+ export interface SeoCheck {
4
+ key: string
5
+ label: string
6
+ score: SeoScore
7
+ message: string
8
+ }
9
+
10
+ // ── Title length ──────────────────────────────────────────────────────────────
11
+
12
+ export function analyzeTitleLength(title: string): SeoCheck {
13
+ const len = title.trim().length
14
+ let score: SeoScore
15
+ let message: string
16
+
17
+ if (len === 0) {
18
+ score = 'poor'
19
+ message = 'SEO title is missing.'
20
+ } else if (len < 10) {
21
+ score = 'poor'
22
+ message = `SEO title is too short (${len} chars). Aim for 50–60 characters.`
23
+ } else if (len > 70) {
24
+ score = 'poor'
25
+ message = `SEO title is too long (${len} chars). Keep it under 70 characters.`
26
+ } else if (len >= 50 && len <= 60) {
27
+ score = 'good'
28
+ message = `SEO title length is ideal (${len} chars).`
29
+ } else {
30
+ score = 'ok'
31
+ message = len < 50
32
+ ? `SEO title is a bit short (${len} chars). Aim for 50–60 characters.`
33
+ : `SEO title is a bit long (${len} chars). Try to keep it under 60 characters.`
34
+ }
35
+
36
+ return { key: 'title-length', label: 'SEO title length', score, message }
37
+ }
38
+
39
+ // ── Meta description length ───────────────────────────────────────────────────
40
+
41
+ export function analyzeMetaDescLength(desc: string): SeoCheck {
42
+ const len = desc.trim().length
43
+ let score: SeoScore
44
+ let message: string
45
+
46
+ if (len === 0) {
47
+ score = 'poor'
48
+ message = 'Meta description is missing.'
49
+ } else if (len < 50) {
50
+ score = 'poor'
51
+ message = `Meta description is too short (${len} chars). Aim for 120–160 characters.`
52
+ } else if (len > 180) {
53
+ score = 'poor'
54
+ message = `Meta description is too long (${len} chars). Keep it under 180 characters.`
55
+ } else if (len >= 120 && len <= 160) {
56
+ score = 'good'
57
+ message = `Meta description length is ideal (${len} chars).`
58
+ } else {
59
+ score = 'ok'
60
+ message = len < 120
61
+ ? `Meta description is a bit short (${len} chars). Aim for 120–160 characters.`
62
+ : `Meta description is a bit long (${len} chars). Try to keep it under 160 characters.`
63
+ }
64
+
65
+ return { key: 'meta-desc-length', label: 'Meta description length', score, message }
66
+ }
67
+
68
+ // ── Keyword in title ──────────────────────────────────────────────────────────
69
+
70
+ export function analyzeKeywordInTitle(title: string, keyword: string): SeoCheck {
71
+ if (!keyword.trim()) {
72
+ return { key: 'keyword-in-title', label: 'Keyword in SEO title', score: 'ok', message: 'No focus keyword set.' }
73
+ }
74
+ const found = title.toLowerCase().includes(keyword.toLowerCase())
75
+ return {
76
+ key: 'keyword-in-title',
77
+ label: 'Keyword in SEO title',
78
+ score: found ? 'good' : 'poor',
79
+ message: found
80
+ ? 'Focus keyword appears in the SEO title.'
81
+ : 'Focus keyword is missing from the SEO title.',
82
+ }
83
+ }
84
+
85
+ // ── Keyword in meta description ───────────────────────────────────────────────
86
+
87
+ export function analyzeKeywordInMetaDesc(desc: string, keyword: string): SeoCheck {
88
+ if (!keyword.trim()) {
89
+ return { key: 'keyword-in-desc', label: 'Keyword in meta description', score: 'ok', message: 'No focus keyword set.' }
90
+ }
91
+ const found = desc.toLowerCase().includes(keyword.toLowerCase())
92
+ return {
93
+ key: 'keyword-in-desc',
94
+ label: 'Keyword in meta description',
95
+ score: found ? 'good' : 'poor',
96
+ message: found
97
+ ? 'Focus keyword appears in the meta description.'
98
+ : 'Focus keyword is missing from the meta description.',
99
+ }
100
+ }
101
+
102
+ // ── Keyword density ───────────────────────────────────────────────────────────
103
+
104
+ export function analyzeKeywordDensity(content: string, keyword: string): SeoCheck {
105
+ if (!keyword.trim()) {
106
+ return { key: 'keyword-density', label: 'Keyword density', score: 'ok', message: 'No focus keyword set.' }
107
+ }
108
+ if (!content.trim()) {
109
+ return { key: 'keyword-density', label: 'Keyword density', score: 'ok', message: 'No content to analyse.' }
110
+ }
111
+
112
+ const words = content.trim().toLowerCase().split(/\s+/)
113
+ const kw = keyword.toLowerCase()
114
+ const kwWords = kw.split(/\s+/)
115
+ let count = 0
116
+
117
+ if (kwWords.length === 1) {
118
+ count = words.filter((w) => w === kw).length
119
+ } else {
120
+ for (let i = 0; i <= words.length - kwWords.length; i++) {
121
+ if (kwWords.every((w, j) => words[i + j] === w)) count++
122
+ }
123
+ }
124
+
125
+ const density = (count / words.length) * 100
126
+ let score: SeoScore
127
+ let message: string
128
+
129
+ if (count === 0) {
130
+ score = 'poor'
131
+ message = 'Focus keyword does not appear in the content.'
132
+ } else if (density > 5) {
133
+ score = 'poor'
134
+ message = `Keyword density is ${density.toFixed(1)}% - this may look like keyword stuffing. Aim for 1–3%.`
135
+ } else if (density >= 1 && density <= 3) {
136
+ score = 'good'
137
+ message = `Keyword density is ${density.toFixed(1)}% - ideal range.`
138
+ } else {
139
+ score = 'ok'
140
+ message = `Keyword density is ${density.toFixed(1)}%. Aim for 1–3%.`
141
+ }
142
+
143
+ return { key: 'keyword-density', label: 'Keyword density', score, message }
144
+ }
145
+
146
+ // ── Readability ───────────────────────────────────────────────────────────────
147
+
148
+ export function analyzeReadability(content: string): SeoCheck {
149
+ if (!content.trim()) {
150
+ return { key: 'readability', label: 'Sentence length', score: 'ok', message: 'No content to analyse.' }
151
+ }
152
+
153
+ const sentences = content.trim().split(/[.!?]+/).filter((s) => s.trim().length > 0)
154
+ if (sentences.length === 0) {
155
+ return { key: 'readability', label: 'Sentence length', score: 'ok', message: 'No sentences found.' }
156
+ }
157
+
158
+ const avgWords = sentences.reduce((sum, s) => sum + s.trim().split(/\s+/).length, 0) / sentences.length
159
+
160
+ let score: SeoScore
161
+ let message: string
162
+
163
+ if (avgWords <= 20) {
164
+ score = 'good'
165
+ message = `Average sentence length is ${avgWords.toFixed(0)} words - great readability.`
166
+ } else if (avgWords <= 25) {
167
+ score = 'ok'
168
+ message = `Average sentence length is ${avgWords.toFixed(0)} words. Try to keep sentences under 20 words.`
169
+ } else {
170
+ score = 'poor'
171
+ message = `Average sentence length is ${avgWords.toFixed(0)} words - sentences are too long. Aim for under 20 words.`
172
+ }
173
+
174
+ return { key: 'readability', label: 'Sentence length', score, message }
175
+ }
176
+
177
+ // ── Overall score ─────────────────────────────────────────────────────────────
178
+
179
+ export function computeOverallScore(checks: SeoCheck[]): SeoScore {
180
+ if (checks.length === 0) return 'ok'
181
+ const poorCount = checks.filter((c) => c.score === 'poor').length
182
+ if (poorCount > checks.length / 2) return 'poor'
183
+ const hasOk = checks.some((c) => c.score === 'ok' || c.score === 'poor')
184
+ return hasOk ? 'ok' : 'good'
185
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * File Name: seo-manager-nav.ts
3
+ * Purpose: The SEO Manager's child menu (plan-seo-manager-v2 V0): one
4
+ * sidebar entry whose context nav lists the mockup's pages in the
5
+ * mockup's order. A page is listed only once its slice has shipped
6
+ * (`ready`), so the menu never leads to an empty screen; the old
7
+ * `?tab=` links of the v1 hub map onto the child paths. Pure and
8
+ * React-free so the nav is testable and the resolver in index.ts
9
+ * stays a one-liner.
10
+ *
11
+ * Author: Raghunath J
12
+ * License: MIT
13
+ */
14
+
15
+ /**
16
+ * Rows per page on the manager's own pages (Redirects, 404 Monitor). 25 is the
17
+ * kit's list-screen default, so these read like every other full-page table.
18
+ */
19
+ export const MANAGER_PAGE_SIZE = 25
20
+
21
+ /**
22
+ * Rows per page inside a DASHBOARD card. A card shares the page with the
23
+ * health ring and the coverage table, so it pages at the DataList default
24
+ * rather than growing to a full screen of rows.
25
+ */
26
+ export const DASHBOARD_PAGE_SIZE = 10
27
+
28
+ export interface SeoManagerNavItem {
29
+ id: string
30
+ label: string
31
+ /** The page path under `extensions/seo`; '' is the root (Dashboard). */
32
+ path: string
33
+ /** A @tangen/icons name. */
34
+ icon: string
35
+ /** `planned` pages are declared here for order and tests, and hidden from the menu until their slice lands. */
36
+ status: 'ready' | 'planned'
37
+ }
38
+
39
+ export const SEO_MANAGER_NAV: readonly SeoManagerNavItem[] = [
40
+ { id: 'dashboard', label: 'Dashboard', path: '', icon: 'IconLayoutGrid', status: 'ready' },
41
+ { id: 'analytics', label: 'Analytics', path: 'analytics', icon: 'IconBarChart', status: 'ready' },
42
+ { id: 'titles', label: 'Titles & Meta', path: 'titles', icon: 'IconText', status: 'ready' },
43
+ { id: 'schema', label: 'Schema', path: 'schema', icon: 'IconCode', status: 'ready' },
44
+ { id: 'sitemap', label: 'Sitemap', path: 'sitemap', icon: 'IconFileList', status: 'ready' },
45
+ { id: 'redirects', label: 'Redirects', path: 'redirects', icon: 'IconArrowLeftRight', status: 'ready' },
46
+ { id: 'not-found', label: '404 Monitor', path: 'not-found', icon: 'IconWarning', status: 'ready' },
47
+ { id: 'ai-geo', label: 'AI & GEO', path: 'ai-geo', icon: 'IconSparkles', status: 'ready' },
48
+ { id: 'tools', label: 'Tools', path: 'tools', icon: 'IconStack', status: 'ready' },
49
+ { id: 'settings', label: 'Settings', path: 'settings', icon: 'IconSettings', status: 'ready' },
50
+ ]
51
+
52
+ /** What the menu shows. */
53
+ export const readyNav = (): SeoManagerNavItem[] => SEO_MANAGER_NAV.filter((i) => i.status === 'ready')
54
+
55
+ /** The Admin URL of one page. */
56
+ export function seoManagerHref(workspaceId: string, path: string): string {
57
+ const base = `/${workspaceId}/extensions/seo`
58
+ return path ? `${base}/${path}` : base
59
+ }
60
+
61
+ /** Whether a pathname is inside the SEO Manager (the context nav's own test). */
62
+ export function isSeoManagerPath(pathname: string, workspaceId: string): boolean {
63
+ const base = seoManagerHref(workspaceId, '')
64
+ return pathname === base || pathname.startsWith(`${base}/`)
65
+ }
66
+
67
+ const LEGACY_TABS: Record<string, string> = { overview: '', settings: 'settings', schemas: 'schema', redirects: 'redirects', sitemap: 'sitemap', geo: 'ai-geo' }
68
+
69
+ /** The child path an old `?tab=` link of the v1 hub means; null when it is not one. */
70
+ export function legacyTabPath(tab: string | null | undefined): string | null {
71
+ return tab !== null && tab !== undefined && Object.hasOwn(LEGACY_TABS, tab) ? LEGACY_TABS[tab]! : null
72
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * File Name: settings.ts
3
+ * Purpose: The DB-backed, workspace-level SEO settings (plan-seo-next Phase 1,
4
+ * the hybrid-config half). Functions and site routing stay in code
5
+ * (`SeoHelpers`); everything an editor can change - title template,
6
+ * social/organization defaults, verification, robots defaults, GEO
7
+ * toggles - lives here, stored under one `ctx.store` key. This module
8
+ * is the ONE validated read/write path, pure and React/server-free, so
9
+ * the Settings page, the routes, and the resolve layer all agree on a
10
+ * single trusted shape (the same discipline as `metadata.ts`).
11
+ *
12
+ * Author: Raghunath J
13
+ * License: MIT
14
+ */
15
+
16
+ /** The `ctx.store` key the settings row occupies (per workspace x env). */
17
+ export const SEO_SETTINGS_KEY = 'settings'
18
+
19
+ /** Bump ONLY alongside a migration branch in `normalizeSettings`. */
20
+ export const SEO_SETTINGS_SCHEMA_VERSION = 1
21
+
22
+ export type TwitterCard = 'summary' | 'summary_large_image'
23
+
24
+ /** What the Settings page edits. Absent optional fields mean "fall back". */
25
+ export interface SeoSettings {
26
+ schemaVersion: number
27
+ general: {
28
+ siteName?: string
29
+ /** e.g. "%title% | %site%" - applied when an object has no title override. */
30
+ titleTemplate?: string
31
+ /** The separator used by title templates; defaults applied by the UI. */
32
+ titleSeparator?: string
33
+ }
34
+ social: {
35
+ /** Media IDENTITY for a default OG image (resolved to a URL at read time). */
36
+ defaultImageId?: string
37
+ twitterCard?: TwitterCard
38
+ twitterHandle?: string
39
+ }
40
+ organization: {
41
+ name?: string
42
+ logoId?: string
43
+ /** Canonical profile URLs for the entity graph (Organization.sameAs). */
44
+ sameAs: string[]
45
+ }
46
+ verification: {
47
+ google?: string
48
+ bing?: string
49
+ }
50
+ robots: {
51
+ defaultIndex: boolean
52
+ defaultFollow: boolean
53
+ }
54
+ geo: {
55
+ /** Publish llms.txt / llms-full.txt for AI crawlers (Phase 4). */
56
+ llmsTxtEnabled: boolean
57
+ }
58
+ }
59
+
60
+ export const DEFAULT_SEO_SETTINGS: SeoSettings = {
61
+ schemaVersion: SEO_SETTINGS_SCHEMA_VERSION,
62
+ general: {},
63
+ social: {},
64
+ organization: { sameAs: [] },
65
+ verification: {},
66
+ robots: { defaultIndex: true, defaultFollow: true },
67
+ geo: { llmsTxtEnabled: false },
68
+ }
69
+
70
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
71
+
72
+ /** Trimmed text, or undefined - an empty setting is an absence, not a value. */
73
+ function text(v: unknown): string | undefined {
74
+ if (typeof v !== 'string') return undefined
75
+ const t = v.trim()
76
+ return t === '' ? undefined : t
77
+ }
78
+
79
+ function bool(v: unknown, fallback: boolean): boolean {
80
+ return typeof v === 'boolean' ? v : fallback
81
+ }
82
+
83
+ function stringList(v: unknown): string[] {
84
+ if (!Array.isArray(v)) return []
85
+ const out: string[] = []
86
+ for (const item of v) { const t = text(item); if (t) out.push(t) }
87
+ return out
88
+ }
89
+
90
+ /**
91
+ * Split a free-text field (the Settings form's sameAs textarea) into a clean
92
+ * list of URLs. Newlines or commas separate; blanks are dropped. Pure, so the
93
+ * form and the codec agree on how a pasted list becomes an array.
94
+ */
95
+ export function parseSameAs(textarea: string): string[] {
96
+ return stringList(String(textarea ?? '').split(/[\n,]/))
97
+ }
98
+
99
+ /**
100
+ * The one validated read path: whatever is in the store becomes a fully
101
+ * defaulted, junk-free `SeoSettings`. Unknown keys are dropped, not stored;
102
+ * empty strings collapse to absence; the enum is clamped. (When
103
+ * SEO_SETTINGS_SCHEMA_VERSION next moves, branch on `raw.schemaVersion` here.)
104
+ */
105
+ export function normalizeSettings(raw: unknown): SeoSettings {
106
+ const src = isRecord(raw) ? raw : {}
107
+ const general = isRecord(src.general) ? src.general : {}
108
+ const social = isRecord(src.social) ? src.social : {}
109
+ const organization = isRecord(src.organization) ? src.organization : {}
110
+ const verification = isRecord(src.verification) ? src.verification : {}
111
+ const robots = isRecord(src.robots) ? src.robots : {}
112
+ const geo = isRecord(src.geo) ? src.geo : {}
113
+
114
+ const twitterCard = social.twitterCard === 'summary' || social.twitterCard === 'summary_large_image'
115
+ ? social.twitterCard
116
+ : undefined
117
+
118
+ const out: SeoSettings = {
119
+ schemaVersion: SEO_SETTINGS_SCHEMA_VERSION,
120
+ general: {},
121
+ social: {},
122
+ organization: { sameAs: stringList(organization.sameAs) },
123
+ verification: {},
124
+ robots: { defaultIndex: bool(robots.defaultIndex, true), defaultFollow: bool(robots.defaultFollow, true) },
125
+ geo: { llmsTxtEnabled: bool(geo.llmsTxtEnabled, false) },
126
+ }
127
+
128
+ const siteName = text(general.siteName); if (siteName) out.general.siteName = siteName
129
+ const titleTemplate = text(general.titleTemplate); if (titleTemplate) out.general.titleTemplate = titleTemplate
130
+ const titleSeparator = text(general.titleSeparator); if (titleSeparator) out.general.titleSeparator = titleSeparator
131
+
132
+ const defaultImageId = text(social.defaultImageId); if (defaultImageId) out.social.defaultImageId = defaultImageId
133
+ if (twitterCard) out.social.twitterCard = twitterCard
134
+ const twitterHandle = text(social.twitterHandle); if (twitterHandle) out.social.twitterHandle = twitterHandle
135
+
136
+ const orgName = text(organization.name); if (orgName) out.organization.name = orgName
137
+ const logoId = text(organization.logoId); if (logoId) out.organization.logoId = logoId
138
+
139
+ const google = text(verification.google); if (google) out.verification.google = google
140
+ const bing = text(verification.bing); if (bing) out.verification.bing = bing
141
+
142
+ return out
143
+ }
144
+
145
+ /** The groups a settings save may name. One save, one group. */
146
+ export const SEO_SETTINGS_GROUPS = ['general', 'social', 'organization', 'verification', 'robots', 'geo'] as const
147
+ export type SeoSettingsGroup = (typeof SEO_SETTINGS_GROUPS)[number]
148
+
149
+ /**
150
+ * A PARTIAL save merged over what is stored: the Settings tab saves the group
151
+ * it edited rather than posting the whole page back (the user, 2026-09-20).
152
+ *
153
+ * The rule that makes it safe: only a group the patch actually NAMES is
154
+ * touched, and a named group is replaced whole - so clearing a field inside a
155
+ * group works (an absent key is an absent value), while a group nobody
156
+ * mentioned keeps every value it had. Anything that is not one of the known
157
+ * groups is ignored, exactly as the codec ignores it.
158
+ */
159
+ export function mergeSettingsGroups(stored: SeoSettings, patch: unknown): Record<string, unknown> {
160
+ const src = isRecord(patch) ? patch : {}
161
+ const out: Record<string, unknown> = { ...(stored as unknown as Record<string, unknown>) }
162
+ for (const group of SEO_SETTINGS_GROUPS) {
163
+ if (!(group in src)) continue
164
+ out[group] = isRecord(src[group]) ? src[group] : {}
165
+ }
166
+ return out
167
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * File Name: sitemap-report.ts
3
+ * Purpose: SEO Manager S2: the sitemap report in words. The server's report
4
+ * is numbers (entries, files, skipped, scanned, truncated); the
5
+ * Sitemap tab shows what they mean, and a truncated sitemap is a
6
+ * warning an editor can act on, not a silent cap.
7
+ *
8
+ * Author: Raghunath J
9
+ * License: MIT
10
+ */
11
+
12
+ export interface SitemapReport {
13
+ entries: number
14
+ pageCount: number
15
+ skipped: number
16
+ scanned: number
17
+ truncated: boolean
18
+ }
19
+
20
+ export interface SitemapDescription {
21
+ headline: string
22
+ details: string[]
23
+ warning: string | null
24
+ }
25
+
26
+ const n = (v: number) => v.toLocaleString('en-US')
27
+ const plural = (v: number, one: string, many: string) => (v === 1 ? one : many)
28
+
29
+ export function describeSitemapReport(r: SitemapReport): SitemapDescription {
30
+ if (r.entries === 0) return { headline: 'No URLs yet', details: [], warning: r.scanned > 0 ? `${n(r.scanned)} published ${plural(r.scanned, 'object', 'objects')} scanned, none resolved to a URL - declare resolveUrl for their types` : null }
31
+ const details = [`${n(r.scanned)} published ${plural(r.scanned, 'object', 'objects')} scanned`]
32
+ if (r.skipped > 0) details.push(`${n(r.skipped)} skipped (no URL could be resolved for ${plural(r.skipped, 'it', 'them')})`)
33
+ return {
34
+ headline: `${n(r.entries)} URLs in ${n(r.pageCount)} sitemap ${plural(r.pageCount, 'file', 'files')}`,
35
+ details,
36
+ warning: r.truncated ? 'The sitemap was cut short at its size limit: not every published URL is listed. Narrow sitemapTypes or split by type.' : null,
37
+ }
38
+ }