@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.
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,269 @@
1
+ /**
2
+ * File Name: contract.ts
3
+ * Purpose: The SEO contract (closure plan Phase 9A). Two shapes and one
4
+ * boundary: what an editor STORES, what a website RECEIVES, and the
5
+ * one function only the consuming application can supply - how its
6
+ * own URLs are built.
7
+ *
8
+ * Author: Raghunath J
9
+ * License: MIT
10
+ *
11
+ * Dependencies/Notes: Types and pure constants only, so this module is
12
+ * importable from a browser panel, a server route and a framework
13
+ * adapter alike. Phase 6B settled that Tangen resolves content
14
+ * IDENTITY and the application resolves site ROUTING; every absolute
15
+ * URL in here therefore arrives from the application or is omitted.
16
+ * Nothing here invents one.
17
+ */
18
+
19
+ // ── Robots ───────────────────────────────────────────────────────────────────
20
+
21
+ /**
22
+ * The two directives with a concrete v1 consumer. Typed rather than free text
23
+ * so an editor cannot write `noindex,index` and so serialization is one
24
+ * function with one output per input.
25
+ */
26
+ export interface SeoRobots {
27
+ index: boolean
28
+ follow: boolean
29
+ }
30
+
31
+ export const DEFAULT_ROBOTS: SeoRobots = { index: true, follow: true }
32
+
33
+ // ── Social ───────────────────────────────────────────────────────────────────
34
+
35
+ /** Open Graph values. One set, shared by every network that reads OG. */
36
+ export interface SeoSocial {
37
+ title?: string | null
38
+ description?: string | null
39
+ /** Media IDENTITY, never a storage path - the URL is resolved at read time. */
40
+ imageId?: string | null
41
+ /** og:type. Free text by the vocabulary's nature; 'website' when unset. */
42
+ type?: string | null
43
+ /** og:image:alt - what the share image shows (S3). Base-only; emitted only beside a resolved image. */
44
+ imageAlt?: string | null
45
+ }
46
+
47
+ // ── Structured data ──────────────────────────────────────────────────────────
48
+
49
+ /** One JSON-LD node. `@type` is required; everything else is the vocabulary's. */
50
+ export interface JsonLdNode {
51
+ '@type': string
52
+ '@id'?: string
53
+ [key: string]: unknown
54
+ }
55
+
56
+ /** Bounds: structure is validated, vocabulary is the author's responsibility. */
57
+ export const STRUCTURED_DATA_LIMITS = {
58
+ maxNodes: 20,
59
+ /** Serialized bytes for the whole array. */
60
+ maxBytes: 32_768,
61
+ maxDepth: 12,
62
+ } as const
63
+
64
+ // ── Stored editorial metadata ────────────────────────────────────────────────
65
+
66
+ /**
67
+ * What an editor writes. Every field is an OVERRIDE: absent means "fall back",
68
+ * never "empty". A field is either localized or it is not, and the split is
69
+ * deliberate - see `SeoStored`.
70
+ */
71
+ export interface SeoLocalizedMetadata {
72
+ title?: string | null
73
+ description?: string | null
74
+ social?: SeoSocial | null
75
+ /**
76
+ * An absolute canonical the editor states outright, overriding whatever the
77
+ * application would resolve. Localized because a site may point each
78
+ * language at a different canonical.
79
+ */
80
+ canonicalOverride?: string | null
81
+ }
82
+
83
+ /** One frequently-asked question and its answer (for FAQPage JSON-LD / GEO). */
84
+ export interface FaqItem {
85
+ question: string
86
+ answer: string
87
+ }
88
+
89
+ /** Editorial metadata that is the same in every language. */
90
+ export interface SeoSharedMetadata {
91
+ robots?: SeoRobots | null
92
+ /** Keep this object out of the sitemap without touching robots. */
93
+ sitemapExclude?: boolean | null
94
+ structuredData?: JsonLdNode[] | null
95
+ /** The existing editorial aid. Never leaves the Admin. */
96
+ focusKeyword?: string | null
97
+ /** Q/A pairs rendered as FAQPage JSON-LD - lifted by search and AI engines. */
98
+ faqs?: FaqItem[] | null
99
+ /**
100
+ * A concise, factual summary written for AI answer engines to extract and
101
+ * cite (GEO). Surfaced in the resolved output for the site to render.
102
+ */
103
+ answerSummary?: string | null
104
+ }
105
+
106
+ export type SeoMetadata = SeoLocalizedMetadata & SeoSharedMetadata
107
+
108
+ /**
109
+ * The row an object's SEO occupies in `extension_data`.
110
+ *
111
+ * `draft` is what the editor sees; `published` is what a website sees, and it
112
+ * is written only when the object publishes.
113
+ *
114
+ * CORRECTION (Phase 9D): Phase 9A said this pair existed because
115
+ * `extension_data.published_data` had no writer. That finding was wrong - the
116
+ * column has had one on the publish path all along, and Phase 9D gave it the
117
+ * rest of the lifecycle plus `ctx.extensionData.getPublished`.
118
+ *
119
+ * The pair stays anyway, and now for a reason rather than for a mistake: it is
120
+ * a PAYLOAD-level snapshot, so the locale dimension this extension carries
121
+ * inside `data` travels with it, Porter moves both halves as one value, and
122
+ * the promote/clear pair below is already symmetric on unpublish. An extension
123
+ * that wants the platform's snapshot instead should call `getPublished`.
124
+ *
125
+ * A payload from before this contract is a bare `SeoMetadata`; `readStored`
126
+ * accepts it as the draft base, so no migration and no data loss.
127
+ */
128
+ /**
129
+ * The current stored-payload schema version. It is stamped on every row this
130
+ * module writes so a future shape change can be migrated in `readStored`
131
+ * deterministically, instead of inferring an old row's meaning from its keys.
132
+ * Bump this ONLY alongside a migration branch in `readStored`.
133
+ */
134
+ export const SEO_SCHEMA_VERSION = 1
135
+
136
+ export interface SeoStored {
137
+ /** Present on every row written since v1; absent on pre-versioning rows. */
138
+ schemaVersion?: number
139
+ draft: SeoScoped
140
+ published?: SeoScoped
141
+ }
142
+
143
+ /**
144
+ * One snapshot: values shared by every locale, plus per-locale overrides.
145
+ * `extension_data` has no locale column, so the extension carries the locale
146
+ * dimension inside its own payload and says so.
147
+ */
148
+ export interface SeoScoped {
149
+ base: SeoMetadata
150
+ locales?: Record<string, SeoLocalizedMetadata>
151
+ }
152
+
153
+ // ── The resolved representation ──────────────────────────────────────────────
154
+
155
+ /**
156
+ * What a website receives. Precedence has already been applied, so a frontend
157
+ * never reconstructs Tangen's rules - that is the whole point of the shape.
158
+ * Editorial-only state (the focus keyword, the checklist) is not in it.
159
+ */
160
+ export interface ResolvedSeo {
161
+ title?: string
162
+ description?: string
163
+ /** Absent when nothing could resolve one. Never a guess. */
164
+ canonical?: string
165
+ robots: SeoRobots & { content: string }
166
+ openGraph?: {
167
+ title?: string
168
+ description?: string
169
+ /** Absolute, from the media URL boundary; absent if it cannot resolve. */
170
+ image?: string
171
+ /** og:image:alt, only beside `image` (S3). */
172
+ imageAlt?: string
173
+ type?: string
174
+ url?: string
175
+ }
176
+ structuredData: JsonLdNode[]
177
+ /** Only locales whose URL actually resolved. Never fabricated. */
178
+ alternates?: Array<{ hreflang: string; href: string }>
179
+ /** The GEO answer summary, when the editor wrote one. Absent otherwise. */
180
+ answerSummary?: string
181
+ }
182
+
183
+ // ── The application boundary ─────────────────────────────────────────────────
184
+
185
+ /** What the resolver is asked about. Identity, never a path. */
186
+ export interface SeoUrlInput {
187
+ workspaceId: string
188
+ type: string
189
+ id: string
190
+ locale?: string | null
191
+ /** The object's slug, for a site whose routing uses it. Advisory only. */
192
+ slug?: string | null
193
+ /**
194
+ * The value of the field the site DECLARED as this type's URL
195
+ * (`urlField`), when there is one and the object has it. Absent otherwise,
196
+ * so a resolver that only needs the slug never sees it.
197
+ */
198
+ fieldValue?: string | null
199
+ }
200
+
201
+ /**
202
+ * The one thing Tangen cannot know. Returning `null` is a legitimate answer
203
+ * and means "this object has no page"; every artifact that needs a URL omits
204
+ * the object rather than inventing one.
205
+ */
206
+ export type SeoUrlResolver = (input: SeoUrlInput) => string | null | Promise<string | null>
207
+
208
+ /** Resolves a media id to an absolute URL, for sites serving media from a CDN. */
209
+ export type SeoMediaUrlResolver = (input: { workspaceId: string; mediaId: string }) => string | null | Promise<string | null>
210
+
211
+ /** A robots.txt group. Paths are written as the file writes them. */
212
+ export interface RobotsTxtGroup {
213
+ userAgents: string[]
214
+ allow?: string[]
215
+ disallow?: string[]
216
+ }
217
+
218
+ export interface RobotsTxtDocument {
219
+ groups: RobotsTxtGroup[]
220
+ sitemaps?: string[]
221
+ /** Verbatim extra lines, appended last. */
222
+ custom?: string[]
223
+ }
224
+
225
+ /**
226
+ * Everything the consuming application declares, spread into the SEO
227
+ * extension's entry options - the convention Flows already established for
228
+ * site-supplied functions (`defineFlowHelpers`).
229
+ */
230
+ export interface SeoHelpers {
231
+ /** The site's origin, e.g. 'https://example.com'. Used for sitemap references. */
232
+ siteUrl?: string
233
+ /**
234
+ * Which FIELD holds a type's URL path, for a site that routes by a field
235
+ * rather than the slug: `{ page: 'path' }`, or one name for every type.
236
+ * Tangen reads that one field - never the whole object - and, with
237
+ * `siteUrl`, that is enough on its own: a type listed here needs no
238
+ * `resolveUrl`. Most sites route by slug and need none of this.
239
+ */
240
+ urlField?: string | Record<string, string>
241
+ /**
242
+ * How this application builds a URL for a content object. Takes precedence
243
+ * over `urlField`, and receives that field's value as `fieldValue` when one
244
+ * is declared, so a resolver can prefix or localise it.
245
+ */
246
+ resolveUrl?: SeoUrlResolver
247
+ /** How this application builds an absolute media URL. */
248
+ resolveMediaUrl?: SeoMediaUrlResolver
249
+ /** Locales to offer as sitemap alternates; only resolvable ones are emitted. */
250
+ locales?: string[]
251
+ /** Last-resort title and description when the content has neither. */
252
+ fallback?: (input: SeoUrlInput) => { title?: string; description?: string } | undefined
253
+ /** Site-wide JSON-LD, merged under every object's own nodes. */
254
+ structuredData?: JsonLdNode[]
255
+ /** Content types eligible for the sitemap. Absent = every type. */
256
+ sitemapTypes?: string[]
257
+ /** The robots.txt served where the environment holds the production role. */
258
+ robotsTxt?: RobotsTxtDocument
259
+ /**
260
+ * The robots.txt served everywhere else. Absent means the safe default:
261
+ * disallow everything, so a staging site is never indexed by accident.
262
+ */
263
+ nonProductionRobotsTxt?: RobotsTxtDocument
264
+ }
265
+
266
+ /** Identity builder for site developers (app/config/extensions.ts options). */
267
+ export function defineSeoHelpers(helpers: SeoHelpers): SeoHelpers {
268
+ return helpers
269
+ }
package/src/hooks.ts ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * File Name: hooks.ts
3
+ * Purpose: What the SEO extension does when content changes (closure plan
4
+ * Phase 9A, Units 2 and 18): validates the editor's write instead of
5
+ * storing it verbatim, keeps its own PUBLISHED snapshot, and retires
6
+ * the cached artifacts that write invalidated.
7
+ *
8
+ * Author: Raghunath J
9
+ * License: MIT
10
+ *
11
+ * Dependencies/Notes: The extension keeps its own published snapshot because
12
+ * `extension_data.published_data` - the column whose comment promises
13
+ * exactly this - has no writer anywhere in the platform (Phase 9A
14
+ * finding 9A-3). Relying on it would have been relying on nothing.
15
+ */
16
+ import type { ContentHooks } from '@tangen/cms'
17
+ import { readStored, writeDraft, promoteToPublished, clearPublished } from './lib/metadata'
18
+ import { ARTIFACT_VERSION_KEY, nextVersion } from './server/artifacts'
19
+
20
+ const SEO_ID = 'seo'
21
+
22
+ type HookCtx = {
23
+ objectId: string
24
+ panelData?: Record<string, unknown>
25
+ statusChange?: { from: string; to: string }
26
+ extensionData: {
27
+ get(id: string, objectId: string): Promise<Record<string, unknown>>
28
+ set(id: string, objectId: string, data: Record<string, unknown>): Promise<void>
29
+ delete(id: string, objectId: string): Promise<void>
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Retires every cached artifact by moving the version they are keyed under.
35
+ *
36
+ * A hook has no `ExtensionServerCtx`, but `extensionData` and `ctx.store` are
37
+ * the same table with the same key - the store's key IS `object_id` - so the
38
+ * hook writes the version row directly. Best-effort: a cache must never fail
39
+ * a save, and the TTL still bounds a miss.
40
+ */
41
+ async function retireArtifacts(ctx: HookCtx): Promise<void> {
42
+ try {
43
+ const current = await ctx.extensionData.get(SEO_ID, ARTIFACT_VERSION_KEY)
44
+ await ctx.extensionData.set(SEO_ID, ARTIFACT_VERSION_KEY, { v: nextVersion(current) })
45
+ } catch { /* the TTL still bounds it */ }
46
+ }
47
+
48
+ export const seoContentHooks: ContentHooks = {
49
+ afterChange: async (rawCtx) => {
50
+ const ctx = rawCtx as unknown as HookCtx
51
+ const panel = ctx.panelData?.[SEO_ID]
52
+ const published = ctx.statusChange?.to === 'published'
53
+ const unpublished = ctx.statusChange && ctx.statusChange.to !== 'published' && ctx.statusChange.from === 'published'
54
+ if (!panel && !ctx.statusChange) return
55
+
56
+ const current = readStored(await ctx.extensionData.get(SEO_ID, ctx.objectId))
57
+ // The editor's write reaches the DRAFT and only the draft: a client that
58
+ // sends a `published` key is ignored, not trusted.
59
+ let next = panel ? writeDraft(current, panel) : current
60
+ if (published) next = promoteToPublished(next)
61
+ else if (unpublished) next = clearPublished(next)
62
+
63
+ await ctx.extensionData.set(SEO_ID, ctx.objectId, next as unknown as Record<string, unknown>)
64
+ // Metadata, publication and unpublication all change what a sitemap and a
65
+ // page's tags say, so all three retire the artifacts.
66
+ await retireArtifacts(ctx)
67
+ },
68
+
69
+ afterDelete: async (rawCtx) => {
70
+ const ctx = rawCtx as unknown as HookCtx
71
+ await ctx.extensionData.delete(SEO_ID, ctx.objectId)
72
+ await retireArtifacts(ctx)
73
+ },
74
+ }
package/src/index.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * File Name: index.ts
3
+ * Purpose: The SEO extension's client entry - what the Admin's extension
4
+ * registry resolves panel and page components from, and what a site
5
+ * developer imports to declare its URL boundary.
6
+ *
7
+ * Author: Raghunath J
8
+ * License: MIT
9
+ */
10
+ import { registerContextNav } from '@/kit'
11
+ import { isSeoManagerPath, readyNav, seoManagerHref } from './lib/seo-manager-nav'
12
+
13
+ export * from './contract'
14
+ export * from './lib/seo-analysis'
15
+ export { SeoPanel } from './components/SeoPanel'
16
+ export type { SeoPanelProps } from './components/SeoPanel'
17
+ export { SeoManagerPage } from './pages/SeoManagerPage'
18
+ export { SeoAnalyticsPage } from './pages/AnalyticsTab'
19
+ export { SeoNotFoundPage } from './pages/NotFoundTab'
20
+ export { SeoTitlesPage } from './pages/TitlesTab'
21
+ export { SeoToolsPage } from './pages/ToolsTab'
22
+ export { SeoSchemaPage, SeoSitemapPage, SeoRedirectsPage, SeoSettingsPage } from './pages/manager-pages'
23
+ export { SeoAiGeoPage } from './pages/AiGeoTab'
24
+ export { RedirectsPanel } from './pages/redirects'
25
+ export { SettingsPanel } from './pages/SettingsTab'
26
+ export { SchemasPanel } from './pages/SchemasTab'
27
+
28
+ // The SEO Manager is one sidebar entry; inside it the sidebar becomes its own
29
+ // menu (plan-seo-manager-v2 V0), the pattern Forms uses. Only shipped pages
30
+ // are listed; each later slice adds its own in lib/seo-manager-nav.ts.
31
+ registerContextNav(({ pathname, workspaceId }) => {
32
+ if (!isSeoManagerPath(pathname, workspaceId)) return null
33
+ return {
34
+ id: 'seo',
35
+ title: 'SEO Manager',
36
+ icon: 'IconSearch',
37
+ backHref: `/${workspaceId}/dashboard`,
38
+ backLabel: 'Back to workspace',
39
+ items: readyNav().map((i) => ({ id: i.id, label: i.label, href: seoManagerHref(workspaceId, i.path), icon: i.icon })),
40
+ }
41
+ })
@@ -0,0 +1,59 @@
1
+ /**
2
+ * File Name: alt-text.ts
3
+ * Purpose: SEO Manager S3: share-image alt text (og:image:alt) written by a
4
+ * vision provider. The prompt, the cleaning of what a model answers
5
+ * into one alt text, and the one question the panel asks before it
6
+ * shows a button: can this installation describe an image at all?
7
+ * Pure - the route and the tests share it.
8
+ *
9
+ * Author: Raghunath J
10
+ * License: MIT
11
+ */
12
+ /** Alt text is read aloud: one plain sentence, what is shown, no preamble. 125 characters is the screen-reader convention. */
13
+ export const ALT_TEXT_PROMPT = 'Write alt text for this image as used on a web page: one plain sentence of at most 125 characters describing what the image shows. No preamble, no quotes, do not start with "image of" or "picture of".'
14
+
15
+ /** The prompt, naming the page when the panel knows its title so the description leans the right way. */
16
+ export function altTextPrompt(input: { title?: string }): string {
17
+ const title = input.title?.trim()
18
+ return title ? `${ALT_TEXT_PROMPT} The page is titled "${title}".` : ALT_TEXT_PROMPT
19
+ }
20
+
21
+ const MAX = 125
22
+
23
+ /** One line, unquoted, no "Alt text:" preamble, cut at a word boundary under the cap. Empty in, empty out. */
24
+ export function cleanAltText(raw: string): string {
25
+ let text = String(raw ?? '').replace(/\s+/g, ' ').trim()
26
+ text = text.replace(/^(alt text|alt|description)\s*:\s*/i, '')
27
+ text = text.replace(/^["'“”‘’]+|["'“”‘’]+$/g, '').trim()
28
+ if (text.length <= MAX) return text
29
+ const cut = text.slice(0, MAX)
30
+ const atWord = cut.lastIndexOf(' ')
31
+ return (atWord > MAX / 2 ? cut.slice(0, atWord) : cut).replace(/[\s,;:]+$/, '')
32
+ }
33
+
34
+ export type GenerateStatus = { available: true; provider: string } | { available: false; reason: string }
35
+
36
+ /** Whether this installation can WRITE metadata with AI (V6): the optional grant, then a provider that generates JSON. */
37
+ export function generateStatus(ctx: {
38
+ ai?: { generateJSON?: unknown; providers?: () => Array<{ id: string; capabilities: string[]; available: boolean }> }
39
+ }): GenerateStatus {
40
+ if (!ctx.ai?.generateJSON) return { available: false, reason: 'Writing metadata with AI needs the ai:generate grant: approve it with `tangen extension upgrade seo --approve-optional ai:generate`.' }
41
+ const provider = (ctx.ai.providers?.() ?? []).find((p) => p.available && p.capabilities.includes('json.generate'))
42
+ if (!provider) return { available: false, reason: 'No enabled AI provider can write text: add a provider key under Settings > AI.' }
43
+ return { available: true, provider: provider.id }
44
+ }
45
+
46
+ export type VisionStatus = { available: true; provider: string } | { available: false; reason: string }
47
+
48
+ /** The three things a description needs, checked in the order an operator fixes them: the two grants, then a provider that can see. */
49
+ export function visionStatus(ctx: {
50
+ ai?: { vision?: unknown; providers?: () => Array<{ id: string; capabilities: string[]; available: boolean }> }
51
+ media?: unknown
52
+ }): VisionStatus {
53
+ if (!ctx.ai?.vision) return { available: false, reason: 'Image descriptions need the ai:vision grant: approve it with `tangen extension upgrade seo --approve-optional ai:vision`.' }
54
+ if (!ctx.media) return { available: false, reason: 'Image descriptions need the media:read grant: approve it with `tangen extension upgrade seo --approve-optional media:read`.' }
55
+ // Any enabled provider that can see; the describe call itself honours the workspace's preferred provider.
56
+ const provider = (ctx.ai.providers?.() ?? []).find((p) => p.available && p.capabilities.includes('vision.describe'))
57
+ if (!provider) return { available: false, reason: 'No enabled AI provider can see images: add an Anthropic, OpenAI or Gemini key under Settings > AI.' }
58
+ return { available: true, provider: provider.id }
59
+ }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * File Name: analytics.ts
3
+ * Purpose: The Search Console numbers the Analytics page reads
4
+ * (plan-seo-manager-v2 V4), pure. Daily aggregates only - one store
5
+ * row per day holding that day's totals and its top pages and
6
+ * queries, never a raw event - summarised over a window, with the
7
+ * previous window beside it so a change is a real comparison. Also
8
+ * the window arithmetic, the limits (defaults, operator-settable)
9
+ * and which day rows retention drops.
10
+ *
11
+ * Author: Raghunath J
12
+ * License: MIT
13
+ */
14
+
15
+ export const DAY_PREFIX = 'gsc:day:'
16
+ export const SYNC_STATE_KEY = 'gsc:state'
17
+
18
+ /** Defaults, not constants: `analyticsRetentionDays` and `analyticsRowLimit` are manifest settings. */
19
+ export const DEFAULT_RETENTION_DAYS = 90
20
+ export const DEFAULT_ROW_LIMIT = 200
21
+ const MAX_RETENTION_DAYS = 480
22
+ const MAX_ROW_LIMIT = 1000
23
+
24
+ /** One row of a dimension on one day, as Search Console reports it. */
25
+ export interface DimensionRow {
26
+ key: string
27
+ clicks: number
28
+ impressions: number
29
+ ctr: number
30
+ position: number
31
+ }
32
+
33
+ /** One day, the only shape stored. */
34
+ export interface DailyRow {
35
+ date: string
36
+ clicks: number
37
+ impressions: number
38
+ ctr: number
39
+ position: number
40
+ pages: DimensionRow[]
41
+ queries: DimensionRow[]
42
+ }
43
+
44
+ /**
45
+ * WHY the last sync failed, as a cause rather than a sentence. The page
46
+ * compares it with the live connection status to tell whether that cause
47
+ * still holds: an operator who sets the property should not keep reading
48
+ * "no property chosen" until tomorrow's run (the user, 2026-09-20).
49
+ */
50
+ export type SyncErrorKind = 'connection' | 'property' | 'provider'
51
+
52
+ export interface SyncState {
53
+ lastSyncedAt?: string
54
+ lastError?: string | null
55
+ lastErrorKind?: SyncErrorKind
56
+ /** When the failure was recorded, so a stale one reads as history. */
57
+ lastErrorAt?: string
58
+ property?: string | null
59
+ /** Days written by the last run. */
60
+ days?: number
61
+ /** The re-arm chain's generation, so a stale wake exits (the Flows pattern). */
62
+ gen?: number
63
+ }
64
+
65
+ export const dayKey = (date: string): string => `${DAY_PREFIX}${date}`
66
+
67
+ /** An ISO date (UTC) n days before the given day. */
68
+ export function isoDay(from: Date, minusDays = 0): string {
69
+ const d = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth(), from.getUTCDate()))
70
+ d.setUTCDate(d.getUTCDate() - minusDays)
71
+ return d.toISOString().slice(0, 10)
72
+ }
73
+
74
+ /** The window a sync asks Google for, and the one a page reads: `days` long, ending today. */
75
+ export function window(now: Date, days: number): { startDate: string; endDate: string } {
76
+ const span = Math.max(1, Math.floor(days))
77
+ return { startDate: isoDay(now, span - 1), endDate: isoDay(now, 0) }
78
+ }
79
+
80
+ /** What an operator's settings mean, bounded: nonsense falls back to the default. */
81
+ export function limitsOf(settings: Record<string, unknown> | undefined): { retentionDays: number; rowLimit: number } {
82
+ const n = (v: unknown, fallback: number, max: number): number => {
83
+ const x = Number(v)
84
+ return Number.isFinite(x) && x >= 1 ? Math.min(Math.floor(x), max) : fallback
85
+ }
86
+ return {
87
+ retentionDays: n(settings?.analyticsRetentionDays, DEFAULT_RETENTION_DAYS, MAX_RETENTION_DAYS),
88
+ rowLimit: n(settings?.analyticsRowLimit, DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT),
89
+ }
90
+ }
91
+
92
+ /** The day rows retention drops: older than `retentionDays`, counted from today. */
93
+ export function expiredDayKeys(keys: readonly string[], now: Date, retentionDays: number): string[] {
94
+ const oldest = isoDay(now, Math.max(1, Math.floor(retentionDays)) - 1)
95
+ return keys.filter((k) => k.startsWith(DAY_PREFIX) && k.slice(DAY_PREFIX.length) < oldest)
96
+ }
97
+
98
+ export interface Totals {
99
+ clicks: number
100
+ impressions: number
101
+ /** A ratio, computed from the totals rather than averaged over days. */
102
+ ctr: number
103
+ /** Impression-weighted, the only honest way to average a position. */
104
+ position: number
105
+ }
106
+
107
+ export interface Summary extends Totals {
108
+ days: number
109
+ /** Clicks per day, oldest first, for a sparkline. */
110
+ series: number[]
111
+ /** The same window before this one; absent when there is no data for it. */
112
+ previous?: Totals
113
+ }
114
+
115
+ const zero = (): Totals => ({ clicks: 0, impressions: 0, ctr: 0, position: 0 })
116
+
117
+ function totalsOf(rows: readonly { clicks: number; impressions: number; position: number }[]): Totals {
118
+ const t = zero()
119
+ let weighted = 0
120
+ for (const r of rows) {
121
+ t.clicks += r.clicks
122
+ t.impressions += r.impressions
123
+ weighted += r.position * r.impressions
124
+ }
125
+ t.ctr = t.impressions ? t.clicks / t.impressions : 0
126
+ t.position = t.impressions ? weighted / t.impressions : 0
127
+ return t
128
+ }
129
+
130
+ /** The window's totals, its click series, and the window before it. */
131
+ export function summarize(rows: readonly DailyRow[], opts: { now: Date; days: number }): Summary {
132
+ const { startDate, endDate } = window(opts.now, opts.days)
133
+ const inWindow = rows.filter((r) => r.date >= startDate && r.date <= endDate).sort((a, b) => a.date.localeCompare(b.date))
134
+ const prevStart = isoDay(opts.now, opts.days * 2 - 1)
135
+ const before = rows.filter((r) => r.date >= prevStart && r.date < startDate)
136
+ return {
137
+ ...totalsOf(inWindow),
138
+ days: inWindow.length,
139
+ series: inWindow.map((r) => r.clicks),
140
+ ...(before.length ? { previous: totalsOf(before) } : {}),
141
+ }
142
+ }
143
+
144
+ export interface TopRow extends DimensionRow {
145
+ /** Clicks per day over the window, oldest first. */
146
+ series: number[]
147
+ }
148
+
149
+ /** The window's top pages or queries: summed clicks and impressions, weighted position, each with its own series. */
150
+ export function topRows(rows: readonly DailyRow[], dimension: 'pages' | 'queries', opts: { now: Date; days: number; limit?: number }): TopRow[] {
151
+ const { startDate, endDate } = window(opts.now, opts.days)
152
+ const inWindow = rows.filter((r) => r.date >= startDate && r.date <= endDate).sort((a, b) => a.date.localeCompare(b.date))
153
+ const acc = new Map<string, { clicks: number; impressions: number; weighted: number; byDay: Map<string, number> }>()
154
+ for (const day of inWindow) {
155
+ for (const row of day[dimension] ?? []) {
156
+ const cur = acc.get(row.key) ?? { clicks: 0, impressions: 0, weighted: 0, byDay: new Map() }
157
+ cur.clicks += row.clicks
158
+ cur.impressions += row.impressions
159
+ cur.weighted += row.position * row.impressions
160
+ cur.byDay.set(day.date, (cur.byDay.get(day.date) ?? 0) + row.clicks)
161
+ acc.set(row.key, cur)
162
+ }
163
+ }
164
+ return [...acc.entries()]
165
+ .map(([key, v]) => ({
166
+ key,
167
+ clicks: v.clicks,
168
+ impressions: v.impressions,
169
+ ctr: v.impressions ? v.clicks / v.impressions : 0,
170
+ position: v.impressions ? v.weighted / v.impressions : 0,
171
+ series: inWindow.map((d) => v.byDay.get(d.date) ?? 0),
172
+ }))
173
+ .sort((a, b) => b.clicks - a.clicks || b.impressions - a.impressions || a.key.localeCompare(b.key))
174
+ .slice(0, Math.max(1, Math.floor(opts.limit ?? 10)))
175
+ }
176
+
177
+ /** The change between a window and the one before it: null when there is nothing to compare with. */
178
+ export function changeOf(summary: Summary, metric: keyof Totals): { delta: number; better: boolean } | null {
179
+ if (!summary.previous) return null
180
+ const before = summary.previous[metric]
181
+ const now = summary[metric]
182
+ if (!before) return null
183
+ const delta = (now - before) / before
184
+ // A lower average position is better; everything else rises to improve.
185
+ return { delta, better: metric === 'position' ? now < before : now > before }
186
+ }
187
+
188
+ /** Google's per-day rows for one dimension, kept to the operator's row limit. */
189
+ export function boundedRows(rows: readonly DimensionRow[], limit: number): DimensionRow[] {
190
+ return [...rows].sort((a, b) => b.clicks - a.clicks || b.impressions - a.impressions).slice(0, Math.max(1, Math.floor(limit)))
191
+ }
192
+
193
+ /**
194
+ * What the Analytics page says about syncing. Three answers, and the order is
195
+ * the point: what blocks a sync NOW outranks what failed before, and a
196
+ * recorded failure whose cause is gone is history with an action, not a
197
+ * verdict.
198
+ */
199
+ export interface SyncNotice {
200
+ kind: 'blocked' | 'failed' | 'stale'
201
+ title: string
202
+ message: string
203
+ /** When it failed, for the two recorded kinds. */
204
+ at?: string
205
+ }
206
+
207
+ export function syncNotice(input: {
208
+ sync: Pick<SyncState, 'lastError' | 'lastErrorKind' | 'lastErrorAt' | 'lastSyncedAt'>
209
+ connection: { connected: boolean; reason?: string; property?: string | null }
210
+ }): SyncNotice | null {
211
+ const { sync, connection } = input
212
+ // The live state first: these are the two conditions an operator fixes.
213
+ if (!connection.connected) {
214
+ return { kind: 'blocked', title: 'Search Console is not connected', message: connection.reason ?? 'The connection is not usable.' }
215
+ }
216
+ if (!connection.property) {
217
+ return {
218
+ kind: 'blocked', title: 'No property chosen',
219
+ message: 'The connection works. Pick the Search Console property under Settings, Extensions, SEO, exactly as Search Console lists it.',
220
+ }
221
+ }
222
+ if (!sync.lastError) return null
223
+ // The connection and the property are in place now, so a failure recorded
224
+ // for either is spent: say what it was, and that a sync will clear it.
225
+ if (sync.lastErrorKind === 'connection' || sync.lastErrorKind === 'property') {
226
+ return {
227
+ kind: 'stale', title: 'The last sync ran before this was set up',
228
+ message: `It failed with: ${sync.lastError} That is resolved now - press Sync now, or wait for the daily run.`,
229
+ ...(sync.lastErrorAt ? { at: sync.lastErrorAt } : {}),
230
+ }
231
+ }
232
+ return {
233
+ kind: 'failed', title: 'The last sync failed', message: sync.lastError,
234
+ ...(sync.lastErrorAt ? { at: sync.lastErrorAt } : {}),
235
+ }
236
+ }