@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/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
+ }