search-visibility 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.es.md +36 -1
  3. package/README.ja.md +36 -1
  4. package/README.ko.md +42 -6
  5. package/README.md +42 -6
  6. package/README.zh.md +36 -1
  7. package/package.json +2 -1
  8. package/skills/seo-orchestrator/scripts/ai-performance.mjs +107 -0
  9. package/skills/seo-orchestrator/scripts/canonical.mjs +175 -0
  10. package/skills/seo-orchestrator/scripts/command.mjs +6 -0
  11. package/skills/seo-orchestrator/scripts/comparison-pairs.mjs +89 -0
  12. package/skills/seo-orchestrator/scripts/crawl-report.mjs +34 -0
  13. package/skills/seo-orchestrator/scripts/fetch-page.mjs +2 -5
  14. package/skills/seo-orchestrator/scripts/hreflang.mjs +273 -0
  15. package/skills/seo-orchestrator/scripts/html.mjs +7 -80
  16. package/skills/seo-orchestrator/scripts/index-status.mjs +181 -0
  17. package/skills/seo-orchestrator/scripts/indexing.mjs +28 -39
  18. package/skills/seo-orchestrator/scripts/internal-crawl.mjs +16 -46
  19. package/skills/seo-orchestrator/scripts/link-header.mjs +93 -0
  20. package/skills/seo-orchestrator/scripts/mcp.mjs +45 -8
  21. package/skills/seo-orchestrator/scripts/naver-advisor.mjs +147 -0
  22. package/skills/seo-orchestrator/scripts/observations.mjs +42 -8
  23. package/skills/seo-orchestrator/scripts/report-html.mjs +35 -0
  24. package/skills/seo-orchestrator/scripts/report-input.mjs +142 -0
  25. package/skills/seo-orchestrator/scripts/report-sources.mjs +202 -0
  26. package/skills/seo-orchestrator/scripts/robots.mjs +270 -0
  27. package/skills/seo-orchestrator/scripts/scope.mjs +185 -0
  28. package/skills/seo-orchestrator/scripts/search-performance.mjs +1 -1
  29. package/skills/seo-orchestrator/scripts/seo-check.mjs +199 -269
  30. package/skills/seo-orchestrator/scripts/site-audit.mjs +102 -46
  31. package/skills/seo-orchestrator/scripts/structured-data.mjs +316 -0
  32. package/skills/seo-orchestrator/scripts/url-inspection.mjs +150 -0
  33. package/skills/seo-orchestrator/scripts/visibility-comparison.mjs +218 -39
  34. package/skills/seo-orchestrator/scripts/visibility-report.mjs +71 -48
  35. package/skills/seo-orchestrator/scripts/visibility.mjs +53 -50
@@ -1,36 +1,13 @@
1
1
  import { referralMetric } from "./ai-referrals.mjs";
2
- import { crawlLines } from "./internal-crawl.mjs";
3
- import { createHash } from "node:crypto";
2
+ import { crawlLines } from "./crawl-report.mjs";
4
3
  import { currentLocale, t, withLocale } from "./locale.mjs";
4
+ import { html, number, rateText, sourceLink } from "./report-html.mjs";
5
+ import { aiPerformanceSection, inspectionSection, naverSection, scopeTable, sourceLinks } from "./report-sources.mjs";
6
+ import { rowsOutsidePeriod } from "./scope.mjs";
7
+ import { describeBlock, describeIndexing } from "./index-status.mjs";
8
+ import { describeRobotsDecision, describeRobotsFetch } from "./robots.mjs";
5
9
 
