|
1 | 1 | import { createHash } from 'node:crypto'; |
2 | 2 | import { parse } from 'node:querystring'; |
3 | 3 |
|
| 4 | +import type { PaginatedList } from 'apify-client'; |
| 5 | + |
| 6 | +import { ACTOR_OUTPUT_TRUNCATED_MESSAGE } from '../const.js'; |
4 | 7 | import { processInput } from '../input.js'; |
5 | 8 | import { addRemoveTools, getActorsAsTools } from '../tools/index.js'; |
6 | 9 | import type { Input, ToolEntry } from '../types.js'; |
@@ -58,3 +61,43 @@ export function parseInputParamsFromUrl(url: string): Input { |
58 | 61 | const params = parse(query) as unknown as Input; |
59 | 62 | return processInput(params); |
60 | 63 | } |
| 64 | + |
| 65 | +/** |
| 66 | + * Truncates dataset items to fit within a specified character limit. |
| 67 | + * |
| 68 | + * This function will remove items from the end of the dataset until the total |
| 69 | + * character count of the dataset items is within the specified limit. |
| 70 | + * If there is only one item (left) in the dataset, it will not be truncated. |
| 71 | + */ |
| 72 | +export function truncateDatasetItems( |
| 73 | + items: PaginatedList<Record<string, unknown>>, |
| 74 | + maxChars: number, |
| 75 | + originalItemCount: number, |
| 76 | +): PaginatedList<Record<string, unknown>> { |
| 77 | + // If within the limit, return as is. |
| 78 | + if (JSON.stringify(items).length <= maxChars) { |
| 79 | + return items; |
| 80 | + } |
| 81 | + |
| 82 | + // Do not truncate single item datasets. |
| 83 | + if (items.items.length < 2) { |
| 84 | + return items; |
| 85 | + } |
| 86 | + |
| 87 | + // Truncate from back and check if the total length is within the limit. |
| 88 | + while (items.items.length > 1) { |
| 89 | + if (JSON.stringify(items).length <= maxChars) { |
| 90 | + break; // If the dataset is within the limit, stop truncating. |
| 91 | + } |
| 92 | + items.items.pop(); // Remove the last item if the dataset exceeds the limit. |
| 93 | + } |
| 94 | + |
| 95 | + // Add truncation message |
| 96 | + items.items.push({ |
| 97 | + truncationInfo: ACTOR_OUTPUT_TRUNCATED_MESSAGE, |
| 98 | + originalItemCount, |
| 99 | + itemCountAfterTruncation: items.items.length, |
| 100 | + }); |
| 101 | + |
| 102 | + return items; |
| 103 | +} |
0 commit comments