@first-ch/tools-mcp 0.4.1 → 0.24.1

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/testdata.mjs ADDED
@@ -0,0 +1,608 @@
1
+ // テストデータ生成(ダミーレコード + 文字種・境界値テキスト)
2
+ // アルゴリズムは site/testdata/app.js(FirstCHTools リポジトリ)と同一。
3
+ // site側が正本で、こちらは追従する(2箇所ルール: 片方を直したらもう片方も同じ内容で直す)。
4
+ // 下の「生成ロジック」ブロックは site 側の該当ブロックをそのまま移植したもので、
5
+ // 差分を取りやすいよう整形も変えていない(Shift_JIS 逆引き表は Node の TextDecoder でも同じ結果になる)。
6
+ // 同期確認(site側リポジトリを隣に置いて実行する。インデント2つ分だけを落として比較する):
7
+ // diff <(sed -n '/ここから生成ロジック/,/ここまで生成ロジック/p' ../FirstCHTools/site/testdata/app.js | sed 's/^ //') \
8
+ // <(sed -n '/ここから生成ロジック/,/MCPツールの入口/p' testdata.mjs)
9
+
10
+ /* ==================== ここから生成ロジック(MCP testdata.mjs と同一) ==================== */
11
+
12
+ /* ---- 乱数(seedで再現可能。FNV-1a → mulberry32) ---- */
13
+ function hashSeed(s) {
14
+ let h = 0x811c9dc5;
15
+ const str = String(s);
16
+ for (let i = 0; i < str.length; i++) {
17
+ h ^= str.charCodeAt(i);
18
+ h = Math.imul(h, 0x01000193);
19
+ }
20
+ return h >>> 0;
21
+ }
22
+
23
+ function mulberry32(a) {
24
+ return () => {
25
+ a = (a + 0x6d2b79f5) | 0;
26
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
27
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
28
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
29
+ };
30
+ }
31
+
32
+ const pick = (rnd, arr) => arr[Math.floor(rnd() * arr.length)];
33
+ const int = (rnd, min, max) => min + Math.floor(rnd() * (max - min + 1));
34
+ const pad = (n, w) => String(n).padStart(w, '0');
35
+
36
+ /* ---- データ辞書(実在の姓名・地名を組み合わせた架空データ。実在の個人・法人とは無関係) ---- */
37
+ const JA = {
38
+ // [漢字, カタカナ, ローマ字]
39
+ surnames: [
40
+ ['佐藤', 'サトウ', 'sato'], ['鈴木', 'スズキ', 'suzuki'], ['高橋', 'タカハシ', 'takahashi'], ['田中', 'タナカ', 'tanaka'],
41
+ ['伊藤', 'イトウ', 'ito'], ['渡辺', 'ワタナベ', 'watanabe'], ['山本', 'ヤマモト', 'yamamoto'], ['中村', 'ナカムラ', 'nakamura'],
42
+ ['小林', 'コバヤシ', 'kobayashi'], ['加藤', 'カトウ', 'kato'], ['吉田', 'ヨシダ', 'yoshida'], ['山田', 'ヤマダ', 'yamada'],
43
+ ['佐々木', 'ササキ', 'sasaki'], ['山口', 'ヤマグチ', 'yamaguchi'], ['松本', 'マツモト', 'matsumoto'], ['井上', 'イノウエ', 'inoue'],
44
+ ['木村', 'キムラ', 'kimura'], ['林', 'ハヤシ', 'hayashi'], ['清水', 'シミズ', 'shimizu'], ['山崎', 'ヤマザキ', 'yamazaki'],
45
+ ['阿部', 'アベ', 'abe'], ['森', 'モリ', 'mori'], ['池田', 'イケダ', 'ikeda'], ['橋本', 'ハシモト', 'hashimoto'],
46
+ ['石川', 'イシカワ', 'ishikawa'], ['前田', 'マエダ', 'maeda'], ['藤田', 'フジタ', 'fujita'], ['後藤', 'ゴトウ', 'goto'],
47
+ ['岡田', 'オカダ', 'okada'], ['長谷川', 'ハセガワ', 'hasegawa'], ['村上', 'ムラカミ', 'murakami'], ['近藤', 'コンドウ', 'kondo'],
48
+ ['石井', 'イシイ', 'ishii'], ['坂本', 'サカモト', 'sakamoto'], ['遠藤', 'エンドウ', 'endo'], ['青木', 'アオキ', 'aoki'],
49
+ ['藤井', 'フジイ', 'fujii'], ['西村', 'ニシムラ', 'nishimura'], ['福田', 'フクダ', 'fukuda'], ['太田', 'オオタ', 'ota'],
50
+ ],
51
+ givenM: [
52
+ ['太郎', 'タロウ', 'taro'], ['一郎', 'イチロウ', 'ichiro'], ['健太', 'ケンタ', 'kenta'], ['大輔', 'ダイスケ', 'daisuke'],
53
+ ['翔太', 'ショウタ', 'shota'], ['拓也', 'タクヤ', 'takuya'], ['直樹', 'ナオキ', 'naoki'], ['雄一', 'ユウイチ', 'yuichi'],
54
+ ['和也', 'カズヤ', 'kazuya'], ['亮', 'リョウ', 'ryo'], ['誠', 'マコト', 'makoto'], ['隆之', 'タカユキ', 'takayuki'],
55
+ ['修平', 'シュウヘイ', 'shuhei'], ['智也', 'トモヤ', 'tomoya'], ['浩二', 'コウジ', 'koji'], ['優斗', 'ユウト', 'yuto'],
56
+ ['陸', 'リク', 'riku'], ['颯太', 'ソウタ', 'sota'], ['蓮', 'レン', 'ren'], ['悠真', 'ユウマ', 'yuma'],
57
+ ],
58
+ givenF: [
59
+ ['花子', 'ハナコ', 'hanako'], ['美咲', 'ミサキ', 'misaki'], ['さくら', 'サクラ', 'sakura'], ['愛', 'アイ', 'ai'],
60
+ ['陽子', 'ヨウコ', 'yoko'], ['真由美', 'マユミ', 'mayumi'], ['恵', 'メグミ', 'megumi'], ['彩', 'アヤ', 'aya'],
61
+ ['優花', 'ユウカ', 'yuka'], ['七海', 'ナナミ', 'nanami'], ['結衣', 'ユイ', 'yui'], ['杏', 'アン', 'an'],
62
+ ['美穂', 'ミホ', 'miho'], ['千尋', 'チヒロ', 'chihiro'], ['直美', 'ナオミ', 'naomi'], ['愛子', 'アイコ', 'aiko'],
63
+ ['莉子', 'リコ', 'riko'], ['葵', 'アオイ', 'aoi'], ['凛', 'リン', 'rin'], ['芽衣', 'メイ', 'mei'],
64
+ ],
65
+ // 実在の郵便番号・地名(丁目以下は乱数)。市外局番は電話番号の生成にも使う
66
+ places: [
67
+ { zip: '150-0041', pref: '東京都', city: '渋谷区', town: '神南', area: '03' },
68
+ { zip: '100-0005', pref: '東京都', city: '千代田区', town: '丸の内', area: '03' },
69
+ { zip: '160-0022', pref: '東京都', city: '新宿区', town: '新宿', area: '03' },
70
+ { zip: '220-0012', pref: '神奈川県', city: '横浜市西区', town: 'みなとみらい', area: '045' },
71
+ { zip: '231-0023', pref: '神奈川県', city: '横浜市中区', town: '山下町', area: '045' },
72
+ { zip: '330-0854', pref: '埼玉県', city: 'さいたま市大宮区', town: '桜木町', area: '048' },
73
+ { zip: '260-0013', pref: '千葉県', city: '千葉市中央区', town: '中央', area: '043' },
74
+ { zip: '460-0008', pref: '愛知県', city: '名古屋市中区', town: '栄', area: '052' },
75
+ { zip: '450-0002', pref: '愛知県', city: '名古屋市中村区', town: '名駅', area: '052' },
76
+ { zip: '530-0001', pref: '大阪府', city: '大阪市北区', town: '梅田', area: '06' },
77
+ { zip: '542-0085', pref: '大阪府', city: '大阪市中央区', town: '心斎橋筋', area: '06' },
78
+ { zip: '650-0001', pref: '兵庫県', city: '神戸市中央区', town: '加納町', area: '078' },
79
+ { zip: '604-8005', pref: '京都府', city: '京都市中京区', town: '中之町', area: '075' },
80
+ { zip: '730-0011', pref: '広島県', city: '広島市中区', town: '基町', area: '082' },
81
+ { zip: '810-0001', pref: '福岡県', city: '福岡市中央区', town: '天神', area: '092' },
82
+ { zip: '060-0002', pref: '北海道', city: '札幌市中央区', town: '北二条西', area: '011' },
83
+ { zip: '980-0021', pref: '宮城県', city: '仙台市青葉区', town: '中央', area: '022' },
84
+ { zip: '900-0006', pref: '沖縄県', city: '那覇市', town: 'おもろまち', area: '098' },
85
+ { zip: '380-0824', pref: '長野県', city: '長野市', town: '南長野', area: '026' },
86
+ { zip: '320-0033', pref: '栃木県', city: '宇都宮市', town: '本町', area: '028' },
87
+ ],
88
+ companyA: ['山手', '青葉', '大和', '北斗', '明和', '日進', '相互', '中央', '若葉', '瑞穂'],
89
+ companyB: ['商事', '製作所', '工業', 'システムズ', 'デザイン', '物産', '企画', '電機', '建設', '運輸'],
90
+ departments: ['営業部', '総務部', '経理部', '人事部', '開発部', '品質保証部', 'マーケティング部', 'カスタマーサポート部', '法務部', '広報部'],
91
+ // CSVのクォート処理を検証できるよう、カンマ・引用符・改行を含む文を意図的に混ぜている
92
+ texts: [
93
+ 'お問い合わせありがとうございます。内容を確認のうえ折り返しご連絡いたします。',
94
+ '資料請求をお願いします。送付先は登録済みの住所で問題ありません。',
95
+ '見積書の "合計金額" について確認したい点があります。',
96
+ '希望日は 5/1, 5/2, 5/8 のいずれかでお願いします。',
97
+ '対応時間帯は平日10:00〜18:00で問題ありません。',
98
+ '添付ファイルが開けませんでした。再送をお願いします。',
99
+ 'テスト投稿です。改行を含みます。\n2行目のテキストです。',
100
+ '担当者名の表記ゆれ(山田/ヤマダ)を統一してください。',
101
+ '特に希望はありません。',
102
+ ],
103
+ };
104
+
105
+ const ENG = {
106
+ surnames: ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Rodriguez', 'Martinez',
107
+ 'Hernandez', 'Lopez', 'Gonzalez', 'Wilson', 'Anderson', 'Thomas', 'Taylor', 'Moore', 'Jackson', 'Martin'],
108
+ givenM: ['James', 'Robert', 'John', 'Michael', 'David', 'William', 'Richard', 'Joseph', 'Daniel', 'Matthew',
109
+ 'Anthony', 'Mark', 'Steven', 'Andrew', 'Kevin'],
110
+ givenF: ['Mary', 'Patricia', 'Jennifer', 'Linda', 'Elizabeth', 'Barbara', 'Susan', 'Jessica', 'Sarah', 'Karen',
111
+ 'Emily', 'Ashley', 'Emma', 'Olivia', 'Sophia'],
112
+ streets: ['Oak St', 'Maple Ave', 'Cedar Ln', 'Pine Rd', 'Elm St', 'Washington Ave', 'Lake Dr', 'Hill Rd', 'Park Ave', 'Sunset Blvd'],
113
+ // 市外局番は実在、加入者番号は 555-0100〜555-0199(架空番号として予約された範囲)を使う
114
+ places: [
115
+ { city: 'Springfield', state: 'IL', zip: '62704', area: '217' },
116
+ { city: 'Austin', state: 'TX', zip: '78701', area: '512' },
117
+ { city: 'Portland', state: 'OR', zip: '97205', area: '503' },
118
+ { city: 'Denver', state: 'CO', zip: '80202', area: '303' },
119
+ { city: 'Boston', state: 'MA', zip: '02108', area: '617' },
120
+ { city: 'Seattle', state: 'WA', zip: '98101', area: '206' },
121
+ { city: 'Atlanta', state: 'GA', zip: '30303', area: '404' },
122
+ { city: 'Phoenix', state: 'AZ', zip: '85004', area: '602' },
123
+ { city: 'Madison', state: 'WI', zip: '53703', area: '608' },
124
+ { city: 'Buffalo', state: 'NY', zip: '14202', area: '716' },
125
+ ],
126
+ companyA: ['Acme', 'Northwind', 'Contoso', 'Globex', 'Initech', 'Vertex', 'Lumen', 'Cobalt', 'Summit', 'Harbor'],
127
+ companyB: ['Systems', 'Logistics', 'Media', 'Industries', 'Partners', 'Solutions', 'Labs', 'Works', 'Group', 'Design'],
128
+ companyC: ['LLC', 'Inc.', 'Co.', 'Ltd.'],
129
+ departments: ['Sales', 'Accounting', 'Human Resources', 'Engineering', 'Marketing', 'Customer Support', 'Legal', 'Operations', 'Product', 'Finance'],
130
+ texts: [
131
+ 'Thank you for your message. We will get back to you shortly.',
132
+ 'Please send the brochure, the address on file is fine.',
133
+ 'I have a question about the "total amount" on the quote.',
134
+ 'Weekday afternoons work best for a call.',
135
+ 'The attachment would not open. Could you resend it?',
136
+ 'This is a test entry.\nIt contains a line break.',
137
+ 'Please keep the spelling of the contact name consistent.',
138
+ 'No particular requests.',
139
+ ],
140
+ };
141
+
142
+ const FIELDS = ['id', 'name', 'name_kana', 'name_romaji', 'gender', 'birthday', 'email', 'tel', 'zip', 'address', 'company', 'department', 'url', 'text'];
143
+ const JA_ONLY_FIELDS = ['name_kana', 'name_romaji'];
144
+ const DEFAULT_FIELDS = ['id', 'name', 'name_kana', 'email', 'tel', 'zip', 'address'];
145
+ const EMAIL_DOMAINS = ['example.com', 'example.net', 'example.org']; // RFC 2606 の予約ドメイン(実在しない=誤送信しない)
146
+ const URL_PATHS = ['users', 'items', 'posts', 'orders', 'articles'];
147
+ const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
148
+
149
+ const daysInMonth = (y, m) => (m === 2 && ((y % 4 === 0 && y % 100 !== 0) || y % 400 === 0) ? 29 : DAYS_IN_MONTH[m - 1]);
150
+
151
+ function buildRecordJa(rnd, i) {
152
+ const sur = pick(rnd, JA.surnames);
153
+ const male = rnd() < 0.5;
154
+ const given = pick(rnd, male ? JA.givenM : JA.givenF);
155
+ const place = pick(rnd, JA.places);
156
+ const y = int(rnd, 1960, 2005);
157
+ const m = int(rnd, 1, 12);
158
+ const d = int(rnd, 1, daysInMonth(y, m));
159
+ const mobile = rnd() < 0.6;
160
+ const tel = mobile
161
+ ? `0${pick(rnd, [70, 80, 90])}-${pad(int(rnd, 0, 9999), 4)}-${pad(int(rnd, 0, 9999), 4)}`
162
+ : place.area.length === 2
163
+ ? `${place.area}-${pad(int(rnd, 1000, 9999), 4)}-${pad(int(rnd, 0, 9999), 4)}`
164
+ : `${place.area}-${pad(int(rnd, 100, 999), 3)}-${pad(int(rnd, 0, 9999), 4)}`;
165
+ return {
166
+ id: String(i + 1),
167
+ name: `${sur[0]} ${given[0]}`,
168
+ name_kana: `${sur[1]} ${given[1]}`,
169
+ name_romaji: `${given[2].charAt(0).toUpperCase()}${given[2].slice(1)} ${sur[2].charAt(0).toUpperCase()}${sur[2].slice(1)}`,
170
+ gender: male ? '男性' : '女性',
171
+ birthday: `${y}-${pad(m, 2)}-${pad(d, 2)}`,
172
+ email: `${given[2]}.${sur[2]}${int(rnd, 1, 99)}@${pick(rnd, EMAIL_DOMAINS)}`,
173
+ tel,
174
+ zip: place.zip,
175
+ address: `${place.pref}${place.city}${place.town}${int(rnd, 1, 9)}-${int(rnd, 1, 30)}-${int(rnd, 1, 30)}`,
176
+ company: `株式会社${pick(rnd, JA.companyA)}${pick(rnd, JA.companyB)}`,
177
+ department: pick(rnd, JA.departments),
178
+ url: `https://example.com/${pick(rnd, URL_PATHS)}/${int(rnd, 1, 9999)}`,
179
+ text: pick(rnd, JA.texts),
180
+ };
181
+ }
182
+
183
+ function buildRecordEn(rnd, i) {
184
+ const sur = pick(rnd, ENG.surnames);
185
+ const male = rnd() < 0.5;
186
+ const given = pick(rnd, male ? ENG.givenM : ENG.givenF);
187
+ const place = pick(rnd, ENG.places);
188
+ const y = int(rnd, 1960, 2005);
189
+ const m = int(rnd, 1, 12);
190
+ const d = int(rnd, 1, daysInMonth(y, m));
191
+ return {
192
+ id: String(i + 1),
193
+ name: `${given} ${sur}`,
194
+ name_kana: '',
195
+ name_romaji: '',
196
+ gender: male ? 'Male' : 'Female',
197
+ birthday: `${y}-${pad(m, 2)}-${pad(d, 2)}`,
198
+ email: `${given.toLowerCase()}.${sur.toLowerCase()}${int(rnd, 1, 99)}@${pick(rnd, EMAIL_DOMAINS)}`,
199
+ tel: `(${place.area}) 555-01${pad(int(rnd, 0, 99), 2)}`,
200
+ zip: place.zip,
201
+ address: `${int(rnd, 1, 9999)} ${pick(rnd, ENG.streets)}, ${place.city}, ${place.state} ${place.zip}`,
202
+ company: `${pick(rnd, ENG.companyA)} ${pick(rnd, ENG.companyB)} ${pick(rnd, ENG.companyC)}`,
203
+ department: pick(rnd, ENG.departments),
204
+ url: `https://example.com/${pick(rnd, URL_PATHS)}/${int(rnd, 1, 9999)}`,
205
+ text: pick(rnd, ENG.texts),
206
+ };
207
+ }
208
+
209
+ /** レコードを生成する。seed が同じなら常に同じ結果を返す */
210
+ function generateRecords(opts) {
211
+ const rows = Math.min(Math.max(parseInt(opts.rows, 10) || 1, 1), 1000);
212
+ const locale = opts.locale === 'en' ? 'en' : 'ja';
213
+ const seed = String(opts.seed == null || opts.seed === '' ? Math.floor(Math.random() * 4294967296) : opts.seed);
214
+ const rnd = mulberry32(hashSeed(seed));
215
+ const build = locale === 'en' ? buildRecordEn : buildRecordJa;
216
+ const out = [];
217
+ for (let i = 0; i < rows; i++) out.push(build(rnd, i));
218
+ return { rows, locale, seed, records: out };
219
+ }
220
+
221
+ /* ---- 直列化 ---- */
222
+ const NEWLINE = { LF: '\n', CRLF: '\r\n' };
223
+
224
+ function cell(v, delimiter, nl) {
225
+ // 値の中の改行も出力の改行コードに揃える(CRLFのCSVにLFが残ると読み手によっては行がずれる)
226
+ const s = String(v == null ? '' : v).replace(/\r\n|\r|\n/g, nl);
227
+ // RFC 4180: 区切り文字・引用符・改行を含む値はダブルクォートで囲み、引用符は2重にする
228
+ return s.includes(delimiter) || /["\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
229
+ }
230
+
231
+ function serialize(records, fields, opts) {
232
+ const nl = NEWLINE[opts.newline] || '\n';
233
+ const cols = fields.filter((f) => FIELDS.includes(f));
234
+ if (opts.format === 'json') {
235
+ const objs = records.map((r) => {
236
+ const o = {};
237
+ for (const f of cols) o[f] = r[f];
238
+ return o;
239
+ });
240
+ return JSON.stringify(objs, null, 2).replace(/\n/g, nl) + nl;
241
+ }
242
+ const delimiter = opts.format === 'tsv' ? '\t' : ',';
243
+ const lines = [];
244
+ if (opts.header) lines.push(cols.join(delimiter));
245
+ for (const r of records) lines.push(cols.map((f) => cell(r[f], delimiter, nl)).join(delimiter));
246
+ return lines.join(nl) + nl;
247
+ }
248
+
249
+ /* ---- .xlsx 書き出し(OOXML SpreadsheetML)----
250
+ * .xlsx の実体は XML を集めた ZIP なので、無圧縮(store)のZIPライターを自前で持てば
251
+ * 外部ライブラリ(SheetJS等)を読み込まずにブラウザ内・Node内のどちらでも書き出せる。
252
+ * タイムスタンプは固定値にしてあるため、同じ seed からは常に同じバイト列になる。 */
253
+
254
+ /** XMLのテキストノードに置ける形にする。XML 1.0 に存在できない制御文字は落とす
255
+ * (該当文字が1つでも残るとExcelはファイルを「破損」と判定して開かない) */
256
+ function xmlText(v) {
257
+ return String(v == null ? '' : v)
258
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '')
259
+ .replace(/&/g, '&amp;')
260
+ .replace(/</g, '&lt;')
261
+ .replace(/>/g, '&gt;');
262
+ }
263
+
264
+ let CRC_TABLE = null;
265
+
266
+ function crcTable() {
267
+ if (CRC_TABLE) return CRC_TABLE;
268
+ const t = new Uint32Array(256);
269
+ for (let i = 0; i < 256; i++) {
270
+ let c = i;
271
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
272
+ t[i] = c >>> 0;
273
+ }
274
+ CRC_TABLE = t;
275
+ return t;
276
+ }
277
+
278
+ function crc32(bytes) {
279
+ const t = crcTable();
280
+ let c = 0xffffffff;
281
+ for (let i = 0; i < bytes.length; i++) c = t[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
282
+ return (c ^ 0xffffffff) >>> 0;
283
+ }
284
+
285
+ /** entries: [{ name, bytes }] を無圧縮(store)のZIPにまとめる */
286
+ function zipStore(entries) {
287
+ const files = entries.map((e) => ({
288
+ name: new TextEncoder().encode(e.name),
289
+ bytes: e.bytes,
290
+ crc: crc32(e.bytes),
291
+ }));
292
+ // ローカルヘッダ30 + 中央ディレクトリ46 + ファイル名2回 + 本体、最後にEOCD22
293
+ let total = 22;
294
+ for (const f of files) total += 30 + 46 + f.name.length * 2 + f.bytes.length;
295
+ const buf = new Uint8Array(total);
296
+ const view = new DataView(buf.buffer);
297
+ let p = 0;
298
+ const u16 = (v) => { view.setUint16(p, v, true); p += 2; };
299
+ const u32 = (v) => { view.setUint32(p, v, true); p += 4; };
300
+ const raw = (b) => { buf.set(b, p); p += b.length; };
301
+ const DOS_DATE = 0x0021; // 1980-01-01(固定=同じ入力からは常に同じファイルになる)
302
+
303
+ const offsets = [];
304
+ for (const f of files) {
305
+ offsets.push(p);
306
+ u32(0x04034b50); u16(20); u16(0); u16(0); u16(0); u16(DOS_DATE);
307
+ u32(f.crc); u32(f.bytes.length); u32(f.bytes.length);
308
+ u16(f.name.length); u16(0);
309
+ raw(f.name); raw(f.bytes);
310
+ }
311
+ const dirStart = p;
312
+ files.forEach((f, i) => {
313
+ u32(0x02014b50); u16(20); u16(20); u16(0); u16(0); u16(0); u16(DOS_DATE);
314
+ u32(f.crc); u32(f.bytes.length); u32(f.bytes.length);
315
+ u16(f.name.length); u16(0); u16(0); u16(0); u16(0); u32(0); u32(offsets[i]);
316
+ raw(f.name);
317
+ });
318
+ const dirSize = p - dirStart; // EOCDを書く前に確定させる(書きながら p が進むため)
319
+ u32(0x06054b50); u16(0); u16(0); u16(files.length); u16(files.length);
320
+ u32(dirSize); u32(dirStart); u16(0);
321
+ return buf;
322
+ }
323
+
324
+ /** 0 → A, 25 → Z, 26 → AA */
325
+ function colName(i) {
326
+ let s = '';
327
+ for (let n = i; n >= 0; n = Math.floor(n / 26) - 1) s = String.fromCharCode(65 + (n % 26)) + s;
328
+ return s;
329
+ }
330
+
331
+ // 列幅(文字数目安)。既定の幅のままだと住所・自由記述が潰れて中身を確認できない
332
+ const XLSX_WIDTHS = {
333
+ id: 6, name: 15, name_kana: 17, name_romaji: 19, gender: 8, birthday: 13, email: 30,
334
+ tel: 17, zip: 11, address: 44, company: 26, department: 18, url: 34, text: 48,
335
+ };
336
+
337
+ const XML_HEAD = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
338
+ const NS_SHEET = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
339
+ const NS_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
340
+ const NS_PKG_REL = 'http://schemas.openxmlformats.org/package/2006/relationships';
341
+
342
+ /**
343
+ * レコードを .xlsx のバイト列にする。
344
+ * 連番(id)だけ数値セルにし、それ以外は文字列セルにする。郵便番号を数値にすると
345
+ * Excelが先頭の0を落として 02108 → 2108 になるため、文字列で固定する。
346
+ */
347
+ function buildXlsx(records, fields, opts = {}) {
348
+ const cols = fields.filter((f) => FIELDS.includes(f));
349
+ const header = opts.header !== false;
350
+ const rows = [];
351
+ let n = 0;
352
+
353
+ if (header) {
354
+ n += 1;
355
+ rows.push(`<row r="${n}">${cols
356
+ .map((f, i) => `<c r="${colName(i)}${n}" s="1" t="inlineStr"><is><t xml:space="preserve">${xmlText(f)}</t></is></c>`)
357
+ .join('')}</row>`);
358
+ }
359
+ for (const rec of records) {
360
+ n += 1;
361
+ const cells = cols.map((f, i) => {
362
+ const v = rec[f];
363
+ if (v === '' || v == null) return ''; // 空セルは書かない(疎な行はSpreadsheetMLとして正しい)
364
+ const ref = `${colName(i)}${n}`;
365
+ if (f === 'id') return `<c r="${ref}"><v>${xmlText(v)}</v></c>`;
366
+ return `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${xmlText(v)}</t></is></c>`;
367
+ });
368
+ rows.push(`<row r="${n}">${cells.join('')}</row>`);
369
+ }
370
+
371
+ const widths = cols
372
+ .map((f, i) => `<col min="${i + 1}" max="${i + 1}" width="${XLSX_WIDTHS[f] || 14}" customWidth="1"/>`)
373
+ .join('');
374
+ // ヘッダー行があるときだけ先頭行を固定する
375
+ const pane = header ? '<pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/>' : '';
376
+
377
+ const sheet = `${XML_HEAD}<worksheet xmlns="${NS_SHEET}">`
378
+ + `<dimension ref="A1:${colName(cols.length - 1)}${n}"/>`
379
+ + `<sheetViews><sheetView workbookViewId="0">${pane}</sheetView></sheetViews>`
380
+ + `<sheetFormatPr defaultRowHeight="18"/><cols>${widths}</cols>`
381
+ + `<sheetData>${rows.join('')}</sheetData></worksheet>`;
382
+
383
+ // ヘッダー行を太字にするための最小スタイル(s="1" が太字)
384
+ const styles = `${XML_HEAD}<styleSheet xmlns="${NS_SHEET}">`
385
+ + '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts>'
386
+ + '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>'
387
+ + '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>'
388
+ + '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
389
+ + '<cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
390
+ + '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>'
391
+ + '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>';
392
+
393
+ const contentTypes = `${XML_HEAD}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">`
394
+ + '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
395
+ + '<Default Extension="xml" ContentType="application/xml"/>'
396
+ + '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
397
+ + '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
398
+ + '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>';
399
+
400
+ const enc = new TextEncoder();
401
+ return zipStore([
402
+ { name: '[Content_Types].xml', bytes: enc.encode(contentTypes) },
403
+ { name: '_rels/.rels', bytes: enc.encode(`${XML_HEAD}<Relationships xmlns="${NS_PKG_REL}"><Relationship Id="rId1" Type="${NS_REL}/officeDocument" Target="xl/workbook.xml"/></Relationships>`) },
404
+ { name: 'xl/workbook.xml', bytes: enc.encode(`${XML_HEAD}<workbook xmlns="${NS_SHEET}" xmlns:r="${NS_REL}"><sheets><sheet name="testdata" sheetId="1" r:id="rId1"/></sheets></workbook>`) },
405
+ { name: 'xl/_rels/workbook.xml.rels', bytes: enc.encode(`${XML_HEAD}<Relationships xmlns="${NS_PKG_REL}"><Relationship Id="rId1" Type="${NS_REL}/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="${NS_REL}/styles" Target="styles.xml"/></Relationships>`) },
406
+ { name: 'xl/styles.xml', bytes: enc.encode(styles) },
407
+ { name: 'xl/worksheets/sheet1.xml', bytes: enc.encode(sheet) },
408
+ ]);
409
+ }
410
+
411
+ /* ---- Shift_JIS エンコード ----
412
+ * TextEncoder は UTF-8 しか書き出せないため、TextDecoder('shift_jis') で
413
+ * 全バイト列を1回だけ復号して逆引き表を作る(変換表を同梱せずCP932相当を得る)。 */
414
+ let SJIS = null;
415
+
416
+ function sjisTable() {
417
+ if (SJIS) return SJIS;
418
+ const seqs = [];
419
+ const probe = [];
420
+ const push = (seq) => { seqs.push(seq); probe.push(...seq, 0x0a); }; // 0x0a は trail バイトに現れないため区切りに使える
421
+ for (let b = 0x20; b <= 0x7e; b++) push([b]);
422
+ for (let b = 0xa1; b <= 0xdf; b++) push([b]); // 半角カナ
423
+ for (let lead = 0x81; lead <= 0xfc; lead++) {
424
+ if (lead > 0x9f && lead < 0xe0) continue;
425
+ for (let trail = 0x40; trail <= 0xfc; trail++) {
426
+ if (trail !== 0x7f) push([lead, trail]);
427
+ }
428
+ }
429
+ const chars = new TextDecoder('shift_jis').decode(Uint8Array.from(probe)).split('\n');
430
+ const map = new Map();
431
+ for (let i = 0; i < seqs.length; i++) {
432
+ const c = chars[i];
433
+ // 未定義領域は U+FFFD になる。重複定義は先に現れる(=JIS標準側の)バイト列を採用する
434
+ if (c && [...c].length === 1 && c !== '�' && !map.has(c)) map.set(c, seqs[i]);
435
+ }
436
+ map.set('\n', [0x0a]);
437
+ map.set('\r', [0x0d]);
438
+ map.set('\t', [0x09]);
439
+ // CP932(Windows/Excel)とUnicodeの対応差。復号表は片側しか持たないため別名を補う
440
+ // 例: 波ダッシュ U+301C は Windows では 0x8160(U+FF5E 側)に載っている
441
+ for (const [from, to] of [['〜', '~'], ['−', '-'], ['¢', '¢'], ['£', '£'],
442
+ ['¬', '¬'], ['‖', '∥'], ['—', '―']]) {
443
+ if (!map.has(from) && map.has(to)) map.set(from, map.get(to));
444
+ }
445
+ SJIS = map;
446
+ return map;
447
+ }
448
+
449
+ /** Shift_JIS のバイト列にする。表現できない文字は '?' に置換し件数を返す */
450
+ function sjisEncode(text) {
451
+ const map = sjisTable();
452
+ const out = [];
453
+ let unencodable = 0;
454
+ for (const ch of String(text)) {
455
+ const seq = map.get(ch);
456
+ if (seq) {
457
+ for (const b of seq) out.push(b);
458
+ } else {
459
+ unencodable++;
460
+ out.push(0x3f); // '?'
461
+ }
462
+ }
463
+ return { bytes: Uint8Array.from(out), unencodable };
464
+ }
465
+
466
+ const BOM_UTF8 = [0xef, 0xbb, 0xbf];
467
+
468
+ /** テキストをバイト列にする。encoding: 'utf-8' | 'shift_jis'(Shift_JIS に BOM は無い) */
469
+ function encodeText(text, opts = {}) {
470
+ if (opts.encoding === 'shift_jis') {
471
+ const r = sjisEncode(text);
472
+ return { bytes: r.bytes, unencodable: r.unencodable, encoding: 'shift_jis', has_bom: false };
473
+ }
474
+ const body = new TextEncoder().encode(text);
475
+ const bytes = opts.bom ? Uint8Array.from([...BOM_UTF8, ...body]) : body;
476
+ return { bytes, unencodable: 0, encoding: 'utf-8', has_bom: !!opts.bom };
477
+ }
478
+
479
+ /* ---- 文字種・境界値テキスト ---- */
480
+ const CHARSETS = {
481
+ upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
482
+ lower: 'abcdefghijklmnopqrstuvwxyz',
483
+ digit: '0123456789',
484
+ alnum: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
485
+ symbol: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~',
486
+ escape: '<>&"\'/\\',
487
+ hiragana: 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをん',
488
+ katakana: 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン',
489
+ kanji: '亜以宇江於加喜久計古佐之寸世曽太知川天登奈仁奴祢乃波比不部保末美武女毛也由与良利留礼呂和',
490
+ mixed: '日本語のテスト文字列サンプル漢字カタカナひらがな混在',
491
+ zenkaku_alnum: 'ABCDEFGHIJ0123456789',
492
+ hankaku_kana: 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン',
493
+ kisyu: '①②③④⑤⑥㈱㈲℡髙﨑濵德',
494
+ emoji: '😀🍣🎉🚀🌸🐱🔥🎌⭐🍺',
495
+ // 不可視文字はエスケープで書く(見た目で消えるとメンテナンスで壊れるため)
496
+ space: ' \u3000あA1',
497
+ zerowidth: 'あ\u200bい\u200cう\ufeff', // ZWSP / ZWNJ / ゼロ幅ノーブレークスペース
498
+ };
499
+
500
+ /** preset の文字を先頭から巡回して、ちょうど n コードポイントの文字列を作る */
501
+ function buildText(preset, n) {
502
+ const set = [...(CHARSETS[preset] || CHARSETS.alnum)];
503
+ const len = Math.max(0, n);
504
+ const out = [];
505
+ for (let i = 0; i < len; i++) out.push(set[i % set.length]);
506
+ // 前後空白のトリム挙動を確かめるプリセットは、先頭を半角スペース・末尾を全角スペースに固定する
507
+ if (preset === 'space' && len >= 2) {
508
+ out[0] = ' ';
509
+ out[len - 1] = ' ';
510
+ }
511
+ return out.join('');
512
+ }
513
+
514
+ function textStats(s) {
515
+ let graphemes = [...s].length;
516
+ if (typeof Intl !== 'undefined' && Intl.Segmenter) {
517
+ graphemes = [...new Intl.Segmenter('ja', { granularity: 'grapheme' }).segment(s)].length;
518
+ }
519
+ return {
520
+ code_points: [...s].length,
521
+ utf16: s.length,
522
+ graphemes,
523
+ utf8_bytes: new TextEncoder().encode(s).length,
524
+ };
525
+ }
526
+
527
+ /** 境界値テスト用に n-1 / n / n+1 の3本を返す */
528
+ function generateBoundaryText(preset, n) {
529
+ const len = Math.min(Math.max(parseInt(n, 10) || 1, 1), 10000);
530
+ return [len - 1, len, len + 1].map((l) => {
531
+ const text = buildText(preset, l);
532
+ return { length: l, label: l === len ? 'N' : l < len ? 'N-1' : 'N+1', text, ...textStats(text) };
533
+ });
534
+ }
535
+
536
+ /* ---- MCPツールの入口 ---- */
537
+
538
+ const PRESETS = Object.keys(CHARSETS);
539
+
540
+ /**
541
+ * mode: 'records'(既定)… ダミーレコードを CSV/TSV/JSON/XLSX で返す
542
+ * mode: 'text' … 指定文字種で n-1 / n / n+1 文字ちょうどの文字列を返す
543
+ */
544
+ export function generateTestData(opts = {}) {
545
+ if (opts.mode === 'text') {
546
+ const preset = opts.preset || 'mixed';
547
+ if (!PRESETS.includes(preset)) throw new Error(`未対応の文字種: ${preset}(${PRESETS.join(' / ')} のいずれか)`);
548
+ return { mode: 'text', preset, length: Math.min(Math.max(parseInt(opts.length ?? 20, 10) || 1, 1), 10000), variants: generateBoundaryText(preset, opts.length ?? 20) };
549
+ }
550
+
551
+ const fields = (opts.fields && opts.fields.length ? opts.fields : DEFAULT_FIELDS).filter((f) => FIELDS.includes(f));
552
+ if (!fields.length) throw new Error(`fields が不正です(${FIELDS.join(' / ')} から選ぶ)`);
553
+ const format = opts.format || 'csv';
554
+ if (!['csv', 'tsv', 'json', 'xlsx'].includes(format)) throw new Error(`未対応の形式: ${format}(csv / tsv / json / xlsx のいずれか)`);
555
+ const encoding = opts.encoding || 'utf-8';
556
+ if (!['utf-8', 'shift_jis'].includes(encoding)) throw new Error(`未対応の文字コード: ${encoding}(utf-8 / shift_jis のいずれか)`);
557
+ const newline = opts.newline || 'LF';
558
+ const header = opts.header !== false;
559
+
560
+ const r = generateRecords({ rows: opts.rows ?? 10, locale: opts.locale, seed: opts.seed });
561
+
562
+ // xlsx はZIP+XMLのバイナリなので、文字コード・改行コード・BOMの指定は対象外。
563
+ // text には中身を確認できるようタブ区切りの表現を入れる(そのままExcelに貼れる)
564
+ if (format === 'xlsx') {
565
+ const bytes = buildXlsx(r.records, fields, { header });
566
+ return {
567
+ mode: 'records',
568
+ rows: r.rows,
569
+ locale: r.locale,
570
+ seed: r.seed,
571
+ fields,
572
+ format,
573
+ encoding: 'utf-8', // xlsx内部のXMLは常にUTF-8
574
+ has_bom: false,
575
+ newline: 'LF',
576
+ bytes: bytes.length,
577
+ unencodable: 0,
578
+ note: 'xlsx はバイナリのため encoding / newline / bom の指定は無視される。text はタブ区切りのプレビューで、ファイル本体は base64(または outputPath)で受け取る。',
579
+ text: serialize(r.records, fields, { format: 'tsv', newline: 'LF', header }),
580
+ base64: Buffer.from(bytes).toString('base64'),
581
+ _bytes: bytes,
582
+ };
583
+ }
584
+
585
+ const text = serialize(r.records, fields, { format, newline, header });
586
+ // Shift_JIS に BOM は無いため、指定されても付けない
587
+ const enc = encodeText(text, { encoding, bom: encoding === 'utf-8' && !!opts.bom });
588
+
589
+ return {
590
+ mode: 'records',
591
+ rows: r.rows,
592
+ locale: r.locale,
593
+ seed: r.seed, // 同じ seed を渡せば同じデータを再現できる
594
+ fields,
595
+ format,
596
+ encoding: enc.encoding,
597
+ has_bom: enc.has_bom,
598
+ newline,
599
+ bytes: enc.bytes.length,
600
+ unencodable: enc.unencodable,
601
+ text,
602
+ // テキストだけでは表せないバイト列(Shift_JIS / BOM付き)のときだけ base64 も返す
603
+ ...(enc.encoding === 'shift_jis' || enc.has_bom ? { base64: Buffer.from(enc.bytes).toString('base64') } : {}),
604
+ _bytes: enc.bytes,
605
+ };
606
+ }
607
+
608
+ export { FIELDS, DEFAULT_FIELDS, CHARSETS, PRESETS, generateRecords, serialize, buildXlsx, encodeText, generateBoundaryText, textStats, sjisEncode };