(arr: JsonArray, path: string[], depth: number)
| 87 | } |
| 88 | |
| 89 | private chunkArray(arr: JsonArray, path: string[], depth: number): Chunk[] { |
| 90 | const chunks: Chunk[] = [] |
| 91 | let currentBatch: JsonValue[] = [] |
| 92 | let currentTokens = 0 |
| 93 | |
| 94 | const contextHeader = path.length > 0 ? `// ${path.join('.')}\n` : '' |
| 95 | |
| 96 | for (let i = 0; i < arr.length; i++) { |
| 97 | const item = arr[i] |
| 98 | const itemStr = JSON.stringify(item, null, 2) |
| 99 | const itemTokens = estimateTokens(itemStr) |
| 100 | |
| 101 | if (itemTokens > this.chunkSize) { |
| 102 | if (currentBatch.length > 0) { |
| 103 | chunks.push( |
| 104 | this.buildBatchChunk(contextHeader, currentBatch, i - currentBatch.length, i - 1) |
| 105 | ) |
| 106 | currentBatch = [] |
| 107 | currentTokens = 0 |
| 108 | } |
| 109 | |
| 110 | if (depth < MAX_DEPTH && typeof item === 'object' && item !== null) { |
| 111 | chunks.push(...this.chunkStructuredData(item, [...path, `[${i}]`], depth + 1)) |
| 112 | } else { |
| 113 | chunks.push({ |
| 114 | text: contextHeader + itemStr, |
| 115 | tokenCount: itemTokens, |
| 116 | metadata: { startIndex: i, endIndex: i }, |
| 117 | }) |
| 118 | } |
| 119 | } else if (currentTokens + itemTokens > this.chunkSize && currentBatch.length > 0) { |
| 120 | chunks.push( |
| 121 | this.buildBatchChunk(contextHeader, currentBatch, i - currentBatch.length, i - 1) |
| 122 | ) |
| 123 | currentBatch = [item] |
| 124 | currentTokens = itemTokens |
| 125 | } else { |
| 126 | currentBatch.push(item) |
| 127 | currentTokens += itemTokens |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | if (currentBatch.length > 0) { |
| 132 | chunks.push( |
| 133 | this.buildBatchChunk( |
| 134 | contextHeader, |
| 135 | currentBatch, |
| 136 | arr.length - currentBatch.length, |
| 137 | arr.length - 1 |
| 138 | ) |
| 139 | ) |
| 140 | } |
| 141 | |
| 142 | return chunks |
| 143 | } |
| 144 | |
| 145 | private chunkObject(obj: JsonObject, path: string[], depth: number): Chunk[] { |
| 146 | const chunks: Chunk[] = [] |
no test coverage detected