-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathzip-wheel-explorer.html
More file actions
506 lines (464 loc) · 15.2 KB
/
Copy pathzip-wheel-explorer.html
File metadata and controls
506 lines (464 loc) · 15.2 KB
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
<!DOCTYPE html>
<html>
<head>
<title>Package File Browser</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
max-width: 800px;
margin: 0 auto;
padding: 1rem;
color: #333;
}
h1 {
font-size: 1.5rem;
margin-bottom: 1rem;
}
input[type="text"] {
font-size: 16px;
width: 100%;
margin-bottom: 0.75rem;
padding: 0.75rem;
border: 1px solid #ccc;
border-radius: 6px;
}
input[type="text"]:focus {
outline: none;
border-color: #007aff;
box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.15);
}
button {
font-size: 16px;
padding: 0.75rem 1.25rem;
background: #007aff;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
width: 100%;
}
button:active {
background: #005ecb;
}
p {
font-size: 0.875rem;
color: #666;
margin-top: 0.75rem;
}
p code {
font-size: 0.75rem;
background: #f0f0f0;
padding: 0.15rem 0.3rem;
border-radius: 3px;
word-break: break-all;
}
#fileList {
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 0;
margin-top: 1rem;
overflow: hidden;
}
#fileList h3 {
font-size: 0.875rem;
font-weight: 600;
margin: 0;
padding: 0.75rem 1rem;
background: #f8f8f8;
border-bottom: 1px solid #e0e0e0;
}
.file-item {
padding: 0.75rem 1rem;
border-bottom: 1px solid #eee;
cursor: pointer;
font-size: 0.875rem;
word-break: break-all;
transition: background 0.1s;
}
.file-item:hover {
background: #f5f5f5;
}
.file-item:active {
background: #e8e8e8;
}
.file-size {
color: #999;
font-size: 0.75rem;
margin-left: 0.5em;
white-space: nowrap;
}
.file-item.selected {
background: #e7f1ff;
border-bottom: none;
}
.file-content {
border-bottom: 1px solid #eee;
}
.file-content pre {
border-top: 1px solid #e0e0e0;
}
pre {
white-space: pre-wrap;
word-wrap: break-word;
background-color: #fafafa;
padding: 0;
margin: 0;
max-height: 60vh;
overflow-y: auto;
font-size: 0.8125rem;
line-height: 1.4;
}
.line-table {
width: 100%;
border-collapse: collapse;
}
.line-table td {
padding: 0;
vertical-align: top;
}
.line-num {
width: 1%;
min-width: 3em;
padding: 0 1rem 0 0.5rem;
text-align: right;
user-select: none;
font-size: 0.75rem;
color: #999;
border-right: 1px solid #e0e0e0;
background: #f5f5f5;
}
.line-num a {
color: inherit;
text-decoration: none;
display: block;
padding-right: 4px;
}
.line-num a:hover {
color: #007aff;
}
.line-code {
padding-left: 0.75rem;
white-space: pre-wrap;
word-wrap: break-word;
}
.line-row.highlighted {
background: #fffbdd;
}
.line-row.highlighted .line-num {
background: #f5efaa;
color: #666;
}
.status {
padding: 1rem;
color: #666;
font-size: 0.875rem;
}
@media (min-width: 500px) {
body {
padding: 2rem;
}
h1 {
font-size: 1.75rem;
}
button {
width: auto;
}
}
</style>
</head>
<body>
<h1>Package File Browser</h1>
<input type="text" id="urlInput" placeholder="Package name (e.g. requests) or URL to .whl/.zip/.tar.gz file" onkeydown="if(event.key==='Enter')fetchAndUnpackFile()">
<button onclick="fetchAndUnpackFile()">Unpack File</button>
<p>Enter a PyPI package name like <code>requests</code> or <code>llm-mistral</code> (<a href="?package=llm-mistral">try it</a>), or paste a direct URL to a .whl, .zip or .tar.gz file. Packages with no wheel fall back to the source distribution (<a href="?package=apple-fm-sdk">try apple-fm-sdk</a>).</p>
<div id="fileList" style="display: none"></div>
<script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js"></script>
<script>
function updateUrl(input, fragment = null) {
const params = new URLSearchParams();
if (input.startsWith('http://') || input.startsWith('https://')) {
params.set('url', input);
} else {
params.set('package', input);
}
const hash = fragment ? '#' + fragment : '';
history.replaceState(null, '', '?' + params.toString() + hash);
}
function encodeFragment(filename, lineNum = null) {
// Encode filename for use in URL fragment
const encoded = encodeURIComponent(filename).replace(/%2F/g, '/');
if (lineNum !== null) {
return encoded + '--L' + lineNum;
}
return encoded;
}
function parseFragment(fragment) {
if (!fragment) return { filename: null, lineNum: null };
// Check for line number suffix
const match = fragment.match(/^(.+)--L(\d+)$/);
if (match) {
return {
filename: decodeURIComponent(match[1]),
lineNum: parseInt(match[2], 10)
};
}
return {
filename: decodeURIComponent(fragment),
lineNum: null
};
}
function formatContentWithLineNumbers(content, filename) {
const lines = content.split('\n');
let html = '<table class="line-table"><tbody>';
lines.forEach((line, index) => {
const lineNum = index + 1;
const fragment = encodeFragment(filename, lineNum);
const rowId = `${encodeURIComponent(filename)}--L${lineNum}`;
html += `<tr class="line-row" id="${escapeHtml(rowId)}">`;
html += `<td class="line-num"><a href="#${escapeHtml(fragment)}" data-line="${lineNum}">${lineNum}</a></td>`;
html += `<td class="line-code">${escapeHtml(line) || ' '}</td>`;
html += '</tr>';
});
html += '</tbody></table>';
return html;
}
function highlightLine(filename, lineNum) {
// Remove any existing highlight
document.querySelectorAll('.line-row.highlighted').forEach(el => el.classList.remove('highlighted'));
// Find and highlight the specified line
const rowId = `${encodeURIComponent(filename)}--L${lineNum}`;
const row = document.getElementById(rowId);
if (row) {
row.classList.add('highlighted');
row.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
function selectFile(filename, lineNum, updateHash = true) {
const files = window.loadedFiles || [];
const file = files.find(f => f.name === filename);
if (!file) return;
const fileEl = document.querySelector(`.file-item[data-filename="${CSS.escape(filename)}"]`);
if (!fileEl) return;
const wasSelected = fileEl.classList.contains('selected');
// Remove any existing content and selection
document.querySelectorAll('.file-content').forEach(el => el.remove());
document.querySelectorAll('.file-item').forEach(el => el.classList.remove('selected'));
// Toggle off if clicking the same file (only when not opening via line number)
if (wasSelected && lineNum === null) {
if (updateHash) {
history.replaceState(null, '', window.location.pathname + window.location.search);
}
return;
}
fileEl.classList.add('selected');
// Insert content right after the clicked file
const contentEl = document.createElement('div');
contentEl.className = 'file-content';
contentEl.innerHTML = `<pre>${formatContentWithLineNumbers(file.content, file.name)}</pre>`;
fileEl.after(contentEl);
// Add click handlers to line number links
contentEl.querySelectorAll('.line-num a').forEach(a => {
a.onclick = (e) => {
e.preventDefault();
const ln = parseInt(a.dataset.line, 10);
const input = document.getElementById('urlInput').value.trim();
updateUrl(input, encodeFragment(file.name, ln));
highlightLine(file.name, ln);
};
});
// Update URL fragment
if (updateHash) {
const input = document.getElementById('urlInput').value.trim();
updateUrl(input, encodeFragment(filename, lineNum));
}
// Scroll to file element so it's visible
fileEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
// Highlight line if specified
if (lineNum !== null) {
setTimeout(() => highlightLine(filename, lineNum), 100);
}
}
function handleFragment() {
const fragment = window.location.hash.slice(1);
if (!fragment) return;
const { filename, lineNum } = parseFragment(fragment);
if (filename) {
selectFile(filename, lineNum, false);
}
}
// Listen for hash changes
window.addEventListener('hashchange', handleFragment);
async function fetchAndUnpackFile() {
let input = document.getElementById('urlInput').value.trim();
const fileListEl = document.getElementById('fileList');
if (!input) return;
fileListEl.style.display = 'block';
// Check if input is a URL or a package name
let url = input;
const isUrl = input.startsWith('http://') || input.startsWith('https://');
if (!isUrl) {
// Treat as PyPI package name
fileListEl.innerHTML = `<div class="status">Looking up "${escapeHtml(input)}" on PyPI...</div>`;
try {
const pypiResponse = await fetch(`https://pypi.org/pypi/${encodeURIComponent(input)}/json`);
if (!pypiResponse.ok) {
fileListEl.innerHTML = `<div class="status">Package "${escapeHtml(input)}" not found on PyPI</div>`;
return;
}
const pypiData = await pypiResponse.json();
// Prefer a wheel, but fall back to a source distribution (.tar.gz)
const fileUrl = pypiData.urls?.find(u => u.url?.endsWith('.whl'))
|| pypiData.urls?.find(u => u.url?.endsWith('.tar.gz'));
if (!fileUrl) {
fileListEl.innerHTML = `<div class="status">No wheel (.whl) or source distribution (.tar.gz) found for "${escapeHtml(input)}"</div>`;
return;
}
url = fileUrl.url;
} catch (error) {
fileListEl.innerHTML = `<div class="status">Error looking up package: ${escapeHtml(error.message)}</div>`;
return;
}
}
// Update URL bar (preserve existing fragment)
const existingFragment = window.location.hash.slice(1);
updateUrl(input, existingFragment || null);
fileListEl.innerHTML = '<div class="status">Downloading file...</div>';
try {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const files = await extractFiles(arrayBuffer, url);
fileListEl.innerHTML = '<h3>Files in package</h3>';
window.loadedFiles = files; // Store for fragment handling
files.forEach((file, index) => {
const fileEl = document.createElement('div');
fileEl.className = 'file-item';
fileEl.dataset.filename = file.name;
const nameSpan = document.createElement('span');
nameSpan.textContent = file.name;
const sizeSpan = document.createElement('span');
sizeSpan.className = 'file-size';
sizeSpan.textContent = formatFileSize(file.size);
fileEl.appendChild(nameSpan);
fileEl.appendChild(sizeSpan);
fileEl.onclick = () => selectFile(file.name, null);
fileListEl.appendChild(fileEl);
});
// Handle fragment after files are loaded
handleFragment();
} catch (error) {
fileListEl.innerHTML = `<div class="status">Error: ${escapeHtml(error.message)}</div>`;
console.error(error);
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function formatFileSize(bytes) {
if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
return bytes + ' bytes';
}
async function extractFiles(arrayBuffer, url) {
const bytes = new Uint8Array(arrayBuffer);
// Gzip magic bytes (0x1f 0x8b) indicate a .tar.gz source distribution
if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
return extractTarGz(arrayBuffer);
}
// Otherwise treat as a zip archive (.whl / .zip)
const files = [];
const zip = await JSZip.loadAsync(arrayBuffer);
for (const [name, file] of Object.entries(zip.files)) {
const content = await file.async('text');
const rawBytes = await file.async('uint8array');
files.push({ name, content, size: rawBytes.byteLength });
}
return files;
}
// Decompress gzip data using the browser's native DecompressionStream
async function gunzip(arrayBuffer) {
if (typeof DecompressionStream === 'undefined') {
throw new Error('Your browser does not support gzip decompression (DecompressionStream)');
}
const stream = new Response(arrayBuffer).body.pipeThrough(new DecompressionStream('gzip'));
return new Response(stream).arrayBuffer();
}
// Parse a tar archive (Uint8Array) into [{name, data}], handling ustar
// prefixes, GNU long names and PAX extended headers.
function parseTar(buffer) {
const bytes = new Uint8Array(buffer);
const decoder = new TextDecoder('utf-8');
const entries = [];
let offset = 0;
let longName = null; // GNU 'L' long name
let paxName = null; // PAX 'x' path override
const readStr = (start, len) => {
let end = start;
const max = start + len;
while (end < max && bytes[end] !== 0) end++;
return decoder.decode(bytes.subarray(start, end));
};
while (offset + 512 <= bytes.length) {
// End of archive is marked by a zero-filled block
let allZero = true;
for (let i = 0; i < 512; i++) {
if (bytes[offset + i] !== 0) { allZero = false; break; }
}
if (allZero) break;
let name = readStr(offset, 100);
const size = parseInt(readStr(offset + 124, 12).trim(), 8) || 0;
const typeflag = bytes[offset + 156];
const magic = readStr(offset + 257, 6);
const prefix = readStr(offset + 345, 155);
if (prefix && magic.startsWith('ustar')) {
name = prefix + '/' + name;
}
const dataStart = offset + 512;
offset = dataStart + Math.ceil(size / 512) * 512;
if (typeflag === 0x4c) { // 'L' GNU long name
longName = decoder.decode(bytes.subarray(dataStart, dataStart + size)).replace(/\0+$/, '');
continue;
}
if (typeflag === 0x78 || typeflag === 0x67) { // 'x' or 'g' PAX header
const records = decoder.decode(bytes.subarray(dataStart, dataStart + size));
const m = records.match(/^\d+ path=(.*)$/m);
if (m) paxName = m[1];
continue;
}
const effectiveName = paxName || longName || name;
paxName = null;
longName = null;
// Only keep regular files ('0' or legacy '\0'); skip directories etc.
if (typeflag === 0x30 || typeflag === 0) {
entries.push({ name: effectiveName, data: bytes.subarray(dataStart, dataStart + size) });
}
}
return entries;
}
async function extractTarGz(arrayBuffer) {
const tarBuffer = await gunzip(arrayBuffer);
const decoder = new TextDecoder('utf-8');
return parseTar(tarBuffer).map(entry => ({
name: entry.name,
content: decoder.decode(entry.data),
size: entry.data.byteLength
}));
}
// Check for query params on page load
const params = new URLSearchParams(window.location.search);
const packageParam = params.get('package');
const urlParam = params.get('url');
if (packageParam || urlParam) {
document.getElementById('urlInput').value = packageParam || urlParam;
fetchAndUnpackFile();
}
</script>
</body>
</html>