-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscript.js
404 lines (350 loc) · 16.3 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
document.addEventListener('DOMContentLoaded', () => {
const dropZone = document.querySelector('.drop-zone');
const loader = document.querySelector('.loader');
const currentFile = document.querySelector('.current-file');
const resultContainer = document.querySelector('.result-container');
const resultTextarea = document.getElementById('result');
const excludePatternsText = document.getElementById('exclude-patterns');
const copyBtn = document.getElementById('copy-btn');
const dropStatus = document.getElementById('drop-status');
const warningDiv = document.getElementById('size-warning');
const warningTitle = document.getElementById('warning-title');
const warningMessage = document.getElementById('warning-message');
let result = '';
let processedFilesCount = 0;
// Add these constants at the top
let MAX_TOKENS = 128000; // GPT-4's limit
let CHARS_PER_TOKEN = 4; // Rough estimation
let MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;
// Add near other constants
const COMMENT_PATTERNS = {
// Single line and multi-line comment patterns for different languages
'.js': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.jsx': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.ts': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.tsx': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.py': [/#.*$/gm, /'''[\s\S]*?'''/g, /"""[\s\S]*?"""/g],
'.php': [/\/\/.*$/gm, /#.*$/gm, /\/\*[\s\S]*?\*\//g],
'.java': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.c': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.cpp': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.h': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.hpp': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.cs': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.rb': [/#.*$/gm, /=begin[\s\S]*?=end/g],
'.sh': [/#.*$/gm],
'.bash': [/#.*$/gm],
'.go': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
'.rs': [/\/\/.*$/gm, /\/\*[\s\S]*?\*\//g],
};
// Add with other constants at the top
const stripCommentsCheckbox = document.getElementById('strip-comments');
const includeBinaryCheckbox = document.getElementById('include-binary');
// Add a button for directory selection
const selectDirBtn = document.createElement('button');
selectDirBtn.textContent = 'Select Directory';
selectDirBtn.className = 'px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors duration-200';
dropZone.appendChild(selectDirBtn);
const fallbackInput = document.getElementById('fallbackInput');
selectDirBtn.addEventListener('click', async () => {
try {
if (window.showDirectoryPicker) {
const dirHandle = await window.showDirectoryPicker();
await processDirectoryHandle(dirHandle);
} else {
// Safari (fallback)
fallbackInput.click();
}
} catch (error) {
console.error('Error selecting directory:', error);
dropStatus.textContent = 'Error selecting directory';
}
});
// For fallback
fallbackInput.addEventListener('change', async (e) => {
const files = e.target.files;
if (!files.length) {
dropStatus.textContent = 'No files selected (fallback).';
return;
}
await processFallbackFiles(files);
});
// Drag and drop handlers
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('dragover');
});
dropZone.addEventListener('drop', async (e) => {
e.preventDefault();
dropZone.classList.remove('dragover');
const items = e.dataTransfer.items;
if (items.length === 0) {
dropStatus.textContent = 'No files dropped';
return;
}
// Try to get directory handle from dropped items
try {
const item = items[0];
if (item.kind === 'file') {
const handle = await item.getAsFileSystemHandle();
if (handle.kind === 'directory') {
await processDirectoryHandle(handle);
} else {
// Handle single file
const file = await handle.getFile();
result = await file.text();
displayResult();
}
}
} catch (error) {
console.error('Error processing drop:', error);
dropStatus.textContent = 'Error processing dropped items. Try using the Select Directory button instead.';
}
});
async function processDirectoryHandle(dirHandle, path = '') {
const excludePatterns = excludePatternsText.value
.split('\n')
.filter(pattern => pattern.trim())
.map(pattern => new RegExp(pattern.trim()
.replace(/\./g, '\\.')
.replace(/\*/g, '.*')));
loader.classList.remove('hidden');
result = '';
resultContainer.classList.add('hidden');
warningDiv.classList.add('hidden'); // Hide any previous warnings
processedFilesCount = 0;
document.getElementById('files-counter').textContent = '0';
// Scroll loader into view
loader.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
try {
const hitLimit = await readDirectory(dirHandle, excludePatterns);
if (!hitLimit) {
displayResult();
}
} catch (error) {
console.error('Error processing directory:', error);
dropStatus.textContent = 'Error processing directory';
}
}
async function processFallbackFiles(files) {
const excludePatterns = excludePatternsText.value
.split('\n')
.filter(pattern => pattern.trim())
.map(pattern => new RegExp(pattern.trim()
.replace(/\./g, '\\.')
.replace(/\*/g, '.*')));
loader.classList.remove('hidden');
result = '';
resultContainer.classList.add('hidden');
warningDiv.classList.add('hidden');
processedFilesCount = 0;
document.getElementById('files-counter').textContent = '0';
loader.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
try {
for (const file of files) {
let fullPath = file.webkitRelativePath || file.name;
currentFile.textContent = fullPath;
if (excludePatterns.some(pattern => pattern.test(fullPath))) {
continue;
}
processedFilesCount++;
document.getElementById('files-counter').textContent = processedFilesCount;
const ext = '.' + file.name.split('.').pop().toLowerCase();
const isText = isTextFile(file.name);
if (isText) {
let content = await file.text();
if (stripCommentsCheckbox.checked && COMMENT_PATTERNS[ext]) {
content = stripComments(content, ext);
}
const pattern = document.getElementById('format-pattern').value;
const newContent = pattern
.replace('{path}', fullPath.replace(file.name, ''))
.replace('{filename}', file.name)
.replace('{content}', content)
.replace(/{newline}/g, '\n');
if ((result.length + newContent.length) > MAX_CHARS) {
result = '';
showSizeWarning();
return;
}
result += newContent;
} else {
if (includeBinaryCheckbox.checked) {
const newContent = `// File: ${fullPath}\n\n`;
if ((result.length + newContent.length) > MAX_CHARS) {
result = '';
showSizeWarning();
return;
}
result += newContent;
}
}
}
displayResult();
} catch (error) {
console.error('Error processing fallback files:', error);
dropStatus.textContent = 'Error processing fallback files';
}
}
// Add this after the constants
const TEXT_FILE_EXTENSIONS = new Set([
// Web files
'.html', '.css', '.js', '.jsx', '.ts', '.tsx', '.json', '.xml', '.svg', '.md', '.mdx',
// Config files
'.env', '.yml', '.yaml', '.toml', '.ini', '.conf', '.config',
// Programming languages
'.py', '.java', '.cpp', '.c', '.h', '.hpp', '.cs', '.php', '.rb', '.go', '.rs', '.swift',
'.kt', '.kts', '.scala', '.sh', '.bash', '.pl', '.pm', '.r', '.lua', '.sql',
// Documentation
'.txt', '.rtf', '.csv', '.log', '.readme',
// Other text files
'.gitignore', '.dockerignore', '.editorconfig'
]);
// Add this helper function
function isTextFile(filename) {
const ext = '.' + filename.split('.').pop().toLowerCase();
return TEXT_FILE_EXTENSIONS.has(ext);
}
// Add this function
function stripComments(content, extension) {
const patterns = COMMENT_PATTERNS[extension];
if (!patterns) return content;
let result = content;
for (const pattern of patterns) {
result = result.replace(pattern, '');
}
// Remove empty lines and normalize spacing
return result
.split('\n')
.filter(line => line.trim())
.join('\n')
.replace(/\n{3,}/g, '\n\n');
}
// Update the readDirectory function
async function readDirectory(dirHandle, excludePatterns, path = '') {
for await (const entry of dirHandle.values()) {
const fullPath = path + entry.name;
if (excludePatterns.some(pattern => pattern.test(fullPath))) {
continue;
}
currentFile.textContent = fullPath;
try {
if (entry.kind === 'file') {
processedFilesCount++;
document.getElementById('files-counter').textContent = processedFilesCount;
if (isTextFile(entry.name)) {
const file = await entry.getFile();
let content = await file.text();
if (stripCommentsCheckbox.checked) {
const ext = '.' + entry.name.split('.').pop().toLowerCase();
if (COMMENT_PATTERNS[ext]) {
content = stripComments(content, ext);
}
}
const pattern = document.getElementById('format-pattern').value;
const newContent = pattern
.replace('{path}', path)
.replace('{filename}', entry.name)
.replace('{content}', content)
.replace(/{newline}/g, '\n');
if ((result.length + newContent.length) > MAX_CHARS) {
result = '';
warningDiv.classList.remove('hidden');
warningTitle.textContent = '⚠️ Project Too Large';
warningMessage.textContent =
`Processing stopped: Project would exceed the ${MAX_TOKENS.toLocaleString()} token limit. ` +
`Try excluding more files or using a model with a larger context window.`;
loader.classList.add('hidden');
// Scroll warning into view
warningDiv.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
return true; // Indicate we hit the limit
}
result += newContent;
} else if (includeBinaryCheckbox.checked) { // Only process binary files if checkbox is checked
const newContent = `// File: ${fullPath}\n\n`;
if ((result.length + newContent.length) > MAX_CHARS) {
result = '';
warningDiv.classList.remove('hidden');
warningTitle.textContent = '⚠️ Project Too Large';
warningMessage.textContent =
`Processing stopped: Project would exceed the ${MAX_TOKENS.toLocaleString()} token limit. ` +
`Try excluding more files or using a model with a larger context window.`;
loader.classList.add('hidden');
// Scroll warning into view
warningDiv.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
return true; // Indicate we hit the limit
}
result += newContent;
}
} else if (entry.kind === 'directory') {
if (await readDirectory(entry, excludePatterns, `${fullPath}/`)) {
return true; // Propagate the limit hit up the call stack
}
}
} catch (error) {
console.error(`Error processing ${fullPath}:`, error);
dropStatus.textContent = `Error processing: ${fullPath}`;
}
}
return false; // Indicate we didn't hit the limit
}
function displayResult() {
loader.classList.add('hidden');
resultContainer.classList.remove('hidden');
resultTextarea.value = result;
updateStats();
// Scroll to result container with smooth animation
resultContainer.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
function updateStats() {
const text = resultTextarea.value;
const chars = text.length;
const words = text.split(/\s+/).filter(Boolean).length;
const tokens = Math.ceil(chars / CHARS_PER_TOKEN);
document.getElementById('char-count').textContent = `${chars.toLocaleString()} / ${MAX_CHARS.toLocaleString()}`;
document.getElementById('word-count').textContent = words.toLocaleString();
document.getElementById('token-count').textContent = `${tokens.toLocaleString()} / ${MAX_TOKENS.toLocaleString()}`;
// Add warning class if close to limit
const tokenCount = document.getElementById('token-count');
if (tokens > MAX_TOKENS * 0.9) {
tokenCount.classList.add('text-red-500');
} else if (tokens > MAX_TOKENS * 0.75) {
tokenCount.classList.add('text-yellow-500');
} else {
tokenCount.classList.remove('text-red-500', 'text-yellow-500');
}
}
copyBtn.addEventListener('click', () => {
navigator.clipboard.writeText(resultTextarea.value);
copyBtn.textContent = 'Copied!';
setTimeout(() => {
copyBtn.textContent = 'Copy to Clipboard';
}, 2000);
});
// Add near the top with other constants
MAX_TOKENS = 128000;
const modelSelect = document.getElementById('model-select');
modelSelect.addEventListener('change', () => {
MAX_TOKENS = parseInt(modelSelect.value);
MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;
updateStats(); // Update display with new limits
});
});