@first-ch/tools-mcp 0.4.1 → 0.24.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/base64.mjs ADDED
@@ -0,0 +1,356 @@
1
+ // Base64 / Data URI 変換(tools.first-ch.com/base64/ と同一ロジック)
2
+ //
3
+ // 「変換コア」ブロックは site 側の site/base64/app.js と同一の実装。
4
+ // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
+ // btoa / atob / TextEncoder / TextDecoder は Node 18+ にグローバルで存在するため、
6
+ // ブラウザ版のコードをそのまま持ってこられる(環境差で結果がずれない)。
7
+ import { readFile, writeFile } from 'node:fs/promises';
8
+ import { basename } from 'node:path';
9
+
10
+ /* ==================== ここから変換コア(site/base64/app.js と同一) ==================== */
11
+
12
+ const STD_B64 = /^[A-Za-z0-9+/]*$/;
13
+
14
+ /* ---- Base64 ---- */
15
+
16
+ // バイト列 → 標準Base64(RFC 4648 §4・パディングあり)
17
+ export function bytesToBase64(bytes) {
18
+ let bin = '';
19
+ // String.fromCharCode の引数個数上限(環境依存)に当たらないよう分割して連結する
20
+ const CHUNK = 0x8000;
21
+ for (let i = 0; i < bytes.length; i += CHUNK) {
22
+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
23
+ }
24
+ return btoa(bin);
25
+ }
26
+
27
+ // Base64 → バイト列。標準/URLセーフ、改行・空白混じり、パディング欠けをすべて受け付ける
28
+ // (貼り付け元がメール・JSON・シェル出力のどれでも通るようにするため)。
29
+ export function base64ToBytes(input) {
30
+ let s = String(input).replace(/\s+/g, '').replace(/-/g, '+').replace(/_/g, '/');
31
+ s = s.replace(/=+$/, '');
32
+ if (!STD_B64.test(s)) throw new RangeError('BAD_CHAR');
33
+ if (s.length % 4 === 1) throw new RangeError('BAD_LENGTH');
34
+ while (s.length % 4) s += '=';
35
+ const bin = atob(s);
36
+ const out = new Uint8Array(bin.length);
37
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
38
+ return out;
39
+ }
40
+
41
+ // 標準Base64を、URLセーフ(-_・パディング無し)/指定桁での改行(MIMEは76桁)へ整形する
42
+ export function formatBase64(b64, opts) {
43
+ const { urlSafe = false, wrap = 0 } = opts || {};
44
+ let out = b64;
45
+ if (urlSafe) out = out.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
46
+ if (wrap > 0) out = (out.match(new RegExp('.{1,' + wrap + '}', 'g')) || []).join('\n');
47
+ return out;
48
+ }
49
+
50
+ /* ---- Data URI ---- */
51
+
52
+ // パーセントエンコードをバイト単位で解く(%XX が非UTF-8のバイトでも壊れないように)
53
+ export function percentDecode(str) {
54
+ const src = new TextEncoder().encode(str);
55
+ const out = [];
56
+ for (let i = 0; i < src.length; i++) {
57
+ if (src[i] === 0x25 && i + 2 < src.length) {
58
+ const hex = String.fromCharCode(src[i + 1], src[i + 2]);
59
+ if (/^[0-9a-f]{2}$/i.test(hex)) {
60
+ out.push(parseInt(hex, 16));
61
+ i += 2;
62
+ continue;
63
+ }
64
+ }
65
+ out.push(src[i]);
66
+ }
67
+ return new Uint8Array(out);
68
+ }
69
+
70
+ // data:[<mediatype>][;charset=…][;base64],<data> を分解する。data URI でなければ null
71
+ export function parseDataUri(input) {
72
+ const m = /^\s*data:([^,]*),([\s\S]*)$/i.exec(String(input));
73
+ if (!m) return null;
74
+ const params = m[1].split(';').filter(Boolean);
75
+ const isBase64 = params.some((p) => p.trim().toLowerCase() === 'base64');
76
+ const mimeType = params.length && params[0].includes('/') ? params[0].trim().toLowerCase() : 'text/plain';
77
+ const cs = params.find((p) => p.trim().toLowerCase().startsWith('charset='));
78
+ return {
79
+ mimeType,
80
+ charset: cs ? cs.trim().slice(8) : '',
81
+ isBase64,
82
+ bytes: isBase64 ? base64ToBytes(m[2]) : percentDecode(m[2].replace(/\s+/g, '')),
83
+ };
84
+ }
85
+
86
+ export const buildDataUri = (bytes, mimeType) =>
87
+ 'data:' + (mimeType || 'application/octet-stream') + ';base64,' + bytesToBase64(bytes);
88
+
89
+ // SVGはbase64(必ず約1.33倍になる)より、パーセントエンコードのまま埋め込む方が小さい。
90
+ // HTML属性にも CSS url("…") にもそのまま貼れるよう、& " < > # % 空白・非ASCIIは必ず退避する。
91
+ export function svgPercentDataUri(svgText) {
92
+ let s = String(svgText)
93
+ .replace(/^/, '')
94
+ .replace(/<\?xml[\s\S]*?\?>/gi, '')
95
+ .replace(/<!--[\s\S]*?-->/g, '')
96
+ .replace(/[\t\n\r]+/g, ' ')
97
+ .replace(/ {2,}/g, ' ')
98
+ .trim();
99
+ // タグ間の空白は詰めたいが、<text>/<tspan> がある場合は語間の空白が描画に効くので触らない
100
+ if (!/<(text|tspan)\b/i.test(s)) s = s.replace(/>\s+</g, '><');
101
+ // 属性の "…" を '…' に寄せると %22 が消えて短くなる。元に ' が無いときだけ(値を壊さないため)
102
+ if (!s.includes("'")) s = s.replace(/"/g, "'");
103
+ // encodeURIComponent は A-Za-z0-9 -_.!~*'() 以外をすべて %XX にする。
104
+ // そのうちURIにそのまま書ける記号だけ戻して短くする(& " < > # % と空白は戻さない)。
105
+ const encoded = encodeURIComponent(s)
106
+ .replace(/%3A/gi, ':')
107
+ .replace(/%2F/gi, '/')
108
+ .replace(/%2C/gi, ',')
109
+ .replace(/%3B/gi, ';')
110
+ .replace(/%3D/gi, '=')
111
+ .replace(/%40/gi, '@')
112
+ .replace(/%2B/gi, '+')
113
+ .replace(/%24/gi, '$')
114
+ .replace(/%3F/gi, '?');
115
+ return 'data:image/svg+xml,' + encoded;
116
+ }
117
+
118
+ /* ---- 種類の判定 ---- */
119
+
120
+ const MAGIC = [
121
+ { mime: 'image/png', test: (b) => b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47 },
122
+ { mime: 'image/jpeg', test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
123
+ { mime: 'image/gif', test: (b) => b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38 },
124
+ {
125
+ mime: 'image/webp',
126
+ test: (b) => b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46
127
+ && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50,
128
+ },
129
+ { mime: 'image/x-icon', test: (b) => b[0] === 0x00 && b[1] === 0x00 && b[2] === 0x01 && b[3] === 0x00 },
130
+ { mime: 'application/pdf', test: (b) => b[0] === 0x25 && b[1] === 0x50 && b[2] === 0x44 && b[3] === 0x46 },
131
+ { mime: 'font/woff2', test: (b) => b[0] === 0x77 && b[1] === 0x4f && b[2] === 0x46 && b[3] === 0x32 },
132
+ { mime: 'font/woff', test: (b) => b[0] === 0x77 && b[1] === 0x4f && b[2] === 0x46 && b[3] === 0x46 },
133
+ { mime: 'application/zip', test: (b) => b[0] === 0x50 && b[1] === 0x4b },
134
+ ];
135
+
136
+ const EXT_BY_MIME = {
137
+ 'image/png': 'png',
138
+ 'image/jpeg': 'jpg',
139
+ 'image/gif': 'gif',
140
+ 'image/webp': 'webp',
141
+ 'image/svg+xml': 'svg',
142
+ 'image/x-icon': 'ico',
143
+ 'application/pdf': 'pdf',
144
+ 'application/zip': 'zip',
145
+ 'application/json': 'json',
146
+ 'font/woff': 'woff',
147
+ 'font/woff2': 'woff2',
148
+ 'text/plain': 'txt',
149
+ 'text/html': 'html',
150
+ 'text/css': 'css',
151
+ 'text/csv': 'csv',
152
+ };
153
+
154
+ // UTF-8として読めればその文字列を、読めなければ null を返す
155
+ export function decodeUtf8(bytes) {
156
+ try {
157
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
158
+ } catch (e) {
159
+ return null;
160
+ }
161
+ }
162
+
163
+ // マジックナンバー → SVG/テキスト判定 の順で中身から種類を推定する
164
+ export function sniffType(bytes) {
165
+ for (const m of MAGIC) {
166
+ if (bytes.length >= 12 && m.test(bytes)) return { mimeType: m.mime, text: null };
167
+ }
168
+ const text = decodeUtf8(bytes);
169
+ if (text === null) return { mimeType: 'application/octet-stream', text: null };
170
+ if (/^\s*(<\?xml[\s\S]*?\?>\s*)?(<!--[\s\S]*?-->\s*)*<svg[\s>]/i.test(text)) {
171
+ return { mimeType: 'image/svg+xml', text };
172
+ }
173
+ return { mimeType: 'text/plain', text };
174
+ }
175
+
176
+ export const extForMime = (mime) => EXT_BY_MIME[String(mime).toLowerCase()] || 'bin';
177
+
178
+ /* ---- 貼り付け用スニペット ---- */
179
+
180
+ export function buildSnippets(uri, opts) {
181
+ const { width = 0, height = 0, mimeType = '' } = opts || {};
182
+ if (!/^image\//i.test(mimeType)) return null;
183
+ const size = width && height ? ` width="${width}" height="${height}"` : '';
184
+ return {
185
+ html: `<img src="${uri}"${size} alt="" decoding="async">`,
186
+ css: '.icon {\n'
187
+ + ` background-image: url("${uri}");\n`
188
+ + ' background-repeat: no-repeat;\n'
189
+ + ' background-size: contain;\n'
190
+ + (width && height ? ` width: ${width}px;\n height: ${height}px;\n` : '')
191
+ + '}',
192
+ };
193
+ }
194
+
195
+ /* ==================== ここまで変換コア ==================== */
196
+
197
+ // SVGのルート要素から width/height を読む。Web版は <img> の naturalWidth で測るが、
198
+ // Node には描画エンジンが無いため、属性(無ければ viewBox)から取る。
199
+ // 数値でない指定(100% など)は「不明」として 0 を返し、スニペットから寸法属性を落とす。
200
+ function svgSize(svgText) {
201
+ const root = /<svg\b[^>]*>/i.exec(svgText);
202
+ if (!root) return { width: 0, height: 0 };
203
+ const attr = (name) => {
204
+ const m = new RegExp(`\\b${name}\\s*=\\s*("[^"]*"|'[^']*'|[^\\s/>]+)`, 'i').exec(root[0]);
205
+ if (!m) return 0;
206
+ // 値の全体が数値(+ 任意の px)のときだけ採る。100% や 2em は「不明」として 0 を返す
207
+ const v = m[1].replace(/^["']|["']$/g, '').trim();
208
+ return /^[0-9.]+(px)?$/i.test(v) ? Math.round(parseFloat(v)) : 0;
209
+ };
210
+ const width = attr('width');
211
+ const height = attr('height');
212
+ if (width && height) return { width, height };
213
+ const vb = /\bviewBox\s*=\s*["']([^"']+)["']/i.exec(root[0]);
214
+ if (vb) {
215
+ const n = vb[1].trim().split(/[\s,]+/).map(Number);
216
+ if (n.length === 4 && n.every((v) => Number.isFinite(v))) {
217
+ return { width: Math.round(n[2]), height: Math.round(n[3]) };
218
+ }
219
+ }
220
+ return { width: 0, height: 0 };
221
+ }
222
+
223
+ const fmtBytes = (n) => (n >= 1048576 ? (n / 1048576).toFixed(2) + ' MB' : n >= 1024 ? (n / 1024).toFixed(1) + ' KB' : n + ' B');
224
+
225
+ export class Base64Error extends Error {}
226
+
227
+ const explain = (e) => {
228
+ if (e instanceof RangeError && e.message === 'BAD_CHAR') {
229
+ return 'Base64として読めません(A-Z a-z 0-9 + / - _ = 以外の文字が含まれています)';
230
+ }
231
+ if (e instanceof RangeError && e.message === 'BAD_LENGTH') {
232
+ return 'Base64として読めません(長さが1文字ずれています。Base64本体の長さは 4n+1 になりません)';
233
+ }
234
+ return `Base64として読めません(${e.message})`;
235
+ };
236
+
237
+ /**
238
+ * テキスト/ファイルを Base64・data URI へ変換する(mode='encode')か、
239
+ * Base64・data URI を元のバイト列へ戻す(mode='decode')。
240
+ *
241
+ * @param {object} opts
242
+ * @param {'encode'|'decode'} [opts.mode='encode']
243
+ * @param {string} [opts.text] encode: 対象テキスト(UTF-8として符号化する)
244
+ * @param {string} [opts.path] encode: 対象ファイルの絶対パス(text と排他)
245
+ * @param {string} [opts.base64] decode: Base64本体または data URI 全体
246
+ * @param {string} [opts.outputPath] decode: 復元したバイト列を書き出す絶対パス
247
+ * @param {boolean}[opts.urlSafe] encode: URLセーフ(-_・パディング無し)にする
248
+ * @param {number} [opts.wrap] encode: n桁ごとに改行(MIMEは76)
249
+ * @param {boolean}[opts.dataUri] encode: data URI も返す(path 指定時は常に返す)
250
+ * @param {string} [opts.mimeType] encode: data URI のMIMEタイプ(未指定なら中身から判定)
251
+ * @param {boolean}[opts.snippets] encode: HTML/CSS スニペットも返す(画像のみ)
252
+ */
253
+ export async function base64Convert(opts = {}) {
254
+ const mode = opts.mode || 'encode';
255
+ if (mode !== 'encode' && mode !== 'decode') throw new Base64Error(`mode は encode か decode: ${opts.mode}`);
256
+
257
+ if (mode === 'decode') {
258
+ const src = opts.base64;
259
+ if (typeof src !== 'string' || !src.trim()) throw new Base64Error('decode には base64(Base64本体または data URI)が必要です');
260
+ let bytes;
261
+ let declared = '';
262
+ try {
263
+ const parsed = parseDataUri(src);
264
+ if (parsed) {
265
+ bytes = parsed.bytes;
266
+ declared = parsed.mimeType;
267
+ } else {
268
+ bytes = base64ToBytes(src);
269
+ }
270
+ } catch (e) {
271
+ throw new Base64Error(explain(e));
272
+ }
273
+ const sniffed = sniffType(bytes);
274
+ // data URI が名乗る種類より、中身から分かる種類を優先する(宣言のずれたコピペを拾わないため)
275
+ const mimeType = !declared || declared === 'text/plain' ? sniffed.mimeType : declared;
276
+ const result = {
277
+ mode: 'decode',
278
+ mime_type: mimeType,
279
+ declared_mime_type: declared || null,
280
+ bytes: bytes.length,
281
+ size_human: fmtBytes(bytes.length),
282
+ is_text: sniffed.text !== null,
283
+ text: sniffed.text,
284
+ base64: bytesToBase64(bytes),
285
+ suggested_extension: extForMime(mimeType),
286
+ };
287
+ if (opts.outputPath) {
288
+ await writeFile(opts.outputPath, bytes);
289
+ result.output = opts.outputPath;
290
+ // ファイルに書けたなら base64 は重複した重い情報でしかない
291
+ delete result.base64;
292
+ }
293
+ return result;
294
+ }
295
+
296
+ /* ---- encode ---- */
297
+ const hasText = typeof opts.text === 'string';
298
+ if (hasText === Boolean(opts.path)) throw new Base64Error('encode には text か path のどちらか一方を渡してください');
299
+
300
+ let bytes;
301
+ let name = null;
302
+ if (hasText) {
303
+ bytes = new TextEncoder().encode(opts.text);
304
+ } else {
305
+ bytes = new Uint8Array(await readFile(opts.path));
306
+ name = basename(opts.path);
307
+ }
308
+
309
+ const sniffed = sniffType(bytes);
310
+ // テキストで渡されても中身がSVGなら画像として扱う(SVGソースを貼って data URI を作る用途が多いため)
311
+ const mimeType = opts.mimeType
312
+ || (hasText && sniffed.mimeType === 'text/plain' ? 'text/plain;charset=utf-8' : sniffed.mimeType);
313
+ const raw = bytesToBase64(bytes);
314
+ const wrap = Number(opts.wrap) > 0 ? Math.floor(Number(opts.wrap)) : 0;
315
+ const base64 = formatBase64(raw, { urlSafe: Boolean(opts.urlSafe), wrap });
316
+
317
+ const result = {
318
+ mode: 'encode',
319
+ source: name ? { path: opts.path, name } : { type: 'text' },
320
+ mime_type: mimeType,
321
+ bytes: bytes.length,
322
+ size_human: fmtBytes(bytes.length),
323
+ base64,
324
+ base64_length: base64.length,
325
+ url_safe: Boolean(opts.urlSafe),
326
+ wrap: wrap || null,
327
+ growth: bytes.length ? `+${Math.round((raw.length / bytes.length - 1) * 100)}%` : '+0%',
328
+ };
329
+
330
+ // data URI は「ファイルを読んだとき」と「明示的に要求されたとき」に返す
331
+ if (opts.dataUri || !hasText) {
332
+ const isSvg = mimeType === 'image/svg+xml' && sniffed.text !== null;
333
+ const base64Uri = 'data:' + mimeType + ';base64,' + raw;
334
+ const percentUri = isSvg ? svgPercentDataUri(sniffed.text) : '';
335
+ // SVGはbase64(必ず約1.33倍)よりパーセントエンコードの方が小さいので、短い方を既定にする
336
+ const uri = percentUri && percentUri.length <= base64Uri.length ? percentUri : base64Uri;
337
+ result.data_uri = uri;
338
+ result.data_uri_length = uri.length;
339
+ if (percentUri) {
340
+ result.data_uri_base64 = base64Uri;
341
+ result.data_uri_percent = percentUri;
342
+ result.data_uri_encoding = uri === percentUri ? 'percent' : 'base64';
343
+ }
344
+ if (opts.snippets) {
345
+ const size = isSvg ? svgSize(sniffed.text) : { width: 0, height: 0 };
346
+ const snippets = buildSnippets(uri, { ...size, mimeType });
347
+ if (snippets) result.snippets = snippets;
348
+ // 寸法が読めなかった画像は、レイアウトシフト対策の width/height を補えないことを伝える
349
+ if (snippets && !size.width) result.snippets_note = 'width/height は読み取れなかったため省略しました(レイアウトシフト対策として手動で追記してください)';
350
+ }
351
+ if (bytes.length > 10240) {
352
+ result.warning = '10 KBを超えています。大きなファイルの埋め込みはHTML/CSSのキャッシュを妨げ初回表示も遅くなるため、通常のファイル参照を推奨します。';
353
+ }
354
+ }
355
+ return result;
356
+ }