From e760455aee6fc21c4d81e5015eeab40b42d5fbf9 Mon Sep 17 00:00:00 2001 From: liqinglian01 <105912712+liqinglian01@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:41:46 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E8=B5=84=E6=96=99=E4=B8=AD?= =?UTF-8?q?=E5=BF=83=E6=90=9C=E7=B4=A2=E6=8A=8A=20S100=20=E4=B8=93?= =?UTF-8?q?=E5=B1=9E=E7=AB=A0=E8=8A=82=E6=A0=87=E6=88=90=20S600=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E5=8E=BB=E6=8E=89=E5=90=8C=E4=B8=80=E7=AB=A0=E8=8A=82?= =?UTF-8?q?=E7=9A=84=E5=A4=9A=E7=89=88=E6=9C=AC=E9=87=8D=E5=A4=8D=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- scripts/algolia-index.mjs | 39 ++++++- scripts/doc-scope-index.mjs | 150 +++++++++++++++++++++++++++ scripts/doc-scope-index.test.mjs | 172 +++++++++++++++++++++++++++++++ src/data/algoliaSites.js | 43 ++++++-- src/data/sites.js | 2 +- src/utils/docCenterSearch.js | 95 +++++++++++------ src/utils/sSeriesSearch.mjs | 108 +++++++++++++++++++ 7 files changed, 563 insertions(+), 46 deletions(-) create mode 100644 scripts/doc-scope-index.mjs create mode 100644 scripts/doc-scope-index.test.mjs create mode 100644 src/utils/sSeriesSearch.mjs diff --git a/scripts/algolia-index.mjs b/scripts/algolia-index.mjs index 8b2b8c1..a61a5be 100644 --- a/scripts/algolia-index.mjs +++ b/scripts/algolia-index.mjs @@ -25,6 +25,11 @@ import { isSphinxOeRoot, rspressPublicPath, } from "../src/utils/rspressDocUrl.mjs"; +import { + pathAllowsProduct, + removeOutOfScope, + stampScopeUrl, +} from "./doc-scope-index.mjs"; const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); const TMP_DIR = join(ROOT, "scripts", "_algolia_tmp"); @@ -204,7 +209,10 @@ async function fetchOnce(url, accept) { return { ok: false, status: 0, url: current, res: null }; } +const fetchCache = new Map(); + async function fetchText(url, { accept = "text/html,application/xhtml+xml,application/xml,application/json,text/xml,*/*", warn = true } = {}) { + if (fetchCache.has(url)) return fetchCache.get(url); const prevTls = process.env.NODE_TLS_REJECT_UNAUTHORIZED; if (isToolchain(url)) { process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; @@ -224,7 +232,9 @@ async function fetchText(url, { accept = "text/html,application/xhtml+xml,applic lastError = `content-type ${ct} ${candidate}`; continue; } - return { url: got.url || candidate, text: await got.res.text() }; + const result = { url: got.url || candidate, text: await got.res.text() }; + fetchCache.set(url, result); + return result; } catch (e) { lastError = `${e.message} ${candidate}`; } @@ -232,7 +242,9 @@ async function fetchText(url, { accept = "text/html,application/xhtml+xml,applic if (warn) { console.warn(` fetch fail: ${url} (${lastError || "no candidate succeeded"})`); } - return null; + const missed = null; + fetchCache.set(url, missed); + return missed; } finally { if (isToolchain(url)) { if (prevTls === undefined) delete process.env.NODE_TLS_REJECT_UNAUTHORIZED; @@ -438,11 +450,21 @@ function readMeta($, name) { ); } -function extractRecords(html, pageUrl, { site, manualTitle, language }) { +function extractRecords(html, pageUrl, { site, manualTitle, language, product = "", version = "" }) { + let pathname = ""; + try { + pathname = new URL(pageUrl).pathname; + } catch { + pathname = ""; + } + if (!pathAllowsProduct(pathname, product)) return []; + const $ = cheerio.load(html); // Prefer markdown article only — avoids sidebar/toc list explosion const root = pickContentRoot($); root.find("nav, .theme-doc-toc-desktop, .theme-doc-toc-mobile, .pagination-nav, .hash-link").remove(); + // Shared sites publish every product/version block in one HTML document. + removeOutOfScope($, root, product, version); const pageTitle = root.find("h1").first().text().trim() || @@ -467,7 +489,7 @@ function extractRecords(html, pageUrl, { site, manualTitle, language }) { lvl6: null, }; - const urlWithoutAnchor = normalizeUrl(pageUrl); + const urlWithoutAnchor = stampScopeUrl(normalizeUrl(pageUrl), product, version); const records = []; let position = 0; let currentAnchor = @@ -574,7 +596,12 @@ async function crawlLocale(target, localeCfg) { const { site, manualTitle } = target; const title = localeCfg.language === "en" ? manualTitle.en : manualTitle.zh; - console.log(`\n[${site}] ${localeCfg.language} ← ${localeCfg.startUrl}`); + const product = localeCfg.product || target.product || ""; + const version = localeCfg.version || target.version || ""; + const scopeLabel = [product, version].filter(Boolean).join(" "); + console.log( + `\n[${site}] ${localeCfg.language}${scopeLabel ? ` ${scopeLabel}` : ""} ← ${localeCfg.startUrl}`, + ); let pageEntries = []; const startPage = await fetchText(localeCfg.startUrl); @@ -611,6 +638,8 @@ async function crawlLocale(target, localeCfg) { site, manualTitle: title, language: localeCfg.language, + product, + version, }), ); } catch (e) { diff --git a/scripts/doc-scope-index.mjs b/scripts/doc-scope-index.mjs new file mode 100644 index 0000000..6ce42bb --- /dev/null +++ b/scripts/doc-scope-index.mjs @@ -0,0 +1,150 @@ +/** + * Doc center crawl helpers for manuals that share one site (S100/S600, X3/X5). + * The published HTML keeps every DocScope block; the indexer must keep only the + * block that matches the manual card's product and version. + */ + +const PRODUCT_PATH_MARKERS = [ + ["/rdk_x5_module", "RDK X5 Module"], + ["/rdk_x3_module", "RDK X3 Module"], + ["/rdk_x5", "RDK X5"], + ["/rdk_x3", "RDK X3"], + ["/rdk_s600", "RDK S600"], + ["/rdk_s100", "RDK S100"], +]; + +function norm(value) { + return String(value || "") + .trim() + .replace(/\s+/g, " ") + .toLowerCase(); +} + +function seriesKey(entry) { + const match = String(entry || "").trim().match(/^rdk\s*-\s*(.+)$/i); + if (!match) return ""; + return norm(`RDK ${match[1]}`); +} + +export function productsMatch(scopeProducts, product) { + if (!scopeProducts || scopeProducts.length === 0) return true; + if (!product) return false; + const current = norm(product); + for (const entry of scopeProducts) { + const series = seriesKey(entry); + if (series && (current === series || current.startsWith(`${series} `))) { + return true; + } + if (norm(entry) === current) return true; + } + return false; +} + +function compareVersions(a, b) { + const left = String(a || "").split(".").map((part) => Number(part) || 0); + const right = String(b || "").split(".").map((part) => Number(part) || 0); + const length = Math.max(left.length, right.length); + for (let i = 0; i < length; i += 1) { + const delta = (left[i] || 0) - (right[i] || 0); + if (delta) return delta > 0 ? 1 : -1; + } + return 0; +} + +function versionRuleMatches(current, rule) { + if (rule == null) return false; + if (typeof rule === "string") { + const parsed = rule.trim().match(/^(>=|<=|>|<)?\s*(\d+(?:\.\d+)*)$/); + if (!parsed) return rule.trim() === current; + return versionRuleMatches(current, { operator: parsed[1] || "", version: parsed[2] }); + } + const operator = rule.operator || ""; + const version = rule.version; + if (!version) return false; + const cmp = compareVersions(current, version); + if (operator === ">") return cmp > 0; + if (operator === ">=") return cmp >= 0; + if (operator === "<") return cmp < 0; + if (operator === "<=") return cmp <= 0; + return cmp === 0; +} + +export function versionsMatch(scopeVersions, version) { + if (!scopeVersions || scopeVersions.length === 0) return true; + if (!version) return false; + return scopeVersions.some((rule) => versionRuleMatches(version, rule)); +} + +export function scopeVisible(scopeProductsAttr, docScopeAttr, product, version) { + if (!product && !version) return true; + + let products = []; + let versions = []; + let parsed = false; + if (docScopeAttr) { + try { + const spec = JSON.parse(docScopeAttr); + products = Array.isArray(spec.products) ? spec.products : []; + versions = Array.isArray(spec.versions) ? spec.versions : []; + parsed = true; + } catch { + parsed = false; + } + } + if (scopeProductsAttr) { + const tokens = String(scopeProductsAttr) + .split(",") + .map((item) => item.trim()) + .filter(Boolean); + if (tokens.length) products = tokens; + parsed = true; + } + if (!parsed) return true; + if (!productsMatch(products, product)) return false; + if (!versionsMatch(versions, version)) return false; + return true; +} + +export function removeOutOfScope($, root, product, version) { + if (!product && !version) return; + const nodes = root + .find("[data-doc-scope]") + .toArray() + .sort((a, b) => $(b).parents().length - $(a).parents().length); + for (const el of nodes) { + const $el = $(el); + if (!$el.parent || $el.parent().length === 0) continue; + if ( + !scopeVisible( + $el.attr("data-scope-products"), + $el.attr("data-doc-scope"), + product, + version, + ) + ) { + $el.remove(); + } + } +} + +export function pathAllowsProduct(pathname, product) { + if (!product) return true; + const path = String(pathname || "").toLowerCase(); + for (const [marker, owner] of PRODUCT_PATH_MARKERS) { + if (path.includes(marker)) return owner === product; + } + return true; +} + +export function stampScopeUrl(url, product, version) { + if (!product && !version) return url; + let parsed; + try { + parsed = new URL(url); + } catch { + return url; + } + if (product && !parsed.searchParams.get("p")) parsed.searchParams.set("p", product); + if (version && !parsed.searchParams.get("v")) parsed.searchParams.set("v", version); + return parsed.toString(); +} diff --git a/scripts/doc-scope-index.test.mjs b/scripts/doc-scope-index.test.mjs new file mode 100644 index 0000000..133930c --- /dev/null +++ b/scripts/doc-scope-index.test.mjs @@ -0,0 +1,172 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import * as cheerio from "cheerio"; +import { + pathAllowsProduct, + productsMatch, + removeOutOfScope, + scopeVisible, + stampScopeUrl, + versionsMatch, +} from "./doc-scope-index.mjs"; +import { getAlgoliaCrawlTargets } from "./algolia-sites.mjs"; +import { + dedupeHits, + mergeSSeriesHits, + sSeriesFilter, + sSeriesPins, + zipByTitleMatch, +} from "../src/utils/sSeriesSearch.mjs"; + +const HTML = ` +
+
+

1.6 资源汇总

+
+

认证资料

+
+
+

系统软件

+
+
+

系统软件

+
+

共用说明

+
+
+`; + +function headings(product, version) { + const $ = cheerio.load(HTML); + const root = $(".theme-doc-markdown"); + removeOutOfScope($, root, product, version); + return root + .find("h2") + .toArray() + .map((el) => $(el).attr("id")); +} + +test("S600 5.1.1 drops the S100 certification chapter and the other S600 version", () => { + assert.deepEqual(headings("RDK S600", "5.1.1"), ["s600-511", "shared"]); +}); + +test("S100 keeps its certification chapter", () => { + assert.deepEqual(headings("RDK S100", "4.0.5"), ["认证资料", "shared"]); +}); + +test("product series and version rules", () => { + assert.equal(productsMatch(["RDK-X5"], "RDK X5 Module"), true); + assert.equal(productsMatch(["RDK-X5"], "RDK X3"), false); + assert.equal(productsMatch(["RDK S100"], "RDK S600"), false); + assert.equal(versionsMatch([{ operator: "", version: "5.1.1" }], "5.1.0"), false); + assert.equal(versionsMatch([{ operator: ">=", version: "5.1.0" }], "5.1.1"), true); + assert.equal( + scopeVisible( + "RDK S100", + '{"versions":[],"products":["RDK S100"]}', + "RDK S600", + "5.1.1", + ), + false, + ); +}); + +test("product folders stay on their own manual", () => { + assert.equal( + pathAllowsProduct("/rdk_s_doc/Quick_start/hardware_introduction/rdk_s100/kit", "RDK S600"), + false, + ); + assert.equal( + pathAllowsProduct("/rdk_x_doc/Advanced_development/rdk_x5_module/accessory", "RDK X5"), + false, + ); + assert.equal( + pathAllowsProduct("/rdk_s_doc/Quick_start/download", "RDK S600"), + true, + ); +}); + +test("scoped url keeps the manual product and version", () => { + assert.equal( + stampScopeUrl("https://developer.d-robotics.cc/rdk_s_doc/Quick_start/download", "RDK S100", "4.0.5"), + "https://developer.d-robotics.cc/rdk_s_doc/Quick_start/download?p=RDK+S100&v=4.0.5", + ); +}); + +test("S100 and S600 are separate crawl targets", () => { + const targets = getAlgoliaCrawlTargets().filter((target) => target.site === "rdk_s_doc"); + const titles = targets.map((target) => `${target.manualTitle.zh} ${target.version}`).sort(); + assert.deepEqual(titles, ["RDK S100 4.0.5", "RDK S600 5.1.1"]); +}); + +test("search replaces collapsed S600 hits with the scoped manual hits", () => { + const federated = [ + { site: "rdk_studio_doc", manualTitle: "RDK Studio", url: "https://developer.d-robotics.cc/rdk_studio_doc/auth" }, + { + site: "rdk_s_doc", + manualTitle: "RDK S600", + url: "https://developer.d-robotics.cc/rdk_s_doc/Quick_start/download#认证资料", + }, + { + site: "rdk_s_doc", + manualTitle: "RDK S600", + url: "https://developer.d-robotics.cc/rdk_s_doc/FAQ/hardware_and_system?p=RDK+S600&v=5.1.0", + }, + ]; + const scoped = [ + { + site: "rdk_s_doc", + manualTitle: "RDK S100", + product: "RDK S100", + url: "https://developer.d-robotics.cc/rdk_s_doc/Quick_start/download?p=RDK+S100&v=4.0.5#认证资料", + }, + { + site: "rdk_s_doc", + manualTitle: "RDK S600", + product: "RDK S600", + url: "https://developer.d-robotics.cc/rdk_s_doc/FAQ/hardware_and_system?p=RDK+S600&v=5.1.1", + }, + ]; + const merged = mergeSSeriesHits(federated, scoped); + assert.deepEqual( + merged.map((hit) => hit.manualTitle), + ["RDK Studio", "RDK S100", "RDK S600"], + ); + assert.equal(merged.some((hit) => hit.url.includes("#认证资料") && hit.manualTitle === "RDK S600"), false); +}); + +test("same chapter in two versions collapses to one hit", () => { + const hits = dedupeHits([ + { + manualTitle: "RDK S600", + url: "https://developer.d-robotics.cc/rdk_s_doc/FAQ/hardware_and_system?p=RDK+S600&v=5.1.1#认证", + }, + { + manualTitle: "RDK S600", + url: "https://developer.d-robotics.cc/rdk_s_doc/FAQ/hardware_and_system?p=RDK+S600&v=5.1.0#认证", + }, + ]); + assert.equal(hits.length, 1); +}); + +test("title match leads the zipped product lists", () => { + const zipped = zipByTitleMatch( + [ + [{ hierarchy: { lvl1: "配件清单" } }], + [{ hierarchy: { lvl2: "认证资料" } }], + ], + "认证", + ); + assert.equal(zipped[0].hierarchy.lvl2, "认证资料"); +}); + +test("latest S series pins become separate filters", () => { + const pins = sSeriesPins({ + "RDK S600": { site: "s", version: "5.1.1" }, + "RDK S100": { site: "s", version: "4.0.5" }, + "RDK X5": { site: "x", version: "3.5.0" }, + }); + assert.equal(pins.length, 2); + assert.match(sSeriesFilter("zh-Hans", pins[0]), /product:"RDK S600"/); + assert.match(sSeriesFilter("zh-Hans", pins[0]), /rdk_version:5\.1\.1/); +}); diff --git a/src/data/algoliaSites.js b/src/data/algoliaSites.js index 1765b18..57293c0 100644 --- a/src/data/algoliaSites.js +++ b/src/data/algoliaSites.js @@ -1,6 +1,8 @@ /** * Algolia 联邦索引抓取源(由 DOC_CENTER_CONFIG 派生)。 * site 稳定 id 用于 facet,二期可映射为各站独立 indexName。 + * S100/S600、X3/X5 共用同一个文档站路径,必须按手册卡片拆开抓取, + * 不能收成第一个产品的标题。 * * 抓取时将 d-robotics.github.io 英文站改写为 developer.d-robotics.cc *(CI / 内网常无法访问 github.io;路径结构一致,例如 @@ -66,6 +68,18 @@ function pathPrefixFromHref(href) { } } +function scopeFromHref(href) { + try { + const u = new URL(href); + return { + product: u.searchParams.get("p") || "", + version: u.searchParams.get("v") || "", + }; + } catch { + return { product: "", version: "" }; + } +} + function crawlHrefsForLocale(entry, locale) { if (isEntryPending(entry, locale)) return []; const i18n = entry[locale]; @@ -88,11 +102,13 @@ function crawlHrefsForLocale(entry, locale) { * site: string, * entryId: string, * manualTitle: { zh: string, en: string }, - * locales: Array<{ language: string, startUrl: string, pathPrefix: string }> + * product: string, + * version: string, + * locales: Array<{ language: string, startUrl: string, pathPrefix: string, product: string, version: string }> * }>} */ export function getAlgoliaCrawlTargets() { - const bySite = new Map(); + const byManual = new Map(); for (const entry of DOC_CENTER_CONFIG.entries) { for (const locale of ["zh", "en"]) { @@ -100,31 +116,38 @@ export function getAlgoliaCrawlTargets() { for (const rawHref of hrefs) { const href = rewriteCrawlUrl(rawHref); const site = siteIdFromHref(href); - if (!bySite.has(site)) { - bySite.set(site, { + const { product, version } = scopeFromHref(href); + const manualTitle = { + zh: entry.zh?.title || entry.id, + en: entry.en?.title || entry.zh?.title || entry.id, + }; + const key = `${site}::${manualTitle.zh}::${product}::${version}`; + if (!byManual.has(key)) { + byManual.set(key, { site, entryId: entry.id, - manualTitle: { - zh: entry.zh?.title || entry.id, - en: entry.en?.title || entry.zh?.title || entry.id, - }, + manualTitle, + product, + version, locales: [], }); } - const target = bySite.get(site); + const target = byManual.get(key); const language = locale === "en" ? "en" : "zh-Hans"; if (target.locales.some((l) => l.language === language)) continue; target.locales.push({ language, startUrl: href, pathPrefix: pathPrefixFromHref(href), + product, + version, }); } } } - return [...bySite.values()]; + return [...byManual.values()]; } export const ALGOLIA_INDEX_NAME_DEFAULT = "rdk_doc_center"; diff --git a/src/data/sites.js b/src/data/sites.js index ef6b8dc..e262d61 100644 --- a/src/data/sites.js +++ b/src/data/sites.js @@ -49,7 +49,7 @@ function productImage(file) { * 卡片 href 由 rdkManualHref 生成,始终携带显式 ?v=<版本>&p=<产品>, * 避免文档站因缺少版本号而回退到 localStorage(用户上次切换的版本)。 */ -const PRODUCT_LATEST_VERSION = { +export const PRODUCT_LATEST_VERSION = { "RDK S600": { site: "s", version: "5.1.1" }, "RDK S100": { site: "s", version: "4.0.5" }, "RDK X5": { site: "x", version: "3.5.0" }, diff --git a/src/utils/docCenterSearch.js b/src/utils/docCenterSearch.js index 058515d..20036ba 100644 --- a/src/utils/docCenterSearch.js +++ b/src/utils/docCenterSearch.js @@ -1,5 +1,15 @@ import { algoliasearch } from "algoliasearch"; +import { PRODUCT_LATEST_VERSION } from "../data/sites"; import { toRspressPublicUrl } from "./rspressDocUrl.mjs"; +import { + S_SERIES_INDEX, + dedupeHits, + mergeSSeriesHits, + sSeriesFilter, + sSeriesPins, + tagSSeriesHit, + zipByTitleMatch, +} from "./sSeriesSearch.mjs"; /** 搜索结果展示用:去掉「1.2 」「3.7.1 」等章节序号前缀 */ export function stripChapterPrefix(title) { @@ -123,41 +133,66 @@ export async function searchAlgoliaChapters(query, { language, algoliaConfig }) const client = algoliasearch(appId, apiKey); const lang = language === "en" ? "en" : "zh-Hans"; - const requests = indexes.map((indexName) => ({ - indexName, - query: q, - hitsPerPage: 40, - filters: `language:${lang}`, - attributesToRetrieve: [ - "hierarchy", - "content", - "anchor", - "url", - "url_without_anchor", - "type", - "site", - "manualTitle", - "language", - ], - attributesToSnippet: ["content:20"], - distinct: true, - })); + const retrieve = [ + "hierarchy", + "content", + "anchor", + "url", + "url_without_anchor", + "type", + "site", + "manualTitle", + "language", + "product", + "rdk_version", + ]; + // The manual index already separates S100 and S600. Don't also query the + // federated copy of the same site, which collapses both products onto S600. + const genericIndexes = indexes.filter((name) => name !== S_SERIES_INDEX); + const pins = sSeriesPins(PRODUCT_LATEST_VERSION); + const requests = [ + ...genericIndexes.map((indexName) => ({ + indexName, + query: q, + hitsPerPage: 40, + filters: `language:${lang}`, + attributesToRetrieve: retrieve, + attributesToSnippet: ["content:20"], + distinct: true, + })), + ...pins.map((pin) => ({ + indexName: S_SERIES_INDEX, + query: q, + hitsPerPage: 20, + filters: sSeriesFilter(lang, pin), + attributesToRetrieve: retrieve, + attributesToSnippet: ["content:20"], + distinct: true, + })), + ]; const { results } = await client.search({ requests }); - const rawHits = []; - for (const result of results || []) { - if (result.hits) rawHits.push(...result.hits); + const genericCount = genericIndexes.length; + const federated = []; + for (let i = 0; i < genericCount; i += 1) { + const result = results?.[i]; + if (result?.hits) federated.push(...result.hits); } - // Dedupe by url, keep first (higher ranked) - const seen = new Set(); - const chapterHits = []; - for (const hit of rawHits) { - const key = hit.url || hit.objectID; - if (!key || seen.has(key)) continue; - seen.add(key); - chapterHits.push(mapHitToChapter(hit)); + const scopedLists = []; + let scopedOk = true; + for (let i = 0; i < pins.length; i += 1) { + const result = results?.[genericCount + i]; + if (!result || result.message) { + scopedOk = false; + break; + } + scopedLists.push((result.hits || []).map(tagSSeriesHit)); } + const scopedHits = scopedOk ? zipByTitleMatch(scopedLists, q) : []; + const rawHits = mergeSSeriesHits(federated, scopedHits); + + const chapterHits = dedupeHits(rawHits).map(mapHitToChapter); return { chapterHits, rawHits }; } diff --git a/src/utils/sSeriesSearch.mjs b/src/utils/sSeriesSearch.mjs new file mode 100644 index 0000000..a3e81b9 --- /dev/null +++ b/src/utils/sSeriesSearch.mjs @@ -0,0 +1,108 @@ +/** + * S100/S600 share rdk_s_doc. The federated doc-center index stamps every hit + * with whichever manual was crawled first (RDK S600) and keeps every DocScope + * block, so S100-only chapters show up as S600 and each version is listed again. + * The manual index already stores one product and one version per record. + */ + +export const S_SERIES_INDEX = "rdk_s_doc"; + +export function sSeriesPins(versionMap) { + return Object.entries(versionMap || []) + .filter(([, info]) => info?.site === "s" && info.version) + .map(([product, info]) => ({ product, version: String(info.version) })); +} + +export function sSeriesFilter(language, pin) { + const lang = language === "en" ? "en" : "zh-Hans"; + return `language:${lang} AND product:"${pin.product}" AND rdk_version:${pin.version}`; +} + +export function isSSeriesHit(hit) { + if (!hit) return false; + if (hit.site === S_SERIES_INDEX) return true; + const url = hit.url || ""; + try { + return new URL(url).pathname.includes(`/${S_SERIES_INDEX}/`); + } catch { + return url.includes(`/${S_SERIES_INDEX}/`); + } +} + +export function tagSSeriesHit(hit) { + const product = typeof hit?.product === "string" ? hit.product : ""; + return { + ...hit, + site: S_SERIES_INDEX, + manualTitle: product || hit?.manualTitle || "", + }; +} + +function hierarchyText(hit) { + return Object.values(hit?.hierarchy || {}) + .filter(Boolean) + .join("\n") + .toLowerCase(); +} + +export function zipByTitleMatch(lists, query) { + const q = String(query || "").trim().toLowerCase(); + const ranked = [...lists].sort((a, b) => { + const aLead = q && hierarchyText(a[0]).includes(q) ? 0 : 1; + const bLead = q && hierarchyText(b[0]).includes(q) ? 0 : 1; + return aLead - bLead; + }); + const max = Math.max(0, ...ranked.map((list) => list.length)); + const out = []; + for (let i = 0; i < max; i += 1) { + for (const list of ranked) { + if (list[i]) out.push(list[i]); + } + } + return out; +} + +export function dedupeKey(hit) { + const manual = hit?.manualTitle || (typeof hit?.product === "string" ? hit.product : ""); + try { + const url = new URL(hit.url); + const hash = decodeURIComponent(url.hash || ""); + return `${manual}|${url.origin}${url.pathname}|${hash}`; + } catch { + return `${manual}|${hit?.url || hit?.objectID || ""}`; + } +} + +export function dedupeHits(hits) { + const seen = new Set(); + const out = []; + for (const hit of hits || []) { + const key = dedupeKey(hit); + if (!key || seen.has(key)) continue; + seen.add(key); + out.push(hit); + } + return out; +} + +/** + * Drop federated S-series hits and put the product-scoped hits in their place. + * If the manual index returned nothing, keep the federated list. + */ +export function mergeSSeriesHits(federatedHits, scopedHits) { + if (!scopedHits || scopedHits.length === 0) return dedupeHits(federatedHits); + const merged = []; + let inserted = false; + for (const hit of federatedHits || []) { + if (isSSeriesHit(hit)) { + if (!inserted) { + merged.push(...scopedHits); + inserted = true; + } + continue; + } + merged.push(hit); + } + if (!inserted) merged.push(...scopedHits); + return dedupeHits(merged); +}