@consilioweb/payload-seo-analyzer 1.7.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { promises } from 'dns';
2
- import { timingSafeEqual } from 'crypto';
2
+ import { randomBytes, timingSafeEqual, createCipheriv, createDecipheriv, scryptSync } from 'crypto';
3
3
 
4
4
  // src/constants.ts
5
5
  var TITLE_LENGTH_MIN = 30;
@@ -13,7 +13,7 @@ var MIN_WORDS_GENERIC = 300;
13
13
  var MIN_WORDS_THIN = 100;
14
14
  var MIN_WORDS_QUALITY_FAIL = 50;
15
15
  var MIN_WORDS_QUALITY_WARN = 200;
16
- var CORNERSTONE_MIN_WORDS = 1500;
16
+ var CORNERSTONE_MIN_WORDS = 600;
17
17
  var THIN_AGING_MIN_WORDS = 500;
18
18
  var KEYWORD_DENSITY_MAX = 3;
19
19
  var KEYWORD_DENSITY_WARN = 2.5;
@@ -1226,6 +1226,44 @@ function buildSeoInputFromDoc(doc, collection, options) {
1226
1226
  const meta = doc.meta || {};
1227
1227
  const hero = doc.hero || {};
1228
1228
  const isPost = collection === "posts";
1229
+ const canonicalUrl = typeof meta.canonicalUrl === "string" && meta.canonicalUrl || typeof doc.canonicalUrl === "string" && doc.canonicalUrl || void 0;
1230
+ let robotsMeta;
1231
+ const rawRobots = typeof meta.robots === "string" && meta.robots || typeof doc.robots === "string" && doc.robots || "";
1232
+ if (rawRobots) {
1233
+ robotsMeta = rawRobots;
1234
+ } else {
1235
+ const directives = [];
1236
+ if (doc.noindex === true || meta.noindex === true) directives.push("noindex");
1237
+ if (doc.nofollow === true || meta.nofollow === true) directives.push("nofollow");
1238
+ if (directives.length > 0) robotsMeta = directives.join(", ");
1239
+ }
1240
+ let author;
1241
+ let authorUrl;
1242
+ const populatedAuthors = doc.populatedAuthors;
1243
+ if (Array.isArray(populatedAuthors) && populatedAuthors.length > 0) {
1244
+ const a = populatedAuthors[0] || {};
1245
+ author = typeof a.name === "string" && a.name || typeof a.firstName === "string" && a.firstName || void 0;
1246
+ if (typeof a.url === "string") authorUrl = a.url;
1247
+ } else if (Array.isArray(doc.authors) && doc.authors.length > 0) {
1248
+ const a = doc.authors[0];
1249
+ if (a && typeof a === "object" && typeof a.name === "string") author = a.name;
1250
+ } else if (typeof doc.author === "string" && doc.author) {
1251
+ author = doc.author;
1252
+ } else if (doc.author && typeof doc.author === "object" && typeof doc.author.name === "string") {
1253
+ author = doc.author.name;
1254
+ }
1255
+ if (!authorUrl && typeof doc.authorUrl === "string") authorUrl = doc.authorUrl;
1256
+ const publishedAt = typeof doc.publishedAt === "string" && doc.publishedAt || typeof doc.createdAt === "string" && doc.createdAt || void 0;
1257
+ const displayedDate = typeof doc.publishedAt === "string" && doc.publishedAt || typeof doc.date === "string" && doc.date || void 0;
1258
+ let localeAlternates;
1259
+ const rawAlts = doc.localeAlternates || doc.alternates || doc.hreflang;
1260
+ if (Array.isArray(rawAlts)) {
1261
+ const mapped = rawAlts.filter((a) => !!a && typeof a === "object").map((a) => ({
1262
+ hreflang: String(a.hreflang || a.locale || a.lang || ""),
1263
+ href: String(a.href || a.url || "")
1264
+ })).filter((a) => a.hreflang && a.href);
1265
+ if (mapped.length > 0) localeAlternates = mapped;
1266
+ }
1229
1267
  return {
1230
1268
  metaTitle: meta.title || "",
1231
1269
  metaDescription: meta.description || "",
@@ -1245,7 +1283,14 @@ function buildSeoInputFromDoc(doc, collection, options) {
1245
1283
  isPost,
1246
1284
  isCornerstone: !!doc.isCornerstone,
1247
1285
  updatedAt: doc.updatedAt || void 0,
1286
+ publishedAt,
1248
1287
  contentLastReviewed: doc.contentLastReviewed || void 0,
1288
+ displayedDate,
1289
+ author,
1290
+ authorUrl,
1291
+ localeAlternates,
1292
+ canonicalUrl,
1293
+ robotsMeta,
1249
1294
  isGlobal: options?.isGlobal ?? false
1250
1295
  };
1251
1296
  }
@@ -1623,6 +1668,7 @@ function analyzeDoc(doc, collection, seoConfig) {
1623
1668
  hasH1: h1Count > 0,
1624
1669
  h1Count,
1625
1670
  score: analysis.score,
1671
+ aiReadiness: analysis.aiReadiness ? analysis.aiReadiness.score : null,
1626
1672
  level: analysis.level,
1627
1673
  status: doc._status || "published",
1628
1674
  updatedAt: doc.updatedAt || "",
@@ -1758,6 +1804,97 @@ function createAuditHandler(collections, seoConfig, globals = []) {
1758
1804
  };
1759
1805
  }
1760
1806
 
1807
+ // src/endpoints/indexationAudit.ts
1808
+ var INDEXATION_CHECK_IDS = /* @__PURE__ */ new Set([
1809
+ "robots-noindex",
1810
+ "robots-nofollow",
1811
+ "canonical-cross",
1812
+ "canonical-external",
1813
+ "canonical-invalid",
1814
+ "canonical-missing"
1815
+ ]);
1816
+ function createIndexationAuditHandler(collections, seoConfig, globals = []) {
1817
+ return async (req) => {
1818
+ try {
1819
+ if (!req.user) {
1820
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
1821
+ }
1822
+ const { config: mergedConfig, ignoredSlugs } = await loadMergedConfig(req.payload, seoConfig);
1823
+ const entries = [];
1824
+ const inspect = (doc, collection, isGlobal = false) => {
1825
+ const input = buildSeoInputFromDoc(doc, collection, { isGlobal });
1826
+ const analysis = analyzeSeo(input, mergedConfig);
1827
+ const issues = analysis.checks.filter(
1828
+ (c) => c.group === "technical" && INDEXATION_CHECK_IDS.has(c.id) && c.status !== "pass"
1829
+ ).map((c) => ({ id: c.id, status: c.status, message: c.message }));
1830
+ const noindex = (input.robotsMeta || "").toLowerCase().includes("noindex");
1831
+ if (issues.length > 0 || noindex) {
1832
+ entries.push({
1833
+ collection,
1834
+ id: doc.id ?? (isGlobal ? collection : ""),
1835
+ slug: doc.slug || "",
1836
+ title: doc.title || doc.slug || String(doc.id ?? collection),
1837
+ noindex,
1838
+ issues
1839
+ });
1840
+ }
1841
+ };
1842
+ for (const collectionSlug of collections) {
1843
+ try {
1844
+ let page = 1;
1845
+ let hasMore = true;
1846
+ while (hasMore) {
1847
+ const result = await req.payload.find({
1848
+ collection: collectionSlug,
1849
+ limit: 100,
1850
+ page,
1851
+ depth: 1,
1852
+ overrideAccess: true
1853
+ });
1854
+ for (const doc of result.docs) {
1855
+ if (ignoredSlugs.includes(doc.slug)) continue;
1856
+ inspect(doc, collectionSlug);
1857
+ }
1858
+ hasMore = result.hasNextPage;
1859
+ page++;
1860
+ }
1861
+ } catch {
1862
+ }
1863
+ }
1864
+ for (const globalSlug of globals) {
1865
+ try {
1866
+ const doc = await req.payload.findGlobal({
1867
+ slug: globalSlug,
1868
+ depth: 1,
1869
+ overrideAccess: true
1870
+ });
1871
+ if (doc) inspect(doc, `global:${globalSlug}`, true);
1872
+ } catch {
1873
+ }
1874
+ }
1875
+ const noindexCount = entries.filter((e) => e.noindex).length;
1876
+ const canonicalIssueCount = entries.filter(
1877
+ (e) => e.issues.some((i) => i.id.startsWith("canonical"))
1878
+ ).length;
1879
+ return Response.json(
1880
+ {
1881
+ entries,
1882
+ summary: {
1883
+ totalFlagged: entries.length,
1884
+ noindexCount,
1885
+ canonicalIssueCount
1886
+ }
1887
+ },
1888
+ { headers: { "Cache-Control": "no-store" } }
1889
+ );
1890
+ } catch (error) {
1891
+ const message = error instanceof Error ? error.message : "Internal server error";
1892
+ req.payload.logger.error(`[seo] indexation-audit error: ${message}`);
1893
+ return Response.json({ error: message }, { status: 500 });
1894
+ }
1895
+ };
1896
+ }
1897
+
1761
1898
  // src/endpoints/history.ts
1762
1899
  var TREND_THRESHOLD = 3;
1763
1900
  function createHistoryHandler() {
@@ -2744,6 +2881,9 @@ function createAiGenerateHandler() {
2744
2881
  }
2745
2882
 
2746
2883
  // src/endpoints/cannibalization.ts
2884
+ function canonicalIntent(keyword) {
2885
+ return keyword.toLowerCase().normalize("NFD").replace(/\p{Diacritic}/gu, "").replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter(Boolean).sort().join(" ");
2886
+ }
2747
2887
  function createCannibalizationHandler(collections, globals = []) {
2748
2888
  return async (req) => {
2749
2889
  try {
@@ -2773,26 +2913,28 @@ function createCannibalizationHandler(collections, globals = []) {
2773
2913
  collection: collectionLabel,
2774
2914
  score: 0
2775
2915
  };
2776
- const keywords = [];
2777
- if (d.focusKeyword && typeof d.focusKeyword === "string" && d.focusKeyword.trim()) {
2778
- keywords.push(d.focusKeyword.trim().toLowerCase());
2779
- }
2916
+ const seenCanon = /* @__PURE__ */ new Set();
2917
+ const docKeywords = [];
2918
+ const addKeyword = (raw) => {
2919
+ if (typeof raw !== "string") return;
2920
+ const display = raw.trim();
2921
+ if (!display) return;
2922
+ const key = canonicalIntent(display);
2923
+ if (!key || seenCanon.has(key)) return;
2924
+ seenCanon.add(key);
2925
+ docKeywords.push({ display, key });
2926
+ };
2927
+ addKeyword(d.focusKeyword);
2780
2928
  if (Array.isArray(d.focusKeywords)) {
2781
2929
  for (const kw of d.focusKeywords) {
2782
- const keyword = typeof kw === "string" ? kw : kw?.keyword;
2783
- if (keyword && typeof keyword === "string" && keyword.trim()) {
2784
- const normalized = keyword.trim().toLowerCase();
2785
- if (!keywords.includes(normalized)) {
2786
- keywords.push(normalized);
2787
- }
2788
- }
2930
+ addKeyword(typeof kw === "string" ? kw : kw?.keyword);
2789
2931
  }
2790
2932
  }
2791
- for (const kw of keywords) {
2792
- if (!keywordMap.has(kw)) {
2793
- keywordMap.set(kw, []);
2933
+ for (const { display, key } of docKeywords) {
2934
+ if (!keywordMap.has(key)) {
2935
+ keywordMap.set(key, { display, pages: [] });
2794
2936
  }
2795
- keywordMap.get(kw).push(pageEntry);
2937
+ keywordMap.get(key).pages.push(pageEntry);
2796
2938
  }
2797
2939
  }
2798
2940
  const scoreMap = /* @__PURE__ */ new Map();
@@ -2818,13 +2960,13 @@ function createCannibalizationHandler(collections, globals = []) {
2818
2960
  const conflicts = [];
2819
2961
  let totalAffectedPages = 0;
2820
2962
  const affectedPageIds = /* @__PURE__ */ new Set();
2821
- for (const [keyword, pages] of keywordMap.entries()) {
2963
+ for (const { display, pages } of keywordMap.values()) {
2822
2964
  if (pages.length < 2) continue;
2823
2965
  const enrichedPages = pages.map((p) => ({
2824
2966
  ...p,
2825
2967
  score: scoreMap.get(`${p.collection}::${p.id}`) || 0
2826
2968
  }));
2827
- conflicts.push({ keyword, pages: enrichedPages });
2969
+ conflicts.push({ keyword: display, pages: enrichedPages });
2828
2970
  for (const p of enrichedPages) {
2829
2971
  const pageKey = `${p.collection}::${p.id}`;
2830
2972
  if (!affectedPageIds.has(pageKey)) {
@@ -3598,6 +3740,420 @@ function createPerformanceHandler() {
3598
3740
  };
3599
3741
  }
3600
3742
 
3743
+ // src/endpoints/coreWebVitals.ts
3744
+ var CWV_THRESHOLDS = {
3745
+ lcp: { good: 2500, poor: 4e3 },
3746
+ // ms
3747
+ inp: { good: 200, poor: 500 },
3748
+ // ms
3749
+ cls: { good: 0.1, poor: 0.25 }
3750
+ // unitless
3751
+ };
3752
+ function rate(value, t) {
3753
+ if (value === null || Number.isNaN(value)) return "unknown";
3754
+ if (value <= t.good) return "good";
3755
+ if (value <= t.poor) return "needs-improvement";
3756
+ return "poor";
3757
+ }
3758
+ function resolveSiteUrl(seoConfig) {
3759
+ return (seoConfig?.siteUrl || process.env.NEXT_PUBLIC_SERVER_URL || process.env.PAYLOAD_PUBLIC_SERVER_URL || void 0)?.replace(/\/$/, "");
3760
+ }
3761
+ function createCoreWebVitalsHandler(seoConfig) {
3762
+ return async (req) => {
3763
+ try {
3764
+ if (!req.user) {
3765
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
3766
+ }
3767
+ const reqUrl = new URL(req.url);
3768
+ const target = reqUrl.searchParams.get("url");
3769
+ const strategy = reqUrl.searchParams.get("strategy") === "desktop" ? "desktop" : "mobile";
3770
+ if (!target) {
3771
+ return Response.json({ error: "Missing required query param: url" }, { status: 400 });
3772
+ }
3773
+ const siteUrl = resolveSiteUrl(seoConfig);
3774
+ if (!siteUrl) {
3775
+ return Response.json(
3776
+ { error: "siteUrl is not configured \u2014 set it in the plugin config or NEXT_PUBLIC_SERVER_URL." },
3777
+ { status: 400 }
3778
+ );
3779
+ }
3780
+ let targetOrigin;
3781
+ let siteOrigin;
3782
+ try {
3783
+ targetOrigin = new URL(target).origin;
3784
+ siteOrigin = new URL(siteUrl).origin;
3785
+ } catch {
3786
+ return Response.json({ error: "Invalid url." }, { status: 400 });
3787
+ }
3788
+ if (targetOrigin !== siteOrigin) {
3789
+ return Response.json(
3790
+ { error: "Only the configured site origin can be tested." },
3791
+ { status: 403 }
3792
+ );
3793
+ }
3794
+ const apiKey = process.env.PAGESPEED_API_KEY || process.env.GOOGLE_PAGESPEED_API_KEY || "";
3795
+ const psi = new URL("https://www.googleapis.com/pagespeedonline/v5/runPagespeed");
3796
+ psi.searchParams.set("url", target);
3797
+ psi.searchParams.set("category", "performance");
3798
+ psi.searchParams.set("strategy", strategy);
3799
+ if (apiKey) psi.searchParams.set("key", apiKey);
3800
+ const controller = new AbortController();
3801
+ const timeout = setTimeout(() => controller.abort(), 3e4);
3802
+ let psiData;
3803
+ try {
3804
+ const resp = await fetch(psi.toString(), { signal: controller.signal });
3805
+ if (!resp.ok) {
3806
+ const detail = resp.status === 429 ? " (PSI quota exceeded \u2014 add a PAGESPEED_API_KEY)" : "";
3807
+ return Response.json(
3808
+ { error: `PageSpeed Insights request failed: ${resp.status}${detail}` },
3809
+ { status: 502 }
3810
+ );
3811
+ }
3812
+ psiData = await resp.json();
3813
+ } finally {
3814
+ clearTimeout(timeout);
3815
+ }
3816
+ const loadingExperience = psiData.loadingExperience || {};
3817
+ const metrics = loadingExperience.metrics || {};
3818
+ const fieldMetric = (key) => {
3819
+ const m = metrics[key];
3820
+ const p = m?.percentile;
3821
+ return typeof p === "number" ? p : null;
3822
+ };
3823
+ const fieldLcp = fieldMetric("LARGEST_CONTENTFUL_PAINT_MS");
3824
+ const fieldInp = fieldMetric("INTERACTION_TO_NEXT_PAINT");
3825
+ const fieldClsRaw = fieldMetric("CUMULATIVE_LAYOUT_SHIFT_SCORE");
3826
+ const fieldCls = fieldClsRaw !== null ? fieldClsRaw / 100 : null;
3827
+ const hasFieldData = fieldLcp !== null || fieldInp !== null || fieldCls !== null;
3828
+ const lighthouse = psiData.lighthouseResult || {};
3829
+ const audits = lighthouse.audits || {};
3830
+ const labNumeric = (id) => {
3831
+ const v = audits[id]?.numericValue;
3832
+ return typeof v === "number" ? v : null;
3833
+ };
3834
+ const labLcp = labNumeric("largest-contentful-paint");
3835
+ const labCls = labNumeric("cumulative-layout-shift");
3836
+ const labTbt = labNumeric("total-blocking-time");
3837
+ const lcp = fieldLcp ?? labLcp;
3838
+ const inp = fieldInp;
3839
+ const cls = fieldCls ?? labCls;
3840
+ return Response.json(
3841
+ {
3842
+ url: target,
3843
+ strategy,
3844
+ source: hasFieldData ? "field" : "lab",
3845
+ hasFieldData,
3846
+ metrics: {
3847
+ lcp: { value: lcp, unit: "ms", rating: rate(lcp, CWV_THRESHOLDS.lcp) },
3848
+ inp: {
3849
+ value: inp,
3850
+ unit: "ms",
3851
+ rating: rate(inp, CWV_THRESHOLDS.inp),
3852
+ note: inp === null ? "INP needs real-user (field) data; not available in lab." : void 0
3853
+ },
3854
+ cls: { value: cls, unit: "score", rating: rate(cls, CWV_THRESHOLDS.cls) },
3855
+ tbt: { value: labTbt, unit: "ms", source: "lab" }
3856
+ },
3857
+ thresholds: CWV_THRESHOLDS,
3858
+ keyConfigured: !!apiKey,
3859
+ note: "Informational only \u2014 Core Web Vitals are a ranking tie-breaker, not part of the on-page SEO score."
3860
+ },
3861
+ { headers: { "Cache-Control": "no-store" } }
3862
+ );
3863
+ } catch (error) {
3864
+ const message = error instanceof Error ? error.message : "Internal server error";
3865
+ req.payload.logger.error(`[seo] core-web-vitals error: ${message}`);
3866
+ return Response.json({ error: message }, { status: 500 });
3867
+ }
3868
+ };
3869
+ }
3870
+ var ALGO = "aes-256-gcm";
3871
+ var KEY_NAMESPACE = "seo-analyzer:gsc:v1";
3872
+ var FORMAT_VERSION = "v1";
3873
+ function deriveKey(secret) {
3874
+ const explicit = process.env.SEO_GSC_ENCRYPTION_KEY;
3875
+ if (explicit) {
3876
+ const buf = explicit.length === 64 ? Buffer.from(explicit, "hex") : Buffer.from(explicit, "base64");
3877
+ if (buf.length === 32) return buf;
3878
+ throw new Error("SEO_GSC_ENCRYPTION_KEY must decode to exactly 32 bytes (hex64 or base64).");
3879
+ }
3880
+ if (!secret) {
3881
+ throw new Error("No encryption secret available (set SEO_GSC_ENCRYPTION_KEY or Payload secret).");
3882
+ }
3883
+ return scryptSync(secret, KEY_NAMESPACE, 32);
3884
+ }
3885
+ function encryptToken(plaintext, secret) {
3886
+ const key = deriveKey(secret);
3887
+ const iv = randomBytes(12);
3888
+ const cipher = createCipheriv(ALGO, key, iv);
3889
+ const enc = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
3890
+ const tag = cipher.getAuthTag();
3891
+ return [FORMAT_VERSION, iv.toString("base64"), tag.toString("base64"), enc.toString("base64")].join(":");
3892
+ }
3893
+ function decryptToken(payload, secret) {
3894
+ const parts = payload.split(":");
3895
+ if (parts.length !== 4 || parts[0] !== FORMAT_VERSION) {
3896
+ throw new Error("Invalid encrypted token format.");
3897
+ }
3898
+ const key = deriveKey(secret);
3899
+ const iv = Buffer.from(parts[1], "base64");
3900
+ const tag = Buffer.from(parts[2], "base64");
3901
+ const enc = Buffer.from(parts[3], "base64");
3902
+ const decipher = createDecipheriv(ALGO, key, iv);
3903
+ decipher.setAuthTag(tag);
3904
+ const dec = Buffer.concat([decipher.update(enc), decipher.final()]);
3905
+ return dec.toString("utf8");
3906
+ }
3907
+ function safeEqual(a, b) {
3908
+ const ba = Buffer.from(a);
3909
+ const bb = Buffer.from(b);
3910
+ if (ba.length !== bb.length) return false;
3911
+ return timingSafeEqual(ba, bb);
3912
+ }
3913
+
3914
+ // src/endpoints/gscOAuth.ts
3915
+ var AUTH_COLLECTION = "seo-gsc-auth";
3916
+ var SCOPES = "https://www.googleapis.com/auth/webmasters.readonly openid email";
3917
+ function isAdmin5(user) {
3918
+ if (!user) return false;
3919
+ if (user.role === "admin") return true;
3920
+ if (Array.isArray(user.roles) && user.roles.includes("admin")) return true;
3921
+ return false;
3922
+ }
3923
+ function resolveSiteUrl2(seoConfig) {
3924
+ return (seoConfig?.siteUrl || process.env.NEXT_PUBLIC_SERVER_URL || process.env.PAYLOAD_PUBLIC_SERVER_URL || void 0)?.replace(/\/$/, "");
3925
+ }
3926
+ function getOAuthConfig(basePath, seoConfig) {
3927
+ const clientId = process.env.GSC_OAUTH_CLIENT_ID || "";
3928
+ const clientSecret = process.env.GSC_OAUTH_CLIENT_SECRET || "";
3929
+ const siteUrl = resolveSiteUrl2(seoConfig);
3930
+ if (!clientId || !clientSecret || !siteUrl) return null;
3931
+ return { clientId, clientSecret, siteUrl, redirectUri: `${siteUrl}/api${basePath}/gsc/callback` };
3932
+ }
3933
+ async function getOrCreateAuthDoc(payload) {
3934
+ const found = await payload.find({ collection: AUTH_COLLECTION, limit: 1, overrideAccess: true });
3935
+ if (found.docs.length > 0) return found.docs[0];
3936
+ return payload.create({ collection: AUTH_COLLECTION, data: {}, overrideAccess: true });
3937
+ }
3938
+ async function tokenRequest(cfg, body) {
3939
+ const resp = await fetch("https://oauth2.googleapis.com/token", {
3940
+ method: "POST",
3941
+ headers: { "content-type": "application/x-www-form-urlencoded" },
3942
+ body: new URLSearchParams({
3943
+ client_id: cfg.clientId,
3944
+ client_secret: cfg.clientSecret,
3945
+ ...body
3946
+ }).toString()
3947
+ });
3948
+ const json = await resp.json();
3949
+ if (!resp.ok) {
3950
+ throw new Error(`Token endpoint error: ${resp.status} ${json.error || ""}`);
3951
+ }
3952
+ return json;
3953
+ }
3954
+ function createGscStatusHandler(basePath, seoConfig) {
3955
+ return async (req) => {
3956
+ try {
3957
+ if (!req.user) return Response.json({ error: "Unauthorized" }, { status: 401 });
3958
+ const cfg = getOAuthConfig(basePath, seoConfig);
3959
+ const doc = await getOrCreateAuthDoc(req.payload);
3960
+ return Response.json(
3961
+ {
3962
+ configured: !!cfg,
3963
+ connected: !!doc.refreshTokenEnc,
3964
+ connectedEmail: doc.connectedEmail || null,
3965
+ connectedAt: doc.connectedAt || null,
3966
+ propertyUrl: doc.propertyUrl || cfg?.siteUrl || null,
3967
+ redirectUri: cfg?.redirectUri || null
3968
+ },
3969
+ { headers: { "Cache-Control": "no-store" } }
3970
+ );
3971
+ } catch (error) {
3972
+ const message = error instanceof Error ? error.message : "Internal server error";
3973
+ req.payload.logger.error(`[seo] gsc-status error: ${message}`);
3974
+ return Response.json({ error: message }, { status: 500 });
3975
+ }
3976
+ };
3977
+ }
3978
+ function createGscAuthStartHandler(basePath, seoConfig) {
3979
+ return async (req) => {
3980
+ try {
3981
+ if (!isAdmin5(req.user)) return Response.json({ error: "Forbidden" }, { status: 403 });
3982
+ const cfg = getOAuthConfig(basePath, seoConfig);
3983
+ if (!cfg) {
3984
+ return Response.json(
3985
+ { error: "GSC OAuth not configured. Set GSC_OAUTH_CLIENT_ID, GSC_OAUTH_CLIENT_SECRET and siteUrl." },
3986
+ { status: 400 }
3987
+ );
3988
+ }
3989
+ const state = randomBytes(24).toString("hex");
3990
+ const doc = await getOrCreateAuthDoc(req.payload);
3991
+ await req.payload.update({
3992
+ collection: AUTH_COLLECTION,
3993
+ id: doc.id,
3994
+ data: { pendingState: state },
3995
+ overrideAccess: true
3996
+ });
3997
+ const authUrl = new URL("https://accounts.google.com/o/oauth2/v2/auth");
3998
+ authUrl.searchParams.set("client_id", cfg.clientId);
3999
+ authUrl.searchParams.set("redirect_uri", cfg.redirectUri);
4000
+ authUrl.searchParams.set("response_type", "code");
4001
+ authUrl.searchParams.set("scope", SCOPES);
4002
+ authUrl.searchParams.set("access_type", "offline");
4003
+ authUrl.searchParams.set("prompt", "consent");
4004
+ authUrl.searchParams.set("state", state);
4005
+ return Response.json({ authUrl: authUrl.toString() }, { headers: { "Cache-Control": "no-store" } });
4006
+ } catch (error) {
4007
+ const message = error instanceof Error ? error.message : "Internal server error";
4008
+ req.payload.logger.error(`[seo] gsc-auth error: ${message}`);
4009
+ return Response.json({ error: message }, { status: 500 });
4010
+ }
4011
+ };
4012
+ }
4013
+ function createGscCallbackHandler(basePath, seoConfig) {
4014
+ return async (req) => {
4015
+ const htmlPage = (title, body) => new Response(
4016
+ `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family:system-ui;padding:2rem;max-width:40rem;margin:auto"><h1>${title}</h1><p>${body}</p><p><a href="/admin/performance">\u2190 Back to the SEO dashboard</a></p></body></html>`,
4017
+ { status: 200, headers: { "content-type": "text/html; charset=utf-8" } }
4018
+ );
4019
+ try {
4020
+ if (!isAdmin5(req.user)) {
4021
+ return htmlPage("Connection failed", "You must be signed in as an admin to connect Google Search Console.");
4022
+ }
4023
+ const cfg = getOAuthConfig(basePath, seoConfig);
4024
+ if (!cfg) return htmlPage("Connection failed", "GSC OAuth is not configured on the server.");
4025
+ const url = new URL(req.url);
4026
+ const code = url.searchParams.get("code");
4027
+ const state = url.searchParams.get("state");
4028
+ const oauthError = url.searchParams.get("error");
4029
+ if (oauthError) return htmlPage("Connection cancelled", `Google returned: ${oauthError}`);
4030
+ if (!code || !state) return htmlPage("Connection failed", "Missing code or state.");
4031
+ const doc = await getOrCreateAuthDoc(req.payload);
4032
+ if (!doc.pendingState || !safeEqual(state, doc.pendingState)) {
4033
+ return htmlPage("Connection failed", "Invalid state (possible CSRF). Please restart the connection.");
4034
+ }
4035
+ const tokens = await tokenRequest(cfg, {
4036
+ code,
4037
+ redirect_uri: cfg.redirectUri,
4038
+ grant_type: "authorization_code"
4039
+ });
4040
+ const refreshToken = tokens.refresh_token;
4041
+ const accessToken = tokens.access_token;
4042
+ if (!refreshToken) {
4043
+ return htmlPage(
4044
+ "Connection failed",
4045
+ "Google did not return a refresh token. Revoke the app access in your Google account and try again (the consent screen must show)."
4046
+ );
4047
+ }
4048
+ let email = null;
4049
+ if (accessToken) {
4050
+ try {
4051
+ const ui = await fetch("https://www.googleapis.com/oauth2/v2/userinfo", {
4052
+ headers: { authorization: `Bearer ${accessToken}` }
4053
+ });
4054
+ if (ui.ok) email = (await ui.json()).email;
4055
+ } catch {
4056
+ }
4057
+ }
4058
+ const secret = req.payload.secret || "";
4059
+ const refreshTokenEnc = encryptToken(refreshToken, secret);
4060
+ await req.payload.update({
4061
+ collection: AUTH_COLLECTION,
4062
+ id: doc.id,
4063
+ data: {
4064
+ refreshTokenEnc,
4065
+ pendingState: null,
4066
+ connectedEmail: email,
4067
+ connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
4068
+ scope: tokens.scope || SCOPES,
4069
+ propertyUrl: doc.propertyUrl || cfg.siteUrl
4070
+ },
4071
+ overrideAccess: true
4072
+ });
4073
+ return htmlPage("Google Search Console connected \u2705", "You can close this tab and return to the SEO dashboard.");
4074
+ } catch (error) {
4075
+ const message = error instanceof Error ? error.message : "Internal server error";
4076
+ req.payload.logger.error(`[seo] gsc-callback error: ${message}`);
4077
+ return htmlPage("Connection failed", "An unexpected error occurred. Check the server logs.");
4078
+ }
4079
+ };
4080
+ }
4081
+ function createGscDataHandler(basePath, seoConfig) {
4082
+ return async (req) => {
4083
+ try {
4084
+ if (!isAdmin5(req.user)) return Response.json({ error: "Forbidden" }, { status: 403 });
4085
+ const cfg = getOAuthConfig(basePath, seoConfig);
4086
+ if (!cfg) return Response.json({ error: "GSC OAuth not configured." }, { status: 400 });
4087
+ const doc = await getOrCreateAuthDoc(req.payload);
4088
+ if (!doc.refreshTokenEnc) {
4089
+ return Response.json({ error: "Not connected to Google Search Console." }, { status: 409 });
4090
+ }
4091
+ const secret = req.payload.secret || "";
4092
+ let refreshToken;
4093
+ try {
4094
+ refreshToken = decryptToken(doc.refreshTokenEnc, secret);
4095
+ } catch {
4096
+ return Response.json(
4097
+ { error: "Stored token could not be decrypted (encryption key changed?). Reconnect GSC." },
4098
+ { status: 409 }
4099
+ );
4100
+ }
4101
+ const tokens = await tokenRequest(cfg, { refresh_token: refreshToken, grant_type: "refresh_token" });
4102
+ const accessToken = tokens.access_token;
4103
+ if (!accessToken) return Response.json({ error: "Could not refresh access token." }, { status: 502 });
4104
+ const url = new URL(req.url);
4105
+ const today = /* @__PURE__ */ new Date();
4106
+ const defaultEnd = today.toISOString().slice(0, 10);
4107
+ const defaultStart = new Date(today.getTime() - 28 * 864e5).toISOString().slice(0, 10);
4108
+ const startDate = url.searchParams.get("startDate") || defaultStart;
4109
+ const endDate = url.searchParams.get("endDate") || defaultEnd;
4110
+ const dimension = url.searchParams.get("dimension") === "page" ? "page" : "query";
4111
+ const rowLimit = Math.min(1e3, Math.max(1, parseInt(url.searchParams.get("rowLimit") || "100", 10)));
4112
+ const property = doc.propertyUrl || cfg.siteUrl;
4113
+ const gscResp = await fetch(
4114
+ `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(property)}/searchAnalytics/query`,
4115
+ {
4116
+ method: "POST",
4117
+ headers: { authorization: `Bearer ${accessToken}`, "content-type": "application/json" },
4118
+ body: JSON.stringify({ startDate, endDate, dimensions: [dimension], rowLimit })
4119
+ }
4120
+ );
4121
+ const gscJson = await gscResp.json();
4122
+ if (!gscResp.ok) {
4123
+ const err = gscJson.error?.message || gscResp.status;
4124
+ return Response.json({ error: `GSC query failed: ${err}` }, { status: 502 });
4125
+ }
4126
+ return Response.json(
4127
+ { property, startDate, endDate, dimension, rows: gscJson.rows || [] },
4128
+ { headers: { "Cache-Control": "no-store" } }
4129
+ );
4130
+ } catch (error) {
4131
+ const message = error instanceof Error ? error.message : "Internal server error";
4132
+ req.payload.logger.error(`[seo] gsc-data error: ${message}`);
4133
+ return Response.json({ error: message }, { status: 500 });
4134
+ }
4135
+ };
4136
+ }
4137
+ function createGscDisconnectHandler() {
4138
+ return async (req) => {
4139
+ try {
4140
+ if (!isAdmin5(req.user)) return Response.json({ error: "Forbidden" }, { status: 403 });
4141
+ const doc = await getOrCreateAuthDoc(req.payload);
4142
+ await req.payload.update({
4143
+ collection: AUTH_COLLECTION,
4144
+ id: doc.id,
4145
+ data: { refreshTokenEnc: null, pendingState: null, connectedEmail: null, connectedAt: null, scope: null },
4146
+ overrideAccess: true
4147
+ });
4148
+ return Response.json({ disconnected: true }, { headers: { "Cache-Control": "no-store" } });
4149
+ } catch (error) {
4150
+ const message = error instanceof Error ? error.message : "Internal server error";
4151
+ req.payload.logger.error(`[seo] gsc-disconnect error: ${message}`);
4152
+ return Response.json({ error: message }, { status: 500 });
4153
+ }
4154
+ };
4155
+ }
4156
+
3601
4157
  // src/endpoints/keywordResearch.ts
3602
4158
  var STOP_WORDS_SET = /* @__PURE__ */ new Set();
3603
4159
  function getStopWords2() {
@@ -4134,12 +4690,12 @@ function detectSchemaType(collection, doc) {
4134
4690
  if (collection === "posts") return "Article";
4135
4691
  const layout = doc.layout;
4136
4692
  if (layout && Array.isArray(layout)) {
4137
- const hasFaqBlock = layout.some((block) => {
4693
+ const hasFaqBlock2 = layout.some((block) => {
4138
4694
  if (!block || typeof block !== "object") return false;
4139
4695
  const b = block;
4140
4696
  return b.blockType === "faq" || b.blockType === "FAQ" || b.blockType === "faqBlock";
4141
4697
  });
4142
- if (hasFaqBlock) return "FAQPage";
4698
+ if (hasFaqBlock2) return "FAQPage";
4143
4699
  }
4144
4700
  if (doc.price !== void 0 || doc.sku !== void 0 || collection === "products") {
4145
4701
  return "Product";
@@ -4290,6 +4846,75 @@ function buildOrganizationSchema(doc, siteUrl) {
4290
4846
  if (doc.logo) {
4291
4847
  schema.logo = typeof doc.logo === "string" ? doc.logo : doc.logo?.url;
4292
4848
  }
4849
+ if (Array.isArray(doc.sameAs)) {
4850
+ const sameAs = doc.sameAs.filter((s) => typeof s === "string");
4851
+ if (sameAs.length > 0) schema.sameAs = sameAs;
4852
+ }
4853
+ return schema;
4854
+ }
4855
+ function buildPersonSchema(doc, siteUrl) {
4856
+ const meta = doc.meta || {};
4857
+ const schema = {
4858
+ "@context": "https://schema.org",
4859
+ "@type": "Person",
4860
+ name: doc.name || doc.title || meta.title || ""
4861
+ };
4862
+ if (doc.jobTitle) schema.jobTitle = doc.jobTitle;
4863
+ if (doc.description || meta.description) schema.description = doc.description || meta.description;
4864
+ schema.url = typeof doc.url === "string" && doc.url || `${siteUrl}/${doc.slug || ""}`;
4865
+ if (Array.isArray(doc.sameAs)) {
4866
+ const sameAs = doc.sameAs.filter((s) => typeof s === "string");
4867
+ if (sameAs.length > 0) schema.sameAs = sameAs;
4868
+ }
4869
+ return schema;
4870
+ }
4871
+ function buildEventSchema(doc, siteUrl) {
4872
+ const meta = doc.meta || {};
4873
+ const schema = {
4874
+ "@context": "https://schema.org",
4875
+ "@type": "Event",
4876
+ name: doc.title || meta.title || "",
4877
+ description: meta.description || "",
4878
+ startDate: doc.startDate || doc.eventStart || void 0,
4879
+ endDate: doc.endDate || doc.eventEnd || void 0,
4880
+ url: `${siteUrl}/${doc.slug || ""}`
4881
+ };
4882
+ if (doc.location) {
4883
+ schema.location = typeof doc.location === "string" ? { "@type": "Place", name: doc.location } : { "@type": "Place", ...doc.location };
4884
+ }
4885
+ return schema;
4886
+ }
4887
+ function buildRecipeSchema(doc, siteUrl) {
4888
+ const meta = doc.meta || {};
4889
+ const heroMedia = doc.hero?.media;
4890
+ const imageUrl = getImageUrl(meta.image, heroMedia, siteUrl);
4891
+ const schema = {
4892
+ "@context": "https://schema.org",
4893
+ "@type": "Recipe",
4894
+ name: doc.title || meta.title || "",
4895
+ description: meta.description || ""
4896
+ };
4897
+ if (imageUrl) schema.image = imageUrl;
4898
+ if (Array.isArray(doc.recipeIngredient)) schema.recipeIngredient = doc.recipeIngredient;
4899
+ else if (Array.isArray(doc.ingredients)) schema.recipeIngredient = doc.ingredients;
4900
+ if (doc.recipeInstructions) schema.recipeInstructions = doc.recipeInstructions;
4901
+ else if (doc.instructions) schema.recipeInstructions = doc.instructions;
4902
+ return schema;
4903
+ }
4904
+ function buildVideoSchema(doc, siteUrl) {
4905
+ const meta = doc.meta || {};
4906
+ const heroMedia = doc.hero?.media;
4907
+ const imageUrl = getImageUrl(meta.image, heroMedia, siteUrl);
4908
+ const schema = {
4909
+ "@context": "https://schema.org",
4910
+ "@type": "VideoObject",
4911
+ name: doc.title || meta.title || "",
4912
+ description: meta.description || "",
4913
+ uploadDate: doc.uploadDate || doc.createdAt || void 0
4914
+ };
4915
+ if (imageUrl) schema.thumbnailUrl = imageUrl;
4916
+ if (doc.videoUrl || doc.contentUrl) schema.contentUrl = doc.videoUrl || doc.contentUrl;
4917
+ if (doc.duration) schema.duration = doc.duration;
4293
4918
  return schema;
4294
4919
  }
4295
4920
  function getImageUrl(metaImage, heroMedia, siteUrl) {
@@ -4328,7 +4953,7 @@ function createSchemaGeneratorHandler(targetCollections) {
4328
4953
  { status: 400 }
4329
4954
  );
4330
4955
  }
4331
- const validTypes = ["Article", "LocalBusiness", "BreadcrumbList", "FAQPage", "Product", "Organization"];
4956
+ const validTypes = ["Article", "LocalBusiness", "BreadcrumbList", "FAQPage", "Product", "Organization", "Person", "Event", "Recipe", "Video"];
4332
4957
  if (typeOverrideRaw !== null && !validTypes.includes(typeOverrideRaw)) {
4333
4958
  return Response.json(
4334
4959
  { error: `Invalid schema type. Valid types: ${validTypes.join(", ")}` },
@@ -4373,6 +4998,18 @@ function createSchemaGeneratorHandler(targetCollections) {
4373
4998
  case "Organization":
4374
4999
  jsonLd = buildOrganizationSchema(doc, siteUrl);
4375
5000
  break;
5001
+ case "Person":
5002
+ jsonLd = buildPersonSchema(doc, siteUrl);
5003
+ break;
5004
+ case "Event":
5005
+ jsonLd = buildEventSchema(doc, siteUrl);
5006
+ break;
5007
+ case "Recipe":
5008
+ jsonLd = buildRecipeSchema(doc, siteUrl);
5009
+ break;
5010
+ case "Video":
5011
+ jsonLd = buildVideoSchema(doc, siteUrl);
5012
+ break;
4376
5013
  }
4377
5014
  const cleaned = JSON.parse(JSON.stringify(jsonLd));
4378
5015
  return Response.json({
@@ -4694,7 +5331,7 @@ function createAiRewriteHandler(targetCollections) {
4694
5331
  }
4695
5332
 
4696
5333
  // src/endpoints/robots.ts
4697
- function isAdmin5(user) {
5334
+ function isAdmin6(user) {
4698
5335
  if (!user) return false;
4699
5336
  if (user.role === "admin") return true;
4700
5337
  if (Array.isArray(user.roles) && user.roles.includes("admin")) return true;
@@ -4743,7 +5380,7 @@ function createRobotsUpdateHandler() {
4743
5380
  if (!req.user) {
4744
5381
  return Response.json({ error: "Unauthorized" }, { status: 401 });
4745
5382
  }
4746
- if (!isAdmin5(req.user)) {
5383
+ if (!isAdmin6(req.user)) {
4747
5384
  return Response.json({ error: "Admin access required" }, { status: 403 });
4748
5385
  }
4749
5386
  const body = await parseJsonBody(req);
@@ -5479,6 +6116,55 @@ function createSeoLogsCollection() {
5479
6116
  };
5480
6117
  }
5481
6118
 
6119
+ // src/collections/SeoGscAuth.ts
6120
+ function createSeoGscAuthCollection() {
6121
+ return {
6122
+ slug: "seo-gsc-auth",
6123
+ admin: {
6124
+ hidden: true,
6125
+ custom: { navHidden: true }
6126
+ },
6127
+ access: {
6128
+ read: ({ req }) => !!req.user,
6129
+ update: ({ req }) => !!req.user,
6130
+ create: ({ req }) => !!req.user,
6131
+ delete: ({ req }) => !!req.user
6132
+ },
6133
+ fields: [
6134
+ {
6135
+ name: "refreshTokenEnc",
6136
+ type: "text",
6137
+ // The encrypted refresh-token blob must never leave the server.
6138
+ access: {
6139
+ read: () => false,
6140
+ create: () => false,
6141
+ update: () => false
6142
+ },
6143
+ admin: { hidden: true }
6144
+ },
6145
+ {
6146
+ name: "pendingState",
6147
+ type: "text",
6148
+ // CSRF state for the in-flight OAuth handshake — also server-only.
6149
+ access: {
6150
+ read: () => false,
6151
+ create: () => false,
6152
+ update: () => false
6153
+ },
6154
+ admin: { hidden: true }
6155
+ },
6156
+ { name: "connectedEmail", type: "text", admin: { readOnly: true } },
6157
+ { name: "connectedAt", type: "date", admin: { readOnly: true } },
6158
+ {
6159
+ name: "propertyUrl",
6160
+ type: "text",
6161
+ admin: { description: "GSC property (e.g. sc-domain:example.com or https://example.com/)" }
6162
+ },
6163
+ { name: "scope", type: "text", admin: { readOnly: true } }
6164
+ ]
6165
+ };
6166
+ }
6167
+
5482
6168
  // src/rateLimiter.ts
5483
6169
  function createRateLimiter(maxRequests, windowMs) {
5484
6170
  const store = /* @__PURE__ */ new Map();
@@ -5526,7 +6212,7 @@ function getClientIp(req) {
5526
6212
 
5527
6213
  // src/endpoints/seoLogs.ts
5528
6214
  var VALID_LOG_TYPES = ["404", "redirect", "error"];
5529
- function isAdmin6(user) {
6215
+ function isAdmin7(user) {
5530
6216
  if (!user) return false;
5531
6217
  if (user.role === "admin") return true;
5532
6218
  if (Array.isArray(user.roles) && user.roles.includes("admin")) return true;
@@ -5623,7 +6309,7 @@ function createSeoLogsHandler(seoLogsSecret) {
5623
6309
  return Response.json({ error: "Unauthorized" }, { status: 401 });
5624
6310
  }
5625
6311
  if (method === "DELETE") {
5626
- if (!isAdmin6(req.user)) {
6312
+ if (!isAdmin7(req.user)) {
5627
6313
  return Response.json({ error: "Admin access required" }, { status: 403 });
5628
6314
  }
5629
6315
  try {
@@ -7207,6 +7893,9 @@ var fr = {
7207
7893
  groupTechnical: "Technique",
7208
7894
  groupAccessibility: "Accessibilit\xE9",
7209
7895
  groupEcommerce: "E-commerce",
7896
+ groupEeat: "E-E-A-T",
7897
+ groupGeo: "GEO (IA)",
7898
+ groupHreflang: "Hreflang",
7210
7899
  levelExcellent: "Excellent",
7211
7900
  levelGood: "Bon",
7212
7901
  levelFair: "Acceptable",
@@ -7215,6 +7904,8 @@ var fr = {
7215
7904
  categoryImportant: "Important",
7216
7905
  categoryBonus: "Bonus",
7217
7906
  seoScore: "Score SEO",
7907
+ aiReadiness: "IA",
7908
+ aiReadinessTooltip: "Pr\xEAt pour l'IA \u2014 qualit\xE9 de structuration pour \xEAtre cit\xE9 par les moteurs g\xE9n\xE9ratifs (AI Overviews, ChatGPT, Perplexity). Distinct du score SEO.",
7218
7909
  outOf100: "/ 100",
7219
7910
  cornerstoneLabel: "PILIER",
7220
7911
  checksPassed: "crit\xE8res valid\xE9s",
@@ -7780,6 +8471,9 @@ var en = {
7780
8471
  groupTechnical: "Technical",
7781
8472
  groupAccessibility: "Accessibility",
7782
8473
  groupEcommerce: "E-commerce",
8474
+ groupEeat: "E-E-A-T",
8475
+ groupGeo: "GEO (AI)",
8476
+ groupHreflang: "Hreflang",
7783
8477
  levelExcellent: "Excellent",
7784
8478
  levelGood: "Good",
7785
8479
  levelFair: "Fair",
@@ -7788,6 +8482,8 @@ var en = {
7788
8482
  categoryImportant: "Important",
7789
8483
  categoryBonus: "Bonus",
7790
8484
  seoScore: "SEO Score",
8485
+ aiReadiness: "AI",
8486
+ aiReadinessTooltip: "AI-readiness \u2014 how well the page is structured to be cited by generative engines (AI Overviews, ChatGPT, Perplexity). Separate from the SEO score.",
7791
8487
  outOf100: "/ 100",
7792
8488
  cornerstoneLabel: "CORNERSTONE",
7793
8489
  checksPassed: "checks passed",
@@ -7957,6 +8653,8 @@ var seoAnalyzerPlugin = (pluginConfig = {}) => (incomingConfig) => {
7957
8653
  aiFeatures: true,
7958
8654
  duplicateContent: true,
7959
8655
  settings: true,
8656
+ gscApi: false,
8657
+ // opt-in — requires Google Cloud OAuth setup + secrets
7960
8658
  ...pluginConfig.features
7961
8659
  };
7962
8660
  function hasExistingSeoMeta(fields) {
@@ -8097,6 +8795,7 @@ var seoAnalyzerPlugin = (pluginConfig = {}) => (incomingConfig) => {
8097
8795
  if (features.redirects && !hasExistingRedirects) pluginCollections.push(createSeoRedirectsCollection(redirectsSlug));
8098
8796
  if (features.performance) pluginCollections.push(createSeoPerformanceCollection());
8099
8797
  if (features.seoLogs) pluginCollections.push(createSeoLogsCollection());
8798
+ if (features.gscApi) pluginCollections.push(createSeoGscAuthCollection());
8100
8799
  config.collections = [
8101
8800
  ...config.collections || [],
8102
8801
  ...pluginCollections
@@ -8149,6 +8848,11 @@ var seoAnalyzerPlugin = (pluginConfig = {}) => (incomingConfig) => {
8149
8848
  method: "get",
8150
8849
  handler: withRateLimit(createAuditHandler(targetCollections, seoConfig, targetGlobals))
8151
8850
  });
8851
+ pluginEndpoints.push({
8852
+ path: `${basePath}/indexation-audit`,
8853
+ method: "get",
8854
+ handler: withRateLimit(createIndexationAuditHandler(targetCollections, seoConfig, targetGlobals))
8855
+ });
8152
8856
  }
8153
8857
  if (features.scoreHistory) {
8154
8858
  pluginEndpoints.push({
@@ -8223,7 +8927,18 @@ var seoAnalyzerPlugin = (pluginConfig = {}) => (incomingConfig) => {
8223
8927
  if (features.performance) {
8224
8928
  pluginEndpoints.push(
8225
8929
  { path: `${basePath}/performance`, method: "get", handler: createPerformanceHandler() },
8226
- { path: `${basePath}/performance`, method: "post", handler: createPerformanceHandler() }
8930
+ { path: `${basePath}/performance`, method: "post", handler: createPerformanceHandler() },
8931
+ // Core Web Vitals via PageSpeed Insights — informational, on-demand, SSRF-safe
8932
+ { path: `${basePath}/core-web-vitals`, method: "get", handler: withRateLimit(createCoreWebVitalsHandler(seoConfig)) }
8933
+ );
8934
+ }
8935
+ if (features.gscApi) {
8936
+ pluginEndpoints.push(
8937
+ { path: `${basePath}/gsc/status`, method: "get", handler: createGscStatusHandler(basePath, seoConfig) },
8938
+ { path: `${basePath}/gsc/auth`, method: "get", handler: createGscAuthStartHandler(basePath, seoConfig) },
8939
+ { path: `${basePath}/gsc/callback`, method: "get", handler: createGscCallbackHandler(basePath, seoConfig) },
8940
+ { path: `${basePath}/gsc/data`, method: "get", handler: withRateLimit(createGscDataHandler(basePath, seoConfig)) },
8941
+ { path: `${basePath}/gsc/disconnect`, method: "post", handler: createGscDisconnectHandler() }
8227
8942
  );
8228
8943
  }
8229
8944
  if (features.keywords) {
@@ -8397,8 +9112,11 @@ var rulesFr = {
8397
9112
  powerWordsPass: (count, words) => `Le title contient ${count} mot(s) puissant(s) : ${words}`,
8398
9113
  powerWordsFail: 'Le title ne contient aucun mot puissant \u2014 Ajoutez un mot comme "gratuit", "guide", "complet" pour booster le CTR.',
8399
9114
  powerWordsTip: "Les mots puissants (gratuit, exclusif, guide, complet, essentiel...) attirent l'attention dans les resultats de recherche.",
9115
+ pixelWidthLabel: "Largeur du title (pixels)",
9116
+ pixelWidthPass: (px) => `Largeur estimee ${px}px \u2014 sous le seuil de troncature SERP (~600px).`,
9117
+ pixelWidthWarn: (px) => `Largeur estimee ${px}px \u2014 risque de troncature dans Google (~600px). Informatif.`,
8400
9118
  hasNumberLabel: "Nombre dans le title",
8401
- hasNumberPass: "Le title contient un nombre \u2014 Les titres avec chiffres generent +36% de CTR.",
9119
+ hasNumberPass: "Le title contient un nombre \u2014 format type liste, souvent plus engageant.",
8402
9120
  hasNumberFail: 'Aucun nombre dans le title \u2014 Les titres avec chiffres (ex: "5 astuces", "Top 10") attirent plus de clics.',
8403
9121
  hasNumberTip: 'Ajoutez un nombre pour creer un titre de type liste (ex: "7 conseils pour...", "Les 3 erreurs a eviter").',
8404
9122
  isQuestionLabel: "Title interrogatif",
@@ -8482,12 +9200,12 @@ var rulesFr = {
8482
9200
  keywordIntroFail: (kw) => `Ajoutez le mot-cle "${kw}" dans les premieres phrases du contenu.`,
8483
9201
  densityLabel: "Densite du mot-cle",
8484
9202
  densityOverstuffed: (density) => `Densite du mot-cle : ${density}% \u2014 Trop eleve (>3%), risque de suroptimisation (keyword stuffing).`,
8485
- densityHigh: (density) => `Densite du mot-cle : ${density}% \u2014 Legerement elevee. Restez entre 0,5% et 2,5%.`,
8486
- densityPass: (density) => `Densite du mot-cle : ${density}% \u2014 Equilibre ideal.`,
9203
+ densityHigh: (density) => `Densite du mot-cle : ${density}% \u2014 Legerement elevee, restez naturel pour eviter la sur-optimisation.`,
9204
+ densityPass: (density) => `Densite du mot-cle : ${density}% \u2014 Usage naturel, aucun bourrage detecte.`,
8487
9205
  densityPassWordLevel: (density) => `Les composants du mot-cle sont presents dans le contenu (densite estimee : ${density}%).`,
8488
9206
  densityLowWordLevel: (density) => `Les composants du mot-cle sont presents mais peu frequents (densite estimee : ${density}%). Renforcez leur presence.`,
8489
9207
  densityLow: (density) => `Densite du mot-cle : ${density}% \u2014 Trop faible. Visez 0,5% a 2,5%.`,
8490
- densityMissing: (kw) => `Le mot-cle "${kw}" n'apparait jamais dans le contenu.`,
9208
+ densityMissing: (kw) => `Le mot-cle "${kw}" n'apparait pas dans le corps \u2014 privilegiez une couverture naturelle du sujet plutot que la repetition.`,
8491
9209
  placeholderLabel: "Contenu placeholder",
8492
9210
  placeholderFail: "Du contenu placeholder a ete detecte (lorem ipsum, TODO, etc.) \u2014 Remplacez par du vrai contenu.",
8493
9211
  placeholderPass: "Aucun contenu placeholder detecte.",
@@ -8573,7 +9291,7 @@ var rulesFr = {
8573
9291
  cornerstone: {
8574
9292
  wordcountLabel: "Longueur du contenu pilier",
8575
9293
  wordcountPass: (count) => `${count} mots \u2014 Le contenu pilier est suffisamment complet.`,
8576
- wordcountFail: (count) => `${count} mots \u2014 Un contenu pilier devrait contenir au moins 1500 mots pour etre vraiment complet.`,
9294
+ wordcountFail: (count) => `${count} mots \u2014 Contenu pilier trop leger ; developpez la couverture du sujet (sans viser un nombre de mots arbitraire).`,
8577
9295
  internalLinksLabel: "Maillage interne du contenu pilier",
8578
9296
  internalLinksPass: (count) => `${count} liens internes \u2014 Bon maillage pour un contenu pilier.`,
8579
9297
  internalLinksFail: (count) => `${count} lien(s) interne(s) \u2014 Un contenu pilier devrait avoir au moins 5 liens internes vers du contenu associe.`,
@@ -8627,12 +9345,23 @@ var rulesFr = {
8627
9345
  yearRefWarn: (oldest, current, last) => `Le contenu mentionne l'annee ${oldest} sans reference a ${current} ou ${last} \u2014 Contenu potentiellement obsolete.`,
8628
9346
  yearRefPass: (year) => `Le contenu fait reference a l'annee en cours (${year}).`,
8629
9347
  thinAgingLabel: "Contenu leger et ancien",
8630
- thinAgingFail: (words, days) => `Seulement ${words} mots et non mis a jour depuis ${days} jours \u2014 Un contenu leger ancien perd rapidement en pertinence.`
9348
+ thinAgingFail: (words, days) => `Seulement ${words} mots et non mis a jour depuis ${days} jours \u2014 Un contenu leger ancien perd rapidement en pertinence.`,
9349
+ fakeRefreshLabel: "Faux rafraichissement",
9350
+ fakeRefreshWarn: (displayedDays, updatedDays) => `La date affichee (il y a ${displayedDays} j) est plus recente que la derniere modification reelle (il y a ${updatedDays} j) \u2014 evitez de rajeunir la date sans vraie mise a jour du contenu.`,
9351
+ fakeRefreshTip: "Google detecte la vraie date de modification. Mettez a jour le fond du contenu, pas seulement la date affichee."
8631
9352
  },
8632
9353
  schema: {
8633
9354
  readinessLabel: "Donnees structurees",
8634
9355
  readinessPass: "La page a suffisamment de metadonnees pour generer du JSON-LD (title, description, image).",
8635
- readinessFail: "Completez le title, la description et ajoutez une image pour exploiter pleinement les donnees structurees."
9356
+ readinessFail: "Completez le title, la description et ajoutez une image pour exploiter pleinement les donnees structurees.",
9357
+ coverageLabel: "Couverture des donnees structurees",
9358
+ coverageOptional: "Les donnees structurees sont optionnelles pour ce type de page.",
9359
+ coveragePass: (type) => `Donnees CMS suffisantes pour generer un schema ${type} valide.`,
9360
+ coverageMissing: (type, fields) => `Schema ${type} attendu pour cette page \u2014 champ(s) requis manquant(s) dans le CMS : ${fields}.`,
9361
+ coverageMissingTip: "Completez ces champs, ou assurez-vous que le JSON-LD correspondant est injecte au rendu (frontend).",
9362
+ coverageRemind: (type, fields) => `Schema ${type} : champs CMS requis presents. Verifiez aussi ces champs requis non detectables automatiquement : ${fields}.`,
9363
+ faqNoRichResultLabel: "FAQ / donnees structurees",
9364
+ faqNoRichResult: "FAQPage detecte \u2014 markup valide et toujours lu par les moteurs et l'IA, mais Google ne genere plus de rich result FAQ (2026). Conservez le markup, n'attendez pas d'extrait enrichi en SERP."
8636
9365
  },
8637
9366
  technical: {
8638
9367
  canonicalMissingLabel: "URL canonique",
@@ -8641,6 +9370,8 @@ var rulesFr = {
8641
9370
  canonicalInvalidMessage: (url) => `URL canonique "${url}" invalide \u2014 Utilisez une URL absolue (https://...).`,
8642
9371
  canonicalExternalLabel: "URL canonique",
8643
9372
  canonicalExternalMessage: "URL canonique pointe vers un domaine externe \u2014 Verifiez que c'est intentionnel.",
9373
+ canonicalCrossLabel: "URL canonique",
9374
+ canonicalCrossMessage: (target) => `URL canonique pointe vers une AUTRE page (${target}) \u2014 cette page se desindexe au profit de cette URL. Verifiez que c'est intentionnel.`,
8644
9375
  canonicalOkLabel: "URL canonique",
8645
9376
  canonicalOkMessage: "URL canonique correctement definie.",
8646
9377
  robotsNoindexLabel: "Robots noindex",
@@ -8765,8 +9496,11 @@ var rulesEn = {
8765
9496
  powerWordsPass: (count, words) => `The title contains ${count} power word(s): ${words}`,
8766
9497
  powerWordsFail: 'The title contains no power words \u2014 Add a word like "free", "guide", "ultimate" to boost CTR.',
8767
9498
  powerWordsTip: "Power words (free, exclusive, guide, ultimate, essential...) attract attention in search results.",
9499
+ pixelWidthLabel: "Title pixel width",
9500
+ pixelWidthPass: (px) => `Estimated width ${px}px \u2014 under the SERP truncation threshold (~600px).`,
9501
+ pixelWidthWarn: (px) => `Estimated width ${px}px \u2014 may be truncated in Google (~600px). Informational.`,
8768
9502
  hasNumberLabel: "Number in title",
8769
- hasNumberPass: "The title contains a number \u2014 Titles with numbers generate +36% CTR.",
9503
+ hasNumberPass: "The title contains a number \u2014 list-style format, often more engaging.",
8770
9504
  hasNumberFail: 'No number in the title \u2014 Titles with numbers (e.g. "5 tips", "Top 10") attract more clicks.',
8771
9505
  hasNumberTip: 'Add a number to create a list-type title (e.g. "7 tips for...", "The 3 mistakes to avoid").',
8772
9506
  isQuestionLabel: "Question title",
@@ -8850,12 +9584,12 @@ var rulesEn = {
8850
9584
  keywordIntroFail: (kw) => `Add the keyword "${kw}" in the first sentences of the content.`,
8851
9585
  densityLabel: "Keyword density",
8852
9586
  densityOverstuffed: (density) => `Keyword density: ${density}% \u2014 Too high (>3%), risk of keyword stuffing.`,
8853
- densityHigh: (density) => `Keyword density: ${density}% \u2014 Slightly high. Stay between 0.5% and 2.5%.`,
8854
- densityPass: (density) => `Keyword density: ${density}% \u2014 Ideal balance.`,
9587
+ densityHigh: (density) => `Keyword density: ${density}% \u2014 Slightly high; keep it natural to avoid over-optimisation.`,
9588
+ densityPass: (density) => `Keyword density: ${density}% \u2014 Natural usage, no stuffing detected.`,
8855
9589
  densityPassWordLevel: (density) => `Keyword components are present in the content (estimated density: ${density}%).`,
8856
9590
  densityLowWordLevel: (density) => `Keyword components are present but infrequent (estimated density: ${density}%). Strengthen their presence.`,
8857
9591
  densityLow: (density) => `Keyword density: ${density}% \u2014 Too low. Aim for 0.5% to 2.5%.`,
8858
- densityMissing: (kw) => `The keyword "${kw}" never appears in the content.`,
9592
+ densityMissing: (kw) => `The keyword "${kw}" does not appear in the body \u2014 focus on covering the topic naturally rather than repeating it.`,
8859
9593
  placeholderLabel: "Placeholder content",
8860
9594
  placeholderFail: "Placeholder content detected (lorem ipsum, TODO, etc.) \u2014 Replace with real content.",
8861
9595
  placeholderPass: "No placeholder content detected.",
@@ -8941,7 +9675,7 @@ var rulesEn = {
8941
9675
  cornerstone: {
8942
9676
  wordcountLabel: "Pillar content length",
8943
9677
  wordcountPass: (count) => `${count} words \u2014 The pillar content is comprehensive enough.`,
8944
- wordcountFail: (count) => `${count} words \u2014 Pillar content should contain at least 1500 words to be truly comprehensive.`,
9678
+ wordcountFail: (count) => `${count} words \u2014 Pillar content seems thin; expand topical coverage (without targeting an arbitrary word count).`,
8945
9679
  internalLinksLabel: "Pillar content internal linking",
8946
9680
  internalLinksPass: (count) => `${count} internal links \u2014 Good linking for pillar content.`,
8947
9681
  internalLinksFail: (count) => `${count} internal link(s) \u2014 Pillar content should have at least 5 internal links to related content.`,
@@ -8995,12 +9729,23 @@ var rulesEn = {
8995
9729
  yearRefWarn: (oldest, current, last) => `The content mentions year ${oldest} without reference to ${current} or ${last} \u2014 Potentially outdated.`,
8996
9730
  yearRefPass: (year) => `The content references the current year (${year}).`,
8997
9731
  thinAgingLabel: "Thin and old content",
8998
- thinAgingFail: (words, days) => `Only ${words} words and not updated for ${days} days \u2014 Thin old content loses relevance quickly.`
9732
+ thinAgingFail: (words, days) => `Only ${words} words and not updated for ${days} days \u2014 Thin old content loses relevance quickly.`,
9733
+ fakeRefreshLabel: "Fake refresh",
9734
+ fakeRefreshWarn: (displayedDays, updatedDays) => `The displayed date (${displayedDays} days ago) is newer than the last real modification (${updatedDays} days ago) \u2014 avoid bumping the date without a real content update.`,
9735
+ fakeRefreshTip: "Google detects the real modification date. Update the actual content, not just the displayed date."
8999
9736
  },
9000
9737
  schema: {
9001
9738
  readinessLabel: "Structured data",
9002
9739
  readinessPass: "The page has sufficient metadata to generate JSON-LD (title, description, image).",
9003
- readinessFail: "Complete the title, description and add an image to fully leverage structured data."
9740
+ readinessFail: "Complete the title, description and add an image to fully leverage structured data.",
9741
+ coverageLabel: "Structured data coverage",
9742
+ coverageOptional: "Structured data is optional for this page type.",
9743
+ coveragePass: (type) => `Enough CMS data to generate a valid ${type} schema.`,
9744
+ coverageMissing: (type, fields) => `${type} schema expected for this page \u2014 required field(s) missing in the CMS: ${fields}.`,
9745
+ coverageMissingTip: "Complete these fields, or make sure the matching JSON-LD is injected at render time (frontend).",
9746
+ coverageRemind: (type, fields) => `${type} schema: required CMS fields are present. Also confirm these required fields the analyzer cannot detect: ${fields}.`,
9747
+ faqNoRichResultLabel: "FAQ / structured data",
9748
+ faqNoRichResult: "FAQPage detected \u2014 markup is valid and still read by search/AI engines, but Google no longer renders FAQ rich results (2026). Keep the markup; do not expect an enhanced SERP snippet."
9004
9749
  },
9005
9750
  technical: {
9006
9751
  canonicalMissingLabel: "Canonical URL",
@@ -9009,6 +9754,8 @@ var rulesEn = {
9009
9754
  canonicalInvalidMessage: (url) => `Canonical URL "${url}" is invalid \u2014 Use an absolute URL (https://...).`,
9010
9755
  canonicalExternalLabel: "Canonical URL",
9011
9756
  canonicalExternalMessage: "Canonical URL points to an external domain \u2014 Verify this is intentional.",
9757
+ canonicalCrossLabel: "Canonical URL",
9758
+ canonicalCrossMessage: (target) => `Canonical URL points to a DIFFERENT page (${target}) \u2014 this page de-indexes itself in favor of that URL. Verify this is intentional.`,
9012
9759
  canonicalOkLabel: "Canonical URL",
9013
9760
  canonicalOkMessage: "Canonical URL is correctly defined.",
9014
9761
  robotsNoindexLabel: "Robots noindex",
@@ -9361,6 +10108,21 @@ function getTranslations(locale) {
9361
10108
  }
9362
10109
 
9363
10110
  // src/rules/title.ts
10111
+ var TITLE_PIXEL_MAX = 600;
10112
+ var NARROW_CHARS = new Set("iIl.,:;|!'`jft()[]{}/\\".split(""));
10113
+ var WIDE_CHARS = new Set("mwMW@%".split(""));
10114
+ function estimateTitlePixelWidth(title) {
10115
+ let px = 0;
10116
+ for (const ch of title) {
10117
+ if (ch === " ") px += 5;
10118
+ else if (NARROW_CHARS.has(ch)) px += 5;
10119
+ else if (WIDE_CHARS.has(ch)) px += 15;
10120
+ else if (ch >= "A" && ch <= "Z") px += 12;
10121
+ else if (ch >= "0" && ch <= "9") px += 10;
10122
+ else px += 9;
10123
+ }
10124
+ return Math.round(px);
10125
+ }
9364
10126
  function checkTitle(input, ctx) {
9365
10127
  const checks = [];
9366
10128
  const r = getTranslations(ctx.locale).rules.title;
@@ -9386,8 +10148,10 @@ function checkTitle(input, ctx) {
9386
10148
  label: r.lengthLabel,
9387
10149
  status: "warning",
9388
10150
  message: r.lengthShort(titleLen),
9389
- category: "critical",
9390
- weight: 3,
10151
+ // SEO desintox: title length is a SERP-display hint, NOT a ranking factor
10152
+ // (Google rewrites 60%+ of titles). Informational weight, never critical.
10153
+ category: "bonus",
10154
+ weight: 1,
9391
10155
  group: "title",
9392
10156
  tip: r.lengthShortTip
9393
10157
  });
@@ -9397,8 +10161,8 @@ function checkTitle(input, ctx) {
9397
10161
  label: r.lengthLabel,
9398
10162
  status: "warning",
9399
10163
  message: r.lengthLong(titleLen),
9400
- category: "critical",
9401
- weight: 3,
10164
+ category: "bonus",
10165
+ weight: 1,
9402
10166
  group: "title",
9403
10167
  tip: r.lengthLongTip
9404
10168
  });
@@ -9408,11 +10172,21 @@ function checkTitle(input, ctx) {
9408
10172
  label: r.lengthLabel,
9409
10173
  status: "pass",
9410
10174
  message: r.lengthPass(titleLen),
9411
- category: "critical",
9412
- weight: 3,
10175
+ category: "bonus",
10176
+ weight: 1,
9413
10177
  group: "title"
9414
10178
  });
9415
10179
  }
10180
+ const titlePx = estimateTitlePixelWidth(title);
10181
+ checks.push({
10182
+ id: "title-pixel-width",
10183
+ label: r.pixelWidthLabel,
10184
+ status: titlePx > TITLE_PIXEL_MAX ? "warning" : "pass",
10185
+ message: titlePx > TITLE_PIXEL_MAX ? r.pixelWidthWarn(titlePx) : r.pixelWidthPass(titlePx),
10186
+ category: "bonus",
10187
+ weight: 0,
10188
+ group: "title"
10189
+ });
9416
10190
  if (kw) {
9417
10191
  const titleNorm = normalizeForComparison(title);
9418
10192
  const kwPresent = keywordMatchesText(kw, titleNorm);
@@ -9948,44 +10722,15 @@ function checkContent(input, ctx) {
9948
10722
  weight: 2,
9949
10723
  group: "content"
9950
10724
  });
9951
- } else if (density >= KEYWORD_DENSITY_MIN) {
9952
- checks.push({
9953
- id: "content-keyword-density",
9954
- label: r.densityLabel,
9955
- status: "pass",
9956
- message: exactCount > 0 ? r.densityPass(density.toFixed(1)) : r.densityPassWordLevel(density.toFixed(1)),
9957
- category: "important",
9958
- weight: 2,
9959
- group: "content"
9960
- });
9961
- } else if (wordLevelMatch) {
9962
- checks.push({
9963
- id: "content-keyword-density",
9964
- label: r.densityLabel,
9965
- status: "warning",
9966
- message: r.densityLowWordLevel(density.toFixed(1)),
9967
- category: "important",
9968
- weight: 2,
9969
- group: "content"
9970
- });
9971
- } else if (exactCount > 0) {
9972
- checks.push({
9973
- id: "content-keyword-density",
9974
- label: r.densityLabel,
9975
- status: "warning",
9976
- message: r.densityLow(density.toFixed(1)),
9977
- category: "important",
9978
- weight: 2,
9979
- group: "content"
9980
- });
9981
10725
  } else {
10726
+ const present = exactCount > 0 || wordLevelMatch;
9982
10727
  checks.push({
9983
10728
  id: "content-keyword-density",
9984
10729
  label: r.densityLabel,
9985
- status: "fail",
9986
- message: r.densityMissing(input.focusKeyword || normalizedKeyword),
9987
- category: "important",
9988
- weight: 2,
10730
+ status: "pass",
10731
+ message: present ? r.densityPass(density.toFixed(1)) : r.densityMissing(input.focusKeyword || normalizedKeyword),
10732
+ category: "bonus",
10733
+ weight: 0,
9989
10734
  group: "content"
9990
10735
  });
9991
10736
  }
@@ -10032,39 +10777,17 @@ function checkContent(input, ctx) {
10032
10777
  const tiersWithKw = [tier1, tier2, tier3].filter(
10033
10778
  (t) => keywordMatchesText(normalizedKeyword, t)
10034
10779
  ).length;
10035
- if (tiersWithKw >= 2) {
10036
- checks.push({
10037
- id: "content-keyword-distribution",
10038
- label: r.distributionLabel,
10039
- status: "pass",
10040
- message: r.distributionPass(tiersWithKw),
10041
- category: "important",
10042
- weight: 2,
10043
- group: "content"
10044
- });
10045
- } else if (tiersWithKw === 1) {
10046
- checks.push({
10047
- id: "content-keyword-distribution",
10048
- label: r.distributionLabel,
10049
- status: "warning",
10050
- message: r.distributionWarn,
10051
- category: "important",
10052
- weight: 2,
10053
- group: "content",
10054
- tip: r.distributionWarnTip
10055
- });
10056
- } else {
10057
- checks.push({
10058
- id: "content-keyword-distribution",
10059
- label: r.distributionLabel,
10060
- status: "fail",
10061
- message: r.distributionFail,
10062
- category: "important",
10063
- weight: 2,
10064
- group: "content",
10065
- tip: r.distributionFailTip
10066
- });
10067
- }
10780
+ const wellDistributed = tiersWithKw >= 2;
10781
+ checks.push({
10782
+ id: "content-keyword-distribution",
10783
+ label: r.distributionLabel,
10784
+ status: wellDistributed ? "pass" : "warning",
10785
+ message: wellDistributed ? r.distributionPass(tiersWithKw) : r.distributionWarn,
10786
+ category: "bonus",
10787
+ weight: 0,
10788
+ group: "content",
10789
+ ...wellDistributed ? {} : { tip: r.distributionWarnTip }
10790
+ });
10068
10791
  }
10069
10792
  if (wordCount > 500) {
10070
10793
  const allLists = [];
@@ -10556,23 +11279,161 @@ function checkSocial(input, ctx) {
10556
11279
  return checks;
10557
11280
  }
10558
11281
 
11282
+ // src/rules/schema-requirements.ts
11283
+ var SCHEMA_REQUIREMENTS = {
11284
+ Article: {
11285
+ required: ["headline", "image"],
11286
+ recommended: ["author", "datePublished", "dateModified", "publisher"],
11287
+ richResult: true
11288
+ },
11289
+ Product: {
11290
+ // Google needs name + at least one of offers / review / aggregateRating
11291
+ required: ["name", "offers"],
11292
+ recommended: ["image", "brand", "aggregateRating", "review", "sku"],
11293
+ richResult: true
11294
+ },
11295
+ LocalBusiness: {
11296
+ required: ["name", "address"],
11297
+ recommended: ["telephone", "openingHours", "geo", "priceRange"],
11298
+ richResult: true
11299
+ },
11300
+ BreadcrumbList: {
11301
+ required: ["itemListElement"],
11302
+ recommended: [],
11303
+ richResult: true
11304
+ },
11305
+ Organization: {
11306
+ required: ["name", "url"],
11307
+ recommended: ["logo", "sameAs"],
11308
+ richResult: false
11309
+ },
11310
+ Person: {
11311
+ required: ["name"],
11312
+ recommended: ["sameAs", "jobTitle", "image", "url"],
11313
+ richResult: false
11314
+ },
11315
+ FAQPage: {
11316
+ required: ["mainEntity"],
11317
+ recommended: [],
11318
+ // FAQ rich results removed by Google (May 2026). Markup still useful for AI/search understanding.
11319
+ richResult: false
11320
+ },
11321
+ Event: {
11322
+ required: ["name", "startDate", "location"],
11323
+ recommended: ["endDate", "offers", "image", "performer"],
11324
+ richResult: true
11325
+ },
11326
+ Recipe: {
11327
+ required: ["name", "image", "recipeIngredient", "recipeInstructions"],
11328
+ recommended: ["nutrition", "aggregateRating", "totalTime", "recipeYield"],
11329
+ richResult: true
11330
+ },
11331
+ Video: {
11332
+ required: ["name", "thumbnailUrl", "uploadDate"],
11333
+ recommended: ["duration", "contentUrl", "description"],
11334
+ richResult: true
11335
+ }
11336
+ };
11337
+ var CMS_VERIFIABLE_SCHEMA_FIELDS = /* @__PURE__ */ new Set([
11338
+ "headline",
11339
+ "name",
11340
+ "image",
11341
+ "url",
11342
+ "itemListElement",
11343
+ "mainEntity"
11344
+ ]);
11345
+
10559
11346
  // src/rules/schema.ts
11347
+ var FAQ_BLOCK_TYPES = /* @__PURE__ */ new Set(["faq", "FAQ", "faqBlock", "faqs"]);
11348
+ function hasFaqBlock(blocks) {
11349
+ if (!Array.isArray(blocks)) return false;
11350
+ return blocks.some((block) => {
11351
+ if (!block || typeof block !== "object") return false;
11352
+ const t = block.blockType;
11353
+ return typeof t === "string" && FAQ_BLOCK_TYPES.has(t);
11354
+ });
11355
+ }
11356
+ function detectExpectedSchemaType(input, ctx) {
11357
+ if (input.isProduct) return "Product";
11358
+ if (input.isPost || ctx.pageType === "blog") return "Article";
11359
+ if (ctx.pageType === "local-seo") return "LocalBusiness";
11360
+ if (ctx.pageType === "agency") return "Organization";
11361
+ if (ctx.pageType === "legal" || ctx.pageType === "contact" || ctx.pageType === "form") return null;
11362
+ return "Article";
11363
+ }
10560
11364
  function checkSchema(input, ctx) {
10561
11365
  const checks = [];
10562
11366
  const r = getTranslations(ctx.locale).rules.schema;
10563
- const hasMetaTitle = !!input.metaTitle;
10564
- const hasMetaDesc = !!input.metaDescription;
10565
- const hasImage = ctx.imageStats.total > 0;
10566
- const readyForSchema = hasMetaTitle && hasMetaDesc && hasImage;
10567
- checks.push({
10568
- id: "schema-readiness",
10569
- label: r.readinessLabel,
10570
- status: readyForSchema ? "pass" : "warning",
10571
- message: readyForSchema ? r.readinessPass : r.readinessFail,
10572
- category: "bonus",
10573
- weight: 1,
10574
- group: "schema"
10575
- });
11367
+ const faqPresent = hasFaqBlock(input.blocks);
11368
+ const present = {
11369
+ headline: !!(input.metaTitle || input.heroTitle) || ctx.allHeadings.some((h) => h.tag === "h1"),
11370
+ name: !!(input.metaTitle || input.heroTitle),
11371
+ image: ctx.imageStats.total > 0 || !!input.metaImage,
11372
+ url: true,
11373
+ itemListElement: !!input.slug,
11374
+ mainEntity: faqPresent
11375
+ };
11376
+ const expected = detectExpectedSchemaType(input, ctx);
11377
+ if (expected === null) {
11378
+ checks.push({
11379
+ id: "schema-coverage",
11380
+ label: r.coverageLabel,
11381
+ status: "pass",
11382
+ message: r.coverageOptional,
11383
+ category: "bonus",
11384
+ weight: 0,
11385
+ group: "schema"
11386
+ });
11387
+ } else {
11388
+ const reqDef = SCHEMA_REQUIREMENTS[expected];
11389
+ const knownMissing = reqDef.required.filter(
11390
+ (f) => CMS_VERIFIABLE_SCHEMA_FIELDS.has(f) && !present[f]
11391
+ );
11392
+ const unverifiable = reqDef.required.filter((f) => !CMS_VERIFIABLE_SCHEMA_FIELDS.has(f));
11393
+ if (knownMissing.length > 0) {
11394
+ checks.push({
11395
+ id: "schema-coverage",
11396
+ label: r.coverageLabel,
11397
+ status: "warning",
11398
+ message: r.coverageMissing(expected, knownMissing.join(", ")),
11399
+ category: "bonus",
11400
+ weight: 1,
11401
+ group: "schema",
11402
+ tip: r.coverageMissingTip
11403
+ });
11404
+ } else if (unverifiable.length > 0) {
11405
+ checks.push({
11406
+ id: "schema-coverage",
11407
+ label: r.coverageLabel,
11408
+ status: "pass",
11409
+ message: r.coverageRemind(expected, unverifiable.join(", ")),
11410
+ category: "bonus",
11411
+ weight: 0,
11412
+ group: "schema"
11413
+ });
11414
+ } else {
11415
+ checks.push({
11416
+ id: "schema-coverage",
11417
+ label: r.coverageLabel,
11418
+ status: "pass",
11419
+ message: r.coveragePass(expected),
11420
+ category: "bonus",
11421
+ weight: 1,
11422
+ group: "schema"
11423
+ });
11424
+ }
11425
+ }
11426
+ if (faqPresent && true) {
11427
+ checks.push({
11428
+ id: "schema-faq-no-rich-result",
11429
+ label: r.faqNoRichResultLabel,
11430
+ status: "pass",
11431
+ message: r.faqNoRichResult,
11432
+ category: "bonus",
11433
+ weight: 0,
11434
+ group: "schema"
11435
+ });
11436
+ }
10576
11437
  return checks;
10577
11438
  }
10578
11439
 
@@ -10694,8 +11555,8 @@ function checkReadability(input, ctx) {
10694
11555
  label: r.passiveLabelFail,
10695
11556
  status: "warning",
10696
11557
  message: r.passiveFail(passiveSentences.length, sentences.length, Math.round(passiveRatio * 100)),
10697
- category: "important",
10698
- weight: 2,
11558
+ category: "bonus",
11559
+ weight: 0,
10699
11560
  group: "readability"
10700
11561
  });
10701
11562
  } else {
@@ -10704,8 +11565,8 @@ function checkReadability(input, ctx) {
10704
11565
  label: r.passiveLabelPass,
10705
11566
  status: "pass",
10706
11567
  message: r.passivePass(Math.round(passiveRatio * 100)),
10707
- category: "important",
10708
- weight: 2,
11568
+ category: "bonus",
11569
+ weight: 0,
10709
11570
  group: "readability"
10710
11571
  });
10711
11572
  }
@@ -10720,7 +11581,7 @@ function checkReadability(input, ctx) {
10720
11581
  status: "warning",
10721
11582
  message: r.transitionsFail(Math.round(transitionRatio * 100)),
10722
11583
  category: "bonus",
10723
- weight: 1,
11584
+ weight: 0,
10724
11585
  group: "readability"
10725
11586
  });
10726
11587
  } else {
@@ -10730,7 +11591,7 @@ function checkReadability(input, ctx) {
10730
11591
  status: "pass",
10731
11592
  message: r.transitionsPass(Math.round(transitionRatio * 100)),
10732
11593
  category: "bonus",
10733
- weight: 1,
11594
+ weight: 0,
10734
11595
  group: "readability"
10735
11596
  });
10736
11597
  }
@@ -11178,10 +12039,34 @@ function checkFreshness(input, ctx) {
11178
12039
  group: "freshness"
11179
12040
  });
11180
12041
  }
12042
+ if (input.displayedDate && input.updatedAt) {
12043
+ const displayedDays = daysSince(input.displayedDate);
12044
+ const updatedDays = daysSince(input.updatedAt);
12045
+ if (displayedDays !== Infinity && updatedDays !== Infinity && updatedDays - displayedDays > 60) {
12046
+ checks.push({
12047
+ id: "freshness-fake-refresh",
12048
+ label: r.fakeRefreshLabel,
12049
+ status: "warning",
12050
+ message: r.fakeRefreshWarn(displayedDays, updatedDays),
12051
+ category: "bonus",
12052
+ weight: 0,
12053
+ group: "freshness",
12054
+ tip: r.fakeRefreshTip
12055
+ });
12056
+ }
12057
+ }
11181
12058
  return checks;
11182
12059
  }
11183
12060
 
11184
12061
  // src/rules/technical.ts
12062
+ function isCrossCanonical(canonical, siteUrl, slug) {
12063
+ const norm = (p) => p.replace(/[?#].*$/, "").replace(/^\/+/, "").replace(/\/+$/, "").toLowerCase();
12064
+ const canonicalPath = norm(canonical.slice(siteUrl.length));
12065
+ const selfPath = norm(slug);
12066
+ const selfIsHome = selfPath === "" || selfPath === "home";
12067
+ if (selfIsHome) return canonicalPath !== "" && canonicalPath !== "home";
12068
+ return canonicalPath !== selfPath;
12069
+ }
11185
12070
  function checkTechnical(input, ctx) {
11186
12071
  const checks = [];
11187
12072
  const r = getTranslations(ctx.locale).rules.technical;
@@ -11219,6 +12104,16 @@ function checkTechnical(input, ctx) {
11219
12104
  weight: 2,
11220
12105
  group: "technical"
11221
12106
  });
12107
+ } else if (siteUrl && input.slug && !input.isGlobal && isCrossCanonical(canonical, siteUrl, input.slug)) {
12108
+ checks.push({
12109
+ id: "canonical-cross",
12110
+ label: r.canonicalCrossLabel,
12111
+ status: "warning",
12112
+ message: r.canonicalCrossMessage(canonical),
12113
+ category: "important",
12114
+ weight: 2,
12115
+ group: "technical"
12116
+ });
11222
12117
  } else {
11223
12118
  checks.push({
11224
12119
  id: "canonical-ok",
@@ -11511,6 +12406,336 @@ function checkEcommerce(input, ctx) {
11511
12406
  return checks;
11512
12407
  }
11513
12408
 
12409
+ // src/rules/eeat.ts
12410
+ var STRINGS = {
12411
+ fr: {
12412
+ authorLabel: "Auteur attribu\xE9 (E-E-A-T)",
12413
+ authorPass: "Un auteur est attribu\xE9 \u2014 bon signal de transparence E-E-A-T.",
12414
+ authorFail: "Aucun auteur identifi\xE9 \u2014 attribuez un auteur r\xE9el pour renforcer la confiance (E-E-A-T).",
12415
+ authorTip: "Ajoutez un auteur avec une courte bio et un lien vers son profil (Person schema + sameAs).",
12416
+ authorEntityLabel: "Entit\xE9 auteur (profil / sameAs)",
12417
+ authorEntityPass: "L'auteur a un lien de profil \u2014 renforce l'entit\xE9 (sameAs) pour les moteurs et l'IA.",
12418
+ authorEntityFail: "L'auteur n'a pas de lien de profil \u2014 ajoutez une URL (LinkedIn, page auteur) comme sameAs.",
12419
+ datesLabel: "Dates de publication / mise \xE0 jour",
12420
+ datesPass: "Dates de publication et de mise \xE0 jour disponibles \u2014 bon pour la fra\xEEcheur et la confiance.",
12421
+ datesFail: "Date de publication ou de mise \xE0 jour manquante \u2014 exposez datePublished et dateModified.",
12422
+ sourcesLabel: "Sources externes cit\xE9es",
12423
+ sourcesPass: (n) => `${n} lien(s) vers des sources externes \u2014 renforce la cr\xE9dibilit\xE9 et l'E-E-A-T.`,
12424
+ sourcesFail: "Aucune source externe cit\xE9e \u2014 liez des sources fiables pour appuyer vos affirmations.",
12425
+ sourcesTip: "Citez des \xE9tudes, donn\xE9es officielles ou r\xE9f\xE9rences sectorielles avec des liens sortants.",
12426
+ dataLabel: "Donn\xE9es originales / chiffr\xE9es",
12427
+ dataPass: "Le contenu pr\xE9sente des donn\xE9es chiffr\xE9es \u2014 signal d'expertise et de contenu original.",
12428
+ dataFail: "Peu de donn\xE9es chiffr\xE9es d\xE9tect\xE9es \u2014 ajoutez des chiffres, statistiques ou r\xE9sultats concrets.",
12429
+ dataTip: "Le contenu d\xE9montrant une exp\xE9rience de premi\xE8re main (donn\xE9es, chiffres, exemples v\xE9cus) est le levier de mont\xE9e n\xB01 en 2026."
12430
+ },
12431
+ en: {
12432
+ authorLabel: "Attributed author (E-E-A-T)",
12433
+ authorPass: "An author is attributed \u2014 good E-E-A-T transparency signal.",
12434
+ authorFail: "No identified author \u2014 attribute a real author to strengthen trust (E-E-A-T).",
12435
+ authorTip: "Add an author with a short bio and a link to their profile (Person schema + sameAs).",
12436
+ authorEntityLabel: "Author entity (profile / sameAs)",
12437
+ authorEntityPass: "The author has a profile link \u2014 strengthens the entity (sameAs) for search and AI.",
12438
+ authorEntityFail: "The author has no profile link \u2014 add a URL (LinkedIn, author page) as sameAs.",
12439
+ datesLabel: "Published / updated dates",
12440
+ datesPass: "Published and modified dates available \u2014 good for freshness and trust.",
12441
+ datesFail: "Published or modified date missing \u2014 expose datePublished and dateModified.",
12442
+ sourcesLabel: "External sources cited",
12443
+ sourcesPass: (n) => `${n} link(s) to external sources \u2014 strengthens credibility and E-E-A-T.`,
12444
+ sourcesFail: "No external source cited \u2014 link reliable sources to back your claims.",
12445
+ sourcesTip: "Cite studies, official data or industry references with outbound links.",
12446
+ dataLabel: "Original / quantitative data",
12447
+ dataPass: "The content includes quantitative data \u2014 a signal of expertise and original content.",
12448
+ dataFail: "Little quantitative data detected \u2014 add figures, statistics or concrete results.",
12449
+ dataTip: "First-hand-experience content (data, figures, lived examples) is the #1 visibility lever in 2026."
12450
+ }
12451
+ };
12452
+ var EEAT_SKIP_PAGE_TYPES = /* @__PURE__ */ new Set(["legal", "contact", "form", "home"]);
12453
+ function checkEeat(input, ctx) {
12454
+ const checks = [];
12455
+ if (EEAT_SKIP_PAGE_TYPES.has(ctx.pageType) || ctx.wordCount < 100) return checks;
12456
+ const s = STRINGS[ctx.locale] ?? STRINGS.fr;
12457
+ const hasAuthor = !!(input.author && input.author.trim());
12458
+ checks.push({
12459
+ id: "eeat-author",
12460
+ label: s.authorLabel,
12461
+ status: hasAuthor ? "pass" : "warning",
12462
+ message: hasAuthor ? s.authorPass : s.authorFail,
12463
+ category: "important",
12464
+ weight: 0,
12465
+ group: "eeat",
12466
+ ...hasAuthor ? {} : { tip: s.authorTip }
12467
+ });
12468
+ if (hasAuthor) {
12469
+ const hasLink = !!(input.authorUrl && input.authorUrl.trim());
12470
+ checks.push({
12471
+ id: "eeat-author-entity",
12472
+ label: s.authorEntityLabel,
12473
+ status: hasLink ? "pass" : "warning",
12474
+ message: hasLink ? s.authorEntityPass : s.authorEntityFail,
12475
+ category: "bonus",
12476
+ weight: 0,
12477
+ group: "eeat"
12478
+ });
12479
+ }
12480
+ const datesOk = !!input.publishedAt && !!input.updatedAt;
12481
+ checks.push({
12482
+ id: "eeat-dates",
12483
+ label: s.datesLabel,
12484
+ status: datesOk ? "pass" : "warning",
12485
+ message: datesOk ? s.datesPass : s.datesFail,
12486
+ category: "bonus",
12487
+ weight: 0,
12488
+ group: "eeat"
12489
+ });
12490
+ const externalLinks = ctx.allLinks.filter((l) => /^https?:\/\//i.test(l.url));
12491
+ const hasSources = externalLinks.length > 0;
12492
+ checks.push({
12493
+ id: "eeat-sources",
12494
+ label: s.sourcesLabel,
12495
+ status: hasSources ? "pass" : "warning",
12496
+ message: hasSources ? s.sourcesPass(externalLinks.length) : s.sourcesFail,
12497
+ category: "bonus",
12498
+ weight: 0,
12499
+ group: "eeat",
12500
+ ...hasSources ? {} : { tip: s.sourcesTip }
12501
+ });
12502
+ const hasPercent = /\d+([.,]\d+)?\s?%/.test(ctx.fullText);
12503
+ const numberCount = (ctx.fullText.match(/\b\d{2,}\b/g) || []).length;
12504
+ const hasData = hasPercent || numberCount >= 3;
12505
+ checks.push({
12506
+ id: "eeat-original-data",
12507
+ label: s.dataLabel,
12508
+ status: hasData ? "pass" : "warning",
12509
+ message: hasData ? s.dataPass : s.dataFail,
12510
+ category: "bonus",
12511
+ weight: 0,
12512
+ group: "eeat",
12513
+ ...hasData ? {} : { tip: s.dataTip }
12514
+ });
12515
+ return checks;
12516
+ }
12517
+
12518
+ // src/rules/geo.ts
12519
+ var QUESTION_WORDS = {
12520
+ fr: ["comment", "pourquoi", "quand", "quel", "quelle", "quels", "quelles", "combien", "ou", "o\xF9", "qui", "que", "quoi", "est-ce"],
12521
+ en: ["how", "why", "when", "what", "which", "where", "who", "can", "do", "does", "is", "are", "should"]
12522
+ };
12523
+ var STRINGS2 = {
12524
+ fr: {
12525
+ answerLabel: "R\xE9ponse en t\xEAte (answer-first)",
12526
+ answerPass: "Le contenu d\xE9marre par une accroche concise \u2014 favorise l'extraction par l'IA.",
12527
+ answerFail: "Le contenu ne d\xE9marre pas par une r\xE9ponse concise \u2014 placez une r\xE9ponse directe en t\xEAte de page/section.",
12528
+ answerTip: "Format BLUF (Bottom Line Up Front) : r\xE9pondez \xE0 l'intention en 1-2 phrases avant de d\xE9velopper.",
12529
+ questionsLabel: "Titres en question",
12530
+ questionsPass: (n) => `${n} sous-titre(s) formul\xE9(s) en question \u2014 structure Q\u2192R id\xE9ale pour l'IA.`,
12531
+ questionsFail: "Aucun titre en question \u2014 formulez certains H2/H3 en questions (les moteurs IA citent les paires question/r\xE9ponse).",
12532
+ structureLabel: "Contenu extractible (listes / tableaux)",
12533
+ structurePass: "Listes ou tableaux d\xE9tect\xE9s \u2014 unit\xE9s facilement extraites et cit\xE9es par l'IA.",
12534
+ structureFail: "Aucune liste ni tableau \u2014 structurez les \xE9num\xE9rations et comparaisons en listes/tableaux.",
12535
+ chunkLabel: "Contenu d\xE9coup\xE9 (scannable)",
12536
+ chunkPass: "Contenu bien d\xE9coup\xE9 en sections \u2014 facilite l'extraction de passages.",
12537
+ chunkFail: "Contenu peu d\xE9coup\xE9 \u2014 ajoutez des sous-titres pour cr\xE9er des passages auto-suffisants."
12538
+ },
12539
+ en: {
12540
+ answerLabel: "Answer-first lead",
12541
+ answerPass: "Content opens with a concise lead \u2014 helps AI extraction.",
12542
+ answerFail: "Content does not open with a concise answer \u2014 put a direct answer at the top of the page/section.",
12543
+ answerTip: "BLUF (Bottom Line Up Front): answer the intent in 1-2 sentences before expanding.",
12544
+ questionsLabel: "Question-style headings",
12545
+ questionsPass: (n) => `${n} heading(s) phrased as questions \u2014 ideal Q\u2192A structure for AI.`,
12546
+ questionsFail: "No question headings \u2014 phrase some H2/H3 as questions (AI engines cite question/answer pairs).",
12547
+ structureLabel: "Extractable content (lists / tables)",
12548
+ structurePass: "Lists or tables detected \u2014 units easily extracted and cited by AI.",
12549
+ structureFail: "No list or table \u2014 structure enumerations and comparisons as lists/tables.",
12550
+ chunkLabel: "Chunked content (scannable)",
12551
+ chunkPass: "Content is well chunked into sections \u2014 helps passage extraction.",
12552
+ chunkFail: "Content is barely chunked \u2014 add subheadings to create self-contained passages."
12553
+ }
12554
+ };
12555
+ var GEO_SKIP_PAGE_TYPES = /* @__PURE__ */ new Set(["legal", "contact", "form", "home"]);
12556
+ function isQuestionHeading(text, locale) {
12557
+ const t = text.trim().toLowerCase();
12558
+ if (t.endsWith("?")) return true;
12559
+ const words = QUESTION_WORDS[locale] ?? QUESTION_WORDS.fr;
12560
+ return words.some((w) => t.startsWith(w + " ") || t.startsWith(w + "-"));
12561
+ }
12562
+ function collectLexicalSources(input) {
12563
+ const sources = [];
12564
+ if (input.heroRichText) sources.push(input.heroRichText);
12565
+ if (input.content) sources.push(input.content);
12566
+ if (Array.isArray(input.blocks)) {
12567
+ for (const b of input.blocks) {
12568
+ if (!b || typeof b !== "object") continue;
12569
+ const blk = b;
12570
+ if (blk.richText) sources.push(blk.richText);
12571
+ if (Array.isArray(blk.columns)) {
12572
+ for (const c of blk.columns) {
12573
+ if (c && typeof c === "object" && c.richText) {
12574
+ sources.push(c.richText);
12575
+ }
12576
+ }
12577
+ }
12578
+ }
12579
+ }
12580
+ return sources;
12581
+ }
12582
+ function containsLexicalType(node, type, depth = 0) {
12583
+ if (depth > 50 || !node || typeof node !== "object") return false;
12584
+ const n = node;
12585
+ if (n.type === type) return true;
12586
+ const root = n.root || n;
12587
+ const children = root.children || n.children;
12588
+ if (Array.isArray(children)) {
12589
+ for (const c of children) {
12590
+ if (containsLexicalType(c, type, depth + 1)) return true;
12591
+ }
12592
+ }
12593
+ return false;
12594
+ }
12595
+ function checkGeo(input, ctx) {
12596
+ const checks = [];
12597
+ if (GEO_SKIP_PAGE_TYPES.has(ctx.pageType) || ctx.wordCount < 150) return checks;
12598
+ const s = STRINGS2[ctx.locale] ?? STRINGS2.fr;
12599
+ const locale = ctx.locale;
12600
+ const firstSentence = (ctx.sentences[0] || "").trim();
12601
+ const firstSentenceWords = firstSentence ? firstSentence.split(/\s+/).length : 0;
12602
+ const answerFirst = firstSentenceWords > 0 && firstSentenceWords <= 30;
12603
+ checks.push({
12604
+ id: "geo-answer-first",
12605
+ label: s.answerLabel,
12606
+ status: answerFirst ? "pass" : "warning",
12607
+ message: answerFirst ? s.answerPass : s.answerFail,
12608
+ category: "bonus",
12609
+ weight: 0,
12610
+ group: "geo",
12611
+ ...answerFirst ? {} : { tip: s.answerTip }
12612
+ });
12613
+ const questionHeadings = ctx.allHeadings.filter(
12614
+ (h) => h.tag !== "h1" && isQuestionHeading(h.text, locale)
12615
+ ).length;
12616
+ checks.push({
12617
+ id: "geo-question-headings",
12618
+ label: s.questionsLabel,
12619
+ status: questionHeadings > 0 ? "pass" : "warning",
12620
+ message: questionHeadings > 0 ? s.questionsPass(questionHeadings) : s.questionsFail,
12621
+ category: "bonus",
12622
+ weight: 0,
12623
+ group: "geo"
12624
+ });
12625
+ const sources = collectLexicalSources(input);
12626
+ const hasList = sources.some((src) => extractListsFromLexical(src).length > 0);
12627
+ const hasTable = sources.some((src) => containsLexicalType(src, "table"));
12628
+ const structured = hasList || hasTable;
12629
+ checks.push({
12630
+ id: "geo-extractable-structure",
12631
+ label: s.structureLabel,
12632
+ status: structured ? "pass" : "warning",
12633
+ message: structured ? s.structurePass : s.structureFail,
12634
+ category: "bonus",
12635
+ weight: 0,
12636
+ group: "geo"
12637
+ });
12638
+ const subheadings = ctx.allHeadings.filter((h) => h.tag !== "h1").length;
12639
+ const expected = Math.max(1, Math.floor(ctx.wordCount / 300));
12640
+ const chunked = subheadings >= expected;
12641
+ checks.push({
12642
+ id: "geo-chunked",
12643
+ label: s.chunkLabel,
12644
+ status: chunked ? "pass" : "warning",
12645
+ message: chunked ? s.chunkPass : s.chunkFail,
12646
+ category: "bonus",
12647
+ weight: 0,
12648
+ group: "geo"
12649
+ });
12650
+ return checks;
12651
+ }
12652
+
12653
+ // src/rules/hreflang.ts
12654
+ var HREFLANG_RE = /^[a-z]{2,3}(-[a-z]{2,4})?$/i;
12655
+ var STRINGS3 = {
12656
+ fr: {
12657
+ codesLabel: "Codes hreflang valides",
12658
+ codesPass: "Tous les codes hreflang sont au format valide (langue ISO 639-1, r\xE9gion ISO 3166-1 optionnelle).",
12659
+ codesFail: (bad) => `Code(s) hreflang invalide(s) : ${bad} \u2014 un seul code erron\xE9 fait ignorer tout le cluster par Google.`,
12660
+ dupLabel: "Doublons hreflang",
12661
+ dupPass: "Aucun doublon de code hreflang.",
12662
+ dupFail: (dup) => `Code(s) hreflang en double : ${dup} \u2014 chaque locale doit \xEAtre d\xE9clar\xE9e une seule fois.`,
12663
+ absLabel: "URLs hreflang absolues",
12664
+ absPass: "Toutes les URLs hreflang sont absolues.",
12665
+ absFail: "Certaines URLs hreflang ne sont pas absolues \u2014 utilisez des URLs compl\xE8tes (https://...).",
12666
+ xdefLabel: "hreflang x-default",
12667
+ xdefPass: "Un x-default est d\xE9fini \u2014 bonne pratique pour les visiteurs hors locales cibl\xE9es.",
12668
+ xdefFail: 'Aucun x-default \u2014 ajoutez un hreflang="x-default" pour les locales non couvertes.'
12669
+ },
12670
+ en: {
12671
+ codesLabel: "Valid hreflang codes",
12672
+ codesPass: "All hreflang codes are well-formed (ISO 639-1 language, optional ISO 3166-1 region).",
12673
+ codesFail: (bad) => `Invalid hreflang code(s): ${bad} \u2014 a single bad code makes Google ignore the whole cluster.`,
12674
+ dupLabel: "Duplicate hreflang",
12675
+ dupPass: "No duplicate hreflang code.",
12676
+ dupFail: (dup) => `Duplicate hreflang code(s): ${dup} \u2014 each locale must be declared once.`,
12677
+ absLabel: "Absolute hreflang URLs",
12678
+ absPass: "All hreflang URLs are absolute.",
12679
+ absFail: "Some hreflang URLs are not absolute \u2014 use full URLs (https://...).",
12680
+ xdefLabel: "hreflang x-default",
12681
+ xdefPass: "An x-default is defined \u2014 good practice for visitors outside targeted locales.",
12682
+ xdefFail: 'No x-default \u2014 add hreflang="x-default" for locales you do not cover.'
12683
+ }
12684
+ };
12685
+ function checkHreflang(input, ctx) {
12686
+ const alts = input.localeAlternates;
12687
+ if (!Array.isArray(alts) || alts.length === 0) return [];
12688
+ const s = STRINGS3[ctx.locale] ?? STRINGS3.fr;
12689
+ const checks = [];
12690
+ const codes = alts.map((a) => (a.hreflang || "").trim()).filter(Boolean);
12691
+ const invalid = codes.filter((c) => c.toLowerCase() !== "x-default" && !HREFLANG_RE.test(c));
12692
+ checks.push({
12693
+ id: "hreflang-codes",
12694
+ label: s.codesLabel,
12695
+ status: invalid.length === 0 ? "pass" : "fail",
12696
+ message: invalid.length === 0 ? s.codesPass : s.codesFail(invalid.join(", ")),
12697
+ category: "important",
12698
+ weight: 2,
12699
+ group: "hreflang"
12700
+ });
12701
+ const seen = /* @__PURE__ */ new Set();
12702
+ const dups = /* @__PURE__ */ new Set();
12703
+ for (const c of codes.map((c2) => c2.toLowerCase())) {
12704
+ if (seen.has(c)) dups.add(c);
12705
+ seen.add(c);
12706
+ }
12707
+ checks.push({
12708
+ id: "hreflang-duplicates",
12709
+ label: s.dupLabel,
12710
+ status: dups.size === 0 ? "pass" : "warning",
12711
+ message: dups.size === 0 ? s.dupPass : s.dupFail([...dups].join(", ")),
12712
+ category: "important",
12713
+ weight: 1,
12714
+ group: "hreflang"
12715
+ });
12716
+ const allAbsolute = alts.every((a) => /^https?:\/\//i.test((a.href || "").trim()));
12717
+ checks.push({
12718
+ id: "hreflang-absolute",
12719
+ label: s.absLabel,
12720
+ status: allAbsolute ? "pass" : "warning",
12721
+ message: allAbsolute ? s.absPass : s.absFail,
12722
+ category: "important",
12723
+ weight: 1,
12724
+ group: "hreflang"
12725
+ });
12726
+ const hasXDefault = codes.some((c) => c.toLowerCase() === "x-default");
12727
+ checks.push({
12728
+ id: "hreflang-x-default",
12729
+ label: s.xdefLabel,
12730
+ status: hasXDefault ? "pass" : "warning",
12731
+ message: hasXDefault ? s.xdefPass : s.xdefFail,
12732
+ category: "bonus",
12733
+ weight: 1,
12734
+ group: "hreflang"
12735
+ });
12736
+ return checks;
12737
+ }
12738
+
11514
12739
  // src/index.ts
11515
12740
  function buildContext(data, config) {
11516
12741
  const {
@@ -11715,6 +12940,9 @@ function analyzeSeo(data, config) {
11715
12940
  { group: "freshness", fn: checkFreshness },
11716
12941
  { group: "technical", fn: checkTechnical },
11717
12942
  { group: "accessibility", fn: checkAccessibility },
12943
+ { group: "eeat", fn: checkEeat },
12944
+ { group: "geo", fn: checkGeo },
12945
+ { group: "hreflang", fn: checkHreflang },
11718
12946
  // E-commerce rules only run for product pages
11719
12947
  ...data.isProduct ? [{ group: "ecommerce", fn: checkEcommerce }] : []
11720
12948
  ];
@@ -11746,7 +12974,24 @@ function analyzeSeo(data, config) {
11746
12974
  if (score >= SCORE_EXCELLENT) level = "excellent";
11747
12975
  else if (score >= SCORE_GOOD) level = "good";
11748
12976
  else if (score >= SCORE_OK) level = "ok";
11749
- return { score, level, checks };
12977
+ const aiChecks = checks.filter(
12978
+ (c) => c.group === "geo" || c.group === "eeat" || c.id === "schema-coverage"
12979
+ );
12980
+ let aiReadiness;
12981
+ if (aiChecks.length > 0) {
12982
+ let aiEarned = 0;
12983
+ for (const c of aiChecks) {
12984
+ if (c.status === "pass") aiEarned += 1;
12985
+ else if (c.status === "warning") aiEarned += WARNING_MULTIPLIER;
12986
+ }
12987
+ const aiScore = Math.round(aiEarned / aiChecks.length * 100);
12988
+ let aiLevel = "poor";
12989
+ if (aiScore >= SCORE_EXCELLENT) aiLevel = "excellent";
12990
+ else if (aiScore >= SCORE_GOOD) aiLevel = "good";
12991
+ else if (aiScore >= SCORE_OK) aiLevel = "ok";
12992
+ aiReadiness = { score: aiScore, level: aiLevel, checkCount: aiChecks.length };
12993
+ }
12994
+ return { score, level, checks, ...aiReadiness ? { aiReadiness } : {} };
11750
12995
  }
11751
12996
 
11752
12997
  export { ACTION_VERBS, EVERGREEN_SLUGS, FLESCH_THRESHOLDS, GENERIC_ANCHORS, KEYWORD_DENSITY_MAX, KEYWORD_DENSITY_MIN, KEYWORD_DENSITY_WARN, LEGAL_SLUGS_MAP, MAX_RECURSION_DEPTH, META_DESC_LENGTH_MAX, META_DESC_LENGTH_MIN, MIN_WORDS_FORM, MIN_WORDS_GENERIC, MIN_WORDS_LEGAL, MIN_WORDS_POST, MIN_WORDS_THIN, POWER_WORDS, POWER_WORDS_FR, READABILITY_THRESHOLDS, SCORE_EXCELLENT, SCORE_GOOD, SCORE_OK, STOP_WORDS, STOP_WORD_COMPOUNDS_MAP, TITLE_LENGTH_MAX, TITLE_LENGTH_MIN, UTILITY_SLUGS, WARNING_MULTIPLIER, analyzeSeo, buildSeoInputFromDoc, calculateFlesch, calculateFleschFR, checkHeadingHierarchy, checkImagesInBlocks, countKeywordOccurrences, countLongSections, countSentences, countSyllablesEN, countSyllablesFR, countWords, createAiRewriteHandler, createDuplicateContentHandler, createGenerateHandler, createHistoryHandler, createKeywordResearchHandler, createPerformanceHandler, createRedirectChainsHandler, createSchemaGeneratorHandler, createSeoPerformanceCollection, createSeoScoreHistoryCollection, createSitemapAuditHandler, createTrackSeoScoreHook, detectPageType, detectPassiveVoice, extractHeadingsFromLexical, extractImagesFromLexical, extractLinkUrlsFromLexical, extractLinksFromLexical, extractListsFromLexical, extractTextFromLexical, fetchAllDocs, getActionVerbs, getActionVerbsFR, getDashboardT, getEvergreenSlugs, getGenericAnchors, getLegalSlugs, getPowerWords, getStopWordCompounds, getStopWords, getStopWordsFR, getUtilitySlugs, hasTransitionWord, isStopWordInCompoundExpression, keywordMatchesText, metaFields, normalizeForComparison, registerDashboardTranslations, resolveAnalysisLocale, seoAnalyzerPlugin, seoFields, seoAnalyzerPlugin as seoPlugin, slugifyKeyword };