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.
- package/CHANGELOG.md +38 -0
- package/README.es.md +36 -1
- package/README.ja.md +36 -1
- package/README.ko.md +42 -6
- package/README.md +42 -6
- package/README.zh.md +36 -1
- package/package.json +2 -1
- package/skills/seo-orchestrator/scripts/ai-performance.mjs +107 -0
- package/skills/seo-orchestrator/scripts/canonical.mjs +175 -0
- package/skills/seo-orchestrator/scripts/command.mjs +6 -0
- package/skills/seo-orchestrator/scripts/comparison-pairs.mjs +89 -0
- package/skills/seo-orchestrator/scripts/crawl-report.mjs +34 -0
- package/skills/seo-orchestrator/scripts/fetch-page.mjs +2 -5
- package/skills/seo-orchestrator/scripts/hreflang.mjs +273 -0
- package/skills/seo-orchestrator/scripts/html.mjs +7 -80
- package/skills/seo-orchestrator/scripts/index-status.mjs +181 -0
- package/skills/seo-orchestrator/scripts/indexing.mjs +28 -39
- package/skills/seo-orchestrator/scripts/internal-crawl.mjs +16 -46
- package/skills/seo-orchestrator/scripts/link-header.mjs +93 -0
- package/skills/seo-orchestrator/scripts/mcp.mjs +45 -8
- package/skills/seo-orchestrator/scripts/naver-advisor.mjs +147 -0
- package/skills/seo-orchestrator/scripts/observations.mjs +42 -8
- package/skills/seo-orchestrator/scripts/report-html.mjs +35 -0
- package/skills/seo-orchestrator/scripts/report-input.mjs +142 -0
- package/skills/seo-orchestrator/scripts/report-sources.mjs +202 -0
- package/skills/seo-orchestrator/scripts/robots.mjs +270 -0
- package/skills/seo-orchestrator/scripts/scope.mjs +185 -0
- package/skills/seo-orchestrator/scripts/search-performance.mjs +1 -1
- package/skills/seo-orchestrator/scripts/seo-check.mjs +199 -269
- package/skills/seo-orchestrator/scripts/site-audit.mjs +102 -46
- package/skills/seo-orchestrator/scripts/structured-data.mjs +316 -0
- package/skills/seo-orchestrator/scripts/url-inspection.mjs +150 -0
- package/skills/seo-orchestrator/scripts/visibility-comparison.mjs +218 -39
- package/skills/seo-orchestrator/scripts/visibility-report.mjs +71 -48
- package/skills/seo-orchestrator/scripts/visibility.mjs +53 -50
|
@@ -3,13 +3,18 @@ import { stat } from "node:fs/promises";
|
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
import { gunzipSync } from "node:zlib";
|
|
5
5
|
import { fetchResource } from "./fetch-page.mjs";
|
|
6
|
-
import { run, UA } from "./seo-check.mjs";
|
|
6
|
+
import { addHreflangFindings, hreflangRecord, hreflangSummary, run, trimHreflang, UA } from "./seo-check.mjs";
|
|
7
|
+
import { analyzeHreflang, declaration } from "./hreflang.mjs";
|
|
8
|
+
import { comparableUrl } from "./link-header.mjs";
|
|
9
|
+
import { checkSiteSettings, RULESET } from "./report-input.mjs";
|
|
7
10
|
|
|
8
11
|
const MAX_SITEMAPS = 10;
|
|
9
12
|
const PAGE_CONCURRENCY = 4;
|
|
10
13
|
const SITEMAP_BYTES = 2 * 1024 * 1024;
|
|
11
|
-
|
|
12
|
-
const
|
|
14
|
+
// 페이지 하나의 점검 한도. MCP의 audit_url도 같은 값을 쓴다.
|
|
15
|
+
export const PAGE_BYTES = 4 * 1024 * 1024;
|
|
16
|
+
export const TIMEOUT_MS = 15_000;
|
|
17
|
+
const MAX_ALTERNATES = 500;
|
|
13
18
|
|
|
14
19
|
function webUrl(raw) {
|
|
15
20
|
if (typeof raw !== "string" || !/^https?:\/\//i.test(raw)) throw new Error(t("HTTP(S) 절대 URL을 입력하세요.", "Enter an absolute HTTP(S) URL."));
|
|
@@ -32,12 +37,24 @@ function decodeLocation(text) {
|
|
|
32
37
|
});
|
|
33
38
|
}
|
|
34
39
|
|
|
35
|
-
|
|
40
|
+
const XHTML = "http://www.w3.org/1999/xhtml";
|
|
41
|
+
|
|
42
|
+
function xmlAttributes(token) {
|
|
43
|
+
const attributes = {};
|
|
44
|
+
for (const [, name, double, single] of token.matchAll(/\s([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attributes[name] = decodeLocation(double ?? single);
|
|
45
|
+
return attributes;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Extract only the direct loc child of url or sitemap, excluding image/video extensions,
|
|
49
|
+
// plus the xhtml:link language alternates of each url entry.
|
|
36
50
|
function parseSitemap(xml) {
|
|
37
51
|
const tokens = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[\w:.-]+(?:\s+[^<>]*?)?\s*\/?>|[^<]+/gy;
|
|
38
52
|
const stack = [];
|
|
39
53
|
const locations = [];
|
|
54
|
+
const alternates = [];
|
|
55
|
+
const xhtmlPrefixes = new Set();
|
|
40
56
|
let type, entry, location, offset = 0;
|
|
57
|
+
let links = [], entryLocation;
|
|
41
58
|
const invalid = () => new Error(t("사이트맵 XML 구조를 읽을 수 없습니다.", "Invalid sitemap XML structure."));
|
|
42
59
|
while (offset < xml.length) {
|
|
43
60
|
const match = tokens.exec(xml);
|
|
@@ -56,8 +73,14 @@ function parseSitemap(xml) {
|
|
|
56
73
|
if (stack.pop() !== tag) throw invalid();
|
|
57
74
|
if (location !== undefined && stack.length === 2) {
|
|
58
75
|
locations.push(location.trim());
|
|
76
|
+
entryLocation = location.trim();
|
|
59
77
|
location = undefined;
|
|
60
78
|
}
|
|
79
|
+
if (stack.length === 1) {
|
|
80
|
+
if (entryLocation && links.length) alternates.push({ location: entryLocation, links });
|
|
81
|
+
links = [];
|
|
82
|
+
entryLocation = undefined;
|
|
83
|
+
}
|
|
61
84
|
continue;
|
|
62
85
|
}
|
|
63
86
|
if (location !== undefined || stack.length >= 128) throw invalid();
|
|
@@ -66,23 +89,31 @@ function parseSitemap(xml) {
|
|
|
66
89
|
type = local;
|
|
67
90
|
entry = type === "urlset" ? "url" : "sitemap";
|
|
68
91
|
}
|
|
92
|
+
const attributes = token.includes("=") ? xmlAttributes(token) : {};
|
|
93
|
+
for (const [name, value] of Object.entries(attributes)) {
|
|
94
|
+
if (name.startsWith("xmlns:") && value === XHTML) xhtmlPrefixes.add(name.slice(6));
|
|
95
|
+
}
|
|
96
|
+
if (stack.length === 2 && type === "urlset" && local === "link" && tag.includes(":") &&
|
|
97
|
+
xhtmlPrefixes.has(tag.split(":")[0]) && attributes.rel?.toLowerCase() === "alternate" && attributes.hreflang !== undefined) {
|
|
98
|
+
links.push({ lang: attributes.hreflang, href: attributes.href });
|
|
99
|
+
}
|
|
69
100
|
if (token.endsWith("/>")) continue;
|
|
70
101
|
if (stack.length === 2 && stack[1].split(":").pop() === entry && local === "loc") location = "";
|
|
71
102
|
stack.push(tag);
|
|
72
103
|
}
|
|
73
104
|
if (stack.length || !type) throw invalid();
|
|
74
|
-
return { type, locations };
|
|
105
|
+
return { type, locations, alternates };
|
|
75
106
|
}
|
|
76
107
|
|
|
77
|
-
async function discover(roots, selected, report, { allowRequest, signal, optionalMissing } = {}) {
|
|
108
|
+
async function discover(roots, selected, report, { allowRequest, signal, optionalMissing, hreflang = new Map() } = {}) {
|
|
78
109
|
const queue = roots.slice(0, MAX_SITEMAPS).map(url => url.href);
|
|
79
110
|
const seen = new Set(queue);
|
|
80
111
|
let skipped = 0, cappedSitemaps = roots.length > MAX_SITEMAPS;
|
|
112
|
+
// 점검 상한에 도달해도 사이트맵의 언어 선언은 읽는다. 문서 수는 MAX_SITEMAPS로 제한한다.
|
|
81
113
|
while (queue.length) {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
}
|
|
114
|
+
// 상한 이후의 사이트맵은 언어 선언 확인용이므로 읽기 실패를 수집 오류로 세지 않는다.
|
|
115
|
+
const beyondLimit = selected.size >= report.limit;
|
|
116
|
+
if (beyondLimit) report.truncated = true;
|
|
86
117
|
const target = queue.shift();
|
|
87
118
|
const origin = new URL(target).origin;
|
|
88
119
|
try {
|
|
@@ -93,8 +124,30 @@ async function discover(roots, selected, report, { allowRequest, signal, optiona
|
|
|
93
124
|
if (res.status !== 200) throw new Error((currentLocale() === "en" ? `Sitemap HTTP ${res.status}` : `사이트맵 HTTP ${res.status}`));
|
|
94
125
|
// .xml.gz files may also be served without a Content-Encoding header.
|
|
95
126
|
const bytes = res.bytes[0] === 0x1f && res.bytes[1] === 0x8b ? gunzipSync(res.bytes, { maxOutputLength: SITEMAP_BYTES }) : res.bytes;
|
|
96
|
-
const { type, locations } = parseSitemap(new TextDecoder().decode(bytes));
|
|
127
|
+
const { type, locations, alternates } = parseSitemap(new TextDecoder().decode(bytes));
|
|
97
128
|
report.sitemapsRead++;
|
|
129
|
+
// 점검 상한을 넘는 항목의 선언도 상호 참조 확인에 쓴다.
|
|
130
|
+
for (const { location, links } of alternates) {
|
|
131
|
+
let url;
|
|
132
|
+
try { url = webUrl(location); } catch { continue; }
|
|
133
|
+
if (url.origin !== origin) continue;
|
|
134
|
+
const key = comparableUrl(url.href);
|
|
135
|
+
if (!hreflang.has(key)) hreflang.set(key, []);
|
|
136
|
+
const declared = hreflang.get(key);
|
|
137
|
+
const known = new Set(declared.map(({ lang, href }) => `${lang}\u0000${href}`));
|
|
138
|
+
for (const { lang, href } of links) {
|
|
139
|
+
const entry = declaration("sitemap", lang, href, { sitemap: target, page: key });
|
|
140
|
+
const id = `${entry.lang}\u0000${entry.href}`;
|
|
141
|
+
if (known.has(id)) continue;
|
|
142
|
+
if (declared.length >= MAX_ALTERNATES) {
|
|
143
|
+
const warning = t(`사이트맵에서 한 URL의 언어 선언은 ${MAX_ALTERNATES}개까지만 읽습니다: ${key}`, `Only ${MAX_ALTERNATES} sitemap language declarations are read per URL: ${key}`);
|
|
144
|
+
if (!report.warnings.includes(warning)) report.warnings.push(warning);
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
known.add(id);
|
|
148
|
+
declared.push(entry);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
98
151
|
for (const raw of locations) {
|
|
99
152
|
let url;
|
|
100
153
|
try { url = webUrl(raw); } catch { skipped++; continue; }
|
|
@@ -110,7 +163,7 @@ async function discover(roots, selected, report, { allowRequest, signal, optiona
|
|
|
110
163
|
}
|
|
111
164
|
}
|
|
112
165
|
} catch (error) {
|
|
113
|
-
report.discoveryErrors.push({ target, error: error.message });
|
|
166
|
+
if (!beyondLimit) report.discoveryErrors.push({ target, error: error.message });
|
|
114
167
|
report.warnings.push((currentLocale() === "en" ? `Could not read sitemap ${target} — ${error.message}` : `사이트맵 ${target} 확인 실패 — ${error.message}`));
|
|
115
168
|
}
|
|
116
169
|
}
|
|
@@ -123,19 +176,23 @@ async function discover(roots, selected, report, { allowRequest, signal, optiona
|
|
|
123
176
|
|
|
124
177
|
export async function discoverCrawlSitemaps(roots, options) {
|
|
125
178
|
const selected = new Map();
|
|
179
|
+
const hreflang = new Map();
|
|
126
180
|
const report = { limit: 1000, truncated: false, sitemapsRead: 0, discoveryErrors: [], warnings: [] };
|
|
127
|
-
await discover(roots, selected, report, options);
|
|
128
|
-
return { ...report, urls: [...selected.keys()] };
|
|
181
|
+
await discover(roots, selected, report, { ...options, hreflang });
|
|
182
|
+
return { ...report, urls: [...selected.keys()], hreflang };
|
|
129
183
|
}
|
|
130
184
|
|
|
131
|
-
export async function auditSite({ targets = [], sitemap, baseDir = process.cwd(), limit = 25, expectIndexable = false, crawlScope } = {}) {
|
|
132
|
-
|
|
133
|
-
if (!Array.isArray(targets)) throw new Error(t("targets는 URL 또는 로컬 HTML 경로의 배열이어야 합니다.", "targets must be an array of URLs or local HTML paths."));
|
|
185
|
+
export async function auditSite({ targets = [], sitemap, baseDir = process.cwd(), limit = 25, expectIndexable = false, intentionallyExcluded = [], crawlScope } = {}) {
|
|
186
|
+
checkSiteSettings({ targets, limit, expectIndexable, intentionallyExcluded });
|
|
134
187
|
if (typeof baseDir !== "string" || !baseDir) throw new Error(t("baseDir에는 디렉터리 경로를 지정하세요.", "baseDir must be a directory path."));
|
|
135
|
-
|
|
188
|
+
// targets와 같은 방식으로 해석해 경로·쿼리가 같은 페이지에만 적용한다.
|
|
189
|
+
const sourceOf = target => (/^[a-z][a-z\d+.-]*:/i.test(target) && !/^[a-z]:[\\/]/i.test(target) ? webUrl(target).href : resolve(baseDir, target));
|
|
190
|
+
const excluded = new Map(intentionallyExcluded.map(value => [sourceOf(value.trim()), value.trim()]));
|
|
191
|
+
const matchedExclusions = new Set();
|
|
136
192
|
const root = !crawlScope && sitemap !== undefined ? webUrl(sitemap) : null;
|
|
137
193
|
const selected = new Map();
|
|
138
|
-
const report = { pages: [], limit, truncated: false, sitemapsRead: 0, discoveryErrors: [], warnings: [] };
|
|
194
|
+
const report = { ruleset: RULESET, pages: [], limit, truncated: false, sitemapsRead: 0, discoveryErrors: [], warnings: [] };
|
|
195
|
+
const sitemapHreflang = new Map(crawlScope?.hreflang ?? []);
|
|
139
196
|
for (const input of (crawlScope && !crawlScope.seedPage ? [] : targets)) {
|
|
140
197
|
if (typeof input !== "string" || !input.trim()) throw new Error(t("targets 항목에 빈 값이 있습니다.", "targets contains an empty entry."));
|
|
141
198
|
const target = input.trim();
|
|
@@ -170,14 +227,16 @@ export async function auditSite({ targets = [], sitemap, baseDir = process.cwd()
|
|
|
170
227
|
if (!file.isFile() || file.size > PAGE_BYTES) throw new Error((currentLocale() === "en" ? `Local HTML must be a regular file of at most ${PAGE_BYTES} bytes.` : `로컬 HTML은 ${PAGE_BYTES}바이트 이하의 일반 파일이어야 합니다.`));
|
|
171
228
|
}
|
|
172
229
|
const network = { allowedOrigin: crawlScope?.origin ?? allowedOrigin, allowRequest: crawlScope?.allowRequest, maxBytes: PAGE_BYTES, signal: AbortSignal.timeout(TIMEOUT_MS) };
|
|
173
|
-
const
|
|
230
|
+
const expectExcluded = excluded.has(source);
|
|
231
|
+
if (expectExcluded) matchedExclusions.add(source);
|
|
232
|
+
const page = await run(source, { expectIndexable: expectIndexable && !expectExcluded, expectExcluded, network, llmsByOrigin, fetchedPage: crawlScope?.seedPage, deferHreflang: true });
|
|
174
233
|
return { ...page, target };
|
|
175
234
|
} catch (error) {
|
|
176
235
|
return { target, results: [], error: error.message };
|
|
177
236
|
}
|
|
178
237
|
}
|
|
179
238
|
if (root) {
|
|
180
|
-
await discover([root], selected, report);
|
|
239
|
+
await discover([root], selected, report, { hreflang: sitemapHreflang });
|
|
181
240
|
} else if (!crawlScope) {
|
|
182
241
|
await auditSelected();
|
|
183
242
|
const roots = new Map();
|
|
@@ -189,7 +248,7 @@ export async function auditSite({ targets = [], sitemap, baseDir = process.cwd()
|
|
|
189
248
|
if (url.origin === new URL(finalUrl).origin) roots.set(url.href, url);
|
|
190
249
|
}
|
|
191
250
|
}
|
|
192
|
-
if (roots.size) await discover([...roots.values()], selected, report);
|
|
251
|
+
if (roots.size) await discover([...roots.values()], selected, report, { hreflang: sitemapHreflang });
|
|
193
252
|
}
|
|
194
253
|
if (report.truncated && selected.size >= limit) report.warnings.push((currentLocale() === "en" ? `Selected up to ${limit} pages to audit. Split the targets across runs to cover the full set.` : `최대 ${limit}페이지까지 선택하여 점검했습니다. 전체 범위를 확인하려면 대상을 나눠 실행하세요.`));
|
|
195
254
|
if (root && !selected.size && !report.discoveryErrors.length) report.warnings.push(t("사이트맵에서 점검할 페이지를 찾지 못했습니다.", "The sitemap contained no pages to audit."));
|
|
@@ -206,32 +265,29 @@ export async function auditSite({ targets = [], sitemap, baseDir = process.cwd()
|
|
|
206
265
|
seenLlms.add(page.llms);
|
|
207
266
|
}
|
|
208
267
|
}
|
|
209
|
-
|
|
268
|
+
checkHreflang([...audited], sitemapHreflang, report.truncated || Boolean(crawlScope?.report.truncated));
|
|
269
|
+
for (const [source, value] of excluded) {
|
|
270
|
+
if (!matchedExclusions.has(source)) report.warnings.push(t(`intentionallyExcluded 항목을 점검 대상에서 찾지 못했습니다: ${value}`,
|
|
271
|
+
`No audited page matches this intentionallyExcluded entry: ${value}`));
|
|
272
|
+
}
|
|
210
273
|
return report;
|
|
211
274
|
}
|
|
212
275
|
|
|
213
|
-
function
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
const
|
|
218
|
-
url.
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
const languages = new Set(page.hreflang.alternates.filter(link => link.url === source).map(link => link.lang));
|
|
223
|
-
if (languages.size > 1) languages.delete("x-default");
|
|
224
|
-
for (const target of new Set(page.hreflang.alternates.map(link => link.url))) {
|
|
225
|
-
const alternate = byUrl.get(target);
|
|
226
|
-
if (!alternate || target === source) continue;
|
|
227
|
-
const linksBack = alternate.hreflang.alternates.some(link =>
|
|
228
|
-
link.url === source && (!languages.size || languages.has(link.lang)));
|
|
229
|
-
if (!linksBack) page.results.push({
|
|
230
|
-
level: "WARN", channel: t("다국어", "International"), item: "hreflang reciprocity",
|
|
231
|
-
detail: t(`${target} 페이지에 ${source}의 언어에 맞는 hreflang 반환 링크가 없습니다.`,
|
|
232
|
-
`${target} has no hreflang return link to ${source} for the source language.`),
|
|
233
|
-
skill: "google-search",
|
|
234
|
-
});
|
|
276
|
+
function checkHreflang(audited, sitemapHreflang, truncated) {
|
|
277
|
+
const records = audited.map(([source, page]) => {
|
|
278
|
+
const requested = /^https?:/i.test(source) ? comparableUrl(source) : null;
|
|
279
|
+
// 리다이렉트된 페이지는 요청 URL에 적힌 선언도 보존한다.
|
|
280
|
+
const urls = page.hreflang?.url ? new Set([page.hreflang.url, requested].filter(Boolean)) : [];
|
|
281
|
+
const declared = [...urls].flatMap(url => sitemapHreflang.get(url) ?? []);
|
|
282
|
+
if (declared.length) {
|
|
283
|
+
for (const entry of declared) page.hreflang.declarations.push(entry);
|
|
284
|
+
page.hreflang.alternates = hreflangSummary(page.hreflang.declarations);
|
|
235
285
|
}
|
|
236
|
-
|
|
286
|
+
return hreflangRecord(page, requested);
|
|
287
|
+
});
|
|
288
|
+
const findings = analyzeHreflang(records, { truncated, sitemapDeclarations: sitemapHreflang });
|
|
289
|
+
audited.forEach(([, page], index) => {
|
|
290
|
+
addHreflangFindings(findings[index], (level, channel, item, detail, skill) => page.results.push({ level, channel, item, detail, skill }));
|
|
291
|
+
trimHreflang(page.hreflang);
|
|
292
|
+
});
|
|
237
293
|
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
// JSON-LD 블록별 문법·타입·필수 속성 판정. CLI·웹·확장 공용이며 의존성이 없다.
|
|
2
|
+
// 브라우저 확장은 이 파일의 사본(extension/structured-data.mjs)을 읽는다.
|
|
3
|
+
|
|
4
|
+
const MAX_TYPES = 50;
|
|
5
|
+
const MAX_BLOCKS = 200;
|
|
6
|
+
const BLOCK_ORDER = { FAIL: 1, WARN: 2 };
|
|
7
|
+
|
|
8
|
+
// 블록이 지나치게 많으면 문법 오류, 실패, 주의, 나머지 순으로 상세 결과를 남기고 원래 순서로 보여준다.
|
|
9
|
+
function listedBlocks(blocks) {
|
|
10
|
+
if (blocks.length <= MAX_BLOCKS) return blocks;
|
|
11
|
+
const rank = (block) => (block.state === "syntax-error" ? 0 : BLOCK_ORDER[block.level] ?? 3);
|
|
12
|
+
return [...blocks].sort((a, b) => rank(a) - rank(b) || a.index - b.index).slice(0, MAX_BLOCKS).sort((a, b) => a.index - b.index);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// 깊게 중첩된 입력에도 중단되지 않도록 재귀 대신 스택을 쓴다. 순서는 @graph 항목, 그다음 감싼 노드다.
|
|
16
|
+
function flatten(root) {
|
|
17
|
+
const out = [];
|
|
18
|
+
const stack = [[root, false]];
|
|
19
|
+
while (stack.length) {
|
|
20
|
+
const [node, ready] = stack.pop();
|
|
21
|
+
if (ready) out.push(node);
|
|
22
|
+
else if (Array.isArray(node)) {
|
|
23
|
+
for (let index = node.length - 1; index >= 0; index--) stack.push([node[index], false]);
|
|
24
|
+
} else if (node && typeof node === "object") {
|
|
25
|
+
if (typesOf(node).length) stack.push([node, true]);
|
|
26
|
+
if (node["@graph"]) stack.push([node["@graph"], false]);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 참조 대상에서 검사에 쓰는 속성
|
|
33
|
+
const REFERENCED = ["@id", "name", "address", "position", "item"];
|
|
34
|
+
const isVirtual = (node) => Boolean(node) && typeof node === "object" && typesOf(node).includes("VirtualLocation");
|
|
35
|
+
|
|
36
|
+
// @id로 참조할 수 있는 노드의 속성을 문서 전체에서 모은다. @id·@type만 있는 객체는 참조이며 정의가 아니다.
|
|
37
|
+
function indexById(roots) {
|
|
38
|
+
const merged = new Map();
|
|
39
|
+
const defined = new Set();
|
|
40
|
+
const stack = [...roots];
|
|
41
|
+
while (stack.length) {
|
|
42
|
+
const node = stack.pop();
|
|
43
|
+
if (Array.isArray(node)) {
|
|
44
|
+
for (const child of node) stack.push(child);
|
|
45
|
+
} else if (node && typeof node === "object") {
|
|
46
|
+
const id = node["@id"];
|
|
47
|
+
if (typeof id === "string") {
|
|
48
|
+
merged.set(id, Object.assign(merged.get(id) ?? {}, node));
|
|
49
|
+
if (Object.keys(node).some((key) => key !== "@id" && key !== "@type")) defined.add(id);
|
|
50
|
+
}
|
|
51
|
+
for (const value of Object.values(node)) if (value && typeof value === "object") stack.push(value);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
// 대상의 타입은 참조 횟수와 관계없이 한 번만 확인한다. 온라인 장소는 타입 선언만으로 알 수 있다.
|
|
55
|
+
const ids = new Map();
|
|
56
|
+
for (const [id, node] of merged) {
|
|
57
|
+
const virtual = isVirtual(node);
|
|
58
|
+
if (virtual || defined.has(id)) ids.set(id, { node, virtual });
|
|
59
|
+
}
|
|
60
|
+
return ids;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// { "@id": ... } 형태의 참조를 대상 노드의 값으로 읽는다. 대상을 복사하지 않고 필요한 속성만 가져온다.
|
|
64
|
+
function resolve(value, ids) {
|
|
65
|
+
const reference = value && typeof value === "object" && typeof value["@id"] === "string";
|
|
66
|
+
const target = reference ? ids.get(value["@id"]) : undefined;
|
|
67
|
+
if (target) {
|
|
68
|
+
const node = Object.fromEntries(REFERENCED.map((key) => [key, Object.hasOwn(value, key) ? value[key] : target.node[key]]));
|
|
69
|
+
return { node, value, target };
|
|
70
|
+
}
|
|
71
|
+
if (reference && Object.keys(value).every((key) => key === "@id" || key === "@type")) return { node: value, value, unresolved: value["@id"] };
|
|
72
|
+
return { node: value, value };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 같은 문자열을 여러 곳에서 참조해도 한 번만 다듬는다.
|
|
76
|
+
function trimmer() {
|
|
77
|
+
const known = new Map();
|
|
78
|
+
return (text) => {
|
|
79
|
+
let result = known.get(text);
|
|
80
|
+
if (result === undefined) known.set(text, result = text.trim());
|
|
81
|
+
return result;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const typesOf = (node) => [].concat(node["@type"] || []).filter((type) => typeof type === "string" && type.trim())
|
|
86
|
+
.map((type) => type.replace(/^(?:https?:\/\/schema\.org\/|schema:)/, ""));
|
|
87
|
+
|
|
88
|
+
// ISO 8601 날짜 또는 일시 전체. 시각과 UTC 오프셋은 범위 안의 값이어야 한다.
|
|
89
|
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}(?:T(?:[01]\d|2[0-3])(?::[0-5]\d(?::[0-5]\d(?:[.,]\d+)?)?)?(?:Z|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/i;
|
|
90
|
+
|
|
91
|
+
function realDate(value) {
|
|
92
|
+
if (!ISO_DATE.test(value)) return false;
|
|
93
|
+
const day = value.slice(0, 10);
|
|
94
|
+
const midnight = Date.parse(`${day}T00:00:00Z`);
|
|
95
|
+
return Number.isFinite(midnight) && new Date(midnight).toISOString().slice(0, 10) === day;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const isEvent = (types) => types.some((type) => /Event$/.test(type));
|
|
99
|
+
|
|
100
|
+
// requirement: required(필수) · recommended(권장) · format(값 형식) · advice(작성 지침)
|
|
101
|
+
// source: 그 속성을 요구한다고 확인한 문서의 엔진
|
|
102
|
+
function checkNode(node, ids, trim) {
|
|
103
|
+
const types = typesOf(node);
|
|
104
|
+
const features = [];
|
|
105
|
+
const checks = [];
|
|
106
|
+
const add = (feature, property, ok, requirement, source, level, code, value) =>
|
|
107
|
+
checks.push({ feature, property, ok, requirement, source, level: ok ? "PASS" : level, code: ok ? "present" : code, ...(value !== undefined && { value }) });
|
|
108
|
+
const reference = (feature, property, id) => add(feature, property, false, "advice", "google", "WARN", "reference", id.slice(0, 200));
|
|
109
|
+
|
|
110
|
+
function date(value, field) {
|
|
111
|
+
const property = `Event.${field}`;
|
|
112
|
+
const fail = (level, code) => add("Event", property, false, "format", "google", level, code, typeof value === "string" ? value.slice(0, 200) : undefined);
|
|
113
|
+
if (typeof value !== "string") return fail("FAIL", "date-type");
|
|
114
|
+
if (!realDate(value)) return fail("FAIL", "date-format");
|
|
115
|
+
if (/T00:00(:00)?/i.test(value)) return fail("WARN", "date-midnight");
|
|
116
|
+
if (/T\d{2}/i.test(value) && !/T.*(?:Z|[+-]\d{2}(?::?\d{2})?)$/i.test(value)) fail("WARN", "date-offset");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (isEvent(types)) {
|
|
120
|
+
features.push("Event");
|
|
121
|
+
add("Event", "Event.name", Boolean(node.name), "required", "google", "FAIL", "missing");
|
|
122
|
+
add("Event", "Event.startDate", Boolean(node.startDate), "required", "google", "FAIL", "missing");
|
|
123
|
+
if (node.startDate) date(node.startDate, "startDate");
|
|
124
|
+
if (node.endDate) date(node.endDate, "endDate");
|
|
125
|
+
const locations = [].concat(node.location || []).map((entry) => resolve(entry, ids));
|
|
126
|
+
add("Event", "Event.location", locations.length > 0, "required", "google", "FAIL", "missing");
|
|
127
|
+
// 온라인 장소는 주소 검사에서 제외한다. 나머지 장소는 모두 확인한다.
|
|
128
|
+
const physical = locations.filter(({ value, target }) => !(target?.virtual || isVirtual(value)));
|
|
129
|
+
if (locations.length && !physical.length) add("Event", "Event.location", false, "required", "google", "FAIL", "physical-location");
|
|
130
|
+
const eventName = typeof node.name === "string" ? trim(node.name) : "";
|
|
131
|
+
const compared = new Map();
|
|
132
|
+
const matchesEvent = (name) => {
|
|
133
|
+
if (!compared.has(name)) compared.set(name, trim(name) === eventName);
|
|
134
|
+
return compared.get(name);
|
|
135
|
+
};
|
|
136
|
+
for (const { node: place, unresolved } of physical) {
|
|
137
|
+
if (unresolved) {
|
|
138
|
+
reference("Event", "Event.location", unresolved);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
add("Event", "Event.location.name", Boolean(place?.name), "recommended", "google", "WARN", "venue-name");
|
|
142
|
+
add("Event", "Event.location.address", Boolean(place?.address), "required", "google", "FAIL", "address");
|
|
143
|
+
if (eventName && typeof place?.name === "string" && matchesEvent(place.name)) {
|
|
144
|
+
add("Event", "Event.name", false, "advice", "google", "WARN", "name-is-venue");
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
add("Event", "Event.eventStatus", Boolean(node.eventStatus), "recommended", "google", "INFO", "event-status");
|
|
148
|
+
add("Event", "Event.image", Boolean(node.image), "recommended", "google", "WARN", "recommended");
|
|
149
|
+
}
|
|
150
|
+
if (types.includes("BreadcrumbList")) {
|
|
151
|
+
features.push("BreadcrumbList");
|
|
152
|
+
const items = [].concat(node.itemListElement || []);
|
|
153
|
+
add("BreadcrumbList", "BreadcrumbList.itemListElement", items.length > 0, "required", "google", "FAIL", "breadcrumb-items");
|
|
154
|
+
if (items.length === 1) add("BreadcrumbList", "BreadcrumbList.itemListElement", false, "required", "google", "WARN", "breadcrumb-count");
|
|
155
|
+
for (const [position, entry] of items.entries()) {
|
|
156
|
+
const { node: item, unresolved } = resolve(entry, ids);
|
|
157
|
+
if (unresolved) {
|
|
158
|
+
reference("BreadcrumbList", "BreadcrumbList.itemListElement", unresolved);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
// Google은 position·name·item을 요구한다(마지막 항목의 item은 예외). 네이버는 position이 필수가 아니다.
|
|
162
|
+
add("BreadcrumbList", "BreadcrumbList.position", item?.position !== undefined && item.position !== "", "required", "google", "WARN", "missing");
|
|
163
|
+
if (position < items.length - 1) add("BreadcrumbList", "BreadcrumbList.item", Boolean(item?.item), "required", "google", "WARN", "missing");
|
|
164
|
+
const target = resolve(item?.item, ids);
|
|
165
|
+
const name = item?.name ?? target.node?.name;
|
|
166
|
+
if (!name && target.unresolved) reference("BreadcrumbList", "BreadcrumbList.name", target.unresolved);
|
|
167
|
+
else add("BreadcrumbList", "BreadcrumbList.name", Boolean(name), "required", "naver", "FAIL", "breadcrumb-name");
|
|
168
|
+
if (typeof name === "string" && /^(홈|home|top)$/i.test(trim(name))) {
|
|
169
|
+
add("BreadcrumbList", "BreadcrumbList.name", false, "advice", "naver", "WARN", "breadcrumb-generic", trim(name));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if ((types.includes("Organization") || types.includes("Person")) && node.sameAs !== undefined) {
|
|
174
|
+
const feature = `${types.includes("Organization") ? "Organization" : "Person"}.sameAs`;
|
|
175
|
+
features.push(feature);
|
|
176
|
+
for (const property of ["name", "url"]) {
|
|
177
|
+
add(feature, `${feature.split(".")[0]}.${property}`, Boolean(node[property]), "required", "naver", "WARN", "channel");
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (types.includes("WebSite")) {
|
|
181
|
+
features.push("WebSite");
|
|
182
|
+
add("WebSite", "WebSite.name", Boolean(node.name), "required", "google", "WARN", "site-name");
|
|
183
|
+
add("WebSite", "WebSite.url", Boolean(node.url), "required", "google", "WARN", "missing");
|
|
184
|
+
}
|
|
185
|
+
return { types, features, checks };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// 블록 판정은 노드 수와 무관한 크기로 요약한다. 같은 속성·사유의 결과는 횟수로 합친다.
|
|
189
|
+
function summarize(index, nodes) {
|
|
190
|
+
const checks = new Map();
|
|
191
|
+
const types = new Set();
|
|
192
|
+
const unsupported = new Set();
|
|
193
|
+
for (const node of nodes) {
|
|
194
|
+
for (const type of node.types) {
|
|
195
|
+
types.add(type);
|
|
196
|
+
if (!node.features.length) unsupported.add(type);
|
|
197
|
+
}
|
|
198
|
+
for (const check of node.checks) {
|
|
199
|
+
const key = [check.property, check.code, check.requirement, check.source].join("\u0000");
|
|
200
|
+
const known = checks.get(key);
|
|
201
|
+
if (known) known.count++;
|
|
202
|
+
else checks.set(key, { ...check, count: 1 });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const list = [...checks.values()];
|
|
206
|
+
const failed = list.filter((check) => !check.ok);
|
|
207
|
+
const state = !nodes.length ? "no-type"
|
|
208
|
+
: !nodes.some((node) => node.features.length) ? "unsupported"
|
|
209
|
+
: failed.some((check) => check.requirement === "required") ? "missing-required"
|
|
210
|
+
: failed.some((check) => check.level !== "INFO") ? "issues" : "checked";
|
|
211
|
+
const level = state === "no-type" ? "WARN" : state === "unsupported" ? "INFO"
|
|
212
|
+
: list.some((check) => check.level === "FAIL") ? "FAIL" : list.some((check) => check.level === "WARN") ? "WARN" : "PASS";
|
|
213
|
+
return {
|
|
214
|
+
index, state, level, nodeCount: nodes.length,
|
|
215
|
+
types: [...types].slice(0, MAX_TYPES), omittedTypes: Math.max(0, types.size - MAX_TYPES),
|
|
216
|
+
unsupported: [...unsupported].slice(0, MAX_TYPES), checks: list,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// onFailure(check, node): 통과하지 못한 항목을 노드 단위로 보고할 때 사용한다.
|
|
221
|
+
// onBlock(block): 상세 목록에서 생략하는 블록까지 모두 받는다.
|
|
222
|
+
export function analyzeJsonLd(rawBlocks, onFailure, onBlock) {
|
|
223
|
+
const parsed = rawBlocks.map((raw) => {
|
|
224
|
+
try {
|
|
225
|
+
return { value: JSON.parse(raw) };
|
|
226
|
+
} catch (error) {
|
|
227
|
+
return { error: String(error.message).slice(0, 120) };
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
const ids = indexById(parsed.filter((entry) => !entry.error).map((entry) => entry.value));
|
|
231
|
+
const trim = trimmer();
|
|
232
|
+
let events = 0;
|
|
233
|
+
const types = new Set();
|
|
234
|
+
const blocks = parsed.map((entry, position) => {
|
|
235
|
+
const index = position + 1;
|
|
236
|
+
if (entry.error) return { index, state: "syntax-error", level: "FAIL", error: entry.error, nodeCount: 0, types: [], omittedTypes: 0, unsupported: [], checks: [] };
|
|
237
|
+
const nodes = flatten(entry.value).map((node) => checkNode(node, ids, trim));
|
|
238
|
+
for (const node of nodes) {
|
|
239
|
+
if (isEvent(node.types)) events++;
|
|
240
|
+
for (const type of node.types) types.add(type);
|
|
241
|
+
if (onFailure) for (const check of node.checks) if (!check.ok) onFailure(check, node);
|
|
242
|
+
}
|
|
243
|
+
return summarize(index, nodes);
|
|
244
|
+
});
|
|
245
|
+
if (onBlock) for (const block of blocks) onBlock(block);
|
|
246
|
+
const listed = listedBlocks(blocks);
|
|
247
|
+
const result = { blocks: listed, types: [...types].slice(0, MAX_TYPES), events };
|
|
248
|
+
if (listed.length === blocks.length) return result;
|
|
249
|
+
// 건수와 점수를 생략 전과 같게 계산할 수 있도록 생략한 블록의 수준별 개수를 남긴다.
|
|
250
|
+
const kept = new Set(listed);
|
|
251
|
+
const omittedLevels = {};
|
|
252
|
+
for (const block of blocks) if (!kept.has(block)) omittedLevels[block.level] = (omittedLevels[block.level] ?? 0) + 1;
|
|
253
|
+
return { ...result, omittedBlocks: blocks.length - listed.length, omittedLevels };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const pick = (locale, ko, en) => (locale === "en" ? en : ko);
|
|
257
|
+
|
|
258
|
+
export function describeCheck({ code, value }, locale) {
|
|
259
|
+
const messages = {
|
|
260
|
+
present: ["있음", "Present"],
|
|
261
|
+
missing: ["필수 속성 없음", "Required property missing"],
|
|
262
|
+
recommended: ["권장 속성 없음", "Recommended property missing"],
|
|
263
|
+
"venue-name": ["장소 이름 없음", "Missing venue name"],
|
|
264
|
+
address: ["주소 없음(Google 필수)", "Missing address (required by Google)"],
|
|
265
|
+
"physical-location": ["실제 장소 없음(Google 이벤트는 오프라인 장소 필요)", "No physical location (Google events require one)"],
|
|
266
|
+
reference: [`@id 참조 대상을 찾지 못해 속성 미확인: ${value}`, `Properties unverified: the @id reference was not found: ${value}`],
|
|
267
|
+
"name-is-venue": ["행사명이 장소명과 같음", "Event name matches the venue name"],
|
|
268
|
+
"event-status": ["없음 → Google은 EventScheduled로 간주", "Missing. Google assumes EventScheduled"],
|
|
269
|
+
"date-type": ["문자열이 아님", "Value must be a string"],
|
|
270
|
+
"date-format": [`ISO-8601 아님: ${value}`, `Invalid ISO 8601 value: ${value}`],
|
|
271
|
+
"date-midnight": [`자정(T00:00)으로 채운 값: ${value}. 시간을 모르면 날짜만 쓰기`, `Midnight placeholder (T00:00): ${value}. Use only the date when the time is unknown`],
|
|
272
|
+
"date-offset": [`시간에 UTC 오프셋 없음: ${value} (예: +09:00)`, `Missing UTC offset: ${value} (example: +09:00)`],
|
|
273
|
+
"breadcrumb-items": ["itemListElement 없음", "Missing itemListElement"],
|
|
274
|
+
"breadcrumb-count": ["ListItem이 2개 미만(Google은 2개 이상 요구)", "Fewer than two ListItems (Google requires at least two)"],
|
|
275
|
+
"breadcrumb-name": ["name 없음(네이버 필수)", "Missing name (required by Naver)"],
|
|
276
|
+
"breadcrumb-generic": [`일반어 "${value}" — 네이버는 페이지를 설명하는 이름 권장`, `Generic name "${value}". Naver recommends a name that describes the page`],
|
|
277
|
+
channel: ["네이버 연관채널은 name·url·sameAs 필수", "Naver associated channels require name, url and sameAs"],
|
|
278
|
+
"site-name": ["사이트 이름 없음", "Missing site name"],
|
|
279
|
+
};
|
|
280
|
+
const [ko, en] = messages[code];
|
|
281
|
+
return pick(locale, ko, en);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// 블록별 판정과 별도인 페이지 전체 지적. 모든 채널이 같은 수준과 문구를 쓴다.
|
|
285
|
+
export function pageFindings(analysis, blockCount, locale) {
|
|
286
|
+
const findings = [];
|
|
287
|
+
if (!blockCount) findings.push({ level: "INFO", item: "JSON-LD", detail: pick(locale, "없음", "Missing") });
|
|
288
|
+
if (analysis.events > 1) findings.push({ level: "WARN", item: pick(locale, "Event 개수", "Event count"), detail: pick(locale, `${analysis.events}개 — Google 이벤트 환경은 한 이벤트에 집중한 상세(리프) 페이지만 지원. 목록 페이지는 ItemList 권장`, `${analysis.events} events. Google's event experience supports pages dedicated to one event. Use ItemList on listing pages`) });
|
|
289
|
+
if (analysis.events) findings.push({ level: "INFO", item: pick(locale, "Event 지역", "Event regions"), detail: pick(locale, "Google 이벤트 검색 환경 제공 지역에 한국 없음(2026-11-04 확인). 네이버 Event 가이드 없음", "Google's event experience excludes South Korea (checked 2026-11-04). Naver has no Event guide") });
|
|
290
|
+
return findings;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function describeOmittedBlocks(count, locale) {
|
|
294
|
+
return pick(locale, `블록이 많아 ${count}개의 상세 결과는 생략했습니다(실패·주의 블록을 먼저 표시)`, `Detailed results for ${count} more blocks are not listed (failing and warning blocks come first)`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function describeBlockResult(block, locale) {
|
|
298
|
+
if (block.state === "syntax-error") return pick(locale, `JSON 문법 오류: ${block.error}`, `Invalid JSON syntax: ${block.error}`);
|
|
299
|
+
if (block.state === "no-type") return pick(locale, "JSON 문법은 정상이지만 @type을 식별하지 못함 — 구조화 데이터 항목 없음", "Valid JSON, but no @type was identified, so there is no structured data item");
|
|
300
|
+
const more = block.omittedTypes ? pick(locale, ` 외 ${block.omittedTypes}개`, ` and ${block.omittedTypes} more`) : "";
|
|
301
|
+
const parts = [pick(locale, `타입: ${block.types.join(", ")}${more}`, `Types: ${block.types.join(", ")}${more}`)];
|
|
302
|
+
const unique = (list) => [...new Set(list)];
|
|
303
|
+
const failures = unique(block.checks.filter((check) => !check.ok).map((check) => {
|
|
304
|
+
const label = { required: pick(locale, "필수", "required"), recommended: pick(locale, "권장", "recommended"), format: pick(locale, "형식", "format"), advice: pick(locale, "지침", "guidance") }[check.requirement];
|
|
305
|
+
const times = check.count > 1 ? ` ×${check.count}` : "";
|
|
306
|
+
return `${check.property} [${label} · ${check.source === "naver" ? pick(locale, "네이버", "Naver") : "Google"}] ${describeCheck(check, locale)}${times}`;
|
|
307
|
+
}));
|
|
308
|
+
parts.push(...failures);
|
|
309
|
+
const checked = unique(block.checks.filter((check) => check.code !== "reference").map((check) => check.property));
|
|
310
|
+
if (checked.length) {
|
|
311
|
+
parts.push(pick(locale, `검사한 속성: ${checked.join(", ")}`, `Properties checked: ${checked.join(", ")}`));
|
|
312
|
+
if (block.state === "checked") parts.push(pick(locale, "위 속성 범위에서만 확인 — 리치 결과 자격이나 다른 속성은 확인하지 않음", "Only these properties were checked, not rich result eligibility or other properties"));
|
|
313
|
+
}
|
|
314
|
+
if (block.unsupported.length) parts.push(pick(locale, `타입 확인·상세 검사 미지원: ${block.unsupported.join(", ")}`, `Type identified; detailed check not supported: ${block.unsupported.join(", ")}`));
|
|
315
|
+
return parts.join(" · ");
|
|
316
|
+
}
|