@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.
- package/package.json +55 -4
- package/src/client.ts +48 -0
- package/src/components/SeoPanel.tsx +489 -0
- package/src/contract.ts +269 -0
- package/src/hooks.ts +74 -0
- package/src/index.ts +41 -0
- package/src/lib/alt-text.ts +59 -0
- package/src/lib/analytics.ts +236 -0
- package/src/lib/canonical.ts +87 -0
- package/src/lib/deployment-role.ts +18 -0
- package/src/lib/health-report.ts +93 -0
- package/src/lib/llms.ts +55 -0
- package/src/lib/metadata.ts +268 -0
- package/src/lib/not-found.ts +83 -0
- package/src/lib/object-url.ts +83 -0
- package/src/lib/optimize.ts +77 -0
- package/src/lib/redirects-csv.ts +84 -0
- package/src/lib/redirects.ts +178 -0
- package/src/lib/resolve.ts +157 -0
- package/src/lib/robots.ts +76 -0
- package/src/lib/schema-map.ts +66 -0
- package/src/lib/schemas.ts +114 -0
- package/src/lib/seo-analysis.ts +185 -0
- package/src/lib/seo-manager-nav.ts +72 -0
- package/src/lib/settings.ts +167 -0
- package/src/lib/sitemap-report.ts +38 -0
- package/src/lib/sitemap.ts +109 -0
- package/src/lib/structured-data.ts +93 -0
- package/src/lib/titles.ts +109 -0
- package/src/nextjs.ts +70 -0
- package/src/pages/AiGeoTab.tsx +78 -0
- package/src/pages/AnalyticsTab.tsx +192 -0
- package/src/pages/GeoTab.tsx +76 -0
- package/src/pages/NotFoundTab.tsx +120 -0
- package/src/pages/SchemasTab.tsx +134 -0
- package/src/pages/SeoManagerPage.tsx +329 -0
- package/src/pages/SettingsTab.tsx +298 -0
- package/src/pages/SitemapTab.tsx +51 -0
- package/src/pages/TitlesTab.tsx +326 -0
- package/src/pages/ToolsTab.tsx +142 -0
- package/src/pages/manager-pages.tsx +46 -0
- package/src/pages/redirects.tsx +411 -0
- package/src/server/analytics-read.ts +51 -0
- package/src/server/analytics-sync.ts +182 -0
- package/src/server/artifacts.ts +305 -0
- package/src/server/health.ts +97 -0
- package/src/server/not-found-store.ts +71 -0
- package/src/server/optimize.ts +75 -0
- package/src/server/redirect-store.ts +128 -0
- package/src/server/routes.ts +604 -0
- package/src/server/search-console.ts +148 -0
- package/src/server/sitemap-source.ts +153 -0
- package/src/server/titles.ts +88 -0
- package/src/server.ts +47 -0
- package/tangen.extension.ts +153 -0
- package/README.md +0 -3
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: sitemap.ts
|
|
3
|
+
* Purpose: The sitemap contract (closure plan Phase 9A, Unit 7): one canonical
|
|
4
|
+
* representation with thin serializers over it, eligibility that can
|
|
5
|
+
* say WHY an object is absent, and partitioning that behaves at the
|
|
6
|
+
* size real sites reach.
|
|
7
|
+
*
|
|
8
|
+
* Author: Raghunath J
|
|
9
|
+
* License: MIT
|
|
10
|
+
*
|
|
11
|
+
* Dependencies/Notes: Pure. The one rule that shapes everything: a sitemap
|
|
12
|
+
* entry needs a URL, and Tangen cannot invent one - an object whose
|
|
13
|
+
* URL the application did not resolve is omitted with a reason, never
|
|
14
|
+
* guessed at from a slug.
|
|
15
|
+
*/
|
|
16
|
+
import { validateCanonical } from './canonical'
|
|
17
|
+
import type { SeoMetadata } from '../contract'
|
|
18
|
+
|
|
19
|
+
/** One page in a sitemap. The only representation; the XML is a view of it. */
|
|
20
|
+
export interface SitemapEntry {
|
|
21
|
+
loc: string
|
|
22
|
+
/** ISO 8601. Absent rather than invented when the object has no timestamp. */
|
|
23
|
+
lastModified?: string
|
|
24
|
+
/** Only locales that actually resolved. Never fabricated. */
|
|
25
|
+
alternates?: Array<{ hreflang: string; href: string }>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The standard's ceiling is 50,000 URLs (and 50 MB) per file. Sitting under
|
|
30
|
+
* it leaves room for the alternates a localized site adds per entry.
|
|
31
|
+
*/
|
|
32
|
+
export const SITEMAP_MAX_ENTRIES = 45_000
|
|
33
|
+
|
|
34
|
+
export type IneligibleReason = 'NOT_PUBLISHED' | 'NOINDEX' | 'EXCLUDED' | 'UNRESOLVED_URL' | 'TYPE_NOT_ELIGIBLE'
|
|
35
|
+
|
|
36
|
+
export interface EligibilityInput {
|
|
37
|
+
published: boolean
|
|
38
|
+
metadata: SeoMetadata
|
|
39
|
+
type: string
|
|
40
|
+
/** What the application's resolver answered, or null when it had no answer. */
|
|
41
|
+
url: string | null
|
|
42
|
+
/** The site's eligible types; absent means every type. */
|
|
43
|
+
sitemapTypes?: string[]
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether one object belongs in the sitemap, and when it does not, why. The
|
|
48
|
+
* reason is the point: "your page is missing" is a support ticket, "excluded
|
|
49
|
+
* by the editor" is an answer.
|
|
50
|
+
*/
|
|
51
|
+
export function sitemapEligibility(input: EligibilityInput): { eligible: true } | { eligible: false; reason: IneligibleReason } {
|
|
52
|
+
if (!input.published) return { eligible: false, reason: 'NOT_PUBLISHED' }
|
|
53
|
+
if (input.sitemapTypes && !input.sitemapTypes.includes(input.type)) return { eligible: false, reason: 'TYPE_NOT_ELIGIBLE' }
|
|
54
|
+
if (input.metadata.robots?.index === false) return { eligible: false, reason: 'NOINDEX' }
|
|
55
|
+
if (input.metadata.sitemapExclude === true) return { eligible: false, reason: 'EXCLUDED' }
|
|
56
|
+
if (!input.url || !validateCanonical(input.url).ok) return { eligible: false, reason: 'UNRESOLVED_URL' }
|
|
57
|
+
return { eligible: true }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** By URL: the same content produces the same file whatever order the rows arrived in. */
|
|
61
|
+
export function sortEntries(entries: SitemapEntry[]): SitemapEntry[] {
|
|
62
|
+
return [...entries].sort((a, b) => (a.loc < b.loc ? -1 : a.loc > b.loc ? 1 : 0))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Fixed-size pages, in order, so page 2 is page 2 on every regeneration. */
|
|
66
|
+
export function partitionEntries(entries: SitemapEntry[], size = SITEMAP_MAX_ENTRIES): SitemapEntry[][] {
|
|
67
|
+
if (entries.length <= size) return [entries]
|
|
68
|
+
const pages: SitemapEntry[][] = []
|
|
69
|
+
for (let i = 0; i < entries.length; i += size) pages.push(entries.slice(i, i + size))
|
|
70
|
+
return pages
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The five XML entities. A URL carrying `&` or `<` must not break the document. */
|
|
74
|
+
export function escapeXml(value: string): string {
|
|
75
|
+
return value
|
|
76
|
+
.replace(/&/g, '&')
|
|
77
|
+
.replace(/</g, '<')
|
|
78
|
+
.replace(/>/g, '>')
|
|
79
|
+
.replace(/"/g, '"')
|
|
80
|
+
.replace(/'/g, ''')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A urlset. Thin: it renders entries and decides nothing. */
|
|
84
|
+
export function sitemapXml(entries: SitemapEntry[]): string {
|
|
85
|
+
const hasAlternates = entries.some((e) => e.alternates?.length)
|
|
86
|
+
const ns = [
|
|
87
|
+
'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"',
|
|
88
|
+
...(hasAlternates ? ['xmlns:xhtml="http://www.w3.org/1999/xhtml"'] : []),
|
|
89
|
+
].join(' ')
|
|
90
|
+
const body = entries.map((e) => {
|
|
91
|
+
const parts = [` <loc>${escapeXml(e.loc)}</loc>`]
|
|
92
|
+
if (e.lastModified) parts.push(` <lastmod>${escapeXml(e.lastModified)}</lastmod>`)
|
|
93
|
+
for (const alt of e.alternates ?? []) {
|
|
94
|
+
parts.push(` <xhtml:link rel="alternate" hreflang="${escapeXml(alt.hreflang)}" href="${escapeXml(alt.href)}"/>`)
|
|
95
|
+
}
|
|
96
|
+
return ` <url>\n${parts.join('\n')}\n </url>`
|
|
97
|
+
}).join('\n')
|
|
98
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset ${ns}>\n${body}${body ? '\n' : ''}</urlset>\n`
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A sitemapindex over the pages a partitioned sitemap produced. */
|
|
102
|
+
export function sitemapIndexXml(pages: Array<{ loc: string; lastModified?: string }>): string {
|
|
103
|
+
const body = pages.map((p) => {
|
|
104
|
+
const parts = [` <loc>${escapeXml(p.loc)}</loc>`]
|
|
105
|
+
if (p.lastModified) parts.push(` <lastmod>${escapeXml(p.lastModified)}</lastmod>`)
|
|
106
|
+
return ` <sitemap>\n${parts.join('\n')}\n </sitemap>`
|
|
107
|
+
}).join('\n')
|
|
108
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${body}${body ? '\n' : ''}</sitemapindex>\n`
|
|
109
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: structured-data.ts
|
|
3
|
+
* Purpose: JSON-LD as data (closure plan Phase 9A, Unit 9). Tangen validates
|
|
4
|
+
* STRUCTURE and bounds and nothing else - implementing Schema.org's
|
|
5
|
+
* vocabulary is not a CMS's job, and pretending to would be worse
|
|
6
|
+
* than saying so.
|
|
7
|
+
*
|
|
8
|
+
* Author: Raghunath J
|
|
9
|
+
* License: MIT
|
|
10
|
+
*
|
|
11
|
+
* Dependencies/Notes: Nothing here executes or renders. The serializer escapes
|
|
12
|
+
* what would end a <script> element early, because the one place this
|
|
13
|
+
* data lands is inside one - that escaping is the whole security
|
|
14
|
+
* story and it lives with the serializer, not with each consumer.
|
|
15
|
+
*/
|
|
16
|
+
import { STRUCTURED_DATA_LIMITS, type JsonLdNode } from '../contract'
|
|
17
|
+
|
|
18
|
+
export type StructuredDataCheck =
|
|
19
|
+
| { ok: true; nodes: JsonLdNode[] }
|
|
20
|
+
| { ok: false; reason: 'NOT_AN_OBJECT' | 'MISSING_TYPE' | 'NOT_SERIALIZABLE' | 'TOO_MANY_NODES' | 'TOO_LARGE' | 'TOO_DEEP'; index?: number }
|
|
21
|
+
|
|
22
|
+
function depthOf(value: unknown, seen = new Set<unknown>()): number {
|
|
23
|
+
if (typeof value !== 'object' || value === null) return 0
|
|
24
|
+
if (seen.has(value)) return Number.POSITIVE_INFINITY
|
|
25
|
+
seen.add(value)
|
|
26
|
+
let max = 0
|
|
27
|
+
for (const child of Object.values(value as Record<string, unknown>)) {
|
|
28
|
+
max = Math.max(max, depthOf(child, seen))
|
|
29
|
+
if (max === Number.POSITIVE_INFINITY) break
|
|
30
|
+
}
|
|
31
|
+
seen.delete(value)
|
|
32
|
+
return max + 1
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Structural validation. What it checks: each node is an object, each has a
|
|
37
|
+
* non-empty `@type`, the whole array serializes, and it stays inside the
|
|
38
|
+
* declared bounds. What it does NOT check: whether `@type` names a real
|
|
39
|
+
* Schema.org type, or whether the properties belong to it. That is the
|
|
40
|
+
* author's responsibility and this function does not pretend otherwise.
|
|
41
|
+
*/
|
|
42
|
+
export function validateStructuredData(input: unknown): StructuredDataCheck {
|
|
43
|
+
if (!Array.isArray(input)) return { ok: false, reason: 'NOT_AN_OBJECT' }
|
|
44
|
+
if (input.length > STRUCTURED_DATA_LIMITS.maxNodes) return { ok: false, reason: 'TOO_MANY_NODES' }
|
|
45
|
+
|
|
46
|
+
for (let i = 0; i < input.length; i++) {
|
|
47
|
+
const node = input[i]
|
|
48
|
+
if (typeof node !== 'object' || node === null || Array.isArray(node)) return { ok: false, reason: 'NOT_AN_OBJECT', index: i }
|
|
49
|
+
const type = (node as Record<string, unknown>)['@type']
|
|
50
|
+
if (typeof type !== 'string' || type.trim() === '') return { ok: false, reason: 'MISSING_TYPE', index: i }
|
|
51
|
+
if (depthOf(node) > STRUCTURED_DATA_LIMITS.maxDepth) return { ok: false, reason: 'TOO_DEEP', index: i }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
let serialized: string
|
|
55
|
+
try { serialized = JSON.stringify(input) } catch { return { ok: false, reason: 'NOT_SERIALIZABLE' } }
|
|
56
|
+
if (serialized === undefined) return { ok: false, reason: 'NOT_SERIALIZABLE' }
|
|
57
|
+
if (Buffer.byteLength(serialized, 'utf8') > STRUCTURED_DATA_LIMITS.maxBytes) return { ok: false, reason: 'TOO_LARGE' }
|
|
58
|
+
|
|
59
|
+
return { ok: true, nodes: input as JsonLdNode[] }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Site defaults first, the object's own nodes after, so a page's own claims
|
|
64
|
+
* read last. A node the object declares with an `@id` the site also used
|
|
65
|
+
* REPLACES it in place; anything else is appended. Two nodes of the same
|
|
66
|
+
* `@type` with no `@id` are two nodes - neither is silently dropped, because
|
|
67
|
+
* a page may legitimately carry several of a kind.
|
|
68
|
+
*/
|
|
69
|
+
export function mergeStructuredData(siteNodes: JsonLdNode[] = [], objectNodes: JsonLdNode[] = []): JsonLdNode[] {
|
|
70
|
+
const out = [...siteNodes]
|
|
71
|
+
for (const node of objectNodes) {
|
|
72
|
+
const id = typeof node['@id'] === 'string' ? node['@id'] : undefined
|
|
73
|
+
const at = id ? out.findIndex((n) => n['@id'] === id) : -1
|
|
74
|
+
if (at >= 0) out[at] = node
|
|
75
|
+
else out.push(node)
|
|
76
|
+
}
|
|
77
|
+
return out
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* JSON for a <script type="application/ld+json"> element. `<`, `>` and `&`
|
|
82
|
+
* become escapes so a value can never close the element early, and U+2028 /
|
|
83
|
+
* U+2029 become escapes because they are line terminators to a JS parser but
|
|
84
|
+
* not to JSON. The output still parses as the same JSON.
|
|
85
|
+
*/
|
|
86
|
+
export function serializeJsonLd(nodes: JsonLdNode[]): string {
|
|
87
|
+
return JSON.stringify(nodes)
|
|
88
|
+
.replace(/</g, '\\u003c')
|
|
89
|
+
.replace(/>/g, '\\u003e')
|
|
90
|
+
.replace(/&/g, '\\u0026')
|
|
91
|
+
.replace(/\u2028/g, '\\u2028')
|
|
92
|
+
.replace(/\u2029/g, '\\u2029')
|
|
93
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: titles.ts
|
|
3
|
+
* Purpose: The Titles & Meta table (plan-seo-manager-v2 V2), pure. One row
|
|
4
|
+
* per published object carrying BOTH halves of the stored payload:
|
|
5
|
+
* what visitors see now (the published snapshot) and what an editor
|
|
6
|
+
* has waiting (the draft). Tangen's publishing semantics decide the
|
|
7
|
+
* rest - an edit here writes the draft, so a row whose draft differs
|
|
8
|
+
* reads "applies on publish" rather than pretending to be live.
|
|
9
|
+
* The state an editor filters on is the state of the LIVE values.
|
|
10
|
+
*
|
|
11
|
+
* Author: Raghunath J
|
|
12
|
+
* License: MIT
|
|
13
|
+
*/
|
|
14
|
+
import { analyzeMetaDescLength, analyzeTitleLength, type SeoScore } from './seo-analysis'
|
|
15
|
+
import { pickMetadata, readStored } from './metadata'
|
|
16
|
+
|
|
17
|
+
/** The title and description of one half of the payload. */
|
|
18
|
+
export interface TitleValues {
|
|
19
|
+
title: string | null
|
|
20
|
+
description: string | null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type TitleState = 'good' | 'needs-work' | 'missing'
|
|
24
|
+
|
|
25
|
+
export interface TitleRow {
|
|
26
|
+
id: string
|
|
27
|
+
type: string
|
|
28
|
+
/** The object's own title, which is what a missing SEO title falls back to. */
|
|
29
|
+
objectTitle: string | null
|
|
30
|
+
/** What a visitor sees now. */
|
|
31
|
+
published: TitleValues
|
|
32
|
+
/** What an editor has waiting; equal to `published` when there is nothing pending. */
|
|
33
|
+
draft: TitleValues
|
|
34
|
+
/** True when the draft says something the published snapshot does not: it applies on publish. */
|
|
35
|
+
pending: boolean
|
|
36
|
+
state: TitleState
|
|
37
|
+
/** The live values' checks, in the panel's words. */
|
|
38
|
+
issues: string[]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const TITLE_STATES: readonly TitleState[] = ['good', 'needs-work', 'missing']
|
|
42
|
+
/** `attention` is not a state a row has; it is every state except `good`. */
|
|
43
|
+
export const ATTENTION_STATE = 'attention'
|
|
44
|
+
export type TitleStateFilter = TitleState | typeof ATTENTION_STATE
|
|
45
|
+
/** Rows per page on Titles & Meta, and the server's default limit for the route. */
|
|
46
|
+
export const TITLES_PAGE_SIZE = 25
|
|
47
|
+
|
|
48
|
+
const text = (v: unknown): string | null => {
|
|
49
|
+
const s = typeof v === 'string' ? v.trim() : ''
|
|
50
|
+
return s || null
|
|
51
|
+
}
|
|
52
|
+
const valuesOf = (meta: { title?: string | null; description?: string | null } | null | undefined): TitleValues =>
|
|
53
|
+
({ title: text(meta?.title), description: text(meta?.description) })
|
|
54
|
+
|
|
55
|
+
const same = (a: TitleValues, b: TitleValues): boolean => a.title === b.title && a.description === b.description
|
|
56
|
+
|
|
57
|
+
/** One published object's row from its stored payload. */
|
|
58
|
+
export function titleRowOf(input: { id: string; type: string; title: string | null; stored: unknown; locale?: string | null }): TitleRow {
|
|
59
|
+
const stored = readStored(input.stored)
|
|
60
|
+
const published = valuesOf(stored.published ? pickMetadata(stored.published, input.locale ?? null) : null)
|
|
61
|
+
const draft = valuesOf(pickMetadata(stored.draft, input.locale ?? null))
|
|
62
|
+
const effectiveTitle = published.title ?? text(input.title) ?? ''
|
|
63
|
+
const checks = [analyzeTitleLength(effectiveTitle), analyzeMetaDescLength(published.description ?? '')]
|
|
64
|
+
const worst: SeoScore = checks.some((c) => c.score === 'poor') ? 'poor' : checks.some((c) => c.score === 'ok') ? 'ok' : 'good'
|
|
65
|
+
const state: TitleState = !published.title && !published.description ? 'missing' : worst === 'good' ? 'good' : 'needs-work'
|
|
66
|
+
return {
|
|
67
|
+
id: input.id, type: input.type, objectTitle: text(input.title),
|
|
68
|
+
published, draft, pending: !same(published, draft), state,
|
|
69
|
+
issues: checks.filter((c) => c.score !== 'good').map((c) => c.message),
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The table's own filtering: by type, by the live state, and a substring of the path-free text an editor can see. */
|
|
74
|
+
export function filterTitleRows(rows: readonly TitleRow[], opts: { type?: string | null; state?: string | null; search?: string | null } = {}): TitleRow[] {
|
|
75
|
+
const needle = (opts.search ?? '').trim().toLowerCase()
|
|
76
|
+
const attention = opts.state === ATTENTION_STATE
|
|
77
|
+
const state = TITLE_STATES.includes(opts.state as TitleState) ? (opts.state as TitleState) : null
|
|
78
|
+
return rows.filter((r) => {
|
|
79
|
+
if (opts.type && r.type !== opts.type) return false
|
|
80
|
+
if (attention && r.state === 'good') return false
|
|
81
|
+
if (state && r.state !== state) return false
|
|
82
|
+
if (!needle) return true
|
|
83
|
+
return [r.objectTitle, r.published.title, r.published.description, r.draft.title, r.draft.description, r.id]
|
|
84
|
+
.some((v) => typeof v === 'string' && v.toLowerCase().includes(needle))
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type TitleSort = 'page' | 'title' | 'state'
|
|
89
|
+
|
|
90
|
+
const STATE_ORDER: Record<TitleState, number> = { missing: 0, 'needs-work': 1, good: 2 }
|
|
91
|
+
|
|
92
|
+
/** The table's order: the page's own title, the SEO title, or the state (worst first). */
|
|
93
|
+
export function sortTitleRows(rows: readonly TitleRow[], opts: { sort?: TitleSort; desc?: boolean } = {}): TitleRow[] {
|
|
94
|
+
const sort = opts.sort ?? 'page'
|
|
95
|
+
const desc = opts.desc ?? false
|
|
96
|
+
const key = (r: TitleRow): string => (sort === 'title' ? r.published.title ?? '' : `${r.objectTitle ?? r.id}`)
|
|
97
|
+
const compare = (a: TitleRow, b: TitleRow): number => {
|
|
98
|
+
const first = sort === 'state' ? STATE_ORDER[a.state] - STATE_ORDER[b.state] : key(a).localeCompare(key(b))
|
|
99
|
+
return (desc ? -first : first) || (a.objectTitle ?? a.id).localeCompare(b.objectTitle ?? b.id)
|
|
100
|
+
}
|
|
101
|
+
return [...rows].sort(compare)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** How many rows sit in each state, for the filter chips. */
|
|
105
|
+
export function countTitleStates(rows: readonly TitleRow[]): Record<TitleState, number> {
|
|
106
|
+
const counts: Record<TitleState, number> = { good: 0, 'needs-work': 0, missing: 0 }
|
|
107
|
+
for (const r of rows) counts[r.state] += 1
|
|
108
|
+
return counts
|
|
109
|
+
}
|
package/src/nextjs.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: nextjs.ts
|
|
3
|
+
* Purpose: The SEO extension's Next.js helpers (plan-seo-next Phase 6). Turn the
|
|
4
|
+
* resolved SEO into a Next.js Metadata object and a JSON-LD script
|
|
5
|
+
* string, so a site's generateMetadata is one call. Pure functions
|
|
6
|
+
* over the extension's own `ResolvedSeo` - no core package touched, and
|
|
7
|
+
* the Metadata shape is structural (no dependency on `next`).
|
|
8
|
+
*
|
|
9
|
+
* Author: Raghunath J
|
|
10
|
+
* License: MIT
|
|
11
|
+
*/
|
|
12
|
+
import type { ResolvedSeo } from './contract'
|
|
13
|
+
|
|
14
|
+
/** A structural subset of Next.js `Metadata` - what the SEO adapter fills. */
|
|
15
|
+
export interface NextSeoMetadata {
|
|
16
|
+
title?: string
|
|
17
|
+
description?: string
|
|
18
|
+
alternates?: { canonical?: string; languages?: Record<string, string> }
|
|
19
|
+
robots?: { index: boolean; follow: boolean }
|
|
20
|
+
openGraph?: { title?: string; description?: string; images?: Array<string | { url: string; alt?: string }>; type?: string; url?: string }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Map resolved SEO to Next.js Metadata. Absent sections are omitted (never
|
|
25
|
+
* blanked); `null` (no published SEO) yields `{}` so the page's static defaults
|
|
26
|
+
* apply. Structured data is NOT here - Next.js Metadata has no JSON-LD slot;
|
|
27
|
+
* render it with `seoJsonLd` in a script tag.
|
|
28
|
+
*/
|
|
29
|
+
export function seoToMetadata(seo: ResolvedSeo | null | undefined): NextSeoMetadata {
|
|
30
|
+
if (!seo) return {}
|
|
31
|
+
const md: NextSeoMetadata = {}
|
|
32
|
+
if (seo.title) md.title = seo.title
|
|
33
|
+
if (seo.description) md.description = seo.description
|
|
34
|
+
|
|
35
|
+
const alternates: NonNullable<NextSeoMetadata['alternates']> = {}
|
|
36
|
+
if (seo.canonical) alternates.canonical = seo.canonical
|
|
37
|
+
if (seo.alternates?.length) {
|
|
38
|
+
alternates.languages = Object.fromEntries(seo.alternates.map((a) => [a.hreflang, a.href]))
|
|
39
|
+
}
|
|
40
|
+
if (Object.keys(alternates).length) md.alternates = alternates
|
|
41
|
+
|
|
42
|
+
md.robots = { index: seo.robots.index, follow: seo.robots.follow }
|
|
43
|
+
|
|
44
|
+
if (seo.openGraph) {
|
|
45
|
+
const og: NonNullable<NextSeoMetadata['openGraph']> = {}
|
|
46
|
+
if (seo.openGraph.title) og.title = seo.openGraph.title
|
|
47
|
+
if (seo.openGraph.description) og.description = seo.openGraph.description
|
|
48
|
+
// An alt text rides on the image entry (Next renders it as og:image:alt); a bare image stays the plain string form.
|
|
49
|
+
if (seo.openGraph.image) og.images = [seo.openGraph.imageAlt ? { url: seo.openGraph.image, alt: seo.openGraph.imageAlt } : seo.openGraph.image]
|
|
50
|
+
if (seo.openGraph.type) og.type = seo.openGraph.type
|
|
51
|
+
if (seo.openGraph.url) og.url = seo.openGraph.url
|
|
52
|
+
if (Object.keys(og).length) md.openGraph = og
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return md
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The JSON-LD for a `<script type="application/ld+json">`. A single node is
|
|
60
|
+
* emitted under @context; several become a @graph. Empty string when there is
|
|
61
|
+
* nothing to emit, so the caller can skip the script tag.
|
|
62
|
+
*/
|
|
63
|
+
export function seoJsonLd(seo: ResolvedSeo | null | undefined): string {
|
|
64
|
+
const nodes = seo?.structuredData ?? []
|
|
65
|
+
if (nodes.length === 0) return ''
|
|
66
|
+
const payload = nodes.length === 1
|
|
67
|
+
? { '@context': 'https://schema.org', ...nodes[0] }
|
|
68
|
+
: { '@context': 'https://schema.org', '@graph': nodes }
|
|
69
|
+
return JSON.stringify(payload)
|
|
70
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: AiGeoTab.tsx
|
|
3
|
+
* Purpose: AI & GEO (plan-seo-manager-v2 V6): how AI answer engines read the
|
|
4
|
+
* site (the llms.txt manifest, from the GEO panel) and what this
|
|
5
|
+
* installation's AI can do for SEO - writing a page's metadata as a
|
|
6
|
+
* draft for review, and describing a share image. Each ability says
|
|
7
|
+
* whether it is available and, when it is not, exactly what is
|
|
8
|
+
* missing. No bulk control is shown, because none is built.
|
|
9
|
+
*
|
|
10
|
+
* Author: Raghunath J
|
|
11
|
+
* License: MIT
|
|
12
|
+
*/
|
|
13
|
+
import { useEffect, useState } from 'react'
|
|
14
|
+
import { Link, useParams } from 'react-router-dom'
|
|
15
|
+
import { AdminPage, FormSection, Panel, Text, adminFetch, TEXT_LINK } from '@/kit'
|
|
16
|
+
import { GeoPanel } from './GeoTab'
|
|
17
|
+
import { seoManagerHref } from '../lib/seo-manager-nav'
|
|
18
|
+
|
|
19
|
+
interface Ability { available: boolean; provider?: string; reason?: string }
|
|
20
|
+
|
|
21
|
+
export function SeoAiGeoPage() {
|
|
22
|
+
const { workspaceId = '' } = useParams<{ workspaceId: string }>()
|
|
23
|
+
const [status, setStatus] = useState<{ generate: Ability; vision: Ability } | null>(null)
|
|
24
|
+
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
let alive = true
|
|
27
|
+
adminFetch<{ data: { generate: Ability; vision: Ability } }>('/admin/ext/seo/ai-status')
|
|
28
|
+
.then((r) => { if (alive) setStatus(r.data) })
|
|
29
|
+
.catch(() => { if (alive) setStatus(null) })
|
|
30
|
+
return () => { alive = false }
|
|
31
|
+
}, [])
|
|
32
|
+
|
|
33
|
+
return (
|
|
34
|
+
<AdminPage
|
|
35
|
+
title="AI & GEO"
|
|
36
|
+
description="How AI answer engines read the site, and what your AI provider can write for it."
|
|
37
|
+
access={{ capability: 'seo:read' }}
|
|
38
|
+
>
|
|
39
|
+
<div className="space-y-6">
|
|
40
|
+
<GeoPanel />
|
|
41
|
+
<FormSection title="What AI can do here" description="Each ability needs a permission and a provider. Where one is missing, the control is absent rather than broken.">
|
|
42
|
+
<div className="space-y-3">
|
|
43
|
+
<Ability
|
|
44
|
+
title="Write a page's metadata"
|
|
45
|
+
body={<>Proposes an SEO title, meta description and answer summary for one page. The proposal is a <strong>draft</strong>: it reaches visitors only when the page is published. Use it from <Link className={TEXT_LINK} to={seoManagerHref(workspaceId, 'titles')}>Titles & Meta</Link> or the page's own SEO panel.</>}
|
|
46
|
+
ability={status?.generate}
|
|
47
|
+
/>
|
|
48
|
+
<Ability
|
|
49
|
+
title="Describe a share image"
|
|
50
|
+
body={<>Writes the alt text for a page's Open Graph image from the image itself, in the page's SEO panel.</>}
|
|
51
|
+
ability={status?.vision}
|
|
52
|
+
/>
|
|
53
|
+
</div>
|
|
54
|
+
<Text variant="help">
|
|
55
|
+
Running either over many pages at once is not built yet. When it is, it will run this same action per page and leave every result as a draft for review.
|
|
56
|
+
</Text>
|
|
57
|
+
</FormSection>
|
|
58
|
+
</div>
|
|
59
|
+
</AdminPage>
|
|
60
|
+
)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function Ability({ title, body, ability }: { title: string; body: React.ReactNode; ability?: Ability }) {
|
|
64
|
+
const state = ability === undefined ? 'unknown' : ability.available ? 'on' : 'off'
|
|
65
|
+
return (
|
|
66
|
+
<Panel>
|
|
67
|
+
<div className="flex items-center gap-2">
|
|
68
|
+
<span className={`size-2 rounded-full ${state === 'on' ? 'bg-success' : state === 'off' ? 'bg-fg-faint' : 'bg-border-strong'}`} aria-hidden="true" />
|
|
69
|
+
<p className="text-sm font-semibold text-fg">{title}</p>
|
|
70
|
+
<span className="ml-auto text-[11px] font-semibold text-fg-subtle">
|
|
71
|
+
{state === 'on' ? `Ready · ${ability!.provider}` : state === 'off' ? 'Unavailable' : 'Checking'}
|
|
72
|
+
</span>
|
|
73
|
+
</div>
|
|
74
|
+
<p className="mt-1.5 text-ui-xs text-fg-subtle">{body}</p>
|
|
75
|
+
{state === 'off' && <p className="mt-1.5 text-ui-xs text-fg-muted">{ability!.reason}</p>}
|
|
76
|
+
</Panel>
|
|
77
|
+
)
|
|
78
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: AnalyticsTab.tsx
|
|
3
|
+
* Purpose: The Analytics page (plan-seo-manager-v2 V4): what Search Console
|
|
4
|
+
* reported, read from the stored daily aggregates - totals with the
|
|
5
|
+
* window before them, a click sparkline, the top pages and the top
|
|
6
|
+
* queries. Nothing is shown that was not synced: without a
|
|
7
|
+
* connection or a property the page says what to do instead of
|
|
8
|
+
* showing zeroes, and Sync now is the only thing that calls Google.
|
|
9
|
+
*
|
|
10
|
+
* Author: Raghunath J
|
|
11
|
+
* License: MIT
|
|
12
|
+
*/
|
|
13
|
+
import { useCallback, useEffect, useState } from 'react'
|
|
14
|
+
import { Link, useParams } from 'react-router-dom'
|
|
15
|
+
import { AdminPage, Button, Callout, Panel, Text, adminFetch, toast, useCan, TEXT_LINK } from '@/kit'
|
|
16
|
+
import { IconRefresh } from '@tangen/icons'
|
|
17
|
+
import { changeOf, syncNotice, type Summary, type TopRow, type Totals } from '../lib/analytics'
|
|
18
|
+
import { seoManagerHref } from '../lib/seo-manager-nav'
|
|
19
|
+
|
|
20
|
+
interface Connection { connected: boolean; label?: string; property?: string | null; reason?: string }
|
|
21
|
+
export interface AnalyticsViewData {
|
|
22
|
+
days: number
|
|
23
|
+
summary: Summary | null
|
|
24
|
+
pages: TopRow[]
|
|
25
|
+
queries: TopRow[]
|
|
26
|
+
sync: { lastSyncedAt?: string; lastError?: string | null; lastErrorKind?: 'connection' | 'property' | 'provider'; lastErrorAt?: string; intervalHours: number }
|
|
27
|
+
connection: Connection
|
|
28
|
+
limits: { retentionDays: number; rowLimit: number }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const RANGES = [7, 28, 90] as const
|
|
32
|
+
|
|
33
|
+
export function SeoAnalyticsPage() {
|
|
34
|
+
const { workspaceId = '' } = useParams<{ workspaceId: string }>()
|
|
35
|
+
const { hasCapability } = useCan()
|
|
36
|
+
const canWrite = hasCapability('seo:write')
|
|
37
|
+
const [days, setDays] = useState<number>(28)
|
|
38
|
+
const [view, setView] = useState<AnalyticsViewData | null>(null)
|
|
39
|
+
const [loading, setLoading] = useState(true)
|
|
40
|
+
const [busy, setBusy] = useState(false)
|
|
41
|
+
|
|
42
|
+
const load = useCallback(async (span: number) => {
|
|
43
|
+
try {
|
|
44
|
+
const r = await adminFetch<{ data: AnalyticsViewData }>(`/admin/ext/seo/analytics?days=${span}`)
|
|
45
|
+
setView(r.data)
|
|
46
|
+
} catch (e) {
|
|
47
|
+
toast.error(e instanceof Error ? e.message : 'Analytics could not be loaded')
|
|
48
|
+
}
|
|
49
|
+
}, [])
|
|
50
|
+
useEffect(() => { load(days).finally(() => setLoading(false)) }, [days, load])
|
|
51
|
+
|
|
52
|
+
const sync = async () => {
|
|
53
|
+
setBusy(true)
|
|
54
|
+
try {
|
|
55
|
+
const r = await adminFetch<{ data?: { days: number }; error?: { message: string } }>('/admin/ext/seo/analytics/sync', { method: 'POST' })
|
|
56
|
+
if (r.error) toast.error(r.error.message)
|
|
57
|
+
else { toast.success(`Synced ${r.data?.days ?? 0} days from Search Console`); await load(days) }
|
|
58
|
+
} catch (e) {
|
|
59
|
+
toast.error(e instanceof Error ? e.message : 'The sync could not run')
|
|
60
|
+
} finally { setBusy(false) }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return (
|
|
64
|
+
<AdminPage
|
|
65
|
+
title="Analytics"
|
|
66
|
+
description="Clicks, impressions and positions from Google Search Console."
|
|
67
|
+
access={{ capability: 'seo:read' }}
|
|
68
|
+
loading={loading}
|
|
69
|
+
actions={canWrite && view?.connection.connected
|
|
70
|
+
? <Button size="sm" variant="secondary" icon={<IconRefresh className="size-3.5" />} disabled={busy} onClick={sync}>{busy ? 'Syncing' : 'Sync now'}</Button>
|
|
71
|
+
: undefined}
|
|
72
|
+
toolbar={view?.connection.connected ? (
|
|
73
|
+
<div className="flex items-center gap-1.5">
|
|
74
|
+
{RANGES.map((r) => (
|
|
75
|
+
<Button key={r} size="xs" variant={r === view.days ? 'primary' : 'ghost'} onClick={() => setDays(r)}>Last {r} days</Button>
|
|
76
|
+
))}
|
|
77
|
+
</div>
|
|
78
|
+
) : undefined}
|
|
79
|
+
>
|
|
80
|
+
{view && (
|
|
81
|
+
<div className="space-y-4">
|
|
82
|
+
{(() => {
|
|
83
|
+
// ONE notice, from one rule: what blocks a sync now outranks what
|
|
84
|
+
// failed before, and a failure whose cause is gone reads as
|
|
85
|
+
// history with an action (the user, 2026-09-20).
|
|
86
|
+
const notice = syncNotice({ sync: view.sync, connection: view.connection })
|
|
87
|
+
if (!notice) return null
|
|
88
|
+
return (
|
|
89
|
+
<Callout
|
|
90
|
+
variant={notice.kind === 'failed' ? 'danger' : notice.kind === 'stale' ? 'info' : view.connection.connected ? 'warning' : 'info'}
|
|
91
|
+
title={notice.title}
|
|
92
|
+
>
|
|
93
|
+
<p>{notice.message}</p>
|
|
94
|
+
{notice.at && <p className="mt-1 text-ui-xs text-fg-subtle">{`Recorded ${new Date(notice.at).toLocaleString()}.`}</p>}
|
|
95
|
+
{notice.kind === 'blocked' && (
|
|
96
|
+
<p className="mt-2">
|
|
97
|
+
{view.connection.connected
|
|
98
|
+
? <>Pick it on this manager's <Link className={TEXT_LINK} to={`/${workspaceId}/extensions/seo/settings`}>Settings</Link> tab, under Search Console.</>
|
|
99
|
+
: <>Add the connection under <Link className={TEXT_LINK} to={`/${workspaceId}/settings/connections`}>Settings, Connections</Link>, then choose it and the property on this manager's <Link className={TEXT_LINK} to={`/${workspaceId}/extensions/seo/settings`}>Settings</Link> tab.</>}
|
|
100
|
+
</p>
|
|
101
|
+
)}
|
|
102
|
+
</Callout>
|
|
103
|
+
)
|
|
104
|
+
})()}
|
|
105
|
+
|
|
106
|
+
{view.summary && view.summary.days > 0 ? (
|
|
107
|
+
<>
|
|
108
|
+
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
|
109
|
+
<Stat label="Clicks" summary={view.summary} metric="clicks" format={(n) => Math.round(n).toLocaleString()} />
|
|
110
|
+
<Stat label="Impressions" summary={view.summary} metric="impressions" format={(n) => Math.round(n).toLocaleString()} />
|
|
111
|
+
<Stat label="Average CTR" summary={view.summary} metric="ctr" format={(n) => `${(n * 100).toFixed(1)}%`} />
|
|
112
|
+
<Stat label="Average position" summary={view.summary} metric="position" format={(n) => n.toFixed(1)} />
|
|
113
|
+
</div>
|
|
114
|
+
<div className="grid gap-4 xl:grid-cols-2">
|
|
115
|
+
<TopTable title="Top pages" sub={`by clicks, last ${view.days} days`} rows={view.pages} />
|
|
116
|
+
<TopTable title="Top queries" sub={`by clicks, last ${view.days} days`} rows={view.queries} />
|
|
117
|
+
</div>
|
|
118
|
+
</>
|
|
119
|
+
) : view.connection.connected ? (
|
|
120
|
+
<Callout variant="info" title="Nothing synced yet">
|
|
121
|
+
Search Console data arrives with the daily sync, or press Sync now. Google reports a day about two days late.
|
|
122
|
+
</Callout>
|
|
123
|
+
) : null}
|
|
124
|
+
|
|
125
|
+
<Text variant="help">
|
|
126
|
+
{view.sync.lastSyncedAt ? `Last synced ${new Date(view.sync.lastSyncedAt).toLocaleString()}.` : 'Not synced yet.'}
|
|
127
|
+
{` Synced every ${view.sync.intervalHours} hours, keeping ${view.limits.retentionDays} days of daily totals with the top ${view.limits.rowLimit} pages and queries per day. Change either on the Settings tab.`}
|
|
128
|
+
</Text>
|
|
129
|
+
</div>
|
|
130
|
+
)}
|
|
131
|
+
</AdminPage>
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** One metric: its total, how it moved against the window before, and its daily shape. Shared with the Dashboard. */
|
|
136
|
+
export function Stat({ label, summary, metric, format }: { label: string; summary: Summary; metric: keyof Totals; format: (n: number) => string }) {
|
|
137
|
+
const change = changeOf(summary, metric)
|
|
138
|
+
return (
|
|
139
|
+
<Panel>
|
|
140
|
+
<p className="text-ui-xs font-medium text-fg-subtle">{label}</p>
|
|
141
|
+
<p className="mt-1.5 text-2xl font-semibold tracking-tight text-fg tabular-nums">{format(summary[metric])}</p>
|
|
142
|
+
{change ? (
|
|
143
|
+
<p className={`text-ui-xs font-semibold ${change.better ? 'text-success-fg' : 'text-danger-fg'}`}>
|
|
144
|
+
{change.delta >= 0 ? '+' : ''}{(change.delta * 100).toFixed(1)}% <span className="font-medium text-fg-faint">vs previous {summary.days} days</span>
|
|
145
|
+
</p>
|
|
146
|
+
) : (
|
|
147
|
+
<p className="text-ui-xs text-fg-subtle">No earlier window to compare</p>
|
|
148
|
+
)}
|
|
149
|
+
<Sparkline values={summary.series} className="mt-2.5" />
|
|
150
|
+
</Panel>
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** A line over the window, scaled to its own range; flat when everything is equal. */
|
|
155
|
+
function Sparkline({ values, className = '' }: { values: number[]; className?: string }) {
|
|
156
|
+
if (values.length < 2) return <div className={`h-8 ${className}`} />
|
|
157
|
+
const w = 180, h = 32, max = Math.max(...values), min = Math.min(...values)
|
|
158
|
+
const span = max - min || 1
|
|
159
|
+
const step = w / (values.length - 1)
|
|
160
|
+
const d = values.map((v, i) => `${i ? 'L' : 'M'}${(i * step).toFixed(1)} ${(h - ((v - min) / span) * (h - 4) - 2).toFixed(1)}`).join(' ')
|
|
161
|
+
return (
|
|
162
|
+
<svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" className={`h-8 w-full text-accent ${className}`} aria-hidden="true">
|
|
163
|
+
<path d={`${d} L${w} ${h} L0 ${h} Z`} fill="currentColor" opacity="0.12" />
|
|
164
|
+
<path d={d} fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
|
|
165
|
+
</svg>
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function TopTable({ title, sub, rows }: { title: string; sub: string; rows: TopRow[] }) {
|
|
170
|
+
return (
|
|
171
|
+
<Panel flush>
|
|
172
|
+
<div className="flex items-baseline gap-2 p-5 pb-3">
|
|
173
|
+
<h3 className="text-sm font-semibold text-fg">{title}</h3>
|
|
174
|
+
<span className="text-ui-xs text-fg-subtle">{sub}</span>
|
|
175
|
+
</div>
|
|
176
|
+
{rows.length === 0 ? (
|
|
177
|
+
<p className="px-5 pb-5 text-ui-xs text-fg-subtle">Nothing reported for this window.</p>
|
|
178
|
+
) : (
|
|
179
|
+
<ul className="divide-y divide-border-subtle">
|
|
180
|
+
{rows.map((r) => (
|
|
181
|
+
<li key={r.key} className="flex items-center gap-3 px-5 py-2.5">
|
|
182
|
+
<span className="min-w-0 flex-1 truncate text-ui-xs font-medium text-fg" title={r.key}>{r.key}</span>
|
|
183
|
+
<span className="w-16 shrink-0 text-right text-ui-xs font-semibold text-fg tabular-nums">{r.clicks.toLocaleString()}</span>
|
|
184
|
+
<span className="w-14 shrink-0 text-right text-ui-xs text-fg-subtle tabular-nums">{r.position.toFixed(1)}</span>
|
|
185
|
+
<span className="w-20 shrink-0"><Sparkline values={r.series} /></span>
|
|
186
|
+
</li>
|
|
187
|
+
))}
|
|
188
|
+
</ul>
|
|
189
|
+
)}
|
|
190
|
+
</Panel>
|
|
191
|
+
)
|
|
192
|
+
}
|