6
- const escapeChars = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
7
- const formats = Object.fromEntries(["ko", "en"].map((locale) => {
8
- const tag = locale === "ko" ? "ko-KR" : "en-US";
9
- return [locale, {
10
- percent: new Intl.NumberFormat(tag, { style: "percent", maximumFractionDigits: 1 }),
11
- number: new Intl.NumberFormat(tag),
12
- }];
13
- }));
14
-
15
- function number(value) {
16
- return formats[currentLocale()].number.format(value);
17
- }
18
-
19
- export function html(value) {
20
- return String(value ?? "").replace(/[&<>"']/g, (char) => escapeChars[char]);
21
- }
22
-
23
- function sourceLink(source) {
24
- try {
25
- const url = new URL(source);
26
- if (["http:", "https:"].includes(url.protocol) && !url.username && !url.password) {
27
- return `<a href="${html(url.href)}" rel="noreferrer">${html(source)}</a>`;
28
- }
29
- } catch {
30
- // A saved report can also contain a source that is no longer a usable URL.
31
- }
32
- return html(source);
33
- }
10
+ export { html };
34
11
 
35
12
  const styles = `
36
13
  :root { color-scheme: light; --ink: #192c29; --muted: #455d57; --line: #c7d5cb; --paper: #f7f9f5; --accent: #075b45; }
@@ -82,6 +59,14 @@ const styles = `
82
59
  .controls button { cursor: pointer; }
83
60
  #share-summary { width: 100%; font: inherit; }
84
61
  .action { border-inline-start: .2rem solid var(--line); padding-inline-start: .65rem; }
62
+ .index-alert { margin: .75rem 0; padding: .7rem 1rem; border: 1px solid #52779a; border-inline-start-width: .4rem; border-radius: .55rem; background: #e5eef5; }
63
+ .index-alert.fail { color: #822f2b; background: #f9e5df; border-color: #822f2b; }
64
+ .index-alert.warn { color: #694411; background: #fcf0cf; border-color: #aa7728; }
65
+ .index-alert .muted { color: inherit; }
66
+ .scroll { overflow-x: auto; }
67
+ .scroll th, .scroll td { overflow-wrap: break-word; word-break: keep-all; }
68
+ .scroll a, .scroll code { overflow-wrap: anywhere; }
69
+ @media print { .scroll { overflow: visible; } .scroll th, .scroll td { overflow-wrap: anywhere; } }
85
70
  @media (max-width: 35rem) { th, td { padding: .4rem .2rem; font-size: .88rem; } details { padding: .65rem; } }
86
71
  @media print { body { background: white; font-size: 10pt; } header { color: black; background: white; padding: .75rem 0; } header p { color: #444; } section { margin-top: 1rem; } nav, .controls, #share-summary, #copy-status, #no-matches { display: none; } .audit-page[hidden], .findings li[hidden] { display: block !important; } .findings li { break-inside: avoid; } summary, h2, h3 { break-after: avoid; } .metrics > div { break-inside: avoid; } }
87
72
  td small { display: block; }
@@ -193,7 +178,8 @@ const interactions = `(() => {
193
178
  });
194
179
  })();`;
195
180
 
196
- const scriptHash = createHash("sha256").update(interactions).digest("base64");
181
+ // 위 스크립트의 SHA-256. 브라우저에서도 보고서를 만들 수 있게 값으로 둔다(시험이 스크립트와 대조한다).
182
+ const scriptHash = "Sa1BUTH3SsdBOuIlTAiTK8kiWvqTaUTYmB7ZxT9Uoqk=";
197
183
 
198
184
  function findingsList(results) {
199
185
  const ranked = [...results].sort((a, b) => (priorities.get(a.level) ?? 4) - (priorities.get(b.level) ?? 4));
@@ -209,13 +195,38 @@ function findingsList(results) {
209
195
  function crawlerDetails(robots) {
210
196
  if (!robots?.crawlers?.length) return "";
211
197
  const purposes = {
212
- search: t("검색", "Search"), training: t("학습", "Training"),
198
+ search: t("검색", "Search"), training: t("학습", "Training"), preview: t("공유 미리보기", "Sharing preview"),
213
199
  "user-request": t("사용자 요청", "User request"), grounding: t("답변 근거", "Grounding"),
214
200
  };
215
- return `<details><summary>${t("AI 크롤러의 robots.txt 규칙", "AI crawler rules in robots.txt")}</summary>
216
- <ul>${robots.crawlers.map(({ agent, purpose, decision }) =>
217
- `<li><code>${html(agent)}</code> · ${html(purposes[purpose])} · ${decision === "blocked" ? t("차단", "Blocked") : t("허용", "Allowed")}</li>`
218
- ).join("")}</ul></details>`;
201
+ const fetched = robots.fetch ? `<p>${html(describeRobotsFetch(robots, currentLocale()))} · ${t("검사 경로", "Inspected path")} <code>${html(robots.path)}</code></p>` : "";
202
+ const list = (title, rows) => (rows?.length ? `<details><summary>${title}</summary>${fetched}
203
+ <ul>${rows.map((row) => `<li><code>${html(row.agent)}</code> · ${html(purposes[row.purpose])} · ${html(describeRobotsDecision(row, currentLocale()))}</li>`).join("")}</ul></details>` : "");
204
+ return list(t("AI 크롤러의 robots.txt 규칙", "AI crawler rules in robots.txt"), robots.crawlers) +
205
+ list(t("검색·미리보기 크롤러의 robots.txt 규칙", "Search and preview crawler rules in robots.txt"), robots.otherCrawlers);
206
+ }
207
+
208
+ // 웹의 배너처럼 지시가 없는 상태만 빼고 알린다. 다만 미확인은 HTTP 오류 응답이나 잘린 본문이 원인일 때만 알려,
209
+ // 응답 헤더를 관측하지 않는 로컬 파일 점검에는 표시하지 않는다.
210
+ function flagged(indexing) {
211
+ if (!indexing || indexing.verdict === "open") return false;
212
+ if (indexing.verdict !== "unverified" || indexing.bodyComplete === false) return true;
213
+ const status = indexing.httpStatus;
214
+ return Number.isInteger(status) && (status < 200 || status >= 300);
215
+ }
216
+
217
+ // 차단 근거와 미확인 사유는 요약 맨 위에 둔다. 의도한 제외는 의도를 함께 설명한다.
218
+ function indexingAlerts(pages) {
219
+ const alerts = pages.filter((page) => flagged(page.indexing));
220
+ if (!alerts.length) return "";
221
+ return alerts.map((page) => {
222
+ const { title, note } = describeIndexing(page.indexing, currentLocale());
223
+ const { verdict, crawlBlocked } = page.indexing;
224
+ const calm = verdict === "unverified" || (verdict === "intended-exclusion" && !crawlBlocked);
225
+ const tone = verdict === "unintended-block" ? " fail" : calm ? "" : " warn";
226
+ return `<div class="index-alert${tone}"><p><strong>${html(title)}</strong></p><p>${html(page.target)}</p>
227
+ ${page.indexing.blocks.length ? `<ul>${page.indexing.blocks.map((block) => `<li>${html(describeBlock(block, currentLocale()))}</li>`).join("")}${page.indexing.omitted ? `<li>… +${html(page.indexing.omitted)}</li>` : ""}</ul>` : ""}
228
+ <p class="muted">${html(note)}</p></div>`;
229
+ }).join("");
219
230
  }
220
231
 
221
232
  function pageDetails(page) {
@@ -261,10 +272,6 @@ function siteSection(site) {
261
272
  <div id="audit-pages">${site.pages.map(pageDetails).join("")}</div>` : `<p>${t("이번 실행에서 점검한 페이지가 없습니다.", "No pages were audited in this run.")}</p>`}</section>`;
262
273
  }
263
274
 
264
- function rateText(rate) {
265
- return Number.isFinite(rate) ? formats[currentLocale()].percent.format(rate) : t("측정 안 됨", "Not measured");
266
- }
267
-
268
275
  function countText(count, sample, rate) {
269
276
  if (!sample) return t("관측 답변 없음", "No observed answers");
270
277
  if (!Number.isFinite(rate)) return t("측정 안 됨", "Not measured");
@@ -276,10 +283,22 @@ function rateCell(rate, count, sample) {
276
283
  return `${rateText(rate)} (${number(count)}/${number(sample)})`;
277
284
  }
278
285
 
286
+ function observationContext(record) {
287
+ return [record.model, record.mode, record.locale, record.region, record.run && `#${record.run}`].filter(Boolean).map(html).join(" · ");
288
+ }
289
+
290
+ function failureList(failures) {
291
+ if (!failures?.length) return "";
292
+ const names = { failed: t("수집 실패", "Collection failed"), "no-answer": t("AI 답변 표시 안 됨", "No AI answer shown") };
293
+ return `<h3>${t("답변을 얻지 못한 시도", "Attempts without an answer")} (${number(failures.length)})</h3>
294
+ <p>${t("언급률·인용률의 표본에서 제외합니다. 답변을 받았지만 인용이 없는 경우와 다릅니다.", "Excluded from mention and citation samples. This differs from an answer that cited no sources.")}</p>
295
+ <ul>${failures.map((row) => `<li>${html(names[row.status])} · ${html(row.engine)} · ${html(row.query)} · <time>${html(row.observedAt)}</time>${observationContext(row) ? ` · ${observationContext(row)}` : ""}${row.reason ? ` · ${html(row.reason)}` : ""}</li>`).join("")}</ul>`;
296
+ }
297
+
279
298
  function observationRow(record) {
280
299
  const mentions = record.mentioned ? t("브랜드 언급 있음", "Brand mentioned") : t("브랜드 언급 없음", "Brand absent");
281
300
  const citation = record.cited == null ? t("소유 출처 인용 측정 안 됨", "Owned citations not measured") : record.cited ? t("소유 출처 인용 있음", "Owned source cited") : t("소유 출처 인용 없음", "No owned source cited");
282
- const context = [record.model, record.locale].filter(Boolean).map(html).join(" · ");
301
+ const context = observationContext(record);
283
302
  const matched = new Set(record.matchedSources ?? []);
284
303
  const sources = new Set([...(record.sources ?? []), ...matched]);
285
304
  return `<details><summary>${html(record.engine)} · ${html(record.query)}</summary>
@@ -325,7 +344,7 @@ function competitionSection(competition) {
325
344
 
326
345
  function observationSection(ai) {
327
346
  if (!ai.sampleSize) {
328
- return `<section aria-labelledby="answers"><h2 id="answers">${t("AI 답변 관측", "AI answer observations")}</h2><p>${t("기록한 답변이 없습니다. 관측한 질문·답변과 인용 URL을 추가하면 엔진별 결과를 볼 수 있습니다.", "No answers were recorded. Add observed questions, answers and citation URLs to see results by engine.")}</p></section>`;
347
+ return `<section aria-labelledby="answers"><h2 id="answers">${t("AI 답변 관측", "AI answer observations")}</h2><p>${t("기록한 답변이 없습니다. 관측한 질문·답변과 인용 URL을 추가하면 엔진별 결과를 볼 수 있습니다.", "No answers were recorded. Add observed questions, answers and citation URLs to see results by engine.")}</p>${failureList(ai.failures)}</section>`;
329
348
  }
330
349
  return `<section aria-labelledby="answers"><h2 id="answers">${t("AI 답변 관측", "AI answer observations")}</h2>
331
350
  <p>${currentLocale() === "en" ? `Brand mentions and owned-source citations are counted across ${number(ai.sampleSize)} supplied answers.` : `입력한 답변 ${html(ai.sampleSize)}개를 기준으로 브랜드 언급과 소유 출처 인용을 집계합니다.`}</p>
@@ -335,7 +354,7 @@ function observationSection(ai) {
335
354
  ${ai.byEngine.map((row) => `<tr><th scope="row">${html(row.engine)}</th><td>${number(row.sampleSize)}${confidenceBadge(row)}</td>
336
355
  <td>${rateCell(row.mentionRate, row.mentions, row.sampleSize)}${intervalText(row.mentionInterval)}</td>
337
356
  <td>${rateCell(row.citationRate, row.citations, row.sampleSize)}${intervalText(row.citationInterval)}</td></tr>`).join("")}</tbody></table>
338
- <h3>${t("질문별 근거", "Evidence by question")}</h3>${ai.records.map(observationRow).join("")}</section>`;
357
+ <h3>${t("질문별 근거", "Evidence by question")}</h3>${ai.records.map(observationRow).join("")}${failureList(ai.failures)}</section>`;
339
358
  }
340
359
 
341
360
  function searchSection(performance) {
@@ -355,7 +374,10 @@ function searchSection(performance) {
355
374
  <div><dt>${t("노출", "Impressions")}</dt><dd>${number(performance.impressions)}${t("회", "")}</dd></div>
356
375
  <div><dt>${t("클릭", "Clicks")}</dt><dd>${number(performance.clicks)}${t("회", "")}</dd></div>
357
376
  <div><dt>${t("클릭률", "CTR")}</dt><dd>${rateText(performance.ctr)}</dd></div>
358
- </dl><table><caption>${currentLocale() === "en" ? `Top ${number(top.length)} entries by impressions` : `노출 순 ${html(dimension)} ${top.length}개`}</caption>
377
+ </dl>${performance.scope ? scopeTable(t("조회 조건", "Query conditions"), performance.scope)
378
+ : `<p class="note">${t("조회 조건(속성·보고서 종류·검색 유형·집계 단위·시간대·필터·완료된 기간)이 기록되지 않아 전후 비교에서 증감을 보류합니다.", "Query conditions (property, report type, search type, aggregation, time zone, filters and a completed period) are not recorded, so comparisons withhold changes.")}</p>`}
379
+ ${rowsOutsidePeriod(performance) ? `<p class="notice">${currentLocale() === "en" ? `${number(rowsOutsidePeriod(performance))} date rows fall outside the declared period.` : `선언한 조회 기간 밖의 날짜가 ${number(rowsOutsidePeriod(performance))}행 있습니다.`}</p>` : ""}
380
+ <table><caption>${currentLocale() === "en" ? `Top ${number(top.length)} entries by impressions` : `노출 순 ${html(dimension)} ${top.length}개`}</caption>
359
381
  <thead><tr><th scope="col">${html(dimension)}</th><th scope="col">${t("노출", "Impressions")}</th><th scope="col">${t("클릭", "Clicks")}</th></tr></thead>
360
382
  <tbody>${top.map((row) => `<tr><th scope="row">${html(row.label)}</th><td>${number(row.impressions)}</td><td>${number(row.clicks)}</td></tr>`).join("")}</tbody>
361
383
  </table></section>`;
@@ -394,7 +416,8 @@ export function renderReport(report) {
394
416
  return withLocale(report.locale ?? "ko", () => renderLocalizedReport(report));
395
417
  }
396
418
 
397
- function renderLocalizedReport({ brand, generatedAt, site, ai, searchPerformance, aiReferrals, sample = false }) {
419
+ function renderLocalizedReport(report) {
420
+ const { brand, generatedAt, site, ai, searchPerformance, aiReferrals, sample = false } = report;
398
421
  const failedPages = site.pages.filter((p) => p.error).length;
399
422
  const title = t("검색 가시성 보고서", "Search Visibility Report");
400
423
  const brandTitle = brand ? `${html(brand)}${t(" ", " · ")}${title}` : title;
@@ -416,8 +439,8 @@ function renderLocalizedReport({ brand, generatedAt, site, ai, searchPerformance
416
439
  <body><header><div class="sheet"><div class="product" lang="en">Search Visibility</div><h1>${brandTitle}</h1>
417
440
  ${sample === true ? `<p class="sample">${t("이 보고서는 합성 예시 데이터로 생성했습니다.", "This report uses synthetic sample data.")}</p>` : ""}
418
441
  <p>${t("생성 시각", "Generated at")} <time>${html(generatedAt)}</time></p></div></header>
419
- <main class="sheet"><nav aria-label="${t("보고서 섹션", "Report sections")}"><a href="#pages">${t("페이지 진단", "Page audit")}</a><a href="#search">${t("Google 검색 실적", "Google Search performance")}</a><a href="#answers">${t("AI 답변 관측", "AI answer observations")}</a>${aiReferrals ? `<a href="#referrals">${t("AI 유입", "AI referrals")}</a>` : ""}</nav>
420
- <section aria-labelledby="overview"><h2 id="overview">${t("점검 요약", "Overview")}</h2><dl class="metrics">
442
+ <main class="sheet"><nav aria-label="${t("보고서 섹션", "Report sections")}"><a href="#pages">${t("페이지 진단", "Page audit")}</a><a href="#search">${t("Google 검색 실적", "Google Search performance")}</a><a href="#answers">${t("AI 답변 관측", "AI answer observations")}</a>${sourceLinks(report)}${aiReferrals ? `<a href="#referrals">${t("AI 유입", "AI referrals")}</a>` : ""}</nav>
443
+ <section aria-labelledby="overview"><h2 id="overview">${t("점검 요약", "Overview")}</h2>${indexingAlerts(site.pages)}<dl class="metrics">
421
444
  <div><dt>${t("페이지 점검 완료", "Pages audited")}</dt><dd>${number(site.pages.length - failedPages)}${t("개", "")}<small>${audited}</small></dd></div>
422
445
  <div><dt>${t("브랜드 언급률", "Brand mention rate")}</dt><dd>${rateText(ai.mentionRate)}<small>${countText(ai.mentions, ai.sampleSize, ai.mentionRate)}</small>${intervalText(ai.mentionInterval)}</dd></div>
423
446
  <div><dt>${t("소유 출처 인용률", "Owned-source citation rate")}</dt><dd>${rateText(ai.citationRate)}<small>${countText(ai.citations, ai.sampleSize, ai.citationRate)}</small>${intervalText(ai.citationInterval)}</dd></div>
@@ -425,5 +448,5 @@ ${sample === true ? `<p class="sample">${t("이 보고서는 합성 예시 데
425
448
  <div class="controls" id="report-actions" hidden><button type="button" id="copy-overview">${t("요약 복사", "Copy overview")}</button><button type="button" id="print-report">${t("인쇄 / PDF 저장", "Print / save PDF")}</button></div>
426
449
  <textarea id="share-summary" aria-label="${t("공유할 점검 요약", "Shareable overview")}" rows="8" readonly hidden>${summary.join("\n")}</textarea>
427
450
  <p id="copy-status" role="status" data-copied="${t("요약을 복사했습니다.", "Overview copied.")}" data-manual="${t("선택된 요약을 복사하세요.", "Copy the selected overview.")}"></p>
428
- </section>${siteSection(site)}${searchSection(searchPerformance)}${observationSection(ai)}${competitionSection(ai.competition)}${referralSection(aiReferrals, ai)}</main><script>${interactions}</script></body></html>\n`;
451
+ </section>${siteSection(site)}${searchSection(searchPerformance)}${aiPerformanceSection(report.aiPerformance, searchPerformance, ai)}${naverSection(report.naverSearchAdvisor)}${inspectionSection(report.urlInspection)}${observationSection(ai)}${competitionSection(ai.competition)}${referralSection(aiReferrals, ai)}</main><script>${interactions}</script></body></html>\n`;
429
452
  }
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { t, currentLocale, validateLocale, withLocale } from "./locale.mjs";
2
+ import { t, currentLocale, withLocale } from "./locale.mjs";
3
3
  import { mkdir, mkdtemp, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
4
4
  import { dirname, basename, join, resolve } from "node:path";
5
5
  import { isCliEntry } from "./cli-entry.mjs";
6
6
  import { parseArgs } from "node:util";
7
- import { parseAiReferrals, referralMetric } from "./ai-referrals.mjs";
8
- import { analyzeObservations } from "./observations.mjs";
9
- import { parseSearchPerformance } from "./search-performance.mjs";
7
+ import { referralMetric } from "./ai-referrals.mjs";
8
+ import { buildReport } from "./report-input.mjs";
9
+ import { describeIndexing } from "./index-status.mjs";
10
+ import { summaryLines } from "./report-sources.mjs";
10
11
  import { crawlLimit, crawlLines, crawlSite } from "./internal-crawl.mjs";
11
12
  import { auditSite } from "./site-audit.mjs";
12
13
  import { compareReports, renderComparison } from "./visibility-comparison.mjs";
@@ -14,23 +15,25 @@ import { serveMcp } from "./mcp.mjs";
14
15
  import { sendNotifications } from "./notify.mjs";
15
16
  import { renderReport } from "./visibility-report.mjs";
16
17
 
17
- const help = () => (currentLocale() === "en" ? `Usage: node visibility.mjs <config.json|URL> [--out <new folder>] [--fail-on-findings] [--crawl [--max-pages n]] [--ai-referrals <file>] [--lang en|ko]
18
- node visibility.mjs --url <URL> [--out <new folder>] [--fail-on-findings] [--crawl [--max-pages n]] [--ai-referrals <file>] [--lang en|ko]
18
+ const help = () => (currentLocale() === "en" ? `Usage: node visibility.mjs <config.json|URL> [--out <new folder>] [--fail-on-findings] [--crawl [--max-pages n]] [--ai-referrals <file>] [--expect-excluded] [--lang en|ko]
19
+ node visibility.mjs --url <URL> [--out <new folder>] [--fail-on-findings] [--crawl [--max-pages n]] [--ai-referrals <file>] [--expect-excluded] [--lang en|ko]
19
20
  node visibility.mjs --ai-referrals <file> [--out <new folder>] [--lang en|ko]
20
21
  node visibility.mjs init [config.json] [--lang en|ko]
21
22
  node visibility.mjs compare <before.report.json> <after.report.json> [--out <new folder>] [--lang en|ko]
22
23
  node visibility.mjs mcp [--lang en|ko]
23
24
  Start an audit with an absolute HTTP(S) URL. init creates visibility.config.json by default.
25
+ --expect-excluded marks the audited URL as intentionally excluded from search.
24
26
  Config input paths are relative to the config file. --ai-referrals is relative to the current directory. Writes report.json and index.html.
25
27
  Language: --lang overrides config locale. The default is ko.
26
28
  The default output is a new folder under visibility-reports/ in the current directory.
27
- Exit codes: 0 completed, 1 FAIL found with --fail-on-findings, 2 input, collection or write error.` : `사용법: node visibility.mjs <설정.json|URL> [--out <새 폴더>] [--fail-on-findings] [--crawl [--max-pages n]] [--ai-referrals <file>] [--lang en|ko]
28
- node visibility.mjs --url <URL> [--out <새 폴더>] [--fail-on-findings] [--crawl [--max-pages n]] [--ai-referrals <file>] [--lang en|ko]
29
+ Exit codes: 0 completed, 1 FAIL found with --fail-on-findings, 2 input, collection or write error.` : `사용법: node visibility.mjs <설정.json|URL> [--out <새 폴더>] [--fail-on-findings] [--crawl [--max-pages n]] [--ai-referrals <file>] [--expect-excluded] [--lang en|ko]
30
+ node visibility.mjs --url <URL> [--out <새 폴더>] [--fail-on-findings] [--crawl [--max-pages n]] [--ai-referrals <file>] [--expect-excluded] [--lang en|ko]
29
31
  node visibility.mjs --ai-referrals <파일> [--out <새 폴더>] [--lang en|ko]
30
32
  node visibility.mjs init [설정.json] [--lang en|ko]
31
33
  node visibility.mjs compare <변경전.report.json> <변경후.report.json> [--out <새 폴더>] [--lang en|ko]
32
34
  node visibility.mjs mcp [--lang en|ko]
33
35
  HTTP(S) 절대 URL을 입력하면 해당 URL에서 점검을 시작합니다. init의 기본 파일은 visibility.config.json입니다.
36
+ --expect-excluded는 점검하는 URL을 의도적으로 검색에서 제외한 페이지로 지정합니다.
34
37
  설정의 상대 경로는 설정 파일, --ai-referrals는 현재 디렉터리를 기준으로 해석합니다. report.json과 index.html을 생성합니다.
35
38
  언어: --lang이 설정의 locale보다 우선하며 기본값은 ko입니다.
36
39
  출력 경로를 생략하면 현재 폴더의 visibility-reports/ 아래에 실행별 보고서를 만듭니다.
@@ -53,48 +56,27 @@ async function readJson(file) {
53
56
  export async function collectReport(configFile, { lang, maxPages, aiReferralsFile } = {}) {
54
57
  return withLocale(lang ?? "ko", async () => {
55
58
  const config = await readJson(configFile);
56
- if (config && Object.hasOwn(config, "locale")) validateLocale(config.locale);
57
- const locale = lang ?? config?.locale ?? "ko";
58
- return withLocale(locale, () => collectConfig(config, dirname(resolve(configFile)), locale, maxPages, aiReferralsFile));
59
+ return collectFrom(config, dirname(resolve(configFile)), { lang, maxPages, aiReferralsFile });
59
60
  });
60
61
  }
61
62
 
62
- async function collectConfig(config, baseDir, locale, maxPages, aiReferralsFile) {
63
- if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(t("설정은 JSON 객체여야 합니다.", "Config must be a JSON object."));
64
- const keys = new Set(["brand", "aliases", "domains", "ownedUrlPrefixes", "competitors", "targets", "sitemap", "limit", "expectIndexable", "observations", "searchConsole", "aiReferrals", "sample", "locale"]);
65
- for (const key of Object.keys(config)) {
66
- if (!keys.has(key)) throw new Error((currentLocale() === "en" ? `Unknown config setting: ${key}` : `알 수 없는 설정: ${key}`));
67
- }
68
- if (config.sample !== undefined && typeof config.sample !== "boolean") throw new Error(t("sample은 true 또는 false여야 합니다.", "sample must be true or false."));
69
- const observations = typeof config.observations === "string"
70
- ? await readJson(resolve(baseDir, config.observations)) : config.observations;
71
- const ai = analyzeObservations({
72
- brand: config.brand, aliases: config.aliases, domains: config.domains,
73
- ownedUrlPrefixes: config.ownedUrlPrefixes, competitors: config.competitors, observations,
63
+ // 설정의 파일 경로는 설정 파일 위치를 기준으로 읽는다.
64
+ function collectFrom(config, baseDir, { lang, maxPages, aiReferralsFile }) {
65
+ return buildReport(config, {
66
+ lang,
67
+ readText: (file) => readText(resolve(baseDir, file)),
68
+ readJson: (file) => readJson(resolve(baseDir, file)),
69
+ referrals: aiReferralsFile,
70
+ audit: async () => {
71
+ if (maxPages !== undefined && (!Array.isArray(config.targets) || config.targets.length !== 1)) {
72
+ throw new Error(t("--crawl에는 targets에 시작 URL 하나가 필요합니다.", "--crawl requires one start URL in targets."));
73
+ }
74
+ const crawlScope = maxPages === undefined ? undefined : await crawlSite(config.targets[0], maxPages, { sitemap: config.sitemap });
75
+ const site = await auditSite({targets: config.targets, sitemap: config.sitemap, limit: config.limit, expectIndexable: config.expectIndexable, intentionallyExcluded: config.intentionallyExcluded, baseDir, crawlScope});
76
+ if (crawlScope) site.crawl = crawlScope.report;
77
+ return site;
78
+ },
74
79
  });
75
- let searchPerformance = null;
76
- if (config.searchConsole !== undefined) {
77
- if (typeof config.searchConsole !== "string" || !config.searchConsole.trim()) throw new Error(t("searchConsole에는 CSV 파일 경로가 필요합니다.", "searchConsole must be a CSV file path."));
78
- searchPerformance = parseSearchPerformance(await readText(resolve(baseDir, config.searchConsole)));
79
- }
80
- const referralFile = aiReferralsFile ?? config.aiReferrals;
81
- let aiReferrals = null;
82
- if (referralFile !== undefined) {
83
- if (typeof referralFile !== "string" || !referralFile.trim()) {
84
- throw new Error(t("AI 유입 자료의 파일 경로를 지정하세요.", "Specify a file path for AI referrals."));
85
- }
86
- aiReferrals = parseAiReferrals(await readText(resolve(baseDir, referralFile)));
87
- }
88
- if (maxPages !== undefined && (!Array.isArray(config.targets) || config.targets.length !== 1)) {
89
- throw new Error(t("--crawl에는 targets에 시작 URL 하나가 필요합니다.", "--crawl requires one start URL in targets."));
90
- }
91
- const crawlScope = maxPages === undefined ? undefined : await crawlSite(config.targets[0], maxPages, { sitemap: config.sitemap });
92
- const site = await auditSite({targets: config.targets, sitemap: config.sitemap, limit: config.limit, expectIndexable: config.expectIndexable, baseDir, crawlScope});
93
- if (crawlScope) site.crawl = crawlScope.report;
94
- if (!site.pages.length && !site.crawl && !config.sitemap && !ai.sampleSize && !searchPerformance && !aiReferrals) {
95
- throw new Error(t("targets, sitemap, observations, searchConsole 또는 aiReferrals 중 점검할 자료를 지정하세요.", "Specify at least one input: targets, sitemap, observations, searchConsole or aiReferrals."));
96
- }
97
- return {schemaVersion: 1, locale, generatedAt: new Date().toISOString(), brand: config.brand || "", sample: config.sample === true, site, searchPerformance, ai, ...(aiReferrals && {aiReferrals})};
98
80
  }
99
81
 
100
82
  async function publishReport(report, requestedPath, render = renderReport) {
@@ -146,7 +128,7 @@ async function initConfig(file) {
146
128
 
147
129
  async function main() {
148
130
  const {values, positionals, tokens} = parseArgs({allowPositionals:true, tokens:true, options:{
149
- "ai-referrals":{type:"string"}, crawl:{type:"boolean"}, "max-pages":{type:"string"}, out:{type:"string"}, url:{type:"string"}, lang:{type:"string"}, "fail-on-findings":{type:"boolean"},
131
+ "ai-referrals":{type:"string"}, "expect-excluded":{type:"boolean"}, crawl:{type:"boolean"}, "max-pages":{type:"string"}, out:{type:"string"}, url:{type:"string"}, lang:{type:"string"}, "fail-on-findings":{type:"boolean"},
150
132
  "notify-discord":{type:"string"}, "notify-slack":{type:"string"}, "notify-telegram":{type:"string"}, "notify-on":{type:"string"},
151
133
  help:{type:"boolean", short:"h"},
152
134
  }});
@@ -172,8 +154,9 @@ async function main() {
172
154
  }
173
155
  return serveMcp();
174
156
  }
157
+ const excluded = values["expect-excluded"];
175
158
  if (input === "compare") {
176
- if (positionals.length !== 3 || values.url !== undefined || values["fail-on-findings"] !== undefined || maxPages !== undefined || aiReferralsFile !== undefined) {
159
+ if (positionals.length !== 3 || values.url !== undefined || values["fail-on-findings"] !== undefined || maxPages !== undefined || aiReferralsFile !== undefined || excluded) {
177
160
  throw new Error(help());
178
161
  }
179
162
  const [before, after] = await Promise.all(positionals.slice(1).map(readJson));
@@ -181,10 +164,11 @@ async function main() {
181
164
  const target = await publishReport(report, values.out, renderComparison);
182
165
  console.log(t("전후 비교 보고서를 생성했습니다.", "Created before-and-after comparison.") +
183
166
  `\nHTML ${join(target, "index.html")}\nJSON ${join(target, "report.json")}`);
167
+ for (const { message } of report.notCompared ?? []) console.log(message);
184
168
  return 0;
185
169
  }
186
170
  if (input === "init") {
187
- if (positionals.length > 2 || values.url !== undefined || values.out !== undefined || values["fail-on-findings"] !== undefined || maxPages !== undefined || aiReferralsFile !== undefined) {
171
+ if (positionals.length > 2 || values.url !== undefined || values.out !== undefined || values["fail-on-findings"] !== undefined || maxPages !== undefined || aiReferralsFile !== undefined || excluded) {
188
172
  throw new Error(help());
189
173
  }
190
174
  return initConfig(configPath ?? "visibility.config.json");
@@ -196,13 +180,30 @@ async function main() {
196
180
  if (url !== undefined && !/^https?:\/\/[^/\\\s?#]/i.test(url)) {
197
181
  throw new Error(t("HTTP(S) 절대 URL을 입력하세요.", "Enter an absolute HTTP(S) URL."));
198
182
  }
183
+ if (excluded && url === undefined) {
184
+ throw new Error(t("--expect-excluded는 URL 점검에만 사용합니다. 설정 파일에는 intentionallyExcluded를 지정하세요.", "--expect-excluded applies to URL audits. In a config file, use intentionallyExcluded."));
185
+ }
186
+ // 의도적 제외는 지정한 URL에만 적용하고, 함께 발견한 다른 페이지는 색인 대상으로 점검한다.
187
+ const urlConfig = url === undefined ? {} : {targets: [url], expectIndexable: true, ...(excluded && {intentionallyExcluded: [url]})};
199
188
  const report = url === undefined && input !== undefined
200
189
  ? await collectReport(input, {lang: values.lang, maxPages, aiReferralsFile})
201
- : await collectConfig(url === undefined ? {} : {targets: [url], expectIndexable: true}, process.cwd(), currentLocale(), maxPages, aiReferralsFile);
190
+ : await collectFrom(urlConfig, process.cwd(), {lang: currentLocale(), maxPages, aiReferralsFile});
202
191
  return withLocale(report.locale, () => writeAndSummarize(report, values));
203
192
  });
204
193
  }
205
194
 
195
+ // 색인 차단이나 의도와 다른 상태는 터미널에서도 건수보다 먼저 알 수 있게 한다.
196
+ const INDEXING_ALERTS = new Set(["unintended-block", "confirm-block", "intended-partial", "intended-but-open", "scope-unverified"]);
197
+ const MAX_ALERT_LINES = 10;
198
+ function indexingLines(pages) {
199
+ // HTML 보고서처럼 HTTP 오류로 확인하지 못한 페이지도 알린다. 헤더가 없는 로컬 파일은 제외한다.
200
+ const alerts = pages.filter(({ indexing }) => INDEXING_ALERTS.has(indexing?.verdict) ||
201
+ (indexing?.verdict === "unverified" && indexing.httpStatus !== null && (indexing.httpStatus < 200 || indexing.httpStatus >= 300)));
202
+ const lines = alerts.slice(0, MAX_ALERT_LINES).map((page) => `${describeIndexing(page.indexing, currentLocale()).title} — ${page.target}`);
203
+ if (alerts.length > MAX_ALERT_LINES) lines.push(`… +${alerts.length - MAX_ALERT_LINES}`);
204
+ return lines;
205
+ }
206
+
206
207
  async function writeAndSummarize(report, values) {
207
208
  const target = await publishReport(report, values.out);
208
209
  const { pages } = report.site;
@@ -215,6 +216,8 @@ async function writeAndSummarize(report, values) {
215
216
  console.log(`${sample}${summary}
216
217
  HTML ${join(target, "index.html")}
217
218
  JSON ${join(target, "report.json")}`);
219
+ for (const line of summaryLines(report)) console.log(line);
220
+ for (const line of indexingLines(pages)) console.log(line);
218
221
  if (report.aiReferrals) {
219
222
  const { totals, byEngine } = report.aiReferrals;
220
223
  console.log(t(`AI 유입 엔진 ${byEngine.length}개`, `AI referral engines: ${byEngine.length}`) +