import { MarkdownDocumentFetcher } from "./markdown-document.fetcher.js"; import { TossPaymentsDocument } from "./toss-payments-document.js"; import { RawDocs } from "./types.js"; export class TossPaymentsDocumentLoader { private readonly links: string[] = []; private readonly tossPaymentsDocuments: Map = new Map(); constructor( private readonly rawDocs: RawDocs[], private readonly documentFetcher: MarkdownDocumentFetcher ) { this.rawDocs.forEach((doc) => { if (doc.link) { this.links.push(doc.link); } }); } async load(): Promise { await this.collectAll(); } /** * ID 순으로 돌려준다. * * Map 은 삽입 순서 — 즉 fetch 완료 순서를 유지한다. BM25 의 청크 순회가 이 * 배열 순서를 그대로 물려받고 `Array.prototype.sort` 는 stable 하므로, * 점수가 완전히 같은 문서 사이의 최종 tie-break 가 응답 도착 순서가 된다. */ getDocuments(): TossPaymentsDocument[] { return Array.from(this.tossPaymentsDocuments.values()).sort( (a, b) => a.id - b.id ); } private async collectAll() { // 같은 링크가 여러 번 실려 오면 첫 등장만 싣는다. // // 이전에는 루프 안에서 `tossPaymentsDocuments.has(link)` 로 걸렀는데, 그 체크는 // fetch 의 await 앞에 있고 `map` 콜백은 전부 같은 턴에서 첫 await 까지 실행된다. // 모든 has() 가 어떤 set() 보다 먼저 끝나므로 한 번의 load() 안에서는 절대 // 발동하지 않았다 — 중복이 두 번 fetch 되고, 어느 index 가 살아남을지는 // 응답 도착 순서에 좌우됐다. const firstIndexByLink = new Map(); this.rawDocs.forEach((docs, index) => { if (!firstIndexByLink.has(docs.link)) { firstIndexByLink.set(docs.link, index); } }); await Promise.all( // ID 는 llms.txt 에서의 위치(index)로 정한다. 카운터를 fetch 뒤에서 증가시키면 // 번호가 **응답 도착 순서**로 매겨져 같은 코퍼스를 다시 로드할 때마다 달라진다 // (247건 재로드 실측: 80%가 다른 문서를 가리켰다). this.rawDocs.map(async (docs, index) => { if (firstIndexByLink.get(docs.link) !== index) { return; } try { const tossPaymentDocument = await this.collect(docs, index); this.tossPaymentsDocuments.set(docs.link, tossPaymentDocument); } catch (error) { console.error(`Failed to fetch document from ${docs.link}:`, error); } }) ); } private async collect(docs: RawDocs, id: number) { const document = await this.documentFetcher.fetch(docs.link); const keywordSet = new Set(); document.metadata.keyword.forEach((keyword) => { keywordSet.add(keyword.toLowerCase()); keywordSet.add(keyword.toUpperCase()); keywordSet.add(keyword); }); const tossPaymentDocument = new TossPaymentsDocument( keywordSet, document, docs.version, id, docs.category ); return tossPaymentDocument; } }