@tangen/ext-seo 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: object-url.ts
|
|
3
|
+
* Purpose: One place that answers "what is this object's URL", for a site that
|
|
4
|
+
* routes by a FIELD rather than by the slug. The site declares the
|
|
5
|
+
* field per type (`urlField: { page: 'path' }`); Tangen reads that one
|
|
6
|
+
* field - never the whole object - and, with `siteUrl`, that is the
|
|
7
|
+
* whole answer. An explicit `resolveUrl` still wins, and receives the
|
|
8
|
+
* field's value so it can prefix or localise it. Pure.
|
|
9
|
+
*
|
|
10
|
+
* Author: Raghunath J
|
|
11
|
+
* License: MIT
|
|
12
|
+
*/
|
|
13
|
+
import type { SeoHelpers } from '../contract'
|
|
14
|
+
import { validateCanonical } from './canonical'
|
|
15
|
+
|
|
16
|
+
/** The field this type's URL lives in, when the site declared one. */
|
|
17
|
+
export function urlFieldName(helpers: SeoHelpers | undefined, type: string): string | null {
|
|
18
|
+
const declared = helpers?.urlField
|
|
19
|
+
if (!declared) return null
|
|
20
|
+
if (typeof declared === 'string') return declared.trim() || null
|
|
21
|
+
const own = declared[type]
|
|
22
|
+
return typeof own === 'string' && own.trim() ? own.trim() : null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The declared field's value for one object: a path, or null. Only ever reads
|
|
27
|
+
* the ONE field the site named, and only accepts what could be a path - a
|
|
28
|
+
* stray title or an id is not a URL.
|
|
29
|
+
*/
|
|
30
|
+
export function urlFieldValue(helpers: SeoHelpers | undefined, type: string, row: Record<string, unknown> | null | undefined): string | null {
|
|
31
|
+
const field = urlFieldName(helpers, type)
|
|
32
|
+
if (!field || !row) return null
|
|
33
|
+
const raw = row[field]
|
|
34
|
+
if (typeof raw !== 'string') return null
|
|
35
|
+
const value = raw.trim()
|
|
36
|
+
if (!value || !value.startsWith('/') || value.startsWith('//')) return null
|
|
37
|
+
return value
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The site's origin without a trailing slash, or null when it declared none. */
|
|
41
|
+
const originOf = (helpers: SeoHelpers | undefined): string | null => {
|
|
42
|
+
const site = helpers?.siteUrl?.trim()
|
|
43
|
+
return site ? site.replace(/\/+$/, '') : null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ObjectUrlInput {
|
|
47
|
+
helpers: SeoHelpers | undefined
|
|
48
|
+
workspaceId: string
|
|
49
|
+
type: string
|
|
50
|
+
id: string
|
|
51
|
+
locale?: string | null
|
|
52
|
+
slug?: string | null
|
|
53
|
+
/** The declared field's value, already read by the caller (it holds the row). */
|
|
54
|
+
fieldValue?: string | null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The object's absolute URL: the site's own resolver first, then the declared
|
|
59
|
+
* field under the site's origin. Null means "this object has no page", which
|
|
60
|
+
* every caller treats as a reason to omit it rather than invent an address.
|
|
61
|
+
*/
|
|
62
|
+
export async function objectUrl(input: ObjectUrlInput): Promise<string | null> {
|
|
63
|
+
const identity = {
|
|
64
|
+
workspaceId: input.workspaceId, type: input.type, id: input.id,
|
|
65
|
+
locale: input.locale ?? null, slug: input.slug ?? null,
|
|
66
|
+
...(input.fieldValue ? { fieldValue: input.fieldValue } : {}),
|
|
67
|
+
}
|
|
68
|
+
const resolver = input.helpers?.resolveUrl
|
|
69
|
+
if (resolver) {
|
|
70
|
+
try {
|
|
71
|
+
const answer = await resolver(identity)
|
|
72
|
+
if (answer) return answer
|
|
73
|
+
} catch { /* a site resolver that throws must not take the page down */ }
|
|
74
|
+
}
|
|
75
|
+
// The convention: the declared field IS the path, under the declared origin.
|
|
76
|
+
const origin = originOf(input.helpers)
|
|
77
|
+
if (origin && input.fieldValue) {
|
|
78
|
+
const candidate = `${origin}${input.fieldValue}`
|
|
79
|
+
const checked = validateCanonical(candidate)
|
|
80
|
+
if (checked.ok) return checked.url
|
|
81
|
+
}
|
|
82
|
+
return null
|
|
83
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: optimize.ts
|
|
3
|
+
* Purpose: The AI optimisation action's pure half (plan-seo-manager-v2 V6,
|
|
4
|
+
* user decision 5): the JSON schema a provider is constrained to,
|
|
5
|
+
* the prompt, and the cleaning of what comes back into values the
|
|
6
|
+
* codec would accept. One object's worth at a time - a later bulk
|
|
7
|
+
* run calls the same action per object, so nothing here knows how
|
|
8
|
+
* many objects there are.
|
|
9
|
+
*
|
|
10
|
+
* Author: Raghunath J
|
|
11
|
+
* License: MIT
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** What the provider must return, and nothing else. */
|
|
15
|
+
export const OPTIMIZE_SCHEMA: Record<string, unknown> = {
|
|
16
|
+
type: 'object',
|
|
17
|
+
additionalProperties: false,
|
|
18
|
+
required: ['title', 'description'],
|
|
19
|
+
properties: {
|
|
20
|
+
title: { type: 'string', description: 'An SEO title of 50 to 60 characters. No quotes, no site name suffix.' },
|
|
21
|
+
description: { type: 'string', description: 'A meta description of 120 to 160 characters, plain text, one or two sentences.' },
|
|
22
|
+
answerSummary: { type: 'string', description: 'Two to four factual sentences an AI answer engine could cite. Optional.' },
|
|
23
|
+
},
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const OPTIMIZE_SYSTEM = 'You write search metadata for a real web page. Be specific and factual, never promotional. Use the page\'s own words and facts; invent nothing that is not in the content.'
|
|
27
|
+
|
|
28
|
+
export interface OptimizeInput {
|
|
29
|
+
title?: string | null
|
|
30
|
+
content?: string | null
|
|
31
|
+
focusKeyword?: string | null
|
|
32
|
+
locale?: string | null
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The prompt for one page. Content is trimmed: a provider does not need the whole body to title it. */
|
|
36
|
+
export function optimizePrompt(input: OptimizeInput): string {
|
|
37
|
+
const lines = [`Page title: ${input.title?.trim() || '(untitled)'}`]
|
|
38
|
+
if (input.focusKeyword?.trim()) lines.push(`Focus keyphrase to include naturally: ${input.focusKeyword.trim()}`)
|
|
39
|
+
if (input.locale) lines.push(`Write in the locale: ${input.locale}`)
|
|
40
|
+
const content = (input.content ?? '').replace(/\s+/g, ' ').trim().slice(0, 4000)
|
|
41
|
+
if (content) lines.push(`Page content: ${content}`)
|
|
42
|
+
lines.push('Write the SEO title, the meta description, and an answer summary for this page.')
|
|
43
|
+
return lines.join('\n')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface SeoProposal {
|
|
47
|
+
title?: string
|
|
48
|
+
description?: string
|
|
49
|
+
answerSummary?: string
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const TITLE_MAX = 70
|
|
53
|
+
const DESCRIPTION_MAX = 180
|
|
54
|
+
const ANSWER_MAX = 600
|
|
55
|
+
|
|
56
|
+
function oneLine(value: unknown, max: number): string | undefined {
|
|
57
|
+
if (typeof value !== 'string') return undefined
|
|
58
|
+
let text = value.replace(/\s+/g, ' ').trim().replace(/^["'“”‘’]+|["'“”‘’]+$/g, '').trim()
|
|
59
|
+
if (!text) return undefined
|
|
60
|
+
if (text.length > max) {
|
|
61
|
+
const cut = text.slice(0, max)
|
|
62
|
+
const atWord = cut.lastIndexOf(' ')
|
|
63
|
+
text = (atWord > max / 2 ? cut.slice(0, atWord) : cut).replace(/[\s,;:]+$/, '')
|
|
64
|
+
}
|
|
65
|
+
return text || undefined
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** What a provider answered, reduced to values the SEO codec would store. */
|
|
69
|
+
export function cleanProposal(raw: unknown): SeoProposal {
|
|
70
|
+
if (!raw || typeof raw !== 'object') return {}
|
|
71
|
+
const value = raw as Record<string, unknown>
|
|
72
|
+
const out: SeoProposal = {}
|
|
73
|
+
const title = oneLine(value.title, TITLE_MAX); if (title) out.title = title
|
|
74
|
+
const description = oneLine(value.description, DESCRIPTION_MAX); if (description) out.description = description
|
|
75
|
+
const answer = oneLine(value.answerSummary, ANSWER_MAX); if (answer) out.answerSummary = answer
|
|
76
|
+
return out
|
|
77
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: redirects-csv.ts
|
|
3
|
+
* Purpose: Redirects as a spreadsheet (plan-seo-manager-v2 V7), pure. Three
|
|
4
|
+
* columns - from, to, status - which is what an operator migrating
|
|
5
|
+
* from another CMS already has. Parsing is strict about the shape
|
|
6
|
+
* and honest about every row it could not read: a partial import
|
|
7
|
+
* says which line failed and why, rather than dropping it quietly.
|
|
8
|
+
*
|
|
9
|
+
* Author: Raghunath J
|
|
10
|
+
* License: MIT
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const REDIRECT_CSV_HEADER = 'from,to,status'
|
|
14
|
+
|
|
15
|
+
export interface CsvRedirect {
|
|
16
|
+
source: string
|
|
17
|
+
url: string
|
|
18
|
+
status: 301 | 302
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface CsvParse {
|
|
22
|
+
rows: CsvRedirect[]
|
|
23
|
+
/** One per line that could not be read, in file order. */
|
|
24
|
+
errors: Array<{ line: number; message: string }>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const quote = (value: string): string => (/[",\n\r]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value)
|
|
28
|
+
|
|
29
|
+
/** Every redirect as a CSV file, header first. An internal destination is exported as the resolved URL when there is one. */
|
|
30
|
+
export function toRedirectCsv(rows: ReadonlyArray<{ source: string; destination: { kind: string; url?: string }; status: number }>): string {
|
|
31
|
+
const lines = [REDIRECT_CSV_HEADER]
|
|
32
|
+
for (const row of rows) {
|
|
33
|
+
lines.push([quote(row.source), quote(row.destination?.url ?? ''), String(row.status === 302 ? 302 : 301)].join(','))
|
|
34
|
+
}
|
|
35
|
+
return `${lines.join('\n')}\n`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One CSV line into fields, honouring quotes and doubled quotes. */
|
|
39
|
+
function splitLine(line: string): string[] {
|
|
40
|
+
const out: string[] = []
|
|
41
|
+
let field = ''
|
|
42
|
+
let quoted = false
|
|
43
|
+
for (let i = 0; i < line.length; i++) {
|
|
44
|
+
const ch = line[i]!
|
|
45
|
+
if (quoted) {
|
|
46
|
+
if (ch === '"') {
|
|
47
|
+
if (line[i + 1] === '"') { field += '"'; i += 1 } else quoted = false
|
|
48
|
+
} else field += ch
|
|
49
|
+
} else if (ch === '"') quoted = true
|
|
50
|
+
else if (ch === ',') { out.push(field); field = '' }
|
|
51
|
+
else field += ch
|
|
52
|
+
}
|
|
53
|
+
out.push(field)
|
|
54
|
+
return out.map((f) => f.trim())
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A CSV file into redirects. The header is optional but respected when
|
|
59
|
+
* present; a row needs a from and a to, and a status that is 301 or 302
|
|
60
|
+
* (301 when it is absent).
|
|
61
|
+
*/
|
|
62
|
+
export function parseRedirectCsv(text: string): CsvParse {
|
|
63
|
+
const rows: CsvRedirect[] = []
|
|
64
|
+
const errors: CsvParse['errors'] = []
|
|
65
|
+
const lines = String(text ?? '').split(/\r?\n/)
|
|
66
|
+
const seen = new Set<string>()
|
|
67
|
+
lines.forEach((raw, index) => {
|
|
68
|
+
const line = raw.trim()
|
|
69
|
+
if (!line) return
|
|
70
|
+
const lineNumber = index + 1
|
|
71
|
+
const fields = splitLine(line)
|
|
72
|
+
const [from, to, status] = fields
|
|
73
|
+
if (index === 0 && from?.toLowerCase() === 'from') return
|
|
74
|
+
if (!from || !to) { errors.push({ line: lineNumber, message: 'needs a from and a to' }); return }
|
|
75
|
+
if (!from.startsWith('/')) { errors.push({ line: lineNumber, message: `from must be a path starting with "/" (got "${from}")` }); return }
|
|
76
|
+
if (!/^https?:\/\//i.test(to)) { errors.push({ line: lineNumber, message: `to must be an http or https URL (got "${to}")` }); return }
|
|
77
|
+
const code = status ? Number(status) : 301
|
|
78
|
+
if (code !== 301 && code !== 302) { errors.push({ line: lineNumber, message: `status must be 301 or 302 (got "${status}")` }); return }
|
|
79
|
+
if (seen.has(from)) { errors.push({ line: lineNumber, message: `"${from}" appears more than once in this file` }); return }
|
|
80
|
+
seen.add(from)
|
|
81
|
+
rows.push({ source: from, url: to, status: code })
|
|
82
|
+
})
|
|
83
|
+
return { rows, errors }
|
|
84
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: redirects.ts
|
|
3
|
+
* Purpose: The redirect model and its safety rules (closure plan Phase 9A,
|
|
4
|
+
* Unit 8). A redirect is a security surface: an open redirect sends a
|
|
5
|
+
* site's visitors wherever an attacker asked, and a loop takes a page
|
|
6
|
+
* down. Both are refused at write time.
|
|
7
|
+
*
|
|
8
|
+
* Author: Raghunath J
|
|
9
|
+
* License: MIT
|
|
10
|
+
*
|
|
11
|
+
* Dependencies/Notes: Pure. An INTERNAL destination stores `{ type, id }` -
|
|
12
|
+
* the Phase 6B identity - and is resolved to a URL at consumption
|
|
13
|
+
* time through the same application boundary the canonical uses. A
|
|
14
|
+
* copied slug would go stale the moment the slug changed, which is
|
|
15
|
+
* the very thing redirects exist to survive.
|
|
16
|
+
*/
|
|
17
|
+
import { validateCanonical, MAX_URL_LENGTH } from './canonical'
|
|
18
|
+
|
|
19
|
+
export const REDIRECT_STATUSES = [301, 302] as const
|
|
20
|
+
export type RedirectStatus = (typeof REDIRECT_STATUSES)[number]
|
|
21
|
+
|
|
22
|
+
export type RedirectDestination =
|
|
23
|
+
/** A full address, including the scheme: `https://example.com/new`, `https://example.com`. */
|
|
24
|
+
| { kind: 'external'; url: string }
|
|
25
|
+
/** A path on this site: `/abc.html`, `/abc/123/`. The site turns it into a Location. */
|
|
26
|
+
| { kind: 'path'; path: string }
|
|
27
|
+
/** A piece of content, stored as identity so it survives the page's URL changing. */
|
|
28
|
+
| { kind: 'internal'; type: string; id: string }
|
|
29
|
+
|
|
30
|
+
export interface SeoRedirect {
|
|
31
|
+
/** A normalized path, always. Never an absolute URL. */
|
|
32
|
+
source: string
|
|
33
|
+
destination: RedirectDestination
|
|
34
|
+
status: RedirectStatus
|
|
35
|
+
enabled: boolean
|
|
36
|
+
createdAt: string
|
|
37
|
+
updatedAt: string
|
|
38
|
+
/** Free-text note for the team. Editorial only; never served. */
|
|
39
|
+
note?: string
|
|
40
|
+
/**
|
|
41
|
+
* Whether the visitor's query string rides along to the destination.
|
|
42
|
+
* Default (absent) is to carry it: a campaign parameter on an old address
|
|
43
|
+
* belongs on the new one.
|
|
44
|
+
*/
|
|
45
|
+
keepQuery?: boolean
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** How far a write-time cycle check walks before it stops claiming anything. */
|
|
49
|
+
export const CYCLE_SCAN_LIMIT = 10
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One canonical spelling of a path, so `/Old/` and `/old` are one entry.
|
|
53
|
+
* Lowercased because a redirect that only fires for one capitalization is a
|
|
54
|
+
* redirect that will be reported as broken.
|
|
55
|
+
*/
|
|
56
|
+
export function normalizeSource(raw: string): string {
|
|
57
|
+
let value = String(raw ?? '').trim()
|
|
58
|
+
const hash = value.indexOf('#')
|
|
59
|
+
if (hash >= 0) value = value.slice(0, hash)
|
|
60
|
+
const q = value.indexOf('?')
|
|
61
|
+
let path = q >= 0 ? value.slice(0, q) : value
|
|
62
|
+
const query = q >= 0 ? value.slice(q) : ''
|
|
63
|
+
path = path.replace(/\/{2,}/g, '/')
|
|
64
|
+
if (!path.startsWith('/')) path = `/${path}`
|
|
65
|
+
if (path.length > 1) path = path.replace(/\/+$/, '')
|
|
66
|
+
if (path === '') path = '/'
|
|
67
|
+
return `${path.toLowerCase()}${query}`
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The path half of a source, with any query string dropped. A redirect is
|
|
72
|
+
* normally FOR a path, so `/old-page?utm_source=mail` must reach the rule
|
|
73
|
+
* written for `/old-page`; a rule that names a query stays exact.
|
|
74
|
+
*/
|
|
75
|
+
export function normalizeSourcePath(raw: string): string {
|
|
76
|
+
const normalized = normalizeSource(raw)
|
|
77
|
+
const q = normalized.indexOf('?')
|
|
78
|
+
return q >= 0 ? normalized.slice(0, q) : normalized
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The query string of a source, '' when it has none. */
|
|
82
|
+
export function sourceQuery(raw: string): string {
|
|
83
|
+
const normalized = normalizeSource(raw)
|
|
84
|
+
const q = normalized.indexOf('?')
|
|
85
|
+
return q >= 0 ? normalized.slice(q) : ''
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The destination a visitor is sent to, with the query they arrived with when
|
|
90
|
+
* the redirect carries it. A destination that already names a query keeps its
|
|
91
|
+
* own and gains the visitor's.
|
|
92
|
+
*/
|
|
93
|
+
export function applyQuery(destination: string, incomingQuery: string, keepQuery?: boolean): string {
|
|
94
|
+
const query = incomingQuery.replace(/^\?/, '')
|
|
95
|
+
if (keepQuery === false || !query) return destination
|
|
96
|
+
const [base, own] = destination.split('#')[0]!.split('?')
|
|
97
|
+
const merged = own ? `${own}&${query}` : query
|
|
98
|
+
const hash = destination.includes('#') ? destination.slice(destination.indexOf('#')) : ''
|
|
99
|
+
return `${base}?${merged}${hash}`
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The store key. Being the source itself is what makes a duplicate impossible. */
|
|
103
|
+
export function redirectKey(source: string): string {
|
|
104
|
+
return `redirect:${normalizeSource(source)}`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export type RedirectCheck =
|
|
108
|
+
| { ok: true }
|
|
109
|
+
| { ok: false; reason: 'SOURCE_EMPTY' | 'SOURCE_NOT_A_PATH' | 'DESTINATION_EMPTY' | 'DESTINATION_SCHEME' | 'DESTINATION_NOT_ABSOLUTE' | 'DESTINATION_NOT_A_PATH' | 'DESTINATION_IDENTITY' | 'SELF_REDIRECT' | 'STATUS' }
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Whether a redirect may be stored. Everything here is a BOUNDED check on one
|
|
113
|
+
* record plus, for the cycle case, a short walk - `detectCycle` says so
|
|
114
|
+
* explicitly rather than implying the whole graph was analysed.
|
|
115
|
+
*/
|
|
116
|
+
export function validateRedirect(r: SeoRedirect & { siteUrl?: string }): RedirectCheck {
|
|
117
|
+
const source = String(r.source ?? '').trim()
|
|
118
|
+
if (!source) return { ok: false, reason: 'SOURCE_EMPTY' }
|
|
119
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(source) || source.startsWith('//')) return { ok: false, reason: 'SOURCE_NOT_A_PATH' }
|
|
120
|
+
if (!REDIRECT_STATUSES.includes(r.status as RedirectStatus)) return { ok: false, reason: 'STATUS' }
|
|
121
|
+
|
|
122
|
+
const normalized = normalizeSource(source)
|
|
123
|
+
|
|
124
|
+
if (r.destination?.kind === 'internal') {
|
|
125
|
+
if (!r.destination.type?.trim() || !r.destination.id?.trim()) return { ok: false, reason: 'DESTINATION_IDENTITY' }
|
|
126
|
+
return { ok: true }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (r.destination?.kind === 'path') {
|
|
130
|
+
const path = String(r.destination.path ?? '').trim()
|
|
131
|
+
if (!path) return { ok: false, reason: 'DESTINATION_EMPTY' }
|
|
132
|
+
// A path, not an address and not a protocol-relative URL in disguise.
|
|
133
|
+
if (!path.startsWith('/') || path.startsWith('//')) return { ok: false, reason: 'DESTINATION_NOT_A_PATH' }
|
|
134
|
+
if (/^\/[a-z][a-z0-9+.-]*:/i.test(path) || path.includes('#')) return { ok: false, reason: 'DESTINATION_NOT_A_PATH' }
|
|
135
|
+
if (path.length > MAX_URL_LENGTH) return { ok: false, reason: 'DESTINATION_NOT_A_PATH' }
|
|
136
|
+
if (normalizeSourcePath(path) === normalizeSourcePath(normalized)) return { ok: false, reason: 'SELF_REDIRECT' }
|
|
137
|
+
return { ok: true }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const url = String((r.destination as { url?: string } | undefined)?.url ?? '').trim()
|
|
141
|
+
if (!url) return { ok: false, reason: 'DESTINATION_EMPTY' }
|
|
142
|
+
const checked = validateCanonical(url)
|
|
143
|
+
if (!checked.ok) {
|
|
144
|
+
return { ok: false, reason: checked.reason === 'CANONICAL_SCHEME' ? 'DESTINATION_SCHEME' : 'DESTINATION_NOT_ABSOLUTE' }
|
|
145
|
+
}
|
|
146
|
+
// A redirect to its own address is a loop of length one.
|
|
147
|
+
try {
|
|
148
|
+
const dest = new URL(checked.url)
|
|
149
|
+
if (normalizeSource(dest.pathname) === normalized && (!r.siteUrl || new URL(r.siteUrl).host === dest.host)) {
|
|
150
|
+
return { ok: false, reason: 'SELF_REDIRECT' }
|
|
151
|
+
}
|
|
152
|
+
} catch { /* validateCanonical already accepted it */ }
|
|
153
|
+
return { ok: true }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Whether adding `source -> destination` closes a loop among the redirects
|
|
158
|
+
* already stored. Bounded to {@link CYCLE_SCAN_LIMIT} hops: this is a
|
|
159
|
+
* write-time guard against the obvious mistake, NOT a global graph analysis,
|
|
160
|
+
* and it says which of the two it did.
|
|
161
|
+
*/
|
|
162
|
+
export function detectCycle(
|
|
163
|
+
source: string,
|
|
164
|
+
destinationPath: string,
|
|
165
|
+
existing: Map<string, string>,
|
|
166
|
+
): { cycle: true; path: string[] } | { cycle: false; truncated?: true } {
|
|
167
|
+
const start = normalizeSource(source)
|
|
168
|
+
const walked = [start]
|
|
169
|
+
let current = normalizeSource(destinationPath)
|
|
170
|
+
for (let hop = 0; hop < CYCLE_SCAN_LIMIT; hop++) {
|
|
171
|
+
walked.push(current)
|
|
172
|
+
if (current === start) return { cycle: true, path: walked }
|
|
173
|
+
const next = existing.get(current)
|
|
174
|
+
if (next === undefined) return { cycle: false }
|
|
175
|
+
current = normalizeSource(next)
|
|
176
|
+
}
|
|
177
|
+
return { cycle: false, truncated: true }
|
|
178
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: resolve.ts
|
|
3
|
+
* Purpose: The resolved SEO representation (closure plan Phase 9A, Unit 11):
|
|
4
|
+
* one function that applies every precedence rule so that no frontend
|
|
5
|
+
* ever reconstructs them. Stored editorial configuration goes in;
|
|
6
|
+
* what a page should render comes out.
|
|
7
|
+
*
|
|
8
|
+
* Author: Raghunath J
|
|
9
|
+
* License: MIT
|
|
10
|
+
*
|
|
11
|
+
* Dependencies/Notes: Pure - every external answer (the object's own fields,
|
|
12
|
+
* the application's URL resolver, the media URL) is passed IN, so the
|
|
13
|
+
* rules can be argued about without a database. Editorial-only state
|
|
14
|
+
* (the focus keyword, the analysis checklist) has no route into the
|
|
15
|
+
* output: it is not read here at all.
|
|
16
|
+
*/
|
|
17
|
+
import { resolveCanonical } from './canonical'
|
|
18
|
+
import { effectiveRobots } from './robots'
|
|
19
|
+
import { mergeStructuredData, validateStructuredData } from './structured-data'
|
|
20
|
+
import { pickMetadata, resolveText } from './metadata'
|
|
21
|
+
import { buildFaqSchema } from './schemas'
|
|
22
|
+
import type { JsonLdNode, ResolvedSeo, SeoHelpers, SeoRobots, SeoScoped, SeoUrlInput } from '../contract'
|
|
23
|
+
|
|
24
|
+
export interface ResolveInput extends SeoUrlInput {
|
|
25
|
+
/** The snapshot to read: the published one for a website, the draft for a preview. */
|
|
26
|
+
scoped: SeoScoped
|
|
27
|
+
/** Whether the object is published. Authoritative over the robots directives. */
|
|
28
|
+
published: boolean
|
|
29
|
+
/** The object's own fields, as far as Core guarantees them. */
|
|
30
|
+
content: { title?: string | null }
|
|
31
|
+
/** What the site declared. */
|
|
32
|
+
helpers: SeoHelpers
|
|
33
|
+
/** The absolute media URL, already resolved by the caller (or null). */
|
|
34
|
+
socialImageUrl?: string | null
|
|
35
|
+
/**
|
|
36
|
+
* The object's page URL, already resolved by the caller (or null) - the
|
|
37
|
+
* same shape as socialImageUrl, so this pure layer never reads a field or
|
|
38
|
+
* calls a site resolver itself.
|
|
39
|
+
*/
|
|
40
|
+
pageUrl?: string | null
|
|
41
|
+
/**
|
|
42
|
+
* The workspace's default robots directives (from SEO settings). Used only
|
|
43
|
+
* when the object sets none of its own - a per-object override still wins,
|
|
44
|
+
* and publication state still overrules both.
|
|
45
|
+
*/
|
|
46
|
+
robotsDefault?: SeoRobots
|
|
47
|
+
/**
|
|
48
|
+
* Site-level JSON-LD from settings (Organization, WebSite - the entity graph
|
|
49
|
+
* every page carries). Merged before the site's own `helpers.structuredData`
|
|
50
|
+
* and the object's nodes.
|
|
51
|
+
*/
|
|
52
|
+
siteSchema?: JsonLdNode[]
|
|
53
|
+
/**
|
|
54
|
+
* The generated per-content-type node (Article, Product, ...), built from the
|
|
55
|
+
* type's schema mapping. Sits after the site nodes and before the object's own
|
|
56
|
+
* structured-data override, which can add to or restate it.
|
|
57
|
+
*/
|
|
58
|
+
typeSchema?: JsonLdNode | null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The precedence, applied once:
|
|
63
|
+
*
|
|
64
|
+
* - title: SEO override for the locale, then the base override, then the
|
|
65
|
+
* object's own title, then the site's fallback, then omitted.
|
|
66
|
+
* - description: the same, minus the content step - Core guarantees a title
|
|
67
|
+
* and does not guarantee a summary field, and guessing which field is one
|
|
68
|
+
* would be inventing an application-specific default.
|
|
69
|
+
* - canonical: explicit override, then the application's resolver, then omitted.
|
|
70
|
+
* - robots: the editor's directives, overruled by publication state.
|
|
71
|
+
* - structured data: site nodes first, the object's own after.
|
|
72
|
+
*/
|
|
73
|
+
export async function resolveSeo(input: ResolveInput): Promise<ResolvedSeo> {
|
|
74
|
+
const metadata = pickMetadata(input.scoped, input.locale)
|
|
75
|
+
const siteFallback = safeFallback(input)
|
|
76
|
+
|
|
77
|
+
const title = resolveText({ override: metadata.title, content: input.content.title, fallback: siteFallback?.title })
|
|
78
|
+
const description = resolveText({ override: metadata.description, content: null, fallback: siteFallback?.description })
|
|
79
|
+
|
|
80
|
+
const canonical = await resolveCanonical({
|
|
81
|
+
workspaceId: input.workspaceId,
|
|
82
|
+
type: input.type,
|
|
83
|
+
id: input.id,
|
|
84
|
+
locale: input.locale,
|
|
85
|
+
slug: input.slug,
|
|
86
|
+
override: metadata.canonicalOverride,
|
|
87
|
+
// The caller already asked the site (resolver, then declared field); this
|
|
88
|
+
// hands that answer to the same precedence the canonical has always used.
|
|
89
|
+
resolveUrl: input.pageUrl === undefined ? input.helpers.resolveUrl : async () => input.pageUrl ?? null,
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
// Precedence: the object's own robots, then the workspace default, then
|
|
93
|
+
// index+follow - all still overruled by publication state inside effectiveRobots.
|
|
94
|
+
const robots = effectiveRobots(metadata.robots ?? input.robotsDefault, { published: input.published })
|
|
95
|
+
|
|
96
|
+
const checked = validateStructuredData(metadata.structuredData ?? [])
|
|
97
|
+
const overrideNodes: JsonLdNode[] = checked.ok ? checked.nodes : []
|
|
98
|
+
// Object layer = the generated per-type node, the FAQ node, then the object's
|
|
99
|
+
// own override. The FAQ comes from the editor's Q/A pairs (GEO + rich results).
|
|
100
|
+
const faqNode = buildFaqSchema(metadata.faqs ?? [])
|
|
101
|
+
const objectNodes = [
|
|
102
|
+
...(input.typeSchema ? [input.typeSchema] : []),
|
|
103
|
+
...(faqNode ? [faqNode] : []),
|
|
104
|
+
...overrideNodes,
|
|
105
|
+
]
|
|
106
|
+
// Site layer = settings entity graph, then the site-declared nodes; object
|
|
107
|
+
// nodes come after, so a page can add to or restate the site's assertions.
|
|
108
|
+
const siteNodes = [...(input.siteSchema ?? []), ...(input.helpers.structuredData ?? [])]
|
|
109
|
+
const structuredData = mergeStructuredData(siteNodes, objectNodes)
|
|
110
|
+
|
|
111
|
+
const out: ResolvedSeo = { robots, structuredData }
|
|
112
|
+
if (title) out.title = title
|
|
113
|
+
if (description) out.description = description
|
|
114
|
+
if (canonical) out.canonical = canonical
|
|
115
|
+
if (metadata.answerSummary) out.answerSummary = metadata.answerSummary
|
|
116
|
+
|
|
117
|
+
const og = openGraph({ metadata, title, description, canonical, imageUrl: input.socialImageUrl })
|
|
118
|
+
if (og) out.openGraph = og
|
|
119
|
+
|
|
120
|
+
return out
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** A site fallback that throws must not take the page down with it. */
|
|
124
|
+
function safeFallback(input: ResolveInput): { title?: string; description?: string } | undefined {
|
|
125
|
+
if (!input.helpers.fallback) return undefined
|
|
126
|
+
try {
|
|
127
|
+
return input.helpers.fallback({
|
|
128
|
+
workspaceId: input.workspaceId, type: input.type, id: input.id, locale: input.locale, slug: input.slug,
|
|
129
|
+
})
|
|
130
|
+
} catch { return undefined }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Open Graph reuses the page's own title and description unless the editor
|
|
135
|
+
* overrode them. One shared set of values, not a second field system per
|
|
136
|
+
* network: every network that matters reads OG.
|
|
137
|
+
*/
|
|
138
|
+
function openGraph(input: {
|
|
139
|
+
metadata: { social?: { title?: string | null; description?: string | null; type?: string | null; imageAlt?: string | null } | null }
|
|
140
|
+
title?: string
|
|
141
|
+
description?: string
|
|
142
|
+
canonical?: string
|
|
143
|
+
imageUrl?: string | null
|
|
144
|
+
}): ResolvedSeo['openGraph'] | undefined {
|
|
145
|
+
const social = input.metadata.social ?? {}
|
|
146
|
+
const og: NonNullable<ResolvedSeo['openGraph']> = { type: social.type?.trim() || 'website' }
|
|
147
|
+
const t = resolveText({ override: social.title, content: input.title, fallback: null }); if (t) og.title = t
|
|
148
|
+
const d = resolveText({ override: social.description, content: input.description, fallback: null }); if (d) og.description = d
|
|
149
|
+
if (input.imageUrl) {
|
|
150
|
+
og.image = input.imageUrl
|
|
151
|
+
// Alt text describes THE image: without one there is nothing it could be about.
|
|
152
|
+
const alt = social.imageAlt?.trim(); if (alt) og.imageAlt = alt
|
|
153
|
+
}
|
|
154
|
+
if (input.canonical) og.url = input.canonical
|
|
155
|
+
// Only worth emitting when it says something beyond the default type.
|
|
156
|
+
return og.title || og.description || og.image || og.url ? og : undefined
|
|
157
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: robots.ts
|
|
3
|
+
* Purpose: Two things that share a name (closure plan Phase 9A, Units 5 and
|
|
4
|
+
* 6): the directives ONE page gives a crawler, and the robots.txt a
|
|
5
|
+
* SITE gives every crawler. Both pure and both deterministic.
|
|
6
|
+
*
|
|
7
|
+
* Author: Raghunath J
|
|
8
|
+
* License: MIT
|
|
9
|
+
*
|
|
10
|
+
* Dependencies/Notes: Typed directives rather than a free-text field, so
|
|
11
|
+
* "noindex, index" cannot be written and serialization has exactly
|
|
12
|
+
* one output per input. Only index and follow: the other directives
|
|
13
|
+
* (max-snippet, max-image-preview, ...) have no v1 consumer, and
|
|
14
|
+
* Phase 9A forbids fields that exist only because a tool exposes one.
|
|
15
|
+
*/
|
|
16
|
+
import type { DeploymentRoleLike } from './deployment-role'
|
|
17
|
+
import type { RobotsTxtDocument, SeoRobots, SeoHelpers } from '../contract'
|
|
18
|
+
|
|
19
|
+
/** Both tokens, always, in this order. */
|
|
20
|
+
export function robotsContent(robots: SeoRobots): string {
|
|
21
|
+
return `${robots.index ? 'index' : 'noindex'}, ${robots.follow ? 'follow' : 'nofollow'}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* What a page actually tells a crawler.
|
|
26
|
+
*
|
|
27
|
+
* Publication is authoritative: content that is not published is `noindex,
|
|
28
|
+
* nofollow` whatever the editor set, so a draft can never be made indexable
|
|
29
|
+
* by a metadata edit alone.
|
|
30
|
+
*/
|
|
31
|
+
export function effectiveRobots(stored: SeoRobots | null | undefined, ctx: { published: boolean }): SeoRobots & { content: string } {
|
|
32
|
+
const robots: SeoRobots = ctx.published
|
|
33
|
+
? { index: stored?.index ?? true, follow: stored?.follow ?? true }
|
|
34
|
+
: { index: false, follow: false }
|
|
35
|
+
return { ...robots, content: robotsContent(robots) }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The document a site gets when it has not earned the right to be crawled. */
|
|
39
|
+
export const DISALLOW_ALL: RobotsTxtDocument = { groups: [{ userAgents: ['*'], disallow: ['/'] }] }
|
|
40
|
+
|
|
41
|
+
/** What production gets when the site declared nothing. */
|
|
42
|
+
const ALLOW_ALL: RobotsTxtDocument = { groups: [{ userAgents: ['*'], allow: ['/'] }] }
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The robots.txt for an environment, chosen by its ROLE.
|
|
46
|
+
*
|
|
47
|
+
* Phase 5A settled that production is a role, never a label or a slug. An
|
|
48
|
+
* environment whose role is unknown - unadopted, or a database from before
|
|
49
|
+
* the role column - is treated as NON-production here. That is the opposite
|
|
50
|
+
* of Phase 1's destructive-operation default and deliberately so: there the
|
|
51
|
+
* cautious answer is "assume production and refuse", here it is "assume this
|
|
52
|
+
* is not the live site and keep it out of the index".
|
|
53
|
+
*/
|
|
54
|
+
export function robotsTxtFor(role: DeploymentRoleLike, helpers: Pick<SeoHelpers, 'robotsTxt' | 'nonProductionRobotsTxt'>): RobotsTxtDocument {
|
|
55
|
+
if (role === 'production') return helpers.robotsTxt ?? ALLOW_ALL
|
|
56
|
+
return helpers.nonProductionRobotsTxt ?? DISALLOW_ALL
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One line's worth of text, with anything that could forge a directive removed. */
|
|
60
|
+
const line = (v: unknown): string => String(v ?? '').replace(/[\r\n]+/g, ' ').trim()
|
|
61
|
+
|
|
62
|
+
/** robots.txt is a line format, so this is a line writer - nothing more. */
|
|
63
|
+
export function serializeRobotsTxt(doc: RobotsTxtDocument): string {
|
|
64
|
+
const out: string[] = []
|
|
65
|
+
for (const group of doc.groups ?? []) {
|
|
66
|
+
const agents = (group.userAgents ?? []).map(line).filter(Boolean)
|
|
67
|
+
if (agents.length === 0) continue
|
|
68
|
+
for (const agent of agents) out.push(`User-agent: ${agent}`)
|
|
69
|
+
for (const path of group.allow ?? []) { const p = line(path); if (p) out.push(`Allow: ${p}`) }
|
|
70
|
+
for (const path of group.disallow ?? []) { const p = line(path); if (p) out.push(`Disallow: ${p}`) }
|
|
71
|
+
out.push('')
|
|
72
|
+
}
|
|
73
|
+
for (const sitemap of doc.sitemaps ?? []) { const s = line(sitemap); if (s) out.push(`Sitemap: ${s}`) }
|
|
74
|
+
for (const extra of doc.custom ?? []) { const c = line(extra); if (c) out.push(c) }
|
|
75
|
+
return out.length ? `${out.join('\n')}\n` : ''
|
|
76
|
+
}
|