@first-ch/tools-mcp 0.34.1 → 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 +134 -20
- package/apps.mjs +538 -0
- package/base64.mjs +3 -2
- package/case-convert.mjs +3 -2
- package/css-layout.mjs +612 -0
- package/csv-json.mjs +3 -2
- package/dpi.mjs +660 -0
- package/faq-jsonld.mjs +401 -0
- package/fs-safe.mjs +35 -0
- package/html-escape.mjs +3 -2
- package/html-md.mjs +3 -2
- package/htpasswd.mjs +740 -0
- package/json-yaml.mjs +3 -2
- package/lib.mjs +3 -1
- package/lines.mjs +423 -0
- package/markdown-table.mjs +3 -2
- package/marp.mjs +73 -21
- package/openapi-doc.mjs +2954 -0
- package/package.json +68 -6
- package/px-rem.mjs +3 -2
- package/qr.mjs +3 -3
- package/robots-txt.mjs +2 -2
- package/serp.mjs +309 -0
- package/server.mjs +423 -50
- package/sql-format.mjs +3 -2
- package/webp.mjs +4 -3
- package/zenkaku.mjs +3 -2
package/json-yaml.mjs
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
// 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
|
|
5
5
|
// 使っているのは String / RegExp / Object だけなので、ブラウザ版のコードをそのまま持ってこられる
|
|
6
6
|
// (YAMLの解析・生成も自前実装で、js-yaml 等の外部ライブラリには依存しない)。
|
|
7
|
-
import { readFile
|
|
7
|
+
import { readFile } from 'node:fs/promises';
|
|
8
|
+
import { writeOutput } from './fs-safe.mjs';
|
|
8
9
|
import { basename } from 'node:path';
|
|
9
10
|
|
|
10
11
|
/* ==================== ここから変換コア(site / MCP で同一) ==================== */
|
|
@@ -1630,7 +1631,7 @@ async function convert(direction, opts) {
|
|
|
1630
1631
|
};
|
|
1631
1632
|
|
|
1632
1633
|
if (o.outputPath) {
|
|
1633
|
-
await
|
|
1634
|
+
await writeOutput(o.outputPath, r.output, { overwrite: o.overwrite });
|
|
1634
1635
|
result.output = o.outputPath;
|
|
1635
1636
|
// ファイルに書けたなら本文は重複した重い情報でしかない
|
|
1636
1637
|
delete result.text;
|
package/lib.mjs
CHANGED
|
@@ -155,7 +155,9 @@ export function buildJsonLd(type, fields = {}) {
|
|
|
155
155
|
const builder = jsonLdBuilders[type];
|
|
156
156
|
if (!builder) throw new Error(`未対応タイプ: ${type}(organization / faqpage / service / breadcrumb のいずれか)`);
|
|
157
157
|
const json = builder(fields);
|
|
158
|
-
|
|
158
|
+
// 値に </script> や <!-- があってもスクリプト要素から抜けないよう、< を \u003c にする(JSONとしては同じ値)
|
|
159
|
+
const body = JSON.stringify(json, null, 2).replace(/</g, '\\u003c');
|
|
160
|
+
const snippet = `<script type="application/ld+json">\n${body}\n</script>`;
|
|
159
161
|
return { json, snippet };
|
|
160
162
|
}
|
|
161
163
|
|
package/lines.mjs
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
/* テキスト行操作(lines_process)
|
|
2
|
+
* 行操作コア(processLines / makeCompare / shuffle / PRESETS ほか)は
|
|
3
|
+
* FirstCHTools の site/lines/app.js と同一
|
|
4
|
+
* (2箇所ルール: site側が正本・片方を直したらもう片方も同じ内容で反映する)。
|
|
5
|
+
* 両ファイルからコアの開始/終了コメントに挟まれた範囲を sed で切り出し
|
|
6
|
+
* (site側は字下げ2文字を落とす・こちらは行頭の export を落とす)、
|
|
7
|
+
* diff が空になることで同期を機械的に確認できる。
|
|
8
|
+
*
|
|
9
|
+
* 適用順は固定: トリム → 空行 → 重複 → 並べ替え → 接頭/接尾辞 → 行番号(各1回)。
|
|
10
|
+
* 並べ替えの照合は Intl.Collator('ja')(Node の ICU)。シャッフルは seed があれば再現可能な
|
|
11
|
+
* 疑似乱数、無ければ crypto.getRandomValues。完全ローカル処理・ネットワーク送信なし。 */
|
|
12
|
+
|
|
13
|
+
import { readFile } from 'node:fs/promises';
|
|
14
|
+
import { basename, isAbsolute } from 'node:path';
|
|
15
|
+
import { writeOutput } from './fs-safe.mjs';
|
|
16
|
+
|
|
17
|
+
/* ==================== ここから行操作コア ==================== */
|
|
18
|
+
|
|
19
|
+
export const DEDUPE_MODES = ['first', 'unique', 'dupes'];
|
|
20
|
+
export const SORT_MODES = ['none', 'asc', 'desc', 'reverse', 'shuffle'];
|
|
21
|
+
export const SEPARATORS = { dot: '. ', paren: ') ', colon: ': ', bracket: ') ', tab: '\t', space: ' ' };
|
|
22
|
+
|
|
23
|
+
// 前後トリムで削る空白(半角・全角スペース・タブ・NBSPと欧文の各種スペース)。改行は含めない
|
|
24
|
+
export const SPACE_CLASS = ' \u0009 - ';
|
|
25
|
+
export const EDGE_RE = new RegExp('^[' + SPACE_CLASS + ']+|[' + SPACE_CLASS + ']+$', 'g');
|
|
26
|
+
export const BLANK_RE = new RegExp('^[' + SPACE_CLASS + ']*$');
|
|
27
|
+
|
|
28
|
+
// 「数値だけの行」。符号・桁区切りのカンマ・小数に対応し、全角数字は半角へ読み替えてから判定する
|
|
29
|
+
export const NUMBER_RE = /^[+\-−]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?$/;
|
|
30
|
+
|
|
31
|
+
// 並べ替えの比較。数値の認識は数字の連なりを数として見る(item2 < item10)
|
|
32
|
+
export const COLLATOR_NUM = new Intl.Collator('ja', { numeric: true });
|
|
33
|
+
export const COLLATOR_TXT = new Intl.Collator('ja', { numeric: false });
|
|
34
|
+
|
|
35
|
+
// 改行コードは入力の最初の1つに揃える(CRLFのファイルを整形してもLFが混ざらない)
|
|
36
|
+
export function detectEol(text) {
|
|
37
|
+
const m = text.match(/\r\n|\n|\r/);
|
|
38
|
+
return m ? m[0] : '\n';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 行へ分ける。末尾が改行で終わる入力の最後の空要素は行として数えない
|
|
42
|
+
export function splitLines(text) {
|
|
43
|
+
if (text === '') return { lines: [], trailing: false };
|
|
44
|
+
const lines = text.split(/\r\n|\n|\r/);
|
|
45
|
+
const trailing = lines.length > 1 && lines[lines.length - 1] === '';
|
|
46
|
+
if (trailing) lines.pop();
|
|
47
|
+
return { lines, trailing };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function toHalfDigits(s) {
|
|
51
|
+
return s.replace(/[0-9.,-+]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 0xfee0));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 数値として読める行なら数を返し、読めなければ null
|
|
55
|
+
export function asNumber(line) {
|
|
56
|
+
const s = toHalfDigits(line.replace(EDGE_RE, ''));
|
|
57
|
+
if (s === '' || !/\d/.test(s) || !NUMBER_RE.test(s)) return null;
|
|
58
|
+
const n = Number(s.replace(/,/g, '').replace('−', '-'));
|
|
59
|
+
return Number.isFinite(n) ? n : null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function makeCompare(numeric) {
|
|
63
|
+
const coll = numeric ? COLLATOR_NUM : COLLATOR_TXT;
|
|
64
|
+
return (a, b) => {
|
|
65
|
+
if (numeric) {
|
|
66
|
+
const na = asNumber(a);
|
|
67
|
+
const nb = asNumber(b);
|
|
68
|
+
// 数値どうしは値で比べる(-10 < -3 < 1.25 < 1.5)。数値の行は文字の行より前に置く
|
|
69
|
+
if (na !== null && nb !== null && na !== nb) return na - nb;
|
|
70
|
+
if (na !== null && nb === null) return -1;
|
|
71
|
+
if (na === null && nb !== null) return 1;
|
|
72
|
+
}
|
|
73
|
+
const c = coll.compare(a, b);
|
|
74
|
+
if (c) return c;
|
|
75
|
+
// 照合順序で同順位になる字(あ/ア・a/A など)は文字コード順で決め、入力の順番に左右されないようにする
|
|
76
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// シード付きの疑似乱数(同じシードなら同じ並びになる。URLの seed で再現できる)。
|
|
81
|
+
// 32ビットの種から作れる並びは高々 2^32 通りなので、13行以上では全順列を出せない=抽選には使わない
|
|
82
|
+
export function mulberry32(seed) {
|
|
83
|
+
let t = seed >>> 0;
|
|
84
|
+
return () => {
|
|
85
|
+
t = (t + 0x6d2b79f5) >>> 0;
|
|
86
|
+
let r = Math.imul(t ^ (t >>> 15), 1 | t);
|
|
87
|
+
r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r;
|
|
88
|
+
return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 0 以上 n 未満の整数を返す関数を作る。seed があれば再現用の疑似乱数、無ければ
|
|
93
|
+
// words()(32ビットの乱数語を順に返す)から棄却法で偏りなく引く
|
|
94
|
+
export function makeRandInt(seed, words) {
|
|
95
|
+
if (Number.isFinite(seed)) {
|
|
96
|
+
const rand = mulberry32(seed);
|
|
97
|
+
return (n) => Math.floor(rand() * n);
|
|
98
|
+
}
|
|
99
|
+
return (n) => {
|
|
100
|
+
// 2^32 を n で割り切れる範囲だけを使う(余りの端数を捨てて剰余の偏りを消す)
|
|
101
|
+
const limit = 4294967296 - (4294967296 % n);
|
|
102
|
+
for (;;) {
|
|
103
|
+
const w = words();
|
|
104
|
+
if (w < limit) return w % n;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Fisher–Yates。randInt が一様なら n! 通りの並びが等確率で出る
|
|
110
|
+
export function shuffle(lines, randInt) {
|
|
111
|
+
const out = lines.slice();
|
|
112
|
+
for (let i = out.length - 1; i > 0; i -= 1) {
|
|
113
|
+
const j = randInt(i + 1);
|
|
114
|
+
const tmp = out[i];
|
|
115
|
+
out[i] = out[j];
|
|
116
|
+
out[j] = tmp;
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// crypto.getRandomValues の乱数語を貯めておき、同じ順で読み直せる源。
|
|
122
|
+
// 他のチェックを切り替えても並びが変わらないよう、reset() するまで同じ語を返す
|
|
123
|
+
export function makeCryptoPool() {
|
|
124
|
+
const pool = [];
|
|
125
|
+
let pos = 0;
|
|
126
|
+
const words = () => {
|
|
127
|
+
if (pos >= pool.length) {
|
|
128
|
+
const a = new Uint32Array(256);
|
|
129
|
+
crypto.getRandomValues(a);
|
|
130
|
+
for (let k = 0; k < a.length; k += 1) pool.push(a[k]);
|
|
131
|
+
}
|
|
132
|
+
return pool[pos++];
|
|
133
|
+
};
|
|
134
|
+
words.rewind = () => { pos = 0; };
|
|
135
|
+
words.reset = () => { pool.length = 0; pos = 0; };
|
|
136
|
+
return words;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// 「ほとんど同じ」行を探す。完全一致では別の行だが、キーを変えると重なる組の数を返す
|
|
140
|
+
export function nearGroups(lines, keyOf) {
|
|
141
|
+
const exact = new Map();
|
|
142
|
+
for (const line of lines) {
|
|
143
|
+
const k = keyOf(line);
|
|
144
|
+
if (!exact.has(k)) exact.set(k, new Set());
|
|
145
|
+
exact.get(k).add(line);
|
|
146
|
+
}
|
|
147
|
+
let groups = 0;
|
|
148
|
+
for (const set of exact.values()) if (set.size > 1) groups += 1;
|
|
149
|
+
return groups;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* 行単位の操作をまとめて適用する。
|
|
154
|
+
*
|
|
155
|
+
* @param {object} opts
|
|
156
|
+
* @param {string} opts.text 対象テキスト
|
|
157
|
+
* @param {boolean} [opts.trim] 各行の前後の空白を削る
|
|
158
|
+
* @param {boolean} [opts.removeBlank] 空行(空白だけの行を含む)を削る
|
|
159
|
+
* @param {boolean} [opts.dedupe] 重複行を削る
|
|
160
|
+
* @param {'first'|'unique'|'dupes'} [opts.dedupeMode='first'] 最初の1行を残す / 重複した行は1行も残さない / 重複した行だけを1行ずつ出す
|
|
161
|
+
* @param {boolean} [opts.ignoreCase] 重複の判定で大文字・小文字を区別しない
|
|
162
|
+
* @param {'none'|'asc'|'desc'|'reverse'|'shuffle'} [opts.sort='none']
|
|
163
|
+
* @param {boolean} [opts.numeric=true] 並べ替えで数値を認識する
|
|
164
|
+
* @param {number} [opts.seed] シャッフルのシード(再現用。指定すると抽選向けの一様性は失われる)
|
|
165
|
+
* @param {function(): number} [opts.words] シャッフル用の32ビット乱数語の源(seed 未指定時。省略時は crypto.getRandomValues)
|
|
166
|
+
* @param {boolean} [opts.affix] 接頭辞・接尾辞を付ける
|
|
167
|
+
* @param {string} [opts.prefix] @param {string} [opts.suffix]
|
|
168
|
+
* @param {boolean} [opts.number] 行番号を付ける
|
|
169
|
+
* @param {number} [opts.start=1] 最初の番号
|
|
170
|
+
* @param {string} [opts.sep='dot'] 番号の後ろの区切り(SEPARATORS のキー)
|
|
171
|
+
* @param {boolean} [opts.pad] 番号の桁をゼロで揃える
|
|
172
|
+
*/
|
|
173
|
+
export function processLines(opts) {
|
|
174
|
+
const o = opts || {};
|
|
175
|
+
const input = typeof o.text === 'string' ? o.text : '';
|
|
176
|
+
const eol = detectEol(input);
|
|
177
|
+
const split = splitLines(input);
|
|
178
|
+
let lines = split.lines;
|
|
179
|
+
const stats = { lines_in: lines.length, trimmed: 0, blank_removed: 0, dup_removed: 0 };
|
|
180
|
+
const notes = [];
|
|
181
|
+
|
|
182
|
+
// ① 前後トリム
|
|
183
|
+
if (o.trim) {
|
|
184
|
+
lines = lines.map((line) => {
|
|
185
|
+
const t = line.replace(EDGE_RE, '');
|
|
186
|
+
if (t !== line) stats.trimmed += 1;
|
|
187
|
+
return t;
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ② 空行
|
|
192
|
+
if (o.removeBlank) {
|
|
193
|
+
const kept = lines.filter((line) => !BLANK_RE.test(line));
|
|
194
|
+
stats.blank_removed = lines.length - kept.length;
|
|
195
|
+
lines = kept;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ③ 重複。数え上げは設定にかかわらず行い、どの行が何回出てきたかを返す
|
|
199
|
+
const keyOf = o.ignoreCase ? (s) => s.toLowerCase() : (s) => s;
|
|
200
|
+
const counts = new Map();
|
|
201
|
+
const firstSeen = new Map();
|
|
202
|
+
for (const line of lines) {
|
|
203
|
+
const k = keyOf(line);
|
|
204
|
+
counts.set(k, (counts.get(k) || 0) + 1);
|
|
205
|
+
if (!firstSeen.has(k)) firstSeen.set(k, line);
|
|
206
|
+
}
|
|
207
|
+
const duplicates = [];
|
|
208
|
+
for (const [k, n] of counts) if (n > 1) duplicates.push({ line: firstSeen.get(k), count: n });
|
|
209
|
+
duplicates.sort((a, b) => b.count - a.count);
|
|
210
|
+
|
|
211
|
+
if (o.dedupe) {
|
|
212
|
+
const mode = DEDUPE_MODES.indexOf(o.dedupeMode) !== -1 ? o.dedupeMode : 'first';
|
|
213
|
+
const seen = new Set();
|
|
214
|
+
const kept = [];
|
|
215
|
+
for (const line of lines) {
|
|
216
|
+
const k = keyOf(line);
|
|
217
|
+
const n = counts.get(k);
|
|
218
|
+
if (mode === 'unique') {
|
|
219
|
+
if (n === 1) kept.push(line);
|
|
220
|
+
} else if (!seen.has(k)) {
|
|
221
|
+
seen.add(k);
|
|
222
|
+
if (mode === 'first' || n > 1) kept.push(line);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
stats.dup_removed = lines.length - kept.length;
|
|
226
|
+
lines = kept;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// 完全一致では別の行だが、設定を変えると重複になる組を知らせる(消したつもりで残る事故の手がかり)
|
|
230
|
+
if (lines.length > 1) {
|
|
231
|
+
if (!o.trim) {
|
|
232
|
+
const g = nearGroups(lines, (s) => keyOf(s.replace(EDGE_RE, '')));
|
|
233
|
+
if (g) notes.push({ code: 'NEAR_SPACE', count: g });
|
|
234
|
+
}
|
|
235
|
+
if (!o.ignoreCase) {
|
|
236
|
+
const g = nearGroups(lines, (s) => s.toLowerCase());
|
|
237
|
+
if (g) notes.push({ code: 'NEAR_CASE', count: g });
|
|
238
|
+
}
|
|
239
|
+
const g = nearGroups(lines, (s) => keyOf(s.normalize('NFKC')));
|
|
240
|
+
if (g) notes.push({ code: 'NEAR_WIDTH', count: g });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ④ 並べ替え
|
|
244
|
+
const sort = SORT_MODES.indexOf(o.sort) !== -1 ? o.sort : 'none';
|
|
245
|
+
if (sort === 'asc' || sort === 'desc') {
|
|
246
|
+
const cmp = makeCompare(o.numeric !== false);
|
|
247
|
+
lines = lines.slice().sort(sort === 'asc' ? cmp : (a, b) => cmp(b, a));
|
|
248
|
+
} else if (sort === 'reverse') {
|
|
249
|
+
lines = lines.slice().reverse();
|
|
250
|
+
} else if (sort === 'shuffle') {
|
|
251
|
+
let words = o.words;
|
|
252
|
+
if (!Number.isFinite(o.seed) && typeof words !== 'function') {
|
|
253
|
+
words = makeCryptoPool();
|
|
254
|
+
}
|
|
255
|
+
lines = shuffle(lines, makeRandInt(o.seed, words));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ⑤ 接頭辞・接尾辞
|
|
259
|
+
if (o.affix && (o.prefix || o.suffix)) {
|
|
260
|
+
const pre = o.prefix || '';
|
|
261
|
+
const suf = o.suffix || '';
|
|
262
|
+
lines = lines.map((line) => pre + line + suf);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ⑥ 行番号(接頭辞の外側に付ける)
|
|
266
|
+
if (o.number && lines.length) {
|
|
267
|
+
const start = Number.isFinite(o.start) ? Math.trunc(o.start) : 1;
|
|
268
|
+
const sep = Object.prototype.hasOwnProperty.call(SEPARATORS, o.sep) ? o.sep : 'dot';
|
|
269
|
+
const width = o.pad ? Math.max(String(start).length, String(start + lines.length - 1).length) : 0;
|
|
270
|
+
lines = lines.map((line, i) => {
|
|
271
|
+
const n = start + i;
|
|
272
|
+
const digits = width && n >= 0 ? String(n).padStart(width, '0') : String(n);
|
|
273
|
+
return (sep === 'bracket' ? '(' + digits : digits) + SEPARATORS[sep] + line;
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const text = lines.join(eol) + (split.trailing && lines.length ? eol : '');
|
|
278
|
+
stats.lines_out = lines.length;
|
|
279
|
+
if (!input) notes.unshift({ code: 'NOTHING' });
|
|
280
|
+
return { text, stats, duplicates, notes, eol };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// プリセット(押すと触れていない項目も既定へ戻すので、必ず同じ結果になる)
|
|
284
|
+
export const PRESETS = {
|
|
285
|
+
uniqsort: { trim: true, removeBlank: true, dedupe: true, sort: 'asc' },
|
|
286
|
+
clean: { trim: true, removeBlank: true },
|
|
287
|
+
numbered: { trim: true, removeBlank: true, number: true, sep: 'dot' },
|
|
288
|
+
mdlist: { trim: true, removeBlank: true, affix: true, prefix: '- ' },
|
|
289
|
+
shuffle: { trim: true, removeBlank: true, sort: 'shuffle' },
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
/* ==================== ここまで行操作コア ==================== */
|
|
293
|
+
|
|
294
|
+
/* ==================== ここからツールのラッパー(MCP のみ) ==================== */
|
|
295
|
+
|
|
296
|
+
export class LinesToolError extends Error {}
|
|
297
|
+
|
|
298
|
+
const MAX_DUPLICATES = 100;
|
|
299
|
+
const MAX_BYTES = 20 * 1024 * 1024;
|
|
300
|
+
|
|
301
|
+
// 指摘事項。site側の文言(T)と同じ内容で、画面の操作名を引数名に置き換えている
|
|
302
|
+
const NOTE_TEXT = {
|
|
303
|
+
ja: {
|
|
304
|
+
NOTHING: () => '処理する行がありません。1行に1項目ずつのテキストを渡してください。',
|
|
305
|
+
DUPS: (n) => `2回以上出てくる行が ${n.kinds} 種類あります(余分な行は計 ${n.extra} 行)。duplicates に多い順に入っています。`,
|
|
306
|
+
NEAR_SPACE: (n) => `前後の空白だけが違う行が ${n.count} 組あります。trim=true にすると重複として扱われます。`,
|
|
307
|
+
NEAR_CASE: (n) => `大文字・小文字だけが違う行が ${n.count} 組あります。ignoreCase=true で重複として扱えます。`,
|
|
308
|
+
NEAR_WIDTH: (n) => `全角・半角だけが違う行が ${n.count} 組あります(A と A、カ と カ など)。先に zenkaku_convert で揃えてください。`,
|
|
309
|
+
RANDOM: () => 'seed を渡していないので、暗号学的乱数で並べました(呼ぶたびに並びが変わります)。再現したいときは seed を渡してください。',
|
|
310
|
+
SEEDED: () => 'seed から作る並びは高々 2^32 通りです。抽選など公平さが要る用途では seed を渡さないでください。',
|
|
311
|
+
},
|
|
312
|
+
en: {
|
|
313
|
+
NOTHING: () => 'Nothing to process — pass text with one item per line.',
|
|
314
|
+
DUPS: (n) => `${n.kinds} line(s) appear more than once (${n.extra} extra cop${n.extra === 1 ? 'y' : 'ies'} in total). They are listed in duplicates, most frequent first.`,
|
|
315
|
+
NEAR_SPACE: (n) => `${n.count} group(s) of lines differ only in leading or trailing spaces. Pass trim=true and they will count as duplicates.`,
|
|
316
|
+
NEAR_CASE: (n) => `${n.count} group(s) of lines differ only in upper / lower case. Pass ignoreCase=true to treat them as duplicates.`,
|
|
317
|
+
NEAR_WIDTH: (n) => `${n.count} group(s) of lines differ only in full-width / half-width characters (A vs A, カ vs カ). Normalise them with zenkaku_convert first.`,
|
|
318
|
+
RANDOM: () => 'No seed was given, so the lines were shuffled with cryptographic randomness (the order changes on every call). Pass seed to reproduce an order.',
|
|
319
|
+
SEEDED: () => 'A seed can produce at most 2^32 orders. Leave seed out when the shuffle must be fair (a draw, for example).',
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
const EOL_NAMES = { '\n': 'LF', '\r\n': 'CRLF', '\r': 'CR' };
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* 行の一覧を整える(重複削除・並べ替え・シャッフル・行番号・空行除去・トリム・接頭/接尾辞)。
|
|
327
|
+
* preset を渡すと site のプリセットボタンと同じ設定から始め、個別の引数で上書きする。
|
|
328
|
+
*
|
|
329
|
+
* @param {object} opts
|
|
330
|
+
* @param {string} [opts.text] 対象テキスト(path と排他)
|
|
331
|
+
* @param {string} [opts.path] 対象ファイルの絶対パス(UTF-8)
|
|
332
|
+
* @param {string} [opts.outputPath] 結果を書き出す絶対パス(指定すると本文は返さない)
|
|
333
|
+
* @param {'uniqsort'|'clean'|'numbered'|'mdlist'|'shuffle'} [opts.preset]
|
|
334
|
+
* 他の引数は processLines と同じ(affix は prefix/suffix を渡せば自動で有効)。
|
|
335
|
+
* @param {'ja'|'en'} [opts.lang='ja']
|
|
336
|
+
*/
|
|
337
|
+
export async function linesProcessTool(opts = {}) {
|
|
338
|
+
const lang = opts.lang || 'ja';
|
|
339
|
+
if (lang !== 'ja' && lang !== 'en') throw new LinesToolError(`lang は ja か en: ${opts.lang}`);
|
|
340
|
+
const hasText = opts.text !== undefined;
|
|
341
|
+
if (hasText && opts.path !== undefined) throw new LinesToolError('text と path は同時に渡せません');
|
|
342
|
+
if (!hasText && opts.path === undefined) throw new LinesToolError('text か path を渡してください');
|
|
343
|
+
let text;
|
|
344
|
+
if (hasText) {
|
|
345
|
+
if (typeof opts.text !== 'string') throw new LinesToolError('text は文字列で渡してください');
|
|
346
|
+
text = opts.text;
|
|
347
|
+
} else {
|
|
348
|
+
if (!isAbsolute(String(opts.path))) throw new LinesToolError('path は絶対パスで指定してください');
|
|
349
|
+
const buf = await readFile(opts.path);
|
|
350
|
+
if (buf.length > MAX_BYTES) throw new LinesToolError(`ファイルが大きすぎます(${MAX_BYTES / 1024 / 1024}MB まで): ${buf.length} bytes`);
|
|
351
|
+
text = buf.toString('utf8').replace(/^/, '');
|
|
352
|
+
}
|
|
353
|
+
if (hasText && Buffer.byteLength(text) > MAX_BYTES) throw new LinesToolError(`text が大きすぎます(${MAX_BYTES / 1024 / 1024}MB まで)`);
|
|
354
|
+
|
|
355
|
+
if (opts.preset !== undefined && !Object.prototype.hasOwnProperty.call(PRESETS, opts.preset)) {
|
|
356
|
+
throw new LinesToolError(`preset は ${Object.keys(PRESETS).join(' / ')} のどれか: ${opts.preset}`);
|
|
357
|
+
}
|
|
358
|
+
if (opts.dedupeMode !== undefined && DEDUPE_MODES.indexOf(opts.dedupeMode) === -1) {
|
|
359
|
+
throw new LinesToolError(`dedupeMode は ${DEDUPE_MODES.join(' / ')} のどれか: ${opts.dedupeMode}`);
|
|
360
|
+
}
|
|
361
|
+
if (opts.sort !== undefined && SORT_MODES.indexOf(opts.sort) === -1) {
|
|
362
|
+
throw new LinesToolError(`sort は ${SORT_MODES.join(' / ')} のどれか: ${opts.sort}`);
|
|
363
|
+
}
|
|
364
|
+
if (opts.sep !== undefined && !Object.prototype.hasOwnProperty.call(SEPARATORS, opts.sep)) {
|
|
365
|
+
throw new LinesToolError(`sep は ${Object.keys(SEPARATORS).join(' / ')} のどれか: ${opts.sep}`);
|
|
366
|
+
}
|
|
367
|
+
if (opts.seed !== undefined && !(Number.isInteger(opts.seed) && opts.seed >= 0 && opts.seed <= 4294967295)) {
|
|
368
|
+
throw new LinesToolError(`seed は 0〜4294967295 の整数: ${opts.seed}`);
|
|
369
|
+
}
|
|
370
|
+
if (opts.start !== undefined && !(Number.isInteger(opts.start) && Math.abs(opts.start) <= 1e9)) {
|
|
371
|
+
throw new LinesToolError(`start は整数(±10億まで): ${opts.start}`);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// site のプリセットは押すと触れていない項目も既定へ戻す。その上に個別の引数を重ねる(URLパラメータと同じ順)
|
|
375
|
+
const o = { ...(opts.preset ? PRESETS[opts.preset] : {}) };
|
|
376
|
+
for (const k of ['trim', 'removeBlank', 'dedupe', 'dedupeMode', 'ignoreCase', 'sort', 'numeric', 'seed', 'number', 'start', 'sep', 'pad']) {
|
|
377
|
+
if (opts[k] !== undefined) o[k] = opts[k];
|
|
378
|
+
}
|
|
379
|
+
if (opts.dedupeMode !== undefined && opts.dedupe === undefined) o.dedupe = true;
|
|
380
|
+
if (opts.prefix !== undefined || opts.suffix !== undefined) {
|
|
381
|
+
o.affix = true;
|
|
382
|
+
o.prefix = opts.prefix === undefined ? '' : String(opts.prefix);
|
|
383
|
+
o.suffix = opts.suffix === undefined ? '' : String(opts.suffix);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const r = processLines({ ...o, text });
|
|
387
|
+
const notes = r.notes.slice();
|
|
388
|
+
if (r.duplicates.length) {
|
|
389
|
+
const extra = r.duplicates.reduce((s, d) => s + d.count - 1, 0);
|
|
390
|
+
notes.splice(notes[0] && notes[0].code === 'NOTHING' ? 1 : 0, 0, { code: 'DUPS', kinds: r.duplicates.length, extra });
|
|
391
|
+
}
|
|
392
|
+
if (o.sort === 'shuffle') notes.push({ code: Number.isFinite(o.seed) ? 'SEEDED' : 'RANDOM' });
|
|
393
|
+
|
|
394
|
+
const result = {
|
|
395
|
+
source: hasText ? { type: 'text' } : { path: opts.path, name: basename(opts.path) },
|
|
396
|
+
text: r.text,
|
|
397
|
+
stats: r.stats,
|
|
398
|
+
eol: EOL_NAMES[r.eol],
|
|
399
|
+
duplicates: r.duplicates.slice(0, MAX_DUPLICATES),
|
|
400
|
+
...(r.duplicates.length > MAX_DUPLICATES ? { duplicates_total: r.duplicates.length } : {}),
|
|
401
|
+
options: {
|
|
402
|
+
trim: Boolean(o.trim),
|
|
403
|
+
removeBlank: Boolean(o.removeBlank),
|
|
404
|
+
dedupe: Boolean(o.dedupe),
|
|
405
|
+
...(o.dedupe ? { dedupeMode: o.dedupeMode || 'first' } : {}),
|
|
406
|
+
ignoreCase: Boolean(o.ignoreCase),
|
|
407
|
+
sort: o.sort || 'none',
|
|
408
|
+
...(o.sort === 'asc' || o.sort === 'desc' ? { numeric: o.numeric !== false } : {}),
|
|
409
|
+
...(o.sort === 'shuffle' && Number.isFinite(o.seed) ? { seed: o.seed } : {}),
|
|
410
|
+
...(o.affix ? { prefix: o.prefix || '', suffix: o.suffix || '' } : {}),
|
|
411
|
+
number: Boolean(o.number),
|
|
412
|
+
...(o.number ? { start: Number.isFinite(o.start) ? o.start : 1, sep: o.sep || 'dot', pad: Boolean(o.pad) } : {}),
|
|
413
|
+
},
|
|
414
|
+
notes: notes.map((n) => ({ code: n.code, message: NOTE_TEXT[lang][n.code](n), ...(n.count !== undefined ? { count: n.count } : {}) })),
|
|
415
|
+
};
|
|
416
|
+
if (opts.outputPath) {
|
|
417
|
+
if (!isAbsolute(opts.outputPath)) throw new LinesToolError('outputPath は絶対パスで指定してください');
|
|
418
|
+
await writeOutput(opts.outputPath, r.text, { overwrite: opts.overwrite });
|
|
419
|
+
result.output = opts.outputPath;
|
|
420
|
+
delete result.text;
|
|
421
|
+
}
|
|
422
|
+
return result;
|
|
423
|
+
}
|
package/markdown-table.mjs
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// 「変換コア」ブロックは site 側の site/markdown-table/app.js と同一の実装。
|
|
4
4
|
// 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
|
|
5
5
|
// 使っているのは String/RegExp/Array だけなので、ブラウザ版のコードをそのまま持ってこられる。
|
|
6
|
-
import { readFile
|
|
6
|
+
import { readFile } from 'node:fs/promises';
|
|
7
|
+
import { writeOutput } from './fs-safe.mjs';
|
|
7
8
|
import { basename } from 'node:path';
|
|
8
9
|
|
|
9
10
|
/* ==================== ここから変換コア(site / MCP で同一) ==================== */
|
|
@@ -632,7 +633,7 @@ export async function markdownTable(opts = {}) {
|
|
|
632
633
|
notes,
|
|
633
634
|
};
|
|
634
635
|
if (opts.outputPath) {
|
|
635
|
-
await
|
|
636
|
+
await writeOutput(opts.outputPath, text, { overwrite: opts.overwrite });
|
|
636
637
|
result.output = opts.outputPath;
|
|
637
638
|
// ファイルに書けたなら本文は重複した重い情報でしかない
|
|
638
639
|
delete result.text;
|
package/marp.mjs
CHANGED
|
@@ -8,10 +8,18 @@
|
|
|
8
8
|
// HTMLから印刷する(puppeteer/Chromium を同梱しない=`npx -y` 導入を軽く保つ)。
|
|
9
9
|
// Chrome が見つからない場合は HTML のみ返し、PDFは skip して理由を添える。
|
|
10
10
|
//
|
|
11
|
-
// 和文テーマ firstch
|
|
11
|
+
// 和文テーマ firstch を marp-theme.css として同梱し、
|
|
12
12
|
// Markdown が theme 指示を持たないときの既定テーマにする。
|
|
13
|
+
//
|
|
14
|
+
// 通信について(既定=外へ取りに行かない):
|
|
15
|
+
// - Webフォントは読み込まない(OSにあるフォントで描く。IBM Plex Sans JP が入っていれば使う)
|
|
16
|
+
// - 絵文字は画像(CDNの twemoji)に置き換えず、文字のまま出す
|
|
17
|
+
// - 組み込みテーマ(gaia/uncover)の CSS にある外部フォントの @import は取り除く
|
|
18
|
+
// - PDF を作る Chrome は外部への通信を止めて起動する
|
|
19
|
+
// allowRemote: true を渡したときだけ、Markdown が参照する外部の画像・CSS を読み込む。
|
|
13
20
|
|
|
14
21
|
import { readFile, writeFile, rm } from 'node:fs/promises';
|
|
22
|
+
import { writeOutput, defaultOutputDir, OutputExistsError } from './fs-safe.mjs';
|
|
15
23
|
import { existsSync } from 'node:fs';
|
|
16
24
|
import { execFile } from 'node:child_process';
|
|
17
25
|
import { promisify } from 'node:util';
|
|
@@ -71,16 +79,28 @@ function slideSize(html, css) {
|
|
|
71
79
|
return { w: 1280, h: 720 };
|
|
72
80
|
}
|
|
73
81
|
|
|
82
|
+
// <title> へ入れる文字列のエスケープ(</title><script> の注入を防ぐ)
|
|
83
|
+
export function escapeHtml(s) {
|
|
84
|
+
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// CSS の外部 @import(例: gaia テーマの fonts.bunny.net)を取り除く。取り除いた URL を返す。
|
|
88
|
+
export function stripRemoteImports(css) {
|
|
89
|
+
const removed = [];
|
|
90
|
+
const out = css.replace(/@import\s+(?:url\(\s*)?(["']?)((?:https?:)?\/\/[^"')\s;]+)\1\s*\)?[^;]*;/gi, (_m, _q, url) => {
|
|
91
|
+
removed.push(url);
|
|
92
|
+
return '';
|
|
93
|
+
});
|
|
94
|
+
return { css: out, removed };
|
|
95
|
+
}
|
|
96
|
+
|
|
74
97
|
function buildHtmlDoc({ html, css, size, title }) {
|
|
75
98
|
return `<!DOCTYPE html>
|
|
76
99
|
<html lang="ja">
|
|
77
100
|
<head>
|
|
78
101
|
<meta charset="utf-8">
|
|
79
102
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
80
|
-
<title>${title}</title>
|
|
81
|
-
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
82
|
-
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
83
|
-
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+JP:wght@400;500;700&family=IBM+Plex+Mono:wght@400;600&display=swap" rel="stylesheet">
|
|
103
|
+
<title>${escapeHtml(title)}</title>
|
|
84
104
|
<style>
|
|
85
105
|
${css}
|
|
86
106
|
</style>
|
|
@@ -117,20 +137,40 @@ ${html}
|
|
|
117
137
|
</html>`;
|
|
118
138
|
}
|
|
119
139
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
140
|
+
// Chrome の起動引数。サンドボックスは既定で有効のまま。
|
|
141
|
+
// root で動かすコンテナなどサンドボックスが使えない環境だけ、利用者が
|
|
142
|
+
// MARP_CHROME_NO_SANDBOX=1 を設定して外す(サーバーが勝手に外さない)。
|
|
143
|
+
export function chromeArgs({ htmlFile, pdfPath, userDataDir, allowRemote = false, env = process.env }) {
|
|
144
|
+
const args = ['--headless', '--disable-gpu', '--no-pdf-header-footer'];
|
|
145
|
+
if (env.MARP_CHROME_NO_SANDBOX === '1') args.push('--no-sandbox');
|
|
146
|
+
if (!allowRemote) {
|
|
147
|
+
// 外部への通信を止める(名前解決を全部失敗させ、IP直書きも届かないプロキシへ向ける)。
|
|
148
|
+
// file:// で開くローカルの HTML と、その中に埋め込んだデータは影響を受けない。
|
|
149
|
+
args.push('--host-resolver-rules=MAP * ~NOTFOUND', '--proxy-server=127.0.0.1:9', '--proxy-bypass-list=<-loopback>');
|
|
150
|
+
}
|
|
151
|
+
args.push(
|
|
152
|
+
'--virtual-time-budget=8000', // 画像の読み込みを待つ
|
|
128
153
|
`--user-data-dir=${userDataDir}`,
|
|
129
154
|
`--print-to-pdf=${pdfPath}`,
|
|
130
155
|
pathToFileURL(htmlFile).href,
|
|
131
|
-
|
|
156
|
+
);
|
|
157
|
+
return args;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function htmlToPdf(chrome, htmlFile, pdfPath, { allowRemote } = {}) {
|
|
161
|
+
const userDataDir = path.join(os.tmpdir(), `marp-chrome-${process.pid}-${Date.now()}`);
|
|
162
|
+
const args = chromeArgs({ htmlFile, pdfPath, userDataDir, allowRemote });
|
|
132
163
|
try {
|
|
133
164
|
await execFileP(chrome, args, { timeout: 60000, maxBuffer: 16 * 1024 * 1024 });
|
|
165
|
+
} catch (e) {
|
|
166
|
+
const msg = String((e && (e.stderr || e.message)) || e);
|
|
167
|
+
if (/sandbox/i.test(msg)) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
'Chrome をサンドボックス付きで起動できませんでした(root で動かすコンテナ等)。' +
|
|
170
|
+
'この環境で使う場合は、利用者の判断で環境変数 MARP_CHROME_NO_SANDBOX=1 を設定してください。',
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
throw e;
|
|
134
174
|
} finally {
|
|
135
175
|
await rm(userDataDir, { recursive: true, force: true }).catch(() => {});
|
|
136
176
|
}
|
|
@@ -143,8 +183,10 @@ async function htmlToPdf(chrome, htmlFile, pdfPath) {
|
|
|
143
183
|
* @param {object} opts
|
|
144
184
|
* - theme {string} 'firstch'(既定)/ 'default' / 'gaia' / 'uncover'。md内 theme 指示が優先される
|
|
145
185
|
* - formats {string[]} ['html'] 既定。'html' / 'pdf' を指定
|
|
146
|
-
* - outputPath {string} 出力ファイルのベースパス(拡張子は format 側で決まる)。省略時は
|
|
147
|
-
* - title {string} HTML の <title>(既定 'Marp slides'
|
|
186
|
+
* - outputPath {string} 出力ファイルのベースパス(拡張子は format 側で決まる)。省略時は OS の一時ディレクトリ下の firstch-tools-mcp/
|
|
187
|
+
* - title {string} HTML の <title>(既定 'Marp slides'・エスケープして入れる)
|
|
188
|
+
* - overwrite {boolean} 既存ファイルを上書きするか(既定 false=同名があればエラー)
|
|
189
|
+
* - allowRemote {boolean} Markdown が参照する外部の画像・CSS を読むか(既定 false=外へ通信しない)
|
|
148
190
|
* @returns {Promise<object>} { theme, slides, size, outputs: {html?, pdf?}, pdf_skipped? }
|
|
149
191
|
*/
|
|
150
192
|
export async function renderMarp(markdown, opts = {}) {
|
|
@@ -160,16 +202,23 @@ export async function renderMarp(markdown, opts = {}) {
|
|
|
160
202
|
if (f !== 'html' && f !== 'pdf') throw new Error(`未対応の format: ${f}(html / pdf のみ)`);
|
|
161
203
|
}
|
|
162
204
|
|
|
205
|
+
const overwrite = opts.overwrite === true;
|
|
206
|
+
const allowRemote = opts.allowRemote === true;
|
|
163
207
|
const base = opts.outputPath
|
|
164
208
|
? opts.outputPath.replace(/\.(html?|pdf)$/i, '')
|
|
165
|
-
: path.join(
|
|
209
|
+
: path.join(await defaultOutputDir(), `marp-${process.pid}-${Date.now()}`);
|
|
166
210
|
const title = opts.title || 'Marp slides';
|
|
167
211
|
|
|
168
212
|
// marp-core は html:false(marp-cli既定と同じ)で生HTML注入を無効化。ディレクティブ用コメントは有効。
|
|
169
|
-
|
|
213
|
+
// 絵文字は CDN の画像へ置き換えない(文字のまま)。
|
|
214
|
+
const marp = new Marp({ html: false, emoji: { shortcode: true, unicode: false } });
|
|
170
215
|
marp.themeSet.add(await firstchThemeCss());
|
|
171
216
|
marp.themeSet.default = marp.themeSet.get(theme);
|
|
172
|
-
const
|
|
217
|
+
const rendered = marp.render(markdown);
|
|
218
|
+
const html = rendered.html;
|
|
219
|
+
let css = rendered.css;
|
|
220
|
+
let removedImports = [];
|
|
221
|
+
if (!allowRemote) ({ css, removed: removedImports } = stripRemoteImports(css));
|
|
173
222
|
|
|
174
223
|
const slides = (html.match(/<section id=/g) || []).length;
|
|
175
224
|
const size = slideSize(html, css);
|
|
@@ -180,13 +229,16 @@ export async function renderMarp(markdown, opts = {}) {
|
|
|
180
229
|
const wantPdf = formats.includes('pdf');
|
|
181
230
|
|
|
182
231
|
let htmlForPrint;
|
|
232
|
+
// PDF は Chrome が書くので、上書きの確認を先に済ませる
|
|
233
|
+
if (wantPdf && !overwrite && existsSync(`${base}.pdf`)) throw new OutputExistsError(`${base}.pdf`);
|
|
183
234
|
if (wantHtml) {
|
|
184
235
|
outputs.html = `${base}.html`;
|
|
185
|
-
await
|
|
236
|
+
await writeOutput(outputs.html, doc, { overwrite });
|
|
186
237
|
htmlForPrint = outputs.html;
|
|
187
238
|
}
|
|
188
239
|
|
|
189
240
|
const result = { theme, slides, size, outputs };
|
|
241
|
+
if (removedImports.length) result.removed_remote_imports = removedImports;
|
|
190
242
|
|
|
191
243
|
if (wantPdf) {
|
|
192
244
|
const chrome = findChrome();
|
|
@@ -205,7 +257,7 @@ export async function renderMarp(markdown, opts = {}) {
|
|
|
205
257
|
}
|
|
206
258
|
try {
|
|
207
259
|
outputs.pdf = `${base}.pdf`;
|
|
208
|
-
await htmlToPdf(chrome, htmlForPrint, outputs.pdf);
|
|
260
|
+
await htmlToPdf(chrome, htmlForPrint, outputs.pdf, { allowRemote });
|
|
209
261
|
} catch (e) {
|
|
210
262
|
delete outputs.pdf;
|
|
211
263
|
result.pdf_skipped = `PDF生成に失敗しました: ${String(e.message || e)}`;
|