-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocal-Userscript-Builder.html
More file actions
1576 lines (1447 loc) · 50.7 KB
/
Local-Userscript-Builder.html
File metadata and controls
1576 lines (1447 loc) · 50.7 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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!-- ==================================================================================================
File: JavaScript-Local-Userscript-Builder-v0.1.2.html
Description: Local HTML browser tool for building one userscript from multiple source files.
Author: Stephan Kühn (LoTeK)
Mail: info@lotek-zone.com
Web: https://lotek-zone.com/
GitHub: https://github.com/LoTeK-Zone
Repository: https://github.com/LoTeK-Zone/javascript-local-userscript-builder
Version: v0.1.2
Last Updated: 2026-04-25
License: MIT
================================================================================================== -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LoTeK Local Userscript Builder v0.1.2</title>
<style>
:root {
--bg: #0f1117;
--panel: #161a23;
--panel-2: #1d2230;
--panel-3: #252b3a;
--text: #e8edf7;
--muted: #a8b1c2;
--soft: #7f8aa0;
--accent: #5fa2ff;
--accent-2: #2f7df6;
--danger: #ff6d6d;
--warn: #ffd166;
--ok: #7dffa1;
--border: rgba(255,255,255,0.12);
--border-strong: rgba(255,255,255,0.22);
--mono: Consolas, Monaco, "Courier New", monospace;
--sans: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: var(--sans);
font-size: 14px;
}
body {
padding: 18px;
}
button,
input,
textarea,
select {
font: inherit;
}
button {
min-height: 34px;
border: 1px solid var(--border-strong);
border-radius: 8px;
background: rgba(95,162,255,0.16);
color: var(--text);
cursor: pointer;
padding: 7px 11px;
}
button:hover {
border-color: var(--accent);
background: rgba(95,162,255,0.24);
}
button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
input[type="checkbox"] {
accent-color: var(--accent-2);
}
textarea {
width: 100%;
min-height: 360px;
resize: vertical;
border: 1px solid var(--border);
border-radius: 10px;
background: #0c0f15;
color: var(--text);
padding: 12px;
font-family: var(--mono);
font-size: 12px;
line-height: 1.45;
white-space: pre;
tab-size: 3;
}
.app {
width: min(1880px, 100%);
margin: 0 auto;
}
.header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
margin-bottom: 14px;
}
.title {
margin: 0;
font-size: 24px;
line-height: 1.15;
}
.subtitle {
margin-top: 6px;
color: var(--muted);
line-height: 1.35;
}
.version-box {
flex: 0 0 auto;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--panel);
color: var(--muted);
font-family: var(--mono);
font-size: 12px;
text-align: right;
}
.grid {
display: grid;
grid-template-columns: minmax(300px, 390px) minmax(520px, 1fr);
gap: 14px;
align-items: start;
}
.panel {
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
overflow: hidden;
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 12px 14px;
border-bottom: 1px solid var(--border);
background: rgba(255,255,255,0.035);
}
.panel-title {
font-weight: 700;
}
.panel-body {
padding: 14px;
}
.stack {
display: flex;
flex-direction: column;
gap: 10px;
}
.row {
display: flex;
gap: 8px;
align-items: center;
flex-wrap: wrap;
}
.row > button {
flex: 1 1 auto;
}
.note {
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.status-line {
display: grid;
grid-template-columns: 100px 1fr;
gap: 8px;
font-size: 12px;
line-height: 1.35;
}
.status-key {
color: var(--soft);
}
.status-value {
color: var(--text);
overflow-wrap: anywhere;
}
.drop-zone {
border: 1px dashed rgba(95,162,255,0.55);
border-radius: 12px;
background: rgba(95,162,255,0.07);
color: var(--muted);
padding: 18px;
text-align: center;
line-height: 1.45;
}
.drop-zone.is-over {
border-color: var(--accent);
background: rgba(95,162,255,0.16);
color: var(--text);
}
.check-row {
display: flex;
align-items: center;
gap: 9px;
padding: 8px 9px;
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(255,255,255,0.035);
}
.check-row span {
line-height: 1.35;
}
.main-right {
display: flex;
flex-direction: column;
gap: 14px;
}
.file-tools {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.file-tools button {
flex: 0 0 auto;
}
.table-wrap {
max-height: 430px;
overflow: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
th,
td {
padding: 8px 9px;
border-bottom: 1px solid rgba(255,255,255,0.075);
text-align: left;
vertical-align: top;
}
th {
position: sticky;
top: 0;
background: #1b202b;
color: #dce6ff;
z-index: 1;
font-weight: 700;
}
tr:hover td {
background: rgba(95,162,255,0.08);
}
.mono {
font-family: var(--mono);
}
.path-cell {
max-width: 620px;
overflow-wrap: anywhere;
}
.badge {
display: inline-block;
padding: 2px 7px;
border-radius: 999px;
font-family: var(--mono);
font-size: 11px;
border: 1px solid var(--border);
color: var(--muted);
}
.badge.ok {
color: var(--ok);
border-color: rgba(125,255,161,0.35);
background: rgba(125,255,161,0.08);
}
.badge.warn {
color: var(--warn);
border-color: rgba(255,209,102,0.35);
background: rgba(255,209,102,0.08);
}
.badge.danger {
color: var(--danger);
border-color: rgba(255,109,109,0.35);
background: rgba(255,109,109,0.08);
}
.output-panel .panel-header {
align-items: center;
}
.output-actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.log {
min-height: 130px;
max-height: 260px;
overflow: auto;
border: 1px solid var(--border);
border-radius: 10px;
background: #0c0f15;
padding: 10px;
color: var(--muted);
font-family: var(--mono);
font-size: 12px;
line-height: 1.45;
white-space: pre-wrap;
}
.hidden-input {
display: none;
}
.small-btn {
min-height: 30px;
padding: 5px 9px;
font-size: 12px;
}
.danger-btn {
background: rgba(255,109,109,0.12);
border-color: rgba(255,109,109,0.35);
}
.danger-btn:hover {
background: rgba(255,109,109,0.20);
border-color: rgba(255,109,109,0.55);
}
.file-action-btn {
min-height: 26px;
padding: 3px 7px;
font-size: 11px;
}
@media (max-width: 980px) {
body {
padding: 10px;
}
.header {
flex-direction: column;
}
.version-box {
width: 100%;
text-align: left;
}
.grid {
grid-template-columns: 1fr;
}
.table-wrap {
max-height: 360px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="header">
<div>
<h1 class="title">LoTeK Local Userscript Builder</h1>
<div class="subtitle">Build one final single-file userscript from a local folder, manifest and separated source files.</div>
</div>
<div class="version-box">
v0.1.2<br>
2026-04-25<br>
Local HTML Tool
</div>
</header>
<main class="grid">
<section class="panel">
<div class="panel-header">
<div class="panel-title">Project Input</div>
</div>
<div class="panel-body stack">
<div class="row">
<button id="btnLoadFolder" type="button">Load Folder</button>
<button id="btnAddFiles" type="button">Add Files</button>
</div>
<div class="row">
<button id="btnReload" type="button" disabled>Reload Current Folder</button>
<button id="btnClear" type="button" class="danger-btn">Clear Project</button>
</div>
<input id="folderInput" class="hidden-input" type="file" webkitdirectory directory multiple>
<input id="fileInput" class="hidden-input" type="file" multiple>
<div id="dropZone" class="drop-zone">
Drop one project folder or project files here.<br>
Folder drops are read recursively when the browser provides entries.
</div>
<div class="note">Folder loading replaces the whole active project. Adding files only replaces or adds individual paths.</div>
</div>
</section>
<section class="main-right">
<section class="panel">
<div class="panel-header">
<div class="panel-title">Loaded Project Files</div>
<div class="file-tools">
<button id="btnParseManifest" type="button" class="small-btn">Parse Manifest</button>
<button id="btnGenerateManifest" type="button" class="small-btn">Generate Manifest</button>
</div>
</div>
<div class="panel-body stack">
<div id="projectStatus" class="stack"></div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>#</th>
<th>Path</th>
<th>Name</th>
<th>Size</th>
<th>Modified</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="fileTableBody"></tbody>
</table>
</div>
</div>
</section>
<section class="panel">
<div class="panel-header">
<div class="panel-title">Build Options</div>
</div>
<div class="panel-body stack">
<label class="check-row">
<input id="optShowEditor" type="checkbox" checked>
<span>Show complete build output in editor window</span>
</label>
<label class="check-row">
<input id="optDownload" type="checkbox" checked>
<span>Download complete build output as .txt</span>
</label>
<label class="check-row">
<input id="optIncludeMarkers" type="checkbox" checked>
<span>Insert BUILD_INCLUDE_START / BUILD_INCLUDE_END markers</span>
</label>
<label class="check-row">
<input id="optBuildHeader" type="checkbox" checked>
<span>Insert generated build header comment</span>
</label>
<div class="row">
<button id="btnBuild" type="button">Build Script</button>
<button id="btnDownload" type="button" disabled>Download Current Output</button>
</div>
<div class="note">At least one output target must be selected: editor window or download.</div>
</div>
</section>
</section>
</main>
<section class="panel output-panel" style="margin-top:14px;">
<div class="panel-header">
<div class="panel-title">Build Output</div>
<div class="output-actions">
<button id="btnCopy" type="button" class="small-btn" disabled>Copy Output</button>
<button id="btnSelectOutput" type="button" class="small-btn" disabled>Select All</button>
</div>
</div>
<div class="panel-body stack">
<textarea id="outputEditor" spellcheck="false" placeholder="Build output appears here when the editor output option is enabled."></textarea>
</div>
</section>
<section class="panel" style="margin-top:14px;">
<div class="panel-header">
<div class="panel-title">Build Log</div>
<button id="btnClearLog" type="button" class="small-btn">Clear Log</button>
</div>
<div class="panel-body">
<div id="logNode" class="log"></div>
</div>
</section>
</div>
<script>
(function () {
'use strict';
const SCRIPT_INFO = {
name: 'LoTeK Local Userscript Builder',
version: 'v0.1.2',
date: '2026-04-25',
description: 'Local browser build tool for single-file userscripts',
scope: 'Local HTML tool',
};
const DEFAULT_EXCLUDED_DIR_PREFIXES = [
'dist/',
'distribution/',
'changelog/',
'changelogs/',
'docs/',
'doc/',
];
const DEFAULT_EXCLUDED_FILE_PATTERNS = [
/^project\.toml$/i,
/^readme(?:[-_.].*)?\.(?:md|txt)$/i,
/^agents?\.md$/i,
/^project-map(?:[-_.].*)?\.(?:md|txt)$/i,
/^project-map\.generated(?:[-_.].*)?\.(?:md|txt)$/i,
];
const state = {
files: [],
fileMap: new Map(),
manifest: null,
manifestPath: '',
projectRootPrefix: '',
folderReloadProvider: null,
outputText: '',
outputFilename: 'userscript-build.txt',
logs: [],
};
const dom = {};
function boot() {
cacheElements();
bindEvents();
renderAll();
log('Ready. Load a project folder, add files, or drop a folder/files.');
}
function cacheElements() {
dom.btnLoadFolder = document.getElementById('btnLoadFolder');
dom.btnAddFiles = document.getElementById('btnAddFiles');
dom.btnReload = document.getElementById('btnReload');
dom.btnClear = document.getElementById('btnClear');
dom.btnParseManifest = document.getElementById('btnParseManifest');
dom.btnGenerateManifest = document.getElementById('btnGenerateManifest');
dom.btnBuild = document.getElementById('btnBuild');
dom.btnDownload = document.getElementById('btnDownload');
dom.btnCopy = document.getElementById('btnCopy');
dom.btnSelectOutput = document.getElementById('btnSelectOutput');
dom.btnClearLog = document.getElementById('btnClearLog');
dom.folderInput = document.getElementById('folderInput');
dom.fileInput = document.getElementById('fileInput');
dom.dropZone = document.getElementById('dropZone');
dom.projectStatus = document.getElementById('projectStatus');
dom.fileTableBody = document.getElementById('fileTableBody');
dom.outputEditor = document.getElementById('outputEditor');
dom.logNode = document.getElementById('logNode');
dom.optShowEditor = document.getElementById('optShowEditor');
dom.optDownload = document.getElementById('optDownload');
dom.optIncludeMarkers = document.getElementById('optIncludeMarkers');
dom.optBuildHeader = document.getElementById('optBuildHeader');
}
function bindEvents() {
dom.btnLoadFolder.addEventListener('click', handleLoadFolderClick);
dom.btnAddFiles.addEventListener('click', () => dom.fileInput.click());
dom.btnReload.addEventListener('click', reloadCurrentFolder);
dom.btnClear.addEventListener('click', clearProject);
dom.btnParseManifest.addEventListener('click', parseManifestFromLoadedFiles);
dom.btnGenerateManifest.addEventListener('click', generateManifestFromLoadedFiles);
dom.btnBuild.addEventListener('click', buildFromUi);
dom.btnDownload.addEventListener('click', () => downloadCurrentOutput());
dom.btnCopy.addEventListener('click', copyCurrentOutput);
dom.btnSelectOutput.addEventListener('click', selectOutputEditor);
dom.btnClearLog.addEventListener('click', clearLog);
dom.folderInput.addEventListener('change', () => handleFolderInput(dom.folderInput.files));
dom.fileInput.addEventListener('change', () => handleFileInput(dom.fileInput.files));
dom.fileTableBody.addEventListener('click', handleFileTableClick);
dom.optShowEditor.addEventListener('change', enforceOutputTargetSelection);
dom.optDownload.addEventListener('change', enforceOutputTargetSelection);
bindDropZone();
}
function bindDropZone() {
['dragenter', 'dragover'].forEach(eventName => {
dom.dropZone.addEventListener(eventName, event => {
event.preventDefault();
event.stopPropagation();
dom.dropZone.classList.add('is-over');
});
});
['dragleave', 'drop'].forEach(eventName => {
dom.dropZone.addEventListener(eventName, event => {
event.preventDefault();
event.stopPropagation();
dom.dropZone.classList.remove('is-over');
});
});
dom.dropZone.addEventListener('drop', async event => {
try {
const files = await readDroppedItems(event.dataTransfer);
if (files.length === 0) {
log('Drop did not provide readable files.');
return;
}
const looksLikeFolderDrop = files.some(item => item.source === 'FileSystemEntry');
if (looksLikeFolderDrop) {
setProjectFiles(files, { replace: true, source: 'drag-and-drop folder' });
} else {
setProjectFiles(files, { replace: false, source: 'drag-and-drop files' });
}
} catch (error) {
log(`Drop failed: ${error.message}`);
}
});
}
async function handleLoadFolderClick() {
if (typeof window.showDirectoryPicker === 'function') {
try {
const handle = await window.showDirectoryPicker({ mode: 'read' });
await loadFromDirectoryHandle(handle);
return;
} catch (error) {
if (error && error.name !== 'AbortError') {
log(`Native directory picker failed, using fallback: ${error.message}`);
}
}
}
dom.folderInput.value = '';
dom.folderInput.click();
}
async function loadFromDirectoryHandle(handle) {
const files = [];
await walkDirectoryHandle(handle, '', files);
state.folderReloadProvider = async () => loadFromDirectoryHandle(handle);
setProjectFiles(files, { replace: true, source: 'native directory picker' });
}
async function walkDirectoryHandle(dirHandle, prefix, output) {
for await (const [name, handle] of dirHandle.entries()) {
const relativePath = prefix ? `${prefix}/${name}` : name;
if (handle.kind === 'directory') {
await walkDirectoryHandle(handle, relativePath, output);
continue;
}
if (handle.kind === 'file') {
const file = await handle.getFile();
output.push(createLoadedFile(file, relativePath, 'DirectoryHandle'));
}
}
}
function handleFolderInput(fileList) {
const loaded = Array.from(fileList || []).map(file => {
const path = file.webkitRelativePath || file.name;
return createLoadedFile(file, path, 'webkitdirectory');
});
state.folderReloadProvider = null;
setProjectFiles(loaded, { replace: true, source: 'folder input' });
dom.folderInput.value = '';
}
function handleFileInput(fileList) {
const loaded = Array.from(fileList || []).map(file => createLoadedFile(file, file.webkitRelativePath || file.name, 'file input'));
setProjectFiles(loaded, { replace: false, source: 'manual file input' });
dom.fileInput.value = '';
}
async function readDroppedItems(dataTransfer) {
const items = Array.from(dataTransfer?.items || []);
const output = [];
if (items.length > 0 && typeof items[0].webkitGetAsEntry === 'function') {
for (const item of items) {
const entry = item.webkitGetAsEntry();
if (entry) {
await walkFileSystemEntry(entry, '', output);
}
}
return output;
}
return Array.from(dataTransfer?.files || []).map(file => createLoadedFile(file, file.webkitRelativePath || file.name, 'drop files'));
}
async function walkFileSystemEntry(entry, prefix, output) {
if (!entry) {
return;
}
const cleanName = String(entry.name || '').replace(/^\/+/, '');
const relativePath = prefix ? `${prefix}/${cleanName}` : cleanName;
if (entry.isFile) {
const file = await readFileSystemFile(entry);
output.push(createLoadedFile(file, relativePath, 'FileSystemEntry'));
return;
}
if (entry.isDirectory) {
const reader = entry.createReader();
const entries = await readAllDirectoryEntries(reader);
for (const child of entries) {
await walkFileSystemEntry(child, relativePath, output);
}
}
}
function readFileSystemFile(fileEntry) {
return new Promise((resolve, reject) => {
fileEntry.file(resolve, reject);
});
}
function readAllDirectoryEntries(reader) {
return new Promise((resolve, reject) => {
const output = [];
const readBatch = () => {
reader.readEntries(entries => {
if (!entries || entries.length === 0) {
resolve(output);
return;
}
output.push(...entries);
readBatch();
}, reject);
};
readBatch();
});
}
function handleFileTableClick(event) {
const button = event.target.closest('button[data-action="remove-file"]');
if (!button) {
return;
}
removeLoadedFile(button.dataset.fileId || '');
}
function removeLoadedFile(fileId) {
if (!fileId) {
return;
}
const removed = state.files.find(item => item.id === fileId);
if (!removed) {
return;
}
state.files = state.files.filter(item => item.id !== fileId);
state.fileMap = new Map(state.files.map(item => [item.path, item]));
detectProjectRootAndNormalizePaths();
parseManifestFromLoadedFiles({ silent: true });
state.outputText = '';
dom.outputEditor.value = '';
log(`Removed file: ${removed.internalPath || removed.path}`);
renderAll();
}
async function reloadCurrentFolder() {
if (typeof state.folderReloadProvider !== 'function') {
log('Reload is only available for native directory handles in this browser session. Use Load Folder again.');
return;
}
try {
await state.folderReloadProvider();
} catch (error) {
log(`Reload failed: ${error.message}`);
}
}
function createLoadedFile(file, relativePath, source) {
return {
id: `${Date.now()}_${Math.random().toString(36).slice(2)}`,
file,
path: normalizePath(relativePath || file.name),
internalPath: normalizePath(relativePath || file.name),
name: file.name,
size: file.size,
modified: file.lastModified || 0,
source,
};
}
function setProjectFiles(files, options = {}) {
const incoming = Array.isArray(files) ? files : [];
if (options.replace) {
state.files = [];
state.fileMap = new Map();
state.manifest = null;
state.manifestPath = '';
state.projectRootPrefix = '';
state.outputText = '';
state.outputFilename = 'userscript-build.txt';
dom.outputEditor.value = '';
}
incoming.forEach(fileInfo => {
const normalized = Object.assign({}, fileInfo, {
path: normalizePath(fileInfo.path),
internalPath: normalizePath(fileInfo.internalPath || fileInfo.path),
});
state.fileMap.set(normalized.path, normalized);
});
state.files = Array.from(state.fileMap.values()).sort((a, b) => a.path.localeCompare(b.path));
detectProjectRootAndNormalizePaths();
parseManifestFromLoadedFiles({ silent: true });
log(`${options.source || 'input'}: ${incoming.length} file(s) loaded. Project now has ${state.files.length} file(s).`);
renderAll();
}
function detectProjectRootAndNormalizePaths() {
const projectTomlCandidates = state.files
.map(item => item.path)
.filter(path => path.toLowerCase().endsWith('/project.toml') || path.toLowerCase() === 'project.toml')
.sort((a, b) => a.split('/').length - b.split('/').length);
if (projectTomlCandidates.length === 0) {
const sourceRootPrefix = detectProjectRootPrefixFromSourceDirectory();
state.projectRootPrefix = sourceRootPrefix;
state.files.forEach(item => {
item.internalPath = sourceRootPrefix && item.path.startsWith(sourceRootPrefix)
? item.path.slice(sourceRootPrefix.length)
: item.path;
});
return;
}
const manifestPath = projectTomlCandidates[0];
const prefix = manifestPath.toLowerCase() === 'project.toml'
? ''
: manifestPath.slice(0, -'project.toml'.length);
state.projectRootPrefix = prefix;
state.files.forEach(item => {
item.internalPath = prefix && item.path.startsWith(prefix)
? item.path.slice(prefix.length)
: item.path;
});
}
function detectProjectRootPrefixFromSourceDirectory() {
const candidates = state.files
.map(item => normalizePath(item.path))
.filter(path => path.toLowerCase().includes('/src/') || path.toLowerCase().startsWith('src/'))
.map(path => {
const lowerPath = path.toLowerCase();
const index = lowerPath.indexOf('src/');
return index > 0 ? path.slice(0, index) : '';
})
.sort((a, b) => a.length - b.length);
return candidates[0] || '';
}
async function parseManifestFromLoadedFiles(options = {}) {
const manifestFile = findFileByInternalPath('project.toml');
if (!manifestFile) {
state.manifest = null;
state.manifestPath = '';
if (!options.silent) {
log('project.toml not found. Build requires a manifest.');
}
renderAll();
return null;
}
try {
const text = await manifestFile.file.text();
const manifest = parseSimpleToml(text);
state.manifest = normalizeManifest(manifest);
state.manifestPath = manifestFile.internalPath;
state.outputFilename = forceTxtFilename(state.manifest.output || buildFallbackOutputName());
if (!options.silent) {
log(`Manifest parsed: ${state.manifest.name || 'Unnamed project'} ${state.manifest.version || ''}`.trim());
}
renderAll();
return state.manifest;
} catch (error) {
state.manifest = null;
state.manifestPath = '';
log(`Manifest parse failed: ${error.message}`);
renderAll();
return null;
}
}
function generateManifestFromLoadedFiles() {
if (state.files.length === 0) {
log('Generate manifest failed: no files loaded.');
return null;
}
detectProjectRootAndNormalizePaths();
const sourceFiles = state.files
.filter(fileInfo => isGeneratedManifestSourceCandidate(fileInfo.internalPath))
.sort((a, b) => naturalCompare(a.internalPath, b.internalPath));
if (sourceFiles.length === 0) {
log('Generate manifest failed: no source files found in src/.');
return null;
}
const manifestFiles = sourceFiles.map(fileInfo => normalizePath(fileInfo.internalPath).replace(/^src\//i, ''));
const projectName = buildProjectNameFromRoot() || 'Userscript Project';
const slug = slugify(projectName);
const version = '0.1.0-build-test';
const output = `${slug}-v0.1.0-build-test.txt`;
const tomlText = buildGeneratedProjectToml(projectName, slug, version, output, manifestFiles);
try {
state.manifest = normalizeManifest(parseSimpleToml(tomlText));
state.manifestPath = 'project.toml (generated)';
state.outputFilename = forceTxtFilename(state.manifest.output || buildFallbackOutputName());
downloadText('project.toml.txt', tomlText);
log(`Generated project.toml from ${manifestFiles.length} src file(s). Downloaded as project.toml.txt; rename to project.toml in the project root.`);
renderAll();
return state.manifest;
} catch (error) {
log(`Generate manifest failed: ${error.message}`);
return null;
}
}
function isGeneratedManifestSourceCandidate(path) {
const normalized = normalizePath(path).toLowerCase();
if (!normalized.startsWith('src/')) {
return false;
}
if (isDefaultExcludedProjectFile(normalized)) {
return false;
}
return /\.(js|txt|css)$/i.test(normalized);
}
function buildGeneratedProjectToml(projectName, slug, version, output, manifestFiles) {
const fileLines = manifestFiles.map(path => ` "${path.replace(/"/g, '\\"')}",`);
return [
`name = "${projectName.replace(/"/g, '\\"')}"`,
`slug = "${slug}"`,
`version = "${version}"`,
`date = "${SCRIPT_INFO.date}"`,
`output = "${output}"`,
'',
'[build]',
'source_dir = "src"',
'output_dir = "dist"',
'newline = "lf"',
'insert_include_markers = true',
'recursive = true',
'',
'files = [',
...fileLines,
']',
'',
'[checks]',
'require_userscript_header = true',
'require_wrapper_start = true',
'require_wrapper_end = true',
'require_boot_call = true',
'warn_unlisted_files = true',
'warn_duplicate_names = true',
'',
].join('\n');
}
function buildProjectNameFromRoot() {
const prefix = normalizePath(state.projectRootPrefix || '').replace(/\/$/, '');
if (!prefix) {
return '';
}
const parts = prefix.split('/').filter(Boolean);
const raw = parts[parts.length - 1] || '';
return raw
.replace(/[-_]+/g, ' ')
.replace(/\b\w/g, char => char.toUpperCase())
.trim();
}
function parseSimpleToml(text) {
const result = {};
const lines = normalizeText(text).split('\n');
let section = result;
let sectionName = '';
let index = 0;
while (index < lines.length) {
let line = stripTomlComment(lines[index]).trim();
index += 1;
if (!line) {
continue;
}
const sectionMatch = line.match(/^\[([A-Za-z0-9_.-]+)\]$/);
if (sectionMatch) {
sectionName = sectionMatch[1];
result[sectionName] = result[sectionName] && typeof result[sectionName] === 'object' ? result[sectionName] : {};
section = result[sectionName];
continue;
}
const keyMatch = line.match(/^([A-Za-z0-9_.-]+)\s*=\s*(.*)$/);
if (!keyMatch) {
continue;
}
const key = keyMatch[1];
let rawValue = keyMatch[2].trim();
if (rawValue === '[' || rawValue.startsWith('[') && !rawValue.includes(']')) {
const arrayLines = [];
if (rawValue !== '[') {
arrayLines.push(rawValue.replace(/^\[/, ''));