@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,298 @@
1
+ /**
2
+ * File Name: SettingsTab.tsx
3
+ * Purpose: The SEO Manager's Settings tab (plan-seo-next Phase 1). The form over
4
+ * the workspace-level SEO settings served by GET/POST
5
+ * /admin/ext/seo/site-settings - the hybrid-config half an editor can
6
+ * change, saved one GROUP at a time
7
+ * without a code deploy. Built entirely on the Lightfield kit (@/kit):
8
+ * Section/Panel/FormRow, Input/Textarea/Select/Toggle - the
9
+ * section's name sits ABOVE its card, so a heading reads as a heading
10
+ * rather than competing with the fields under it. Save and Reset live
11
+ * in the page header (the page scrolls past a screen) and Save is
12
+ * offered only while the form differs from what the server sent. The
13
+ * server codec (normalizeSettings) is the source of truth; this renders
14
+ * it and sends it back, never re-authoring the rules.
15
+ *
16
+ * Author: Raghunath J
17
+ * License: MIT
18
+ *
19
+ * Dependencies/Notes: @/kit only, no raw form elements (kit-lint). No em dashes.
20
+ */
21
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
22
+ import {
23
+ adminFetch, useCan, toast, usePageHeaderActions,
24
+ Section, Panel, FormRow,
25
+ Input, Textarea, Select, SelectItem, Toggle, Button, Callout, Skeleton, Text,
26
+ ExtensionSettingsForm,
27
+ } from '@/kit'
28
+ import { parseSameAs, SEO_SETTINGS_GROUPS } from '../lib/settings'
29
+ import type { SeoSettings, SeoSettingsGroup } from '../lib/settings'
30
+
31
+ /**
32
+ * NOT `/admin/ext/seo/settings`: core serves that path itself for any
33
+ * extension whose manifest declares typed settings, and SEO declares the
34
+ * Search Console ones - so this page was handed the manifest form's payload
35
+ * and could not read its own shape (found in acme, 2026-09-20).
36
+ */
37
+ const SEO_SETTINGS_PATH = '/admin/ext/seo/site-settings'
38
+
39
+ const TWITTER_AUTO = 'auto'
40
+
41
+ export function SettingsPanel() {
42
+ const { hasCapability } = useCan()
43
+ const mayWrite = hasCapability('seo:write' as never)
44
+
45
+ const [loading, setLoading] = useState(true)
46
+ const [error, setError] = useState<string | null>(null)
47
+ /** The group being saved, 'all' for the header's Save changes, else null. */
48
+ const [savingGroup, setSavingGroup] = useState<SeoSettingsGroup | 'all' | null>(null)
49
+ const saving = savingGroup !== null
50
+ /**
51
+ * What the server last gave us, serialised. Save is offered only while the
52
+ * form differs from it: a page this long should not leave an editor
53
+ * wondering whether they changed anything.
54
+ */
55
+ const [baseline, setBaseline] = useState('')
56
+
57
+ // Flat form state - the nested SeoSettings is assembled on save.
58
+ const [siteName, setSiteName] = useState('')
59
+ const [titleTemplate, setTitleTemplate] = useState('')
60
+ const [titleSeparator, setTitleSeparator] = useState('')
61
+ const [defaultImageId, setDefaultImageId] = useState('')
62
+ const [twitterCard, setTwitterCard] = useState<string>(TWITTER_AUTO)
63
+ const [twitterHandle, setTwitterHandle] = useState('')
64
+ const [orgName, setOrgName] = useState('')
65
+ const [logoId, setLogoId] = useState('')
66
+ const [sameAsText, setSameAsText] = useState('')
67
+ const [google, setGoogle] = useState('')
68
+ const [bing, setBing] = useState('')
69
+ const [defaultIndex, setDefaultIndex] = useState(true)
70
+ const [defaultFollow, setDefaultFollow] = useState(true)
71
+ // S2: llms.txt is the GEO tab's; the settings write is a full replace, so what was loaded is sent back untouched.
72
+ const [geo, setGeo] = useState<SeoSettings['geo']>({ llmsTxtEnabled: false })
73
+
74
+ /** The write body, assembled from the flat form state. Also the dirty check. */
75
+ const body = useMemo(() => ({
76
+ general: { siteName, titleTemplate, titleSeparator },
77
+ social: {
78
+ defaultImageId,
79
+ ...(twitterCard === TWITTER_AUTO ? {} : { twitterCard }),
80
+ twitterHandle,
81
+ },
82
+ organization: { name: orgName, logoId, sameAs: parseSameAs(sameAsText) },
83
+ verification: { google, bing },
84
+ robots: { defaultIndex, defaultFollow },
85
+ geo,
86
+ }), [siteName, titleTemplate, titleSeparator, defaultImageId, twitterCard, twitterHandle, orgName, logoId, sameAsText, google, bing, defaultIndex, defaultFollow, geo])
87
+
88
+ const dirty = baseline !== '' && JSON.stringify(body) !== baseline
89
+ /** Which groups differ from what the server last sent. */
90
+ const dirtyGroups = useMemo(() => {
91
+ if (baseline === '') return [] as SeoSettingsGroup[]
92
+ const was = JSON.parse(baseline) as Record<string, unknown>
93
+ const now = body as unknown as Record<string, unknown>
94
+ return SEO_SETTINGS_GROUPS.filter((g) => JSON.stringify(now[g]) !== JSON.stringify(was[g]))
95
+ }, [body, baseline])
96
+ /**
97
+ * The header's Save closes over this, not over `body`. Registering the
98
+ * overlay again on every keystroke would rerender the header for each
99
+ * character; a ref keeps the button's deps down to what it DISPLAYS while
100
+ * still sending the latest form.
101
+ */
102
+ const bodyRef = useRef(body)
103
+ bodyRef.current = body
104
+ const dirtyGroupsRef = useRef(dirtyGroups)
105
+ dirtyGroupsRef.current = dirtyGroups
106
+ /** The header's action closes over this, so it re-registers on state, not on keystrokes. */
107
+ const saveGroupsRef = useRef<(groups: readonly SeoSettingsGroup[], label: string) => Promise<void>>(async () => {})
108
+
109
+ const hydrate = useCallback((s: SeoSettings) => {
110
+ setSiteName(s.general.siteName ?? '')
111
+ setTitleTemplate(s.general.titleTemplate ?? '')
112
+ setTitleSeparator(s.general.titleSeparator ?? '')
113
+ setDefaultImageId(s.social.defaultImageId ?? '')
114
+ setTwitterCard(s.social.twitterCard ?? TWITTER_AUTO)
115
+ setTwitterHandle(s.social.twitterHandle ?? '')
116
+ setOrgName(s.organization.name ?? '')
117
+ setLogoId(s.organization.logoId ?? '')
118
+ setSameAsText((s.organization.sameAs ?? []).join('\n'))
119
+ setGoogle(s.verification.google ?? '')
120
+ setBing(s.verification.bing ?? '')
121
+ setDefaultIndex(s.robots.defaultIndex)
122
+ setDefaultFollow(s.robots.defaultFollow)
123
+ setGeo(s.geo)
124
+ // The same shape the dirty check compares, built from what the server sent.
125
+ setBaseline(JSON.stringify({
126
+ general: { siteName: s.general.siteName ?? '', titleTemplate: s.general.titleTemplate ?? '', titleSeparator: s.general.titleSeparator ?? '' },
127
+ social: {
128
+ defaultImageId: s.social.defaultImageId ?? '',
129
+ ...(s.social.twitterCard ? { twitterCard: s.social.twitterCard } : {}),
130
+ twitterHandle: s.social.twitterHandle ?? '',
131
+ },
132
+ organization: { name: s.organization.name ?? '', logoId: s.organization.logoId ?? '', sameAs: s.organization.sameAs ?? [] },
133
+ verification: { google: s.verification.google ?? '', bing: s.verification.bing ?? '' },
134
+ robots: { defaultIndex: s.robots.defaultIndex, defaultFollow: s.robots.defaultFollow },
135
+ geo: s.geo,
136
+ }))
137
+ }, [])
138
+
139
+ const load = useCallback(async () => {
140
+ setLoading(true); setError(null)
141
+ try {
142
+ const res = await adminFetch<{ data: SeoSettings }>(SEO_SETTINGS_PATH)
143
+ hydrate(res.data)
144
+ } catch (e) {
145
+ setError((e as Error).message || 'The SEO settings could not be loaded.')
146
+ } finally { setLoading(false) }
147
+ }, [hydrate])
148
+
149
+ useEffect(() => { load() }, [load])
150
+
151
+ /**
152
+ * Saves the GROUPS it is given, and only those (the user, 2026-09-20: "can
153
+ * we have save for each group in settings so that not big payload is sent
154
+ * and broken down into chunks"). The route merges by group, so a section
155
+ * saves itself: two people editing different sections do not overwrite each
156
+ * other, and a failed save loses one section rather than the page.
157
+ */
158
+ const saveGroups = useCallback(async (groups: readonly SeoSettingsGroup[], label: string) => {
159
+ const patch: Record<string, unknown> = {}
160
+ for (const g of groups) patch[g] = (bodyRef.current as Record<string, unknown>)[g]
161
+ setSavingGroup(groups.length === 1 ? groups[0]! : 'all'); setError(null)
162
+ try {
163
+ const res = await adminFetch<{ data: SeoSettings }>(SEO_SETTINGS_PATH, { method: 'POST', body: JSON.stringify(patch) })
164
+ hydrate(res.data) // reflect exactly what the server stored
165
+ toast.success(`${label} saved`)
166
+ } catch (e) {
167
+ setError((e as Error).message || 'These settings could not be saved.')
168
+ } finally { setSavingGroup(null) }
169
+ }, [hydrate])
170
+ saveGroupsRef.current = saveGroups
171
+
172
+ /** One section's own Save: this group, nothing else. */
173
+ const GroupSave = ({ group, label }: { group: SeoSettingsGroup; label: string }) => (
174
+ mayWrite ? (
175
+ <Button
176
+ size="xs"
177
+ variant="secondary"
178
+ isLoading={savingGroup === group}
179
+ disabled={saving || !dirtyGroups.includes(group)}
180
+ onClick={() => saveGroups([group], label)}
181
+ >
182
+ Save
183
+ </Button>
184
+ ) : null
185
+ )
186
+
187
+ // The actions live in the page header: this page scrolls past a screen, and
188
+ // a footer button under six cards is a footer nobody reaches. Save is offered
189
+ // only while something has changed.
190
+ usePageHeaderActions(
191
+ mayWrite && !loading ? (
192
+ <>
193
+ <Button variant="secondary" size="xs" onClick={load} disabled={saving || !dirty}>Reset</Button>
194
+ {/* Saves the CHANGED groups, not the page: one request carrying what
195
+ moved, where a section's own Save carries just that section. */}
196
+ <Button size="xs" isLoading={savingGroup === 'all'} disabled={!dirty} onClick={() => saveGroupsRef.current(dirtyGroupsRef.current, 'Settings')}>
197
+ {`Save changes${dirty ? ` (${dirtyGroupsRef.current.length})` : ''}`}
198
+ </Button>
199
+ </>
200
+ ) : null,
201
+ [mayWrite, loading, savingGroup, dirty],
202
+ )
203
+
204
+ if (loading) return <div className="space-y-4"><Skeleton className="h-40 w-full" /><Skeleton className="h-40 w-full" /></div>
205
+
206
+ const ro = !mayWrite
207
+
208
+ return (
209
+ <div className="space-y-8">
210
+ {error && <Callout variant="danger">{error}</Callout>}
211
+ {ro && <Callout variant="info">You can view these settings but not change them. Managing SEO settings needs the seo:write permission.</Callout>}
212
+
213
+ {/* The connection and the property ARE the analytics source, so they
214
+ belong where the feature lives - not on Settings > Extensions, which
215
+ an operator configuring SEO has no reason to visit (the user,
216
+ 2026-09-20). The same generated form, same store: this is the
217
+ platform's own, brought here. */}
218
+ <ExtensionSettingsForm
219
+ extensionId="seo"
220
+ title="Search Console"
221
+ description="The Google connection SEO reads Search Console with, the property to read, and how much of it to keep. Analytics fills from this."
222
+ />
223
+
224
+ <Section title="General" description="How your site is named across search results and titles." action={<GroupSave group="general" label="General" />}>
225
+ <Panel className="space-y-4">
226
+ <FormRow label="Site name" htmlFor="seo-site-name" help="Used by title templates and structured data.">
227
+ <Input id="seo-site-name" value={siteName} disabled={ro} onChange={(e) => setSiteName((e.target as HTMLInputElement).value)} placeholder="Acme Corp" />
228
+ </FormRow>
229
+ <FormRow label="Title template" htmlFor="seo-title-template" help="Use %title% and %site%. Example: %title% | %site%">
230
+ <Input id="seo-title-template" value={titleTemplate} disabled={ro} onChange={(e) => setTitleTemplate((e.target as HTMLInputElement).value)} placeholder="%title% | %site%" />
231
+ </FormRow>
232
+ <FormRow label="Title separator" htmlFor="seo-title-sep" help="The character between the parts of a title. Defaults to a pipe.">
233
+ <Input id="seo-title-sep" value={titleSeparator} disabled={ro} onChange={(e) => setTitleSeparator((e.target as HTMLInputElement).value)} placeholder="|" className="max-w-24" />
234
+ </FormRow>
235
+ </Panel>
236
+ </Section>
237
+
238
+ <Section title="Social defaults" description="Fallback Open Graph and Twitter values when a page sets none." action={<GroupSave group="social" label="Social defaults" />}>
239
+ <Panel className="space-y-4">
240
+ <FormRow label="Default share image" htmlFor="seo-og-image" help="A media id used as the Open Graph image when a page has none.">
241
+ <Input id="seo-og-image" value={defaultImageId} disabled={ro} onChange={(e) => setDefaultImageId((e.target as HTMLInputElement).value)} placeholder="Media id" />
242
+ </FormRow>
243
+ <FormRow label="Twitter card" htmlFor="seo-tw-card">
244
+ {/* A Select's trigger is a button, and a button takes its name from
245
+ its CONTENT, not from a label pointing at it - so the row's
246
+ label alone left it unnamed (axe button-name, critical). */}
247
+ <Select id="seo-tw-card" aria-label="Twitter card" value={twitterCard} onValueChange={setTwitterCard} disabled={ro}>
248
+ <SelectItem value={TWITTER_AUTO}>Default (let the network decide)</SelectItem>
249
+ <SelectItem value="summary">Summary</SelectItem>
250
+ <SelectItem value="summary_large_image">Summary with large image</SelectItem>
251
+ </Select>
252
+ </FormRow>
253
+ <FormRow label="Twitter handle" htmlFor="seo-tw-handle" help="The @handle credited on shared cards.">
254
+ <Input id="seo-tw-handle" value={twitterHandle} disabled={ro} onChange={(e) => setTwitterHandle((e.target as HTMLInputElement).value)} placeholder="@acme" />
255
+ </FormRow>
256
+ </Panel>
257
+ </Section>
258
+
259
+ <Section title="Organization" description="Your identity for the entity graph (Organization schema)." action={<GroupSave group="organization" label="Organization" />}>
260
+ <Panel className="space-y-4">
261
+ <FormRow label="Organization name" htmlFor="seo-org-name">
262
+ <Input id="seo-org-name" value={orgName} disabled={ro} onChange={(e) => setOrgName((e.target as HTMLInputElement).value)} placeholder="Acme Corporation" />
263
+ </FormRow>
264
+ <FormRow label="Logo" htmlFor="seo-org-logo" help="A media id for the organization logo.">
265
+ <Input id="seo-org-logo" value={logoId} disabled={ro} onChange={(e) => setLogoId((e.target as HTMLInputElement).value)} placeholder="Media id" />
266
+ </FormRow>
267
+ <FormRow label="Profiles (sameAs)" htmlFor="seo-org-sameas" help="One profile URL per line: your social and directory profiles.">
268
+ <Textarea id="seo-org-sameas" value={sameAsText} disabled={ro} rows={3} onChange={(e) => setSameAsText((e.target as HTMLTextAreaElement).value)} placeholder={'https://twitter.com/acme\nhttps://www.linkedin.com/company/acme'} />
269
+ </FormRow>
270
+ </Panel>
271
+ </Section>
272
+
273
+ <Section title="Verification" description="Site ownership codes for search consoles." action={<GroupSave group="verification" label="Verification" />}>
274
+ <Panel className="space-y-4">
275
+ <FormRow label="Google verification" htmlFor="seo-ver-google">
276
+ <Input id="seo-ver-google" value={google} disabled={ro} onChange={(e) => setGoogle((e.target as HTMLInputElement).value)} placeholder="google-site-verification code" />
277
+ </FormRow>
278
+ <FormRow label="Bing verification" htmlFor="seo-ver-bing">
279
+ <Input id="seo-ver-bing" value={bing} disabled={ro} onChange={(e) => setBing((e.target as HTMLInputElement).value)} placeholder="msvalidate.01 code" />
280
+ </FormRow>
281
+ </Panel>
282
+ </Section>
283
+
284
+ <Section title="Robots" description="The default indexing directives for pages that set none." action={<GroupSave group="robots" label="Robots" />}>
285
+ <Panel rows>
286
+ <Toggle className="px-4 py-3" label="Allow indexing by default" description="Search engines may list your pages (index)." checked={defaultIndex} disabled={ro} onCheckedChange={setDefaultIndex} />
287
+ <Toggle className="px-4 py-3" label="Allow following links by default" description="Search engines may follow links on your pages (follow)." checked={defaultFollow} disabled={ro} onCheckedChange={setDefaultFollow} />
288
+ </Panel>
289
+ </Section>
290
+
291
+ {/* The grey card: a note that should sit BELOW the settings it qualifies,
292
+ not compete with them. Same component, quieter tone. */}
293
+ <Panel tone="sunken">
294
+ <Text variant="help">Functions your app owns (how a URL is built, how media resolves) stay in code. Everything here is stored per workspace.</Text>
295
+ </Panel>
296
+ </div>
297
+ )
298
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * File Name: SitemapTab.tsx
3
+ * Purpose: SEO Manager S2: the Sitemap tab. The report the server already
4
+ * keeps (entries, files, skipped, scanned, truncated), said in words,
5
+ * with the served URL to copy and a way to re-count.
6
+ *
7
+ * Author: Raghunath J
8
+ * License: MIT
9
+ */
10
+ import { useCallback, useEffect, useState } from 'react'
11
+ import { useParams } from 'react-router-dom'
12
+ import { adminFetch, toast, FormSection, Input, Button, Callout, Skeleton, Text } from '@/kit'
13
+ import { describeSitemapReport, type SitemapReport } from '../lib/sitemap-report'
14
+
15
+ export function SitemapPanel() {
16
+ const { workspaceId } = useParams<{ workspaceId: string }>()
17
+ const [report, setReport] = useState<SitemapReport | null>(null)
18
+ const [error, setError] = useState<string | null>(null)
19
+ const [loading, setLoading] = useState(true)
20
+ const load = useCallback(async () => {
21
+ setLoading(true); setError(null)
22
+ try { setReport((await adminFetch<{ data: SitemapReport }>('/admin/ext/seo/sitemap-report')).data) }
23
+ catch (e) { setError((e as Error).message || 'The sitemap report could not be loaded.') }
24
+ finally { setLoading(false) }
25
+ }, [])
26
+ useEffect(() => { void load() }, [load])
27
+
28
+ const url = `${window.location.origin}/api/v1/ext/seo/sitemap.xml?workspace=${encodeURIComponent(workspaceId ?? '')}`
29
+ const described = report ? describeSitemapReport(report) : null
30
+ return (
31
+ <div className="max-w-2xl space-y-5">
32
+ <FormSection title="Sitemap" description="Every published object of the types your site lists, one URL each, served as sitemap.xml (a sitemap index when it spans files).">
33
+ {loading && <Skeleton className="h-16 w-full" />}
34
+ {error && <Callout variant="danger" title="Could not load the report">{error}</Callout>}
35
+ {described && (
36
+ <div className="space-y-2">
37
+ <p className="text-sm font-semibold text-fg">{described.headline}</p>
38
+ {described.details.map((d) => <Text key={d} variant="help">{d}</Text>)}
39
+ {described.warning && <Callout variant="warning">{described.warning}</Callout>}
40
+ </div>
41
+ )}
42
+ <div className="flex flex-wrap items-center gap-2">
43
+ <Input readOnly value={url} className="min-w-0 flex-1 font-mono text-[11px]" aria-label="sitemap URL" />
44
+ <Button size="sm" variant="secondary" onClick={() => { navigator.clipboard?.writeText(url); toast.success('sitemap URL copied') }}>Copy</Button>
45
+ <Button size="sm" variant="secondary" onClick={() => { void load() }} disabled={loading}>Re-count</Button>
46
+ </div>
47
+ </FormSection>
48
+ <Text variant="help">Which types are listed is your site&apos;s call: `sitemapTypes` in the SEO options, else every type with a resolvable URL. Locales ride as alternates.</Text>
49
+ </div>
50
+ )
51
+ }