@first-ch/tools-mcp 0.36.0 → 0.37.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/README.md +124 -22
- package/apps.mjs +538 -0
- package/css-layout.mjs +612 -0
- package/dpi.mjs +660 -0
- package/faq-jsonld.mjs +401 -0
- package/htpasswd.mjs +740 -0
- package/lines.mjs +423 -0
- package/openapi-doc.mjs +2954 -0
- package/package.json +65 -4
- package/serp.mjs +309 -0
- package/server.mjs +322 -1
package/faq-jsonld.mjs
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
/* FAQ構造化データ(JSON-LD)&Markdown ジェネレーター(faq_jsonld_generate)
|
|
2
|
+
* 質問と回答のペアから、schema.org の FAQPage 形式の JSON-LD・同じ内容の Markdown・
|
|
3
|
+
* 貼り付け用の HTML(details/summary)を同時に作る。
|
|
4
|
+
* 変換のコア(parseAnswer / build / parseBulk ほか)は FirstCHTools の site/faq-jsonld/app.js と同一
|
|
5
|
+
* (2箇所ルール: site側が正本・片方を直したらもう片方も同じ内容で反映する)。
|
|
6
|
+
* 両ファイルからコアの開始/終了コメントに挟まれた範囲を sed で切り出し
|
|
7
|
+
* (site側は字下げ2文字を落とす・こちらは行頭の export を落とす)、
|
|
8
|
+
* diff が空になることで同期を機械的に確認できる。
|
|
9
|
+
*
|
|
10
|
+
* 既存の jsonld_generate(type=faqpage)は質問と回答をそのまま文字列で入れるだけ。こちらは回答を
|
|
11
|
+
* 「空行で段落・改行・[文字](URL) と裸のURLはリンク・行頭の - ・ 1. は箇条書き」として読んで HTML にし、
|
|
12
|
+
* Markdown と details/summary の HTML も同時に返し、「Q: / A:」「## 見出し」形式の一括貼り付けも解析する。
|
|
13
|
+
* 完全ローカル処理・ネットワーク送信なし。 */
|
|
14
|
+
|
|
15
|
+
// 件数と文字数の上限(site の LIMITS と同じ値。site では入力欄の maxlength と行数の上限)
|
|
16
|
+
export const LIMITS = { rows: 200, q: 500, a: 5000 };
|
|
17
|
+
|
|
18
|
+
/* ==================== ここから変換のコア ==================== */
|
|
19
|
+
|
|
20
|
+
// リンクにしてよい宛先。javascript: などはリンクにせず文字のまま残す
|
|
21
|
+
export const SAFE_HREF = /^(?:https?:\/\/|mailto:|tel:|\/|#)/i;
|
|
22
|
+
export const ABS_HREF = /^(?:https?:\/\/|mailto:|tel:)/i;
|
|
23
|
+
// [文字](URL) か、裸の http(s) URL。URL に使える文字は ASCII に限る(「https://example.com/です」の「です」を含めない)
|
|
24
|
+
export const INLINE_RE = /\[([^\[\]\n]+)\]\(\s*<?([^\s<>()]*(?:\([^\s<>()]*\)[^\s<>()]*)*)>?\s*\)|(https?:\/\/[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+)/g;
|
|
25
|
+
export const BULLET_RE = /^[ \t\u3000]*(?:[-*•]\s+|・\s*)(.*\S.*)$/;
|
|
26
|
+
export const ORDERED_RE = /^[ \t\u3000]*(\d{1,3})(?:[.)]\s+|[.)]\s*)(.*\S.*)$/;
|
|
27
|
+
|
|
28
|
+
export const nl = (s) => String(s == null ? '' : s).replace(/\r\n?/g, '\n');
|
|
29
|
+
|
|
30
|
+
/** 裸のURLの末尾に付いた句読点や、対になっていない閉じ括弧を外す */
|
|
31
|
+
export function trimUrl(u) {
|
|
32
|
+
let s = u;
|
|
33
|
+
for (;;) {
|
|
34
|
+
const last = s.slice(-1);
|
|
35
|
+
if (/[.,;:!?'"*]/.test(last)) { s = s.slice(0, -1); continue; }
|
|
36
|
+
if (last === ')' && (s.match(/\(/g) || []).length < (s.match(/\)/g) || []).length) { s = s.slice(0, -1); continue; }
|
|
37
|
+
if (last === ']' && (s.match(/\[/g) || []).length < (s.match(/\]/g) || []).length) { s = s.slice(0, -1); continue; }
|
|
38
|
+
return s;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 1行を文字とリンクに分ける。flags に使えないリンク・相対リンクの有無を記録する */
|
|
43
|
+
export function inlineTokens(line, flags) {
|
|
44
|
+
const out = [];
|
|
45
|
+
let last = 0;
|
|
46
|
+
INLINE_RE.lastIndex = 0;
|
|
47
|
+
let m;
|
|
48
|
+
const pushText = (v) => { if (!v) return; if (out.length && out[out.length - 1].t === 'text') out[out.length - 1].v += v; else out.push({ t: 'text', v }); };
|
|
49
|
+
while ((m = INLINE_RE.exec(line))) {
|
|
50
|
+
if (m[3]) {
|
|
51
|
+
const url = trimUrl(m[3]);
|
|
52
|
+
pushText(line.slice(last, m.index));
|
|
53
|
+
out.push({ t: 'link', text: url, href: url, bare: true });
|
|
54
|
+
last = m.index + url.length;
|
|
55
|
+
INLINE_RE.lastIndex = last;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
pushText(line.slice(last, m.index));
|
|
59
|
+
const href = m[2];
|
|
60
|
+
const text = m[1].trim();
|
|
61
|
+
if (href && SAFE_HREF.test(href) && text) {
|
|
62
|
+
out.push({ t: 'link', text, href, bare: false });
|
|
63
|
+
if (!ABS_HREF.test(href)) flags.rel = true;
|
|
64
|
+
} else {
|
|
65
|
+
pushText(m[0]);
|
|
66
|
+
flags.bad = true;
|
|
67
|
+
}
|
|
68
|
+
last = m.index + m[0].length;
|
|
69
|
+
}
|
|
70
|
+
pushText(line.slice(last));
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 回答の文字列を段落・箇条書きのかたまりに分ける */
|
|
75
|
+
export function parseAnswer(src) {
|
|
76
|
+
const flags = { rel: false, bad: false };
|
|
77
|
+
const blocks = [];
|
|
78
|
+
let cur = null;
|
|
79
|
+
for (const raw of nl(src).split('\n')) {
|
|
80
|
+
const line = raw.replace(/[ \t]+$/, '');
|
|
81
|
+
if (!line.trim()) { cur = null; continue; }
|
|
82
|
+
let mb = BULLET_RE.exec(line);
|
|
83
|
+
let mo = mb ? null : ORDERED_RE.exec(line);
|
|
84
|
+
if (mb || mo) {
|
|
85
|
+
const type = mb ? 'ul' : 'ol';
|
|
86
|
+
const body = (mb ? mb[1] : mo[2]).trim();
|
|
87
|
+
if (!cur || cur.type !== type) {
|
|
88
|
+
cur = { type, items: [] };
|
|
89
|
+
if (mo) cur.start = Number(mo[1]);
|
|
90
|
+
blocks.push(cur);
|
|
91
|
+
}
|
|
92
|
+
cur.items.push(inlineTokens(body, flags));
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (!cur || cur.type !== 'p') { cur = { type: 'p', lines: [] }; blocks.push(cur); }
|
|
96
|
+
cur.lines.push(inlineTokens(line.replace(/^[ \t]+/, ''), flags));
|
|
97
|
+
}
|
|
98
|
+
return { blocks, flags };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/* ---------- HTML ---------- */
|
|
102
|
+
// 本文の中では & < > だけを実体参照にする(日本語の引用符「」“”や全角記号はそのまま残す)
|
|
103
|
+
export const escHtml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
104
|
+
export const escAttr = (s) => escHtml(s).replace(/"/g, '"');
|
|
105
|
+
export const htmlInline = (toks) => toks.map((k) => (k.t === 'text' ? escHtml(k.v) : '<a href="' + escAttr(k.href) + '">' + escHtml(k.text) + '</a>')).join('');
|
|
106
|
+
|
|
107
|
+
export function htmlBlocks(blocks, indent) {
|
|
108
|
+
const pad = indent || '';
|
|
109
|
+
return blocks.map((b) => {
|
|
110
|
+
if (b.type === 'p') return pad + '<p>' + b.lines.map(htmlInline).join('<br>') + '</p>';
|
|
111
|
+
const open = b.type === 'ol' && b.start && b.start !== 1 ? '<ol start="' + b.start + '">' : '<' + b.type + '>';
|
|
112
|
+
return pad + open + b.items.map((it) => '<li>' + htmlInline(it) + '</li>').join('') + '</' + b.type + '>';
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** JSON-LD の acceptedAnswer.text に入れる HTML。1行だけの文章は <p> で包まない */
|
|
117
|
+
export function answerHtml(blocks) {
|
|
118
|
+
if (blocks.length === 1 && blocks[0].type === 'p' && blocks[0].lines.length === 1) return htmlInline(blocks[0].lines[0]);
|
|
119
|
+
return htmlBlocks(blocks).join('');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** JSON-LD をプレーンテキストで書くとき。リンクは「文字(URL)」、箇条書きは記号を付けた行にする */
|
|
123
|
+
export function answerText(blocks, lang) {
|
|
124
|
+
const inl = (toks) => toks.map((k) => {
|
|
125
|
+
if (k.t === 'text') return k.v;
|
|
126
|
+
if (k.bare || k.text === k.href) return k.href;
|
|
127
|
+
return lang === 'en' ? k.text + ' (' + k.href + ')' : k.text + '(' + k.href + ')';
|
|
128
|
+
}).join('');
|
|
129
|
+
return blocks.map((b) => {
|
|
130
|
+
if (b.type === 'p') return b.lines.map(inl).join('\n');
|
|
131
|
+
return b.items.map((it, i) => (b.type === 'ul' ? (lang === 'en' ? '- ' : '・') : (b.start || 1) + i + '. ') + inl(it)).join('\n');
|
|
132
|
+
}).join('\n\n');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/* ---------- Markdown ---------- */
|
|
136
|
+
export function mdEscape(s) {
|
|
137
|
+
return String(s)
|
|
138
|
+
.replace(/([\\`*_[\]<>~|])/g, '\\$1')
|
|
139
|
+
.replace(/&(?=#?[A-Za-z0-9]+;)/g, '\\&');
|
|
140
|
+
}
|
|
141
|
+
// 行頭で見出し・引用・箇条書き・番号付きリストと読まれる文字を逃がす
|
|
142
|
+
export const mdLineStart = (s) => s.replace(/^(\s*)([#>+=-])/, '$1\\$2').replace(/^(\s*\d+)([.)])/, '$1\\$2');
|
|
143
|
+
export function mdDest(href) {
|
|
144
|
+
return /[\s()<>]/.test(href) ? '<' + href.replace(/</g, '%3C').replace(/>/g, '%3E').replace(/ /g, '%20') + '>' : href;
|
|
145
|
+
}
|
|
146
|
+
export function mdInline(toks) {
|
|
147
|
+
return toks.map((k, i) => {
|
|
148
|
+
if (k.t === 'text') return i === 0 ? mdLineStart(mdEscape(k.v)) : mdEscape(k.v);
|
|
149
|
+
if (k.bare) return '<' + k.href + '>';
|
|
150
|
+
return '[' + mdEscape(k.text) + '](' + mdDest(k.href) + ')';
|
|
151
|
+
}).join('');
|
|
152
|
+
}
|
|
153
|
+
export function mdBlocks(blocks) {
|
|
154
|
+
return blocks.map((b) => {
|
|
155
|
+
// 段落の中の改行は CommonMark のハードブレーク(行末の \)にする。行末の空白2つは編集中に消えやすいため使わない
|
|
156
|
+
if (b.type === 'p') return b.lines.map(mdInline).join('\\\n');
|
|
157
|
+
return b.items.map((it, i) => (b.type === 'ul' ? '- ' : (b.start || 1) + i + '. ') + mdInline(it)).join('\n');
|
|
158
|
+
}).join('\n\n');
|
|
159
|
+
}
|
|
160
|
+
export function mdHeading(level, text) {
|
|
161
|
+
const body = mdLineStart(mdEscape(text)).replace(/(\s)(#+)\s*$/, '$1\\$2');
|
|
162
|
+
return '#'.repeat(level) + ' ' + body;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** <script> の中に置いても途切れない JSON。</script と <!-- を逃がし、U+2028/2029 も念のためエスケープする */
|
|
166
|
+
export function safeJson(obj) {
|
|
167
|
+
return JSON.stringify(obj, null, 2)
|
|
168
|
+
.replace(/<\/(script)/gi, '<\\/$1')
|
|
169
|
+
.replace(/<!--/g, '\\u003c!--')
|
|
170
|
+
.replace(/\u2028/g, '\\u2028')
|
|
171
|
+
.replace(/\u2029/g, '\\u2029');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 入力の行を整える。質問は1行に、空の行は数えて外す */
|
|
175
|
+
export function cleanItems(items) {
|
|
176
|
+
const out = [];
|
|
177
|
+
let skipped = 0;
|
|
178
|
+
for (const it of items || []) {
|
|
179
|
+
const q = nl(it && it.q).replace(/\s*\n\s*/g, ' ').trim();
|
|
180
|
+
const a = nl(it && it.a).replace(/^\s*\n/, '').replace(/\s+$/, '');
|
|
181
|
+
if (!q && !a.trim()) continue;
|
|
182
|
+
if (!q || !a.trim()) { skipped++; continue; }
|
|
183
|
+
out.push({ q, a });
|
|
184
|
+
}
|
|
185
|
+
return { items: out, skipped };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 3つの形式を作る。
|
|
190
|
+
* opts: { title, level(2|3), answerFormat('html'|'text'), wrapScript, exclusive, lang }
|
|
191
|
+
*/
|
|
192
|
+
export function build(rawItems, opts) {
|
|
193
|
+
const o = Object.assign({ title: '', level: 3, answerFormat: 'html', wrapScript: true, exclusive: false, lang: 'ja' }, opts || {});
|
|
194
|
+
const level = o.level === 2 ? 2 : 3;
|
|
195
|
+
const { items, skipped } = cleanItems(rawItems);
|
|
196
|
+
const title = nl(o.title).replace(/\s*\n\s*/g, ' ').trim();
|
|
197
|
+
const warnings = [];
|
|
198
|
+
if (skipped) warnings.push({ k: 'skipped', n: skipped });
|
|
199
|
+
const seen = new Map();
|
|
200
|
+
const dups = [];
|
|
201
|
+
let rel = 0;
|
|
202
|
+
let bad = 0;
|
|
203
|
+
const parsed = items.map((it, i) => {
|
|
204
|
+
const key = it.q.normalize('NFKC').replace(/\s+/g, '').toLowerCase();
|
|
205
|
+
if (seen.has(key)) dups.push(i + 1); else seen.set(key, i + 1);
|
|
206
|
+
const p = parseAnswer(it.a);
|
|
207
|
+
if (p.flags.rel) rel++;
|
|
208
|
+
if (p.flags.bad) bad++;
|
|
209
|
+
return { q: it.q, blocks: p.blocks };
|
|
210
|
+
});
|
|
211
|
+
if (dups.length) warnings.push({ k: 'dup', list: dups });
|
|
212
|
+
if (bad) warnings.push({ k: 'bad', n: bad });
|
|
213
|
+
if (rel) warnings.push({ k: 'rel', n: rel });
|
|
214
|
+
if (!parsed.length) warnings.push({ k: 'none' });
|
|
215
|
+
|
|
216
|
+
const data = {
|
|
217
|
+
'@context': 'https://schema.org',
|
|
218
|
+
'@type': 'FAQPage',
|
|
219
|
+
mainEntity: parsed.map((p) => ({
|
|
220
|
+
'@type': 'Question',
|
|
221
|
+
name: p.q,
|
|
222
|
+
acceptedAnswer: { '@type': 'Answer', text: o.answerFormat === 'text' ? answerText(p.blocks, o.lang) : answerHtml(p.blocks) },
|
|
223
|
+
})),
|
|
224
|
+
};
|
|
225
|
+
const json = safeJson(data);
|
|
226
|
+
const jsonld = o.wrapScript ? '<script type="application/ld+json">\n' + json + '\n</script>' : json;
|
|
227
|
+
|
|
228
|
+
const md = [];
|
|
229
|
+
if (title) md.push(mdHeading(level - 1, title));
|
|
230
|
+
for (const p of parsed) md.push(mdHeading(level, p.q), mdBlocks(p.blocks));
|
|
231
|
+
const markdown = md.length ? md.join('\n\n') + '\n' : '';
|
|
232
|
+
|
|
233
|
+
const h = ['<section class="faq">'];
|
|
234
|
+
if (title) h.push(' <h' + (level - 1) + '>' + escHtml(title) + '</h' + (level - 1) + '>');
|
|
235
|
+
for (const p of parsed) {
|
|
236
|
+
h.push(' <details' + (o.exclusive ? ' name="faq"' : '') + '>');
|
|
237
|
+
h.push(' <summary>' + escHtml(p.q) + '</summary>');
|
|
238
|
+
h.push(' <div class="faq-answer">');
|
|
239
|
+
h.push(...htmlBlocks(p.blocks, ' '));
|
|
240
|
+
h.push(' </div>');
|
|
241
|
+
h.push(' </details>');
|
|
242
|
+
}
|
|
243
|
+
h.push('</section>');
|
|
244
|
+
const html = parsed.length ? h.join('\n') + '\n' : '';
|
|
245
|
+
|
|
246
|
+
return { jsonld, json, data, markdown, html, warnings, count: parsed.length };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* まとめて貼り付けた文章を質問と回答に分ける。
|
|
251
|
+
* 「Q: / Q1. / Q. / 質問:」で始まる行を質問、「A: / A. / 回答:/ 答え:」で始まる行を回答の始まりとし、
|
|
252
|
+
* Markdown の見出し(## …)も質問として読む。回答の次の行からは次の質問までを回答に含める。
|
|
253
|
+
*/
|
|
254
|
+
// 未追加分を原文のまま残せるよう、質問の開始位置も記録する。
|
|
255
|
+
export function parseBulkEntries(text) {
|
|
256
|
+
const Q_RE = /^\s*(?:[QQqq]\s*[0-90-9]*\s*[.::.、))]|質問\s*[0-90-9]*\s*[::..、))]|問\s*[0-90-9]+\s*[::..、))]?)\s*(.*)$/;
|
|
257
|
+
const A_RE = /^\s*(?:[AAaa]\s*[0-90-9]*\s*[.::.、))]|(?:回答|答え|答)\s*[0-90-9]*\s*[::..、))])\s*(.*)$/;
|
|
258
|
+
const H_RE = /^\s{0,3}#{1,6}\s+(.*?)\s*#*\s*$/;
|
|
259
|
+
const out = [];
|
|
260
|
+
let cur = null;
|
|
261
|
+
let inAnswer = false;
|
|
262
|
+
const lines = String(text == null ? '' : text).split(/(\r\n|\r|\n)/);
|
|
263
|
+
let offset = 0;
|
|
264
|
+
const finish = () => {
|
|
265
|
+
if (!cur) return;
|
|
266
|
+
cur.a = cur.a.replace(/^\n+|\s+$/g, '');
|
|
267
|
+
if (cur.q.trim() && (cur.a || !cur.heading)) out.push({ item: { q: cur.q.trim(), a: cur.a }, start: cur.start });
|
|
268
|
+
cur = null;
|
|
269
|
+
};
|
|
270
|
+
for (let i = 0; i < lines.length; i += 2) {
|
|
271
|
+
const line = lines[i];
|
|
272
|
+
const start = offset;
|
|
273
|
+
offset += line.length + (lines[i + 1] || '').length;
|
|
274
|
+
const mq = Q_RE.exec(line);
|
|
275
|
+
const mh = mq ? null : H_RE.exec(line);
|
|
276
|
+
if (mq || mh) {
|
|
277
|
+
finish();
|
|
278
|
+
let q = (mq ? mq[1] : mh[1]);
|
|
279
|
+
// 見出しの中の「Q.」も外す
|
|
280
|
+
const inner = Q_RE.exec(q);
|
|
281
|
+
if (inner) q = inner[1];
|
|
282
|
+
cur = { q, a: '', heading: !!mh, start };
|
|
283
|
+
inAnswer = false;
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const ma = A_RE.exec(line);
|
|
287
|
+
if (ma && cur && !inAnswer) { cur.a = ma[1]; inAnswer = true; continue; }
|
|
288
|
+
if (!cur) continue;
|
|
289
|
+
if (!inAnswer) {
|
|
290
|
+
if (!line.trim()) continue;
|
|
291
|
+
if (cur.heading) { inAnswer = true; cur.a = line; continue; }
|
|
292
|
+
// 質問の続きの行(回答の印が来るまで)
|
|
293
|
+
cur.q += ' ' + line.trim();
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
cur.a += '\n' + line;
|
|
297
|
+
}
|
|
298
|
+
finish();
|
|
299
|
+
return out;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function parseBulk(text) {
|
|
303
|
+
return parseBulkEntries(text).map((entry) => entry.item);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export const safeFileName = (s, fallback) => {
|
|
307
|
+
const x = String(s || '').normalize('NFKC').replace(/[\\/:*?"<>|\u0000-\u001f]+/g, '').replace(/\s+/g, '-').replace(/^[.-]+|[.-]+$/g, '').slice(0, 60);
|
|
308
|
+
return x || fallback;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
/* ==================== ここまで変換のコア ==================== */
|
|
312
|
+
|
|
313
|
+
/* ==================== ここから MCP 側だけ(ツールの入出力) ==================== */
|
|
314
|
+
|
|
315
|
+
// 警告の文言(site の T.warn と同じ文)
|
|
316
|
+
const WARN_TEXT = {
|
|
317
|
+
ja: {
|
|
318
|
+
skipped: (w) => '質問か回答の片方が空の行が' + w.n + '件あります。出力には含めていません。',
|
|
319
|
+
dup: (w) => '同じ質問が重複しています(' + w.list.join('・') + '件目)。',
|
|
320
|
+
bad: (w) => 'リンクにできない宛先(javascript: など)が' + w.n + '件の回答にあります。リンクにせず文字のまま出力しています。',
|
|
321
|
+
rel: (w) => '相対URL(/ や # で始まるリンク)が' + w.n + '件の回答にあります。JSON-LD はページの外で読まれることがあるので、https:// から始まるURLにするのが確実です。',
|
|
322
|
+
none: () => '質問と回答の両方を入れると、ここに出力されます。',
|
|
323
|
+
},
|
|
324
|
+
en: {
|
|
325
|
+
skipped: (w) => w.n + ' row' + (w.n === 1 ? ' has' : 's have') + ' only a question or only an answer and ' + (w.n === 1 ? 'is' : 'are') + ' left out.',
|
|
326
|
+
dup: (w) => 'Duplicate question (no. ' + w.list.join(', ') + ').',
|
|
327
|
+
bad: (w) => w.n + ' answer' + (w.n === 1 ? ' has' : 's have') + ' a link target that cannot be used (such as javascript:). It is kept as plain text.',
|
|
328
|
+
rel: (w) => w.n + ' answer' + (w.n === 1 ? ' uses' : 's use') + ' a relative link (starting with / or #). JSON-LD may be read outside the page, so a full https:// URL is safer.',
|
|
329
|
+
none: () => 'Enter both a question and an answer to see the output.',
|
|
330
|
+
},
|
|
331
|
+
};
|
|
332
|
+
const WARN_CODE = { skipped: 'SKIPPED', dup: 'DUPLICATE', bad: 'UNSAFE_LINK', rel: 'RELATIVE_LINK', none: 'EMPTY' };
|
|
333
|
+
|
|
334
|
+
export class FaqJsonldToolError extends Error {}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* FAQ の JSON-LD・Markdown・HTML を作る。
|
|
338
|
+
* @param {object} opts
|
|
339
|
+
* @param {{q:string, a:string}[]} [opts.items] 質問と回答(200件まで・質問500字・回答5000字まで)
|
|
340
|
+
* @param {string} [opts.bulk] 「Q: / A:」や「## 見出し」で書いたまとめての文章。items の後ろへ足す
|
|
341
|
+
* @param {string} [opts.title] 見出し(Markdown・HTML の先頭に level-1 の見出しで入る)
|
|
342
|
+
* @param {2|3} [opts.level=3] 質問の見出しの段(2 なら ##、3 なら ###)
|
|
343
|
+
* @param {'html'|'text'} [opts.answer_format='html'] JSON-LD の acceptedAnswer.text の書き方
|
|
344
|
+
* @param {boolean} [opts.wrap_script=true] JSON-LD を <script type="application/ld+json"> で包む
|
|
345
|
+
* @param {boolean} [opts.exclusive=false] details に name="faq" を付け、1つ開くとほかが閉じるようにする
|
|
346
|
+
* @param {'ja'|'en'} [opts.lang='ja'] 警告の言語と、answer_format=text のときのリンク・箇条書きの書き方
|
|
347
|
+
*/
|
|
348
|
+
export async function faqJsonldTool(opts = {}) {
|
|
349
|
+
const lang = opts.lang || 'ja';
|
|
350
|
+
if (lang !== 'ja' && lang !== 'en') throw new FaqJsonldToolError(`lang は ja か en: ${opts.lang}`);
|
|
351
|
+
const level = opts.level === undefined ? 3 : opts.level;
|
|
352
|
+
if (level !== 2 && level !== 3) throw new FaqJsonldToolError(`level は 2 か 3: ${opts.level}`);
|
|
353
|
+
const answerFormat = opts.answer_format === undefined ? 'html' : opts.answer_format;
|
|
354
|
+
if (answerFormat !== 'html' && answerFormat !== 'text') throw new FaqJsonldToolError(`answer_format は html か text: ${opts.answer_format}`);
|
|
355
|
+
if (opts.items === undefined && opts.bulk === undefined) throw new FaqJsonldToolError('items か bulk を渡してください');
|
|
356
|
+
if (opts.items !== undefined && !Array.isArray(opts.items)) throw new FaqJsonldToolError('items は {q, a} の配列で渡してください');
|
|
357
|
+
if (opts.bulk !== undefined && typeof opts.bulk !== 'string') throw new FaqJsonldToolError('bulk は文字列で渡してください');
|
|
358
|
+
|
|
359
|
+
const items = [];
|
|
360
|
+
(opts.items || []).forEach((it, i) => {
|
|
361
|
+
const q = it && it.q != null ? String(it.q) : '';
|
|
362
|
+
const a = it && it.a != null ? String(it.a) : '';
|
|
363
|
+
if ([...q].length > LIMITS.q) throw new FaqJsonldToolError(`items[${i}].q は ${LIMITS.q} 文字まで`);
|
|
364
|
+
if ([...a].length > LIMITS.a) throw new FaqJsonldToolError(`items[${i}].a は ${LIMITS.a} 文字まで`);
|
|
365
|
+
items.push({ q, a });
|
|
366
|
+
});
|
|
367
|
+
let fromBulk = 0;
|
|
368
|
+
if (opts.bulk !== undefined) {
|
|
369
|
+
const parsed = parseBulk(opts.bulk);
|
|
370
|
+
if (!parsed.length) {
|
|
371
|
+
throw new FaqJsonldToolError('bulk から質問を読み取れませんでした。「Q:」「A:」で始まる行か、「## 」の見出しで質問を書いてください');
|
|
372
|
+
}
|
|
373
|
+
fromBulk = parsed.length;
|
|
374
|
+
items.push(...parsed);
|
|
375
|
+
}
|
|
376
|
+
if (items.length > LIMITS.rows) throw new FaqJsonldToolError(`質問は ${LIMITS.rows} 件まで: ${items.length}`);
|
|
377
|
+
|
|
378
|
+
const r = build(items, {
|
|
379
|
+
title: opts.title == null ? '' : String(opts.title),
|
|
380
|
+
level,
|
|
381
|
+
answerFormat,
|
|
382
|
+
wrapScript: opts.wrap_script !== false,
|
|
383
|
+
exclusive: opts.exclusive === true,
|
|
384
|
+
lang,
|
|
385
|
+
});
|
|
386
|
+
return {
|
|
387
|
+
count: r.count,
|
|
388
|
+
...(opts.bulk !== undefined ? { parsed_from_bulk: fromBulk } : {}),
|
|
389
|
+
// site と同じく、質問が1件も無いときは JSON-LD を出さない
|
|
390
|
+
jsonld: r.count ? r.jsonld : '',
|
|
391
|
+
data: r.data,
|
|
392
|
+
markdown: r.markdown,
|
|
393
|
+
html: r.html,
|
|
394
|
+
warnings: r.warnings.map((w) => ({
|
|
395
|
+
code: WARN_CODE[w.k],
|
|
396
|
+
message: WARN_TEXT[lang][w.k](w),
|
|
397
|
+
...(w.n !== undefined ? { count: w.n } : {}),
|
|
398
|
+
...(w.list ? { items: w.list } : {}),
|
|
399
|
+
})),
|
|
400
|
+
};
|
|
401
|
+
}
|