atl-fetch 1.2.0 → 1.2.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.
@@ -2,667 +2,14 @@
2
2
  * テキスト変換サービス
3
3
  *
4
4
  * Jira の ADF(Atlassian Document Format)と Confluence の Storage Format を
5
- * プレーンテキストに変換する機能を提供する。
6
- * また、Confluence の Storage Format を Markdown に変換する機能も提供する。
5
+ * プレーンテキストや Markdown に変換する機能を提供する。
7
6
  */
8
- import TurndownService from 'turndown';
9
- import { gfm } from 'turndown-plugin-gfm';
10
- /**
11
- * 入力が ADF ドキュメント形式かどうかを判定する
12
- *
13
- * @param input 入力値
14
- * @returns ADF ドキュメント形式の場合 true
15
- */
16
- const isAdfDocument = (input) => {
17
- if (typeof input !== 'object' || input === null) {
18
- return false;
19
- }
20
- const doc = input;
21
- return doc['type'] === 'doc' && Array.isArray(doc['content']);
22
- };
23
- /**
24
- * ADF ノードからプレーンテキストを抽出する
25
- *
26
- * @param node ADF ノード
27
- * @returns 抽出されたプレーンテキスト
28
- */
29
- const extractTextFromAdfNode = (node) => {
30
- // テキストノードの場合
31
- if (node.type === 'text' && node.text !== undefined) {
32
- return node.text;
33
- }
34
- // 硬い改行の場合
35
- if (node.type === 'hardBreak') {
36
- return '\n';
37
- }
38
- // メンションの場合
39
- if (node.type === 'mention' && node.attrs !== undefined) {
40
- const text = node.attrs['text'];
41
- if (typeof text === 'string') {
42
- return text;
43
- }
44
- return '@ユーザー';
45
- }
46
- // 絵文字の場合
47
- if (node.type === 'emoji' && node.attrs !== undefined) {
48
- const text = node.attrs['text'];
49
- const shortName = node.attrs['shortName'];
50
- if (typeof text === 'string') {
51
- return text;
52
- }
53
- if (typeof shortName === 'string') {
54
- return shortName;
55
- }
56
- return '';
57
- }
58
- // メディアの場合
59
- if (node.type === 'media') {
60
- return '[添付ファイル]';
61
- }
62
- // mediaSingle の場合(メディアコンテナ)
63
- if (node.type === 'mediaSingle' && node.content !== undefined) {
64
- return node.content.map(extractTextFromAdfNode).join('');
65
- }
66
- // 子ノードがある場合は再帰的に処理
67
- if (node.content !== undefined && Array.isArray(node.content)) {
68
- const texts = node.content.map(extractTextFromAdfNode);
69
- // パラグラフや見出しの後には改行を追加
70
- if (node.type === 'paragraph' || node.type === 'heading') {
71
- return texts.join('');
72
- }
73
- // リストアイテムの後には改行を追加
74
- if (node.type === 'listItem') {
75
- return `${texts.join('')}\n`;
76
- }
77
- // テーブルセルとヘッダーはタブで区切る
78
- if (node.type === 'tableCell' || node.type === 'tableHeader') {
79
- return `${texts.join('')}\t`;
80
- }
81
- // テーブル行は改行で区切る
82
- if (node.type === 'tableRow') {
83
- return `${texts.join('').trimEnd()}\n`;
84
- }
85
- return texts.join('');
86
- }
87
- return '';
88
- };
89
- /**
90
- * ADF ドキュメントのトップレベルコンテンツを処理する
91
- *
92
- * @param content トップレベルのコンテンツ配列
93
- * @returns プレーンテキスト
94
- */
95
- const processAdfContent = (content) => {
96
- const results = [];
97
- for (const node of content) {
98
- const text = extractTextFromAdfNode(node);
99
- if (text !== '') {
100
- results.push(text);
101
- }
102
- }
103
- // パラグラフや見出しは改行で結合
104
- return results.join('\n');
105
- };
106
- /**
107
- * ADF(Atlassian Document Format)をプレーンテキストに変換する
108
- *
109
- * @param adf ADF ドキュメント(オブジェクトまたは JSON 文字列)
110
- * @returns プレーンテキスト
111
- */
112
- export const convertAdfToPlainText = (adf) => {
113
- // null または undefined の場合は空文字列を返す
114
- if (adf === null || adf === undefined) {
115
- return '';
116
- }
117
- // 文字列の場合は JSON としてパースを試みる
118
- if (typeof adf === 'string') {
119
- try {
120
- const parsed = JSON.parse(adf);
121
- if (isAdfDocument(parsed)) {
122
- return processAdfContent(parsed.content);
123
- }
124
- }
125
- catch {
126
- // JSON パースに失敗した場合は元の文字列を返す
127
- return adf;
128
- }
129
- // パースできたが ADF 形式でない場合は元の文字列を返す
130
- return adf;
131
- }
132
- // オブジェクトの場合は ADF ドキュメントとして処理
133
- if (isAdfDocument(adf)) {
134
- return processAdfContent(adf.content);
135
- }
136
- return '';
137
- };
138
- // ============================================================
139
- // ADF → Markdown 変換(Confluence と同じ TurndownService を使用)
140
- // ============================================================
141
- /**
142
- * HTML 特殊文字をエスケープする
143
- *
144
- * @param text エスケープ対象の文字列
145
- * @returns エスケープ済み文字列
146
- */
147
- const escapeHtml = (text) => {
148
- return text
149
- .replace(/&/g, '&')
150
- .replace(/</g, '&lt;')
151
- .replace(/>/g, '&gt;')
152
- .replace(/"/g, '&quot;')
153
- .replace(/'/g, '&#39;');
154
- };
155
- /**
156
- * ADF マークを HTML タグで囲む
157
- *
158
- * @param text 対象のテキスト
159
- * @param marks 適用するマーク配列
160
- * @returns マークを適用した HTML
161
- */
162
- const applyMarksToHtml = (text, marks) => {
163
- let result = text;
164
- for (const mark of marks) {
165
- switch (mark.type) {
166
- case 'strong':
167
- result = `<strong>${result}</strong>`;
168
- break;
169
- case 'em':
170
- result = `<em>${result}</em>`;
171
- break;
172
- case 'code':
173
- result = `<code>${result}</code>`;
174
- break;
175
- case 'strike':
176
- result = `<s>${result}</s>`;
177
- break;
178
- case 'underline':
179
- result = `<u>${result}</u>`;
180
- break;
181
- case 'link': {
182
- const href = mark.attrs?.['href'];
183
- if (typeof href === 'string') {
184
- result = `<a href="${escapeHtml(href)}">${result}</a>`;
185
- }
186
- break;
187
- }
188
- case 'textColor': {
189
- const color = mark.attrs?.['color'];
190
- if (typeof color === 'string') {
191
- result = `<span style="color: ${escapeHtml(color)}">${result}</span>`;
192
- }
193
- break;
194
- }
195
- case 'subsup': {
196
- const subType = mark.attrs?.['type'];
197
- if (subType === 'sub') {
198
- result = `<sub>${result}</sub>`;
199
- }
200
- else if (subType === 'sup') {
201
- result = `<sup>${result}</sup>`;
202
- }
203
- break;
204
- }
205
- // 未知のマークタイプは無視
206
- default:
207
- break;
208
- }
209
- }
210
- return result;
211
- };
212
- /**
213
- * ADF ノードを HTML に変換する
214
- *
215
- * @param node ADF ノード
216
- * @param attachmentPaths 添付ファイル ID → ローカルパスのマッピング
217
- * @returns HTML 文字列
218
- */
219
- const convertAdfNodeToHtml = (node, attachmentPaths) => {
220
- // テキストノードの場合
221
- if (node.type === 'text' && node.text !== undefined) {
222
- const escapedText = escapeHtml(node.text);
223
- if (node.marks !== undefined && node.marks.length > 0) {
224
- return applyMarksToHtml(escapedText, node.marks);
225
- }
226
- return escapedText;
227
- }
228
- // hardBreak の場合
229
- if (node.type === 'hardBreak') {
230
- return '<br>';
231
- }
232
- // rule(水平線)の場合
233
- if (node.type === 'rule') {
234
- return '<hr>';
235
- }
236
- // メンションの場合
237
- if (node.type === 'mention' && node.attrs !== undefined) {
238
- const text = node.attrs['text'];
239
- if (typeof text === 'string') {
240
- return escapeHtml(text);
241
- }
242
- return '@ユーザー';
243
- }
244
- // 絵文字の場合
245
- if (node.type === 'emoji' && node.attrs !== undefined) {
246
- const text = node.attrs['text'];
247
- const shortName = node.attrs['shortName'];
248
- if (typeof text === 'string') {
249
- return text;
250
- }
251
- if (typeof shortName === 'string') {
252
- return shortName;
253
- }
254
- return '';
255
- }
256
- // media ノードの場合(添付ファイル)
257
- if (node.type === 'media' && node.attrs !== undefined) {
258
- const mediaId = node.attrs['id'];
259
- const mediaType = node.attrs['type'];
260
- if (typeof mediaId === 'string' && attachmentPaths?.[mediaId] !== undefined) {
261
- const localPath = attachmentPaths[mediaId];
262
- const alt = typeof node.attrs['alt'] === 'string' ? node.attrs['alt'] : mediaId;
263
- return `<img src="${escapeHtml(localPath)}" alt="${escapeHtml(alt)}">`;
264
- }
265
- // 外部リンクの場合
266
- if (mediaType === 'external' || mediaType === 'link') {
267
- const url = node.attrs['url'];
268
- if (typeof url === 'string') {
269
- return `<img src="${escapeHtml(url)}" alt="">`;
270
- }
271
- }
272
- // マッピングがない場合はプレースホルダー
273
- return '[添付ファイル]';
274
- }
275
- // mediaSingle(メディアコンテナ)の場合
276
- if (node.type === 'mediaSingle' && node.content !== undefined) {
277
- return node.content.map((child) => convertAdfNodeToHtml(child, attachmentPaths)).join('');
278
- }
279
- // mediaGroup の場合
280
- if (node.type === 'mediaGroup' && node.content !== undefined) {
281
- return node.content.map((child) => convertAdfNodeToHtml(child, attachmentPaths)).join('');
282
- }
283
- // inlineCard(インラインリンク)の場合
284
- if (node.type === 'inlineCard' && node.attrs !== undefined) {
285
- const url = node.attrs['url'];
286
- if (typeof url === 'string') {
287
- return `<a href="${escapeHtml(url)}">${escapeHtml(url)}</a>`;
288
- }
289
- return '';
290
- }
291
- // blockCard(ブロックリンク)の場合
292
- if (node.type === 'blockCard' && node.attrs !== undefined) {
293
- const url = node.attrs['url'];
294
- if (typeof url === 'string') {
295
- return `<p><a href="${escapeHtml(url)}">${escapeHtml(url)}</a></p>`;
296
- }
297
- return '';
298
- }
299
- // 子ノードがある場合
300
- if (node.content !== undefined && Array.isArray(node.content)) {
301
- const childrenHtml = node.content.map((child) => convertAdfNodeToHtml(child, attachmentPaths)).join('');
302
- switch (node.type) {
303
- case 'doc':
304
- return childrenHtml;
305
- case 'paragraph':
306
- return `<p>${childrenHtml}</p>`;
307
- case 'heading': {
308
- const level = typeof node.attrs?.['level'] === 'number' ? node.attrs['level'] : 1;
309
- const safeLevel = Math.max(1, Math.min(6, level));
310
- return `<h${safeLevel}>${childrenHtml}</h${safeLevel}>`;
311
- }
312
- case 'bulletList':
313
- return `<ul>${childrenHtml}</ul>`;
314
- case 'orderedList':
315
- return `<ol>${childrenHtml}</ol>`;
316
- case 'listItem':
317
- return `<li>${childrenHtml}</li>`;
318
- case 'blockquote':
319
- return `<blockquote>${childrenHtml}</blockquote>`;
320
- case 'codeBlock': {
321
- const language = typeof node.attrs?.['language'] === 'string' ? node.attrs['language'] : '';
322
- const langClass = language ? ` class="language-${escapeHtml(language)}"` : '';
323
- // コードブロック内のテキストは子ノードから取得
324
- const codeText = node.content
325
- .map((child) => (child.type === 'text' && child.text !== undefined ? child.text : ''))
326
- .join('');
327
- return `<pre><code${langClass}>${escapeHtml(codeText)}</code></pre>`;
328
- }
329
- case 'table':
330
- return `<table>${childrenHtml}</table>`;
331
- case 'tableRow':
332
- return `<tr>${childrenHtml}</tr>`;
333
- case 'tableHeader':
334
- return `<th>${childrenHtml}</th>`;
335
- case 'tableCell':
336
- return `<td>${childrenHtml}</td>`;
337
- case 'panel': {
338
- // panel タイプを GitHub Alerts 形式に変換
339
- const panelType = typeof node.attrs?.['panelType'] === 'string' ? node.attrs['panelType'] : 'info';
340
- const alertTypeMap = {
341
- error: 'WARNING',
342
- info: 'NOTE',
343
- note: 'NOTE',
344
- success: 'TIP',
345
- warning: 'WARNING',
346
- };
347
- const alertType = alertTypeMap[panelType] || 'NOTE';
348
- return `<blockquote data-github-alert="${alertType}">${childrenHtml}</blockquote>`;
349
- }
350
- // 未知のノードタイプは子ノードの内容を返す
351
- default:
352
- return childrenHtml;
353
- }
354
- }
355
- // 子ノードもテキストもない場合は空文字列
356
- return '';
357
- };
358
- /**
359
- * ADF ドキュメントを HTML に変換する
360
- *
361
- * @param content ADF ドキュメントのコンテンツ配列
362
- * @param attachmentPaths 添付ファイル ID → ローカルパスのマッピング
363
- * @returns HTML 文字列
364
- */
365
- const convertAdfContentToHtml = (content, attachmentPaths) => {
366
- return content.map((node) => convertAdfNodeToHtml(node, attachmentPaths)).join('');
367
- };
368
- /**
369
- * HTML エンティティをデコードする
370
- *
371
- * @param text エンコードされた文字列
372
- * @returns デコードされた文字列
373
- */
374
- const decodeHtmlEntities = (text) => {
375
- return text
376
- .replace(/&nbsp;/g, ' ')
377
- .replace(/&amp;/g, '&')
378
- .replace(/&lt;/g, '<')
379
- .replace(/&gt;/g, '>')
380
- .replace(/&quot;/g, '"')
381
- .replace(/&#39;/g, "'")
382
- .replace(/&#x27;/g, "'")
383
- .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number.parseInt(code, 10)));
384
- };
385
- /**
386
- * CDATA セクションからテキストを抽出する
387
- *
388
- * @param html HTML 文字列
389
- * @returns CDATA セクションを処理した文字列
390
- */
391
- const extractCdata = (html) => {
392
- return html.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
393
- };
394
- /**
395
- * Confluence マクロのパラメータからテキストを抽出する
396
- *
397
- * @param html HTML 文字列
398
- * @returns 処理された文字列
399
- */
400
- const extractMacroParameters = (html) => {
401
- // ac:parameter タグから title などのテキストを抽出
402
- return html.replace(/<ac:parameter[^>]*ac:name="title"[^>]*>([^<]*)<\/ac:parameter>/g, '$1');
403
- };
404
- /**
405
- * 画像タグをプレースホルダーに変換する
406
- *
407
- * @param html HTML 文字列
408
- * @returns 処理された文字列
409
- */
410
- const convertImagesToPlaceholders = (html) => {
411
- // ac:image タグと ri:attachment から画像ファイル名を抽出
412
- return html.replace(/<ac:image[^>]*>[\s\S]*?<ri:attachment\s+ri:filename="([^"]*)"[^>]*\/>[\s\S]*?<\/ac:image>/g, '[画像: $1]');
413
- };
414
- /**
415
- * ユーザーリンクをプレースホルダーに変換する
416
- *
417
- * @param html HTML 文字列
418
- * @returns 処理された文字列
419
- */
420
- const convertUserLinksToPlaceholders = (html) => {
421
- // ri:user タグをプレースホルダーに変換
422
- return html.replace(/<ac:link[^>]*>[\s\S]*?<ri:user[^>]*\/>[\s\S]*?<\/ac:link>/g, '[ユーザー]');
423
- };
424
- /**
425
- * ブロック要素のタグを処理して改行を適切に挿入する
426
- *
427
- * @param html HTML 文字列
428
- * @returns 処理された文字列
429
- */
430
- const processBlockElements = (html) => {
431
- // 閉じタグの前後に改行マーカーを追加
432
- let result = html;
433
- // パラグラフと見出しの後に改行
434
- result = result.replace(/<\/(p|h[1-6])>/gi, '</$1>\n');
435
- // リストアイテムの後に改行
436
- result = result.replace(/<\/li>/gi, '</li>\n');
437
- // テーブル行の後に改行
438
- result = result.replace(/<\/tr>/gi, '</tr>\n');
439
- // テーブルセルの後にタブ
440
- result = result.replace(/<\/(td|th)>/gi, '\t</$1>');
441
- // br タグを改行に変換
442
- result = result.replace(/<br\s*\/?>/gi, '\n');
443
- // blockquote の後に改行
444
- result = result.replace(/<\/blockquote>/gi, '</blockquote>\n');
445
- return result;
446
- };
447
- /**
448
- * HTML タグを除去する
449
- *
450
- * @param html HTML 文字列
451
- * @returns タグを除去した文字列
452
- */
453
- const stripHtmlTags = (html) => {
454
- return html.replace(/<[^>]*>/g, '');
455
- };
456
- /**
457
- * 連続する空白を正規化する
458
- *
459
- * @param text テキスト
460
- * @returns 正規化されたテキスト
461
- */
462
- const normalizeWhitespace = (text) => {
463
- // 行ごとに処理
464
- const lines = text.split('\n');
465
- const normalizedLines = lines.map((line) => {
466
- // 行内の連続する空白を単一スペースに
467
- return line.replace(/[ \t]+/g, ' ').trim();
468
- });
469
- // 空行を除去して結合
470
- return normalizedLines.filter((line) => line !== '').join('\n');
471
- };
472
- /**
473
- * Confluence の Storage Format(XHTML)をプレーンテキストに変換する
474
- *
475
- * @param storageFormat Storage Format 文字列
476
- * @returns プレーンテキスト
477
- */
478
- export const convertStorageFormatToPlainText = (storageFormat) => {
479
- // null または undefined の場合は空文字列を返す
480
- if (storageFormat === null || storageFormat === undefined || storageFormat === '') {
481
- return '';
482
- }
483
- let result = storageFormat;
484
- // CDATA セクションを処理
485
- result = extractCdata(result);
486
- // マクロパラメータからテキストを抽出
487
- result = extractMacroParameters(result);
488
- // 画像をプレースホルダーに変換
489
- result = convertImagesToPlaceholders(result);
490
- // ユーザーリンクをプレースホルダーに変換
491
- result = convertUserLinksToPlaceholders(result);
492
- // ブロック要素を処理
493
- result = processBlockElements(result);
494
- // HTML タグを除去
495
- result = stripHtmlTags(result);
496
- // HTML エンティティをデコード
497
- result = decodeHtmlEntities(result);
498
- // 空白を正規化
499
- result = normalizeWhitespace(result);
500
- return result;
501
- };
502
- /**
503
- * テーブルが Markdown に変換可能か判定する
504
- * - セル結合(colspan/rowspan)がないこと
505
- * - セル内改行(<br>)がないこと
506
- *
507
- * @param tableHtml テーブルの HTML 文字列
508
- * @returns 変換可能な場合 true
509
- */
510
- const isTableConvertibleToMarkdown = (tableHtml) => {
511
- // colspan/rowspan 属性チェック
512
- const hasCellMerge = /\b(colspan|rowspan)\s*=/i.test(tableHtml);
513
- // セル内 <br> チェック(<td> または <th> 内の <br>)
514
- const hasCellBreak = /<t[dh][^>]*>[\s\S]*?<br[\s/]*>[\s\S]*?<\/t[dh]>/i.test(tableHtml);
515
- return !hasCellMerge && !hasCellBreak;
516
- };
517
- /**
518
- * 前処理: 無視する要素を削除し、Confluence 固有タグを処理
519
- *
520
- * @param html HTML 文字列
521
- * @param attachmentPaths 添付ファイルマッピング
522
- * @returns 前処理済み HTML
523
- */
524
- const preprocessHtmlForMarkdown = (html, attachmentPaths) => {
525
- let result = html;
526
- // colgroup/col を削除
527
- result = result.replace(/<colgroup[\s\S]*?<\/colgroup>/gi, '');
528
- result = result.replace(/<col[^>]*\/?>/gi, '');
529
- // data-highlight-colour 属性を削除
530
- result = result.replace(/\s*data-highlight-colour="[^"]*"/gi, '');
531
- // ac:local-id, local-id 属性を削除
532
- result = result.replace(/\s*(ac:)?local-id="[^"]*"/gi, '');
533
- // ac:inline-comment-marker を内容のみに置換
534
- result = result.replace(/<ac:inline-comment-marker[^>]*>([\s\S]*?)<\/ac:inline-comment-marker>/gi, '$1');
535
- // CDATA セクションを処理
536
- result = result.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
537
- // --------------------------------------------------
538
- // Confluence 固有タグを標準 HTML タグに変換(turndown が認識できる形式へ)
539
- // --------------------------------------------------
540
- // ac:image + ac:caption を <img> + <figcaption> に変換(キャプション付きを先に処理)
541
- result = result.replace(/<ac:image[^>]*>[\s\S]*?<ri:attachment[^>]*ri:filename="([^"]*)"[^>]*\/?>[\s\S]*?<ac:caption>([^<]*)<\/ac:caption>[\s\S]*?<\/ac:image>/gi, (_match, filename, caption) => {
542
- const localPath = attachmentPaths?.[filename] || filename;
543
- return `<figure><img src="${localPath}" alt="${filename}"><figcaption>${caption}</figcaption></figure>`;
544
- });
545
- // ac:image を <img> に変換(キャプションなしの残り)
546
- result = result.replace(/<ac:image[^>]*>[\s\S]*?<ri:attachment[^>]*ri:filename="([^"]*)"[^>]*\/?>[\s\S]*?<\/ac:image>/gi, (_match, filename) => {
547
- const localPath = attachmentPaths?.[filename] || filename;
548
- return `<img src="${localPath}" alt="${filename}">`;
549
- });
550
- // ac:structured-macro name="code" を <pre><code> に変換
551
- result = result.replace(/<ac:structured-macro[^>]*ac:name="code"[^>]*>([\s\S]*?)<\/ac:structured-macro>/gi, (_match, innerContent) => {
552
- // language パラメータを抽出
553
- const langMatch = innerContent.match(/<ac:parameter[^>]*ac:name="language"[^>]*>([^<]*)<\/ac:parameter>/i);
554
- const lang = langMatch?.[1] || '';
555
- // plain-text-body の内容を抽出
556
- const bodyMatch = innerContent.match(/<ac:plain-text-body[^>]*>([\s\S]*?)<\/ac:plain-text-body>/i);
557
- const code = bodyMatch?.[1] || '';
558
- // turndown が認識できる形式に変換
559
- const langClass = lang ? ` class="language-${lang}"` : '';
560
- return `<pre><code${langClass}>${code}</code></pre>`;
561
- });
562
- // ac:structured-macro name="info/note/tip/warning" を GitHub Alerts 形式の blockquote に変換
563
- const alertMacros = ['info', 'note', 'tip', 'warning'];
564
- const alertTypeMap = {
565
- info: 'NOTE',
566
- note: 'NOTE',
567
- tip: 'TIP',
568
- warning: 'WARNING',
569
- };
570
- for (const macroName of alertMacros) {
571
- const pattern = new RegExp(`<ac:structured-macro[^>]*ac:name="${macroName}"[^>]*>[\\s\\S]*?<ac:rich-text-body>([\\s\\S]*?)<\\/ac:rich-text-body>[\\s\\S]*?<\\/ac:structured-macro>`, 'gi');
572
- result = result.replace(pattern, (_match, content) => {
573
- const alertType = alertTypeMap[macroName] || 'NOTE';
574
- // 専用のマーカー属性を持つ blockquote に変換
575
- return `<blockquote data-github-alert="${alertType}">${content}</blockquote>`;
576
- });
577
- }
578
- return result;
579
- };
580
- /**
581
- * TurndownService インスタンスを作成する(共通設定)
582
- * Jira ADF と Confluence Storage Format の両方で使用する
583
- *
584
- * @returns 設定済みの TurndownService インスタンス
585
- */
586
- const createTurndownService = () => {
587
- const turndownService = new TurndownService({
588
- bulletListMarker: '-',
589
- codeBlockStyle: 'fenced',
590
- emDelimiter: '*',
591
- headingStyle: 'atx',
592
- strongDelimiter: '**',
593
- });
594
- // GFM プラグイン(テーブル、取り消し線など)を使用
595
- turndownService.use(gfm);
596
- // カスタムルール: キャプション付き画像(<figure>)
597
- turndownService.addRule('figureWithCaption', {
598
- filter: (node) => {
599
- return node.nodeName === 'FIGURE';
600
- },
601
- replacement: (_content, node) => {
602
- const element = node;
603
- const img = element.querySelector('img');
604
- const figcaption = element.querySelector('figcaption');
605
- if (img) {
606
- const src = img.getAttribute('src') || '';
607
- const alt = img.getAttribute('alt') || '';
608
- let result = `![${alt}](${src})`;
609
- if (figcaption) {
610
- const captionText = figcaption.textContent?.trim() || '';
611
- if (captionText) {
612
- result += `\n\n*${captionText}*`;
613
- }
614
- }
615
- return result;
616
- }
617
- return '';
618
- },
619
- });
620
- // カスタムルール: GitHub Alerts(<blockquote data-github-alert="...">)
621
- turndownService.addRule('githubAlerts', {
622
- filter: (node) => {
623
- if (node.nodeName !== 'BLOCKQUOTE')
624
- return false;
625
- return node.hasAttribute('data-github-alert');
626
- },
627
- replacement: (content, node) => {
628
- const element = node;
629
- const alertType = element.getAttribute('data-github-alert') || 'NOTE';
630
- // 内容を再帰的に Markdown 変換
631
- const innerMarkdown = content.trim();
632
- // 各行に > プレフィックス付加
633
- const lines = innerMarkdown.split('\n');
634
- const quotedContent = lines.map((line) => `> ${line}`).join('\n');
635
- return `\n> [!${alertType}]\n${quotedContent}\n`;
636
- },
637
- });
638
- // カスタムルール: 色変更テキスト(HTML のまま出力)
639
- turndownService.addRule('coloredText', {
640
- filter: (node) => {
641
- if (node.nodeName !== 'SPAN')
642
- return false;
643
- const style = node.getAttribute('style') || '';
644
- return style.includes('color:') || style.includes('color :');
645
- },
646
- replacement: (_content, node) => {
647
- // HTML のまま出力
648
- return node.outerHTML;
649
- },
650
- });
651
- // カスタムルール: セル結合/セル内改行のあるテーブル(HTML のまま出力)
652
- turndownService.addRule('complexTable', {
653
- filter: (node) => {
654
- if (node.nodeName !== 'TABLE')
655
- return false;
656
- const tableHtml = node.outerHTML;
657
- return !isTableConvertibleToMarkdown(tableHtml);
658
- },
659
- replacement: (_content, node) => {
660
- // HTML のまま出力
661
- return node.outerHTML;
662
- },
663
- });
664
- return turndownService;
665
- };
7
+ import { convertAdfContentToHtml } from './adf-to-html.js';
8
+ import { createTurndownService, preprocessHtmlForMarkdown } from './markdown-utils.js';
9
+ import { isAdfDocument } from './types.js';
10
+ // 公開 API の再エクスポート
11
+ export { convertAdfToPlainText } from './adf-to-plain-text.js';
12
+ export { convertStorageFormatToPlainText } from './storage-to-plain-text.js';
666
13
  /**
667
14
  * ADF(Atlassian Document Format)を Markdown に変換する
668
15
  *
@@ -725,230 +72,3 @@ export const convertStorageFormatToMarkdown = (storageFormat, attachmentPaths) =
725
72
  // 末尾の空白を除去
726
73
  return markdown.trim();
727
74
  };
728
- // ============================================================
729
- // In-source Testing(プライベート関数のテスト)
730
- // ============================================================
731
- if (import.meta.vitest) {
732
- const { describe, expect, it } = import.meta.vitest;
733
- describe('extractTextFromAdfNode (in-source testing)', () => {
734
- // テストの目的: hardBreak が正確に '\n' を返すこと
735
- describe('hardBreak の戻り値検証', () => {
736
- it('Given: hardBreak ノード, When: extractTextFromAdfNode を呼び出す, Then: 厳密に "\\n" が返される', () => {
737
- // Given: hardBreak ノード
738
- const node = { type: 'hardBreak' };
739
- // When: extractTextFromAdfNode を呼び出す
740
- const result = extractTextFromAdfNode(node);
741
- // Then: 厳密に '\n' が返される
742
- expect(result).toBe('\n');
743
- expect(result.length).toBe(1);
744
- expect(result.charCodeAt(0)).toBe(10); // LF のコードポイント
745
- });
746
- });
747
- // テストの目的: media ノードが '[添付ファイル]' を返すこと
748
- describe('media の戻り値検証', () => {
749
- it('Given: media ノード, When: extractTextFromAdfNode を呼び出す, Then: 厳密に "[添付ファイル]" が返される', () => {
750
- // Given: media ノード
751
- const node = { attrs: { id: 'test-123' }, type: 'media' };
752
- // When: extractTextFromAdfNode を呼び出す
753
- const result = extractTextFromAdfNode(node);
754
- // Then: 厳密に '[添付ファイル]' が返される
755
- expect(result).toBe('[添付ファイル]');
756
- expect(result.length).toBe(8);
757
- });
758
- });
759
- // テストの目的: mention で text がない場合 '@ユーザー' を返すこと
760
- describe('mention のデフォルトプレースホルダー検証', () => {
761
- it('Given: text のない mention, When: extractTextFromAdfNode を呼び出す, Then: 厳密に "@ユーザー" が返される', () => {
762
- // Given: text のない mention
763
- const node = { attrs: { id: 'user-123' }, type: 'mention' };
764
- // When: extractTextFromAdfNode を呼び出す
765
- const result = extractTextFromAdfNode(node);
766
- // Then: 厳密に '@ユーザー' が返される
767
- expect(result).toBe('@ユーザー');
768
- expect(result.length).toBe(5);
769
- });
770
- });
771
- // テストの目的: listItem が末尾に改行を追加すること
772
- describe('listItem の末尾改行検証', () => {
773
- it('Given: listItem ノード, When: extractTextFromAdfNode を呼び出す, Then: 末尾に改行が付く', () => {
774
- // Given: listItem ノード
775
- const node = {
776
- content: [{ content: [{ text: 'アイテム', type: 'text' }], type: 'paragraph' }],
777
- type: 'listItem',
778
- };
779
- // When: extractTextFromAdfNode を呼び出す
780
- const result = extractTextFromAdfNode(node);
781
- // Then: 末尾に改行が付く
782
- expect(result).toBe('アイテム\n');
783
- expect(result.endsWith('\n')).toBe(true);
784
- });
785
- });
786
- // テストの目的: tableCell がタブで終わること
787
- describe('tableCell の末尾タブ検証', () => {
788
- it('Given: tableCell ノード, When: extractTextFromAdfNode を呼び出す, Then: 末尾にタブが付く', () => {
789
- // Given: tableCell ノード
790
- const node = {
791
- content: [{ content: [{ text: 'セル', type: 'text' }], type: 'paragraph' }],
792
- type: 'tableCell',
793
- };
794
- // When: extractTextFromAdfNode を呼び出す
795
- const result = extractTextFromAdfNode(node);
796
- // Then: 末尾にタブが付く
797
- expect(result).toBe('セル\t');
798
- expect(result.endsWith('\t')).toBe(true);
799
- });
800
- });
801
- // テストの目的: tableRow が末尾の空白を削除して改行を追加すること
802
- describe('tableRow の処理検証', () => {
803
- it('Given: tableRow ノード, When: extractTextFromAdfNode を呼び出す, Then: 末尾のタブが削除されて改行が付く', () => {
804
- // Given: tableRow ノード
805
- const node = {
806
- content: [
807
- { content: [{ content: [{ text: 'A', type: 'text' }], type: 'paragraph' }], type: 'tableCell' },
808
- { content: [{ content: [{ text: 'B', type: 'text' }], type: 'paragraph' }], type: 'tableCell' },
809
- ],
810
- type: 'tableRow',
811
- };
812
- // When: extractTextFromAdfNode を呼び出す
813
- const result = extractTextFromAdfNode(node);
814
- // Then: 末尾の空白が削除されて改行が付く
815
- expect(result).toBe('A\tB\n');
816
- });
817
- });
818
- // テストの目的: 未知のノードタイプが空文字列を返すこと
819
- describe('未知のノードタイプの処理', () => {
820
- it('Given: 未知のノードタイプ, When: extractTextFromAdfNode を呼び出す, Then: 空文字列が返される', () => {
821
- // Given: 未知のノードタイプ
822
- const node = { type: 'unknownType' };
823
- // When: extractTextFromAdfNode を呼び出す
824
- const result = extractTextFromAdfNode(node);
825
- // Then: 空文字列が返される
826
- expect(result).toBe('');
827
- });
828
- });
829
- });
830
- describe('decodeHtmlEntities (in-source testing)', () => {
831
- // テストの目的: 各エンティティが正確に変換されること
832
- describe('個別エンティティの変換検証', () => {
833
- it('Given: &nbsp;, When: decodeHtmlEntities を呼び出す, Then: スペースに変換される', () => {
834
- expect(decodeHtmlEntities('&nbsp;')).toBe(' ');
835
- });
836
- it('Given: &amp;, When: decodeHtmlEntities を呼び出す, Then: & に変換される', () => {
837
- expect(decodeHtmlEntities('&amp;')).toBe('&');
838
- });
839
- it('Given: &lt;, When: decodeHtmlEntities を呼び出す, Then: < に変換される', () => {
840
- expect(decodeHtmlEntities('&lt;')).toBe('<');
841
- });
842
- it('Given: &gt;, When: decodeHtmlEntities を呼び出す, Then: > に変換される', () => {
843
- expect(decodeHtmlEntities('&gt;')).toBe('>');
844
- });
845
- it('Given: &quot;, When: decodeHtmlEntities を呼び出す, Then: " に変換される', () => {
846
- expect(decodeHtmlEntities('&quot;')).toBe('"');
847
- });
848
- it("Given: &#39;, When: decodeHtmlEntities を呼び出す, Then: ' に変換される", () => {
849
- expect(decodeHtmlEntities('&#39;')).toBe("'");
850
- });
851
- it("Given: &#x27;, When: decodeHtmlEntities を呼び出す, Then: ' に変換される", () => {
852
- expect(decodeHtmlEntities('&#x27;')).toBe("'");
853
- });
854
- it('Given: 数値文字参照 &#65;, When: decodeHtmlEntities を呼び出す, Then: A に変換される', () => {
855
- expect(decodeHtmlEntities('&#65;')).toBe('A');
856
- });
857
- it('Given: 数値文字参照 &#12354;, When: decodeHtmlEntities を呼び出す, Then: あ に変換される', () => {
858
- expect(decodeHtmlEntities('&#12354;')).toBe('あ');
859
- });
860
- });
861
- // テストの目的: 複数のエンティティが正しい順序で変換されること
862
- describe('変換順序の検証', () => {
863
- it('Given: &amp;nbsp;, When: decodeHtmlEntities を呼び出す, Then: &nbsp; に変換される(&amp; が先に処理される)', () => {
864
- // &amp;nbsp; → &nbsp; になること(&nbsp; → スペース にはならない)
865
- expect(decodeHtmlEntities('&amp;nbsp;')).toBe('&nbsp;');
866
- });
867
- it('Given: &amp;lt;, When: decodeHtmlEntities を呼び出す, Then: < に変換される(連鎖的に置換される)', () => {
868
- // &amp; -> & になり、その後 &lt; -> < になる
869
- expect(decodeHtmlEntities('&amp;lt;')).toBe('<');
870
- });
871
- });
872
- });
873
- describe('convertImagesToPlaceholders (in-source testing)', () => {
874
- // テストの目的: 画像タグが '[画像: ファイル名]' に変換されること
875
- describe('画像プレースホルダーの検証', () => {
876
- it('Given: ac:image タグ, When: convertImagesToPlaceholders を呼び出す, Then: [画像: filename] 形式になる', () => {
877
- const html = '<ac:image><ri:attachment ri:filename="test.png"/></ac:image>';
878
- const result = convertImagesToPlaceholders(html);
879
- expect(result).toBe('[画像: test.png]');
880
- });
881
- it('Given: 日本語ファイル名の画像, When: convertImagesToPlaceholders を呼び出す, Then: ファイル名がそのまま含まれる', () => {
882
- const html = '<ac:image><ri:attachment ri:filename="テスト画像.png"/></ac:image>';
883
- const result = convertImagesToPlaceholders(html);
884
- expect(result).toBe('[画像: テスト画像.png]');
885
- });
886
- it('Given: 空のファイル名, When: convertImagesToPlaceholders を呼び出す, Then: [画像: ] となる', () => {
887
- const html = '<ac:image><ri:attachment ri:filename=""/></ac:image>';
888
- const result = convertImagesToPlaceholders(html);
889
- expect(result).toBe('[画像: ]');
890
- });
891
- });
892
- });
893
- describe('convertUserLinksToPlaceholders (in-source testing)', () => {
894
- // テストの目的: ユーザーリンクが '[ユーザー]' に変換されること
895
- describe('ユーザープレースホルダーの検証', () => {
896
- it('Given: ri:user タグ, When: convertUserLinksToPlaceholders を呼び出す, Then: [ユーザー] になる', () => {
897
- const html = '<ac:link><ri:user ri:account-id="123"/></ac:link>';
898
- const result = convertUserLinksToPlaceholders(html);
899
- expect(result).toBe('[ユーザー]');
900
- });
901
- it('Given: 複数のユーザーリンク, When: convertUserLinksToPlaceholders を呼び出す, Then: それぞれ [ユーザー] になる', () => {
902
- const html = '<ac:link><ri:user ri:account-id="1"/></ac:link>と<ac:link><ri:user ri:account-id="2"/></ac:link>';
903
- const result = convertUserLinksToPlaceholders(html);
904
- expect(result).toBe('[ユーザー]と[ユーザー]');
905
- });
906
- });
907
- });
908
- describe('normalizeWhitespace (in-source testing)', () => {
909
- // テストの目的: 連続空白が単一スペースに正規化されること
910
- describe('空白正規化の検証', () => {
911
- it('Given: 連続スペース, When: normalizeWhitespace を呼び出す, Then: 単一スペースになる', () => {
912
- expect(normalizeWhitespace('a b')).toBe('a b');
913
- });
914
- it('Given: 連続タブ, When: normalizeWhitespace を呼び出す, Then: 単一スペースになる', () => {
915
- expect(normalizeWhitespace('a\t\t\tb')).toBe('a b');
916
- });
917
- it('Given: 空行, When: normalizeWhitespace を呼び出す, Then: 空行が削除される', () => {
918
- expect(normalizeWhitespace('a\n\n\nb')).toBe('a\nb');
919
- });
920
- it('Given: 先頭末尾の空白, When: normalizeWhitespace を呼び出す, Then: トリムされる', () => {
921
- expect(normalizeWhitespace(' a ')).toBe('a');
922
- });
923
- });
924
- });
925
- describe('isAdfDocument (in-source testing)', () => {
926
- // テストの目的: ADF ドキュメント判定が正しく動作すること
927
- describe('ADF 判定の検証', () => {
928
- it('Given: 有効な ADF, When: isAdfDocument を呼び出す, Then: true が返される', () => {
929
- const doc = { content: [], type: 'doc', version: 1 };
930
- expect(isAdfDocument(doc)).toBe(true);
931
- });
932
- it('Given: type が doc でない, When: isAdfDocument を呼び出す, Then: false が返される', () => {
933
- const doc = { content: [], type: 'paragraph' };
934
- expect(isAdfDocument(doc)).toBe(false);
935
- });
936
- it('Given: content がない, When: isAdfDocument を呼び出す, Then: false が返される', () => {
937
- const doc = { type: 'doc', version: 1 };
938
- expect(isAdfDocument(doc)).toBe(false);
939
- });
940
- it('Given: content が配列でない, When: isAdfDocument を呼び出す, Then: false が返される', () => {
941
- const doc = { content: 'string', type: 'doc', version: 1 };
942
- expect(isAdfDocument(doc)).toBe(false);
943
- });
944
- it('Given: null, When: isAdfDocument を呼び出す, Then: false が返される', () => {
945
- expect(isAdfDocument(null)).toBe(false);
946
- });
947
- it('Given: プリミティブ値, When: isAdfDocument を呼び出す, Then: false が返される', () => {
948
- expect(isAdfDocument('string')).toBe(false);
949
- expect(isAdfDocument(123)).toBe(false);
950
- expect(isAdfDocument(true)).toBe(false);
951
- });
952
- });
953
- });
954
- }