FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
adminforth/adminforth/modules/codeInjector.ts at main · devforth/adminforth · GitHub
devforth
adminforth
Repository navigation
Code
Issues
16
(16)
Pull requests
4
(4)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
adminforth
/
adminforth
/
modules
/
codeInjector.ts
Copy path
More file actions
More file actions
Latest commit
History
History
History
1573 lines (1370 loc) · 63.2 KB
Breadcrumbs
adminforth
/
adminforth
/
modules
/
codeInjector.ts
Copy path
File metadata and controls
1573 lines (1370 loc) · 63.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
{
exec
,
spawn
}
from
'child_process'
;
import
chokidar
from
'chokidar'
;
import
fs
from
'fs'
;
import
os
from
'os'
;
import
path
from
'path'
;
import
pLimit
from
'p-limit'
;
import
{
promisify
}
from
'util'
;
import
yaml
from
'yaml'
;
import
AdminForth
,
{
AdminForthConfigMenuItem
}
from
'../index.js'
;
import
{
ADMIN_FORTH_ABSOLUTE_PATH
,
getComponentNameFromPath
,
transformObject
,
deepMerge
,
md5hash
,
slugifyString
}
from
'./utils.js'
;
import
{
ICodeInjector
}
from
'../types/Back.js'
;
import
{
StylesGenerator
}
from
'./styleGenerator.js'
;
import
{
afLogger
}
from
'../modules/logger.js'
;
import
{
pathToFileURL
}
from
'url'
;
let
TMP_DIR
;
try
{
TMP_DIR
=
os
.
tmpdir
(
)
;
}
catch
(
e
)
{
if
(
process
.
platform
===
'win32'
)
{
TMP_DIR
=
process
.
env
.
TEMP
||
process
.
env
.
TMP
||
'C:\\Windows\\Temp'
;
}
else
{
TMP_DIR
=
'/tmp'
;
}
//maybe we can consider to use node_modules/.cache/adminforth here instead of tmp
}
function
stripAnsiCodes
(
str
)
{
// Regular expression to match ANSI escape codes
return
str
.
replace
(
/
\x1B
\[
[
0
-
9
;
]
*
[
a
-
z
A
-
Z
]
/
g
,
''
)
;
}
// how many files we copy into spa_tmp at the same time, to not exhaust file descriptors on big trees.
// One limiter for the whole module, so several copyTreeAtomic calls in a row share the same budget
// instead of each opening its own 32.
const
copyLimit
=
pLimit
(
32
)
;
// marks serveDir as created by AdminForth, so it is safe to remove it before a rebuild
const
SERVE_DIR_MARKER
=
'.adminforth_serve_dir'
;
// the only spa_tmp entries which survive prepareSources: node_modules is the install cache and hashes.json
// explains the next build cache miss. Everything else is copied from the sources again.
const
SPA_TMP_KEPT_ENTRIES
=
[
'node_modules'
,
'hashes.json'
]
;
// what prepareSources found out about SPA dependencies, installSpaDependencies installs them when they are needed
type
SpaDependencies
=
{
hash
:
string
,
icons
:
string
[
]
,
packages
:
string
[
]
,
}
;
let
atomicCopySeq
=
0
;
const
ATOMIC_COPY_TMP_RE
=
/
\.
a
f
-
(
\d
+
)
-
\d
+
\.
t
m
p
$
/
;
const
LOGIN_PAGE_ROUTE_PART_RE
=
/
\/
\*
I
M
P
O
R
T
A
N
T
:
A
D
M
I
N
F
O
R
T
H
L
O
G
I
N
P
A
G
E
S
T
A
R
T
\*
\/
[
\s
\S
]
*
?
\/
\*
I
M
P
O
R
T
A
N
T
:
A
D
M
I
N
F
O
R
T
H
L
O
G
I
N
P
A
G
E
E
N
D
\*
\/
/
;
function
isAtomicCopyTempName
(
name
:
string
)
:
boolean
{
return
ATOMIC_COPY_TMP_RE
.
test
(
name
)
;
}
// the pid baked into a copyFileAtomic temp name, so we can tell our own leftovers from someone else's
function
atomicCopyTempPid
(
name
:
string
)
:
number
|
null
{
const
match
=
name
.
match
(
ATOMIC_COPY_TMP_RE
)
;
return
match
?
parseInt
(
match
[
1
]
,
10
)
:
null
;
}
function
isProcessAlive
(
pid
:
number
)
:
boolean
{
try
{
process
.
kill
(
pid
,
0
)
;
return
true
;
}
catch
(
e
:
any
)
{
return
e
?.
code
===
'EPERM'
;
// exists but is not ours to signal
}
}
/**
* Copies a single file to dest atomically: the content goes to a unique temp file next to dest
* and is then renamed over it. rename(2) replaces the destination in one step (and MoveFileEx with
* MOVEFILE_REPLACE_EXISTING does the same on Windows), so dest is never missing or half-written.
*
* fsExtra.copy() cannot be used for this: for an existing destination it does
* unlink(dest) -> copyFile(src, dest) -> chmod(dest, mode) as three separate syscalls. Anything that
* writes the same destination in between - a second hot reload event, or another process bundling into
* the same spa_tmp - makes it fail with `ENOENT: ... unlink` or `ENOENT: ... chmod`, and readers
* (vite, computeSourcesHash) can observe a missing file.
*/
async
function
copyFileAtomic
(
src
:
string
,
dest
:
string
,
mode
?:
number
)
:
Promise
<
void
>
{
await
fs
.
promises
.
mkdir
(
path
.
dirname
(
dest
)
,
{
recursive
:
true
}
)
;
const
tmp
=
`
${
dest
}
.af-
${
process
.
pid
}
-
${
atomicCopySeq
++
}
.tmp`
;
try
{
await
fs
.
promises
.
copyFile
(
src
,
tmp
)
;
if
(
mode
!==
undefined
)
{
// safe to chmod before the rename: tmp is private to this call, nobody else can see it
await
fs
.
promises
.
chmod
(
tmp
,
mode
)
;
}
await
renameWithRetry
(
tmp
,
dest
)
;
}
catch
(
e
)
{
await
fs
.
promises
.
rm
(
tmp
,
{
force
:
true
}
)
.
catch
(
(
)
=>
{
}
)
;
throw
e
;
}
}
/**
* On Windows a rename over an open destination fails with EPERM/EACCES/EBUSY until the other holder
* (vite, an editor, an antivirus scanner) lets go, so give it a few short tries before giving up.
* On POSIX the first attempt always succeeds.
*/
async
function
renameWithRetry
(
from
:
string
,
to
:
string
,
attempts
=
5
)
:
Promise
<
void
>
{
for
(
let
attempt
=
1
;
;
attempt
++
)
{
try
{
await
fs
.
promises
.
rename
(
from
,
to
)
;
return
;
}
catch
(
e
:
any
)
{
const
retriable
=
e
?.
code
===
'EPERM'
||
e
?.
code
===
'EACCES'
||
e
?.
code
===
'EBUSY'
;
if
(
!
retriable
||
attempt
>=
attempts
)
{
throw
e
;
}
await
new
Promise
(
(
resolve
)
=>
setTimeout
(
resolve
,
10
*
attempt
)
)
;
}
}
}
/**
* Recursive copy with the semantics prepareSources relies on: symlinks are dereferenced,
* `filter` prunes a source path together with its subtree. Every file lands atomically
* (see copyFileAtomic) and file copies go through the shared copyLimit.
*/
async
function
copyTreeAtomic
(
src
:
string
,
dest
:
string
,
{
filter
}
:
{
filter
?:
(
src
:
string
)
=>
boolean
}
=
{
}
)
:
Promise
<
void
>
{
const
walk
=
async
(
from
:
string
,
to
:
string
)
=>
{
if
(
filter
&&
!
filter
(
from
)
)
{
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲⚙️ copyTreeAtomic filtered out,
${
from
}
`
)
;
return
;
}
// stat (not lstat) follows symlinks, same as fsExtra's dereference: true
const
stat
=
await
fs
.
promises
.
stat
(
from
)
;
if
(
stat
.
isDirectory
(
)
)
{
await
fs
.
promises
.
mkdir
(
to
,
{
recursive
:
true
}
)
;
const
entries
=
await
fs
.
promises
.
readdir
(
from
)
;
await
Promise
.
all
(
entries
.
map
(
(
name
)
=>
walk
(
path
.
join
(
from
,
name
)
,
path
.
join
(
to
,
name
)
)
)
)
;
}
else
{
await
copyLimit
(
(
)
=>
copyFileAtomic
(
from
,
to
,
stat
.
mode
)
)
;
}
}
;
await
walk
(
src
,
dest
)
;
}
function
findHomePage
(
menuItem
:
AdminForthConfigMenuItem
[
]
)
:
AdminForthConfigMenuItem
|
undefined
{
for
(
const
item
of
menuItem
)
{
if
(
item
.
homepage
)
{
return
item
;
}
if
(
item
.
children
)
{
const
found
=
findHomePage
(
item
.
children
)
;
if
(
found
)
{
return
found
;
}
}
}
return
undefined
;
}
async
function
findFirstMenuItemWithResource
(
menuItem
:
AdminForthConfigMenuItem
[
]
)
:
Promise
<
AdminForthConfigMenuItem
|
undefined
>
{
for
(
const
item
of
menuItem
)
{
if
(
item
.
path
||
item
.
resourceId
)
{
return
item
;
}
if
(
item
.
children
)
{
const
found
=
await
findFirstMenuItemWithResource
(
item
.
children
)
;
if
(
found
)
{
return
found
;
}
}
}
return
undefined
;
}
const
execAsync
=
promisify
(
exec
)
;
function
hashify
(
obj
)
{
return
md5hash
(
JSON
.
stringify
(
obj
)
)
;
}
function
isFulfilled
<
T
>
(
result
:
PromiseSettledResult
<
T
>
)
:
result
is
PromiseFulfilledResult
<
T
>
{
return
result
.
status
===
'fulfilled'
;
}
/**
* chokidar options shared by both watchers.
*
* awaitWriteFinish is what makes a save safe to act on: chokidar waits for the size to stop changing
* before emitting, so we never copy a half-written .vue file. atomic (default true) collapses the
* unlink+add pair that editors produce when they save via a temp file and rename.
*
* Polling is deliberately not configured here: chokidar honours CHOKIDAR_USEPOLLING and
* CHOKIDAR_INTERVAL on its own, and that is the same switch vite's watcher reads.
*/
function
watcherOptions
(
)
{
return
{
ignoreInitial
:
true
,
awaitWriteFinish
:
{
stabilityThreshold
:
60
,
pollInterval
:
20
,
}
,
ignored
:
(
checkedPath
:
string
)
=>
{
const
base
=
path
.
basename
(
checkedPath
)
;
return
base
===
'node_modules'
||
base
===
'dist'
||
isAtomicCopyTempName
(
base
)
;
}
,
}
;
}
class
CodeInjector
implements
ICodeInjector
{
allWatchers
=
[
]
;
adminforth
:
AdminForth
;
allComponentNames
:
{
[
key
:
string
]
:
string
}
=
{
}
;
srcFoldersToSync
:
{
[
key
:
string
]
:
string
}
=
{
}
;
publicFoldersToSync
:
{
[
key
:
string
]
:
string
}
=
{
}
;
devServerPort
:
number
=
null
;
spaTmpPath
(
)
:
string
{
const
{
spaBuildDir
,
brandNameSlug
}
=
this
.
adminforth
.
config
.
customization
;
if
(
spaBuildDir
)
{
return
path
.
join
(
spaBuildDir
,
'spa_tmp'
)
;
}
if
(
!
brandNameSlug
)
{
throw
new
Error
(
'brandSlug is empty, but it should be populated at least by config Validator '
)
;
}
return
path
.
join
(
TMP_DIR
,
'adminforth'
,
brandNameSlug
,
'spa_tmp'
)
;
}
/**
* spa_tmp is named after the brand slug only, so every run of the same project shares one folder.
* We record who owns it next to it (not inside, so it stays out of the sources hash) purely to make
* a second process visible: two of them copy over each other's files, which surfaces later as a
* random fs error in an unrelated place. Investigation notes are in AdminForth/1519.
*/
private
async
claimSpaTmp
(
)
:
Promise
<
void
>
{
const
ownerFile
=
path
.
join
(
path
.
dirname
(
this
.
spaTmpPath
(
)
)
,
'.owner'
)
;
const
previous
=
await
this
.
tryReadFile
(
ownerFile
)
;
if
(
previous
)
{
const
[
pidText
,
...
command
]
=
previous
.
trim
(
)
.
split
(
' '
)
;
const
pid
=
parseInt
(
pidText
,
10
)
;
if
(
pid
&&
pid
!==
process
.
pid
&&
isProcessAlive
(
pid
)
)
{
afLogger
.
warn
(
`Another AdminForth process is already using
${
this
.
spaTmpPath
(
)
}
: pid
${
pid
}
`
+
`
${
command
.
length
?
` (
${
command
.
join
(
' '
)
}
)`
:
''
}
. They share this folder because it is named `
+
`after the brand only, so their file copies overwrite each other. If you did not start a second `
+
`dev server or "npx adminforth bundle" on purpose, please report this on AdminForth/1519.`
)
;
}
}
await
fs
.
promises
.
writeFile
(
ownerFile
,
`
${
process
.
pid
}
${
process
.
argv
.
slice
(
1
)
.
join
(
' '
)
}
`
)
.
catch
(
(
)
=>
{
}
)
;
}
async
checkIconNames
(
icons
:
string
[
]
)
{
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`Checking icon names:
${
icons
.
join
(
', '
)
}
`
)
;
const
uniqueIcons
=
Array
.
from
(
new
Set
(
icons
)
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`Unique icons:
${
uniqueIcons
.
join
(
', '
)
}
`
)
;
const
collections
=
new
Set
(
icons
.
map
(
(
icon
)
=>
icon
.
split
(
':'
)
[
0
]
)
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`Icon collections:
${
Array
.
from
(
collections
)
.
join
(
', '
)
}
`
)
;
const
iconPackageNames
=
Array
.
from
(
collections
)
.
map
(
(
collection
)
=>
`@iconify-prerendered/vue-
${
collection
}
`
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`Icon package names:
${
iconPackageNames
.
join
(
', '
)
}
`
)
;
const
iconPackages
=
(
await
Promise
.
allSettled
(
iconPackageNames
.
map
(
async
(
pkg
)
=>
(
{
pkg
:
await
import
(
pathToFileURL
(
path
.
join
(
this
.
spaTmpPath
(
)
,
'node_modules'
,
pkg
,
'index.js'
)
)
.
href
)
,
name
:
pkg
}
)
)
)
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`Icon packages load results:
${
iconPackages
.
map
(
res
=>
res
.
status
===
'fulfilled'
?
res
.
value
.
name
:
'error:'
+
res
.
reason
)
.
join
(
', '
)
}
`
)
;
const
loadedIconPackages
=
iconPackages
.
filter
(
isFulfilled
)
.
map
(
(
res
)
=>
res
.
value
)
.
reduce
(
(
acc
,
{
pkg
,
name
}
)
=>
{
acc
[
name
.
slice
(
`@iconify-prerendered/vue-`
.
length
)
]
=
pkg
;
return
acc
;
}
,
{
}
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`Loaded icon packages:
${
Object
.
keys
(
loadedIconPackages
)
.
join
(
', '
)
}
`
)
;
uniqueIcons
.
forEach
(
(
icon
)
=>
{
const
[
collection
,
iconName
]
=
icon
.
split
(
':'
)
;
const
PascalIconName
=
'Icon'
+
iconName
.
split
(
'-'
)
.
map
(
(
part
,
index
)
=>
{
return
part
[
0
]
.
toUpperCase
(
)
+
part
.
slice
(
1
)
;
}
)
.
join
(
''
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`Checking icon:
${
icon
}
, collection:
${
collection
}
, iconName:
${
iconName
}
, PascalIconName:
${
PascalIconName
}
`
)
;
if
(
!
loadedIconPackages
[
collection
]
)
{
throw
new
Error
(
`Collection
${
collection
}
not found`
)
;
}
if
(
!
loadedIconPackages
[
collection
]
[
PascalIconName
]
)
{
throw
new
Error
(
`Icon
${
iconName
}
not found in collection
${
collection
}
`
)
;
}
}
)
;
}
registerCustomComponent
(
filePath
:
string
)
:
void
{
const
componentName
=
getComponentNameFromPath
(
filePath
)
;
this
.
allComponentNames
[
filePath
]
=
componentName
;
}
collectTailwindSafelist
(
)
:
string
[
]
{
const
classes
=
new
Set
<
string
>
(
)
;
for
(
const
resource
of
this
.
adminforth
.
config
.
resources
)
{
for
(
const
column
of
resource
.
columns
||
[
]
)
{
if
(
!
column
.
listCssClass
)
{
continue
;
}
column
.
listCssClass
.
split
(
/
\s
+
/
)
.
filter
(
Boolean
)
.
forEach
(
(
className
)
=>
classes
.
add
(
className
)
)
;
}
}
return
Array
.
from
(
classes
)
;
}
cleanup
(
)
{
console
.
log
(
'Cleaning up...'
)
;
this
.
allWatchers
.
forEach
(
(
watcher
)
=>
{
// close() is async, but the signal handler exits right after us - firing it is all we can do,
// and an already-closed watcher must not throw out of a signal handler
try
{
watcher
.
close
(
)
;
}
catch
(
e
)
{
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲 Failed to close a watcher:
${
e
}
`
)
;
}
}
)
;
}
constructor
(
adminforth
)
{
this
.
adminforth
=
adminforth
;
[
'SIGINT'
,
'SIGTERM'
,
'SIGQUIT'
]
.
forEach
(
signal
=>
process
.
on
(
signal
,
(
)
=>
{
this
.
cleanup
(
)
;
process
.
exit
(
)
;
}
)
)
;
}
public
async
doesUserHasPnpmLockFile
(
dir
:
string
)
:
Promise
<
boolean
>
{
if
(
!
dir
)
{
return
false
;
}
const
usersPackagePath
=
path
.
join
(
dir
,
'package.json'
)
;
let
packageContent
:
{
dependencies
:
any
,
devDependencies
:
any
}
=
null
;
try
{
packageContent
=
JSON
.
parse
(
await
fs
.
promises
.
readFile
(
usersPackagePath
,
'utf-8'
)
)
;
}
catch
(
e
)
{
// user package.json does not exist, user does not have custom components
}
if
(
packageContent
)
{
const
lockPath
=
path
.
join
(
dir
,
'pnpm-lock.yaml'
)
;
let
lock
:
any
=
null
;
try
{
lock
=
yaml
.
parse
(
await
fs
.
promises
.
readFile
(
lockPath
,
'utf-8'
)
)
;
return
true
;
}
catch
(
e
)
{
return
false
;
}
}
return
false
;
}
async
runPackageManagerShell
(
{
command
,
cwd
,
envOverrides
=
{
}
}
:
{
command
:
string
,
cwd
:
string
,
envOverrides
?:
{
[
key
:
string
]
:
string
}
}
)
{
const
nodeBinary
=
process
.
execPath
;
// Path to the Node.js binary running this script
const
doesUserHavePnpmLock
=
await
this
.
doesUserHasPnpmLockFile
(
this
.
adminforth
.
config
.
customization
.
customComponentsDir
)
;
// On Windows, npm/pnpm is npm/pnpm.cmd, on Unix systems it's npm/pnpm
let
packageExecutable
if
(
doesUserHavePnpmLock
)
{
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`User has pnpm-lock.yaml, using pnpm for installing custom components`
)
;
packageExecutable
=
process
.
platform
===
'win32'
?
'pnpm.cmd'
:
'pnpm'
;
}
else
{
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`User does not have pnpm-lock.yaml, falling back to npm for installing custom components`
)
;
packageExecutable
=
process
.
platform
===
'win32'
?
'npm.cmd'
:
'npm'
;
}
const
packagePath
=
path
.
join
(
path
.
dirname
(
nodeBinary
)
,
packageExecutable
)
;
// Path to the package executable
const
env
=
{
VITE_ADMINFORTH_PUBLIC_PATH
:
this
.
adminforth
.
config
.
baseUrl
,
FORCE_COLOR
:
'1'
,
...
process
.
env
,
...
envOverrides
,
}
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`⚙️ exec:
${
packageExecutable
}
${
command
}
`
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲
${
packageExecutable
}
${
command
}
cwd:
${
cwd
}
`
)
;
let
execCommand
:
string
;
if
(
process
.
platform
===
'win32'
)
{
// Quote path if it contains spaces
const
quotedPackagePath
=
packagePath
.
includes
(
' '
)
?
`"
${
packagePath
}
"`
:
packagePath
;
execCommand
=
`
${
quotedPackagePath
}
${
command
}
`
;
}
else
{
// Quote paths that contain spaces (for Unix systems)
const
quotedNodeBinary
=
nodeBinary
.
includes
(
' '
)
?
`"
${
nodeBinary
}
"`
:
nodeBinary
;
const
quotedPackagePath
=
packagePath
.
includes
(
' '
)
?
`"
${
packagePath
}
"`
:
packagePath
;
execCommand
=
`
${
quotedNodeBinary
}
${
quotedPackagePath
}
${
command
}
`
;
}
const
execOptions
:
any
=
{
cwd
,
env
,
}
;
if
(
process
.
platform
===
'win32'
)
{
execOptions
.
shell
=
true
;
}
const
{
stderr
:
err
}
=
await
execAsync
(
execCommand
,
execOptions
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`
${
packageExecutable
}
${
command
}
done in`
)
;
if
(
err
)
{
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲
${
packageExecutable
}
${
command
}
errors/warnings:
${
err
}
`
)
;
}
}
async
rmTmpDir
(
)
{
// remove spa_tmp folder if it is exists
try
{
await
fs
.
promises
.
rm
(
this
.
spaTmpPath
(
)
,
{
recursive
:
true
}
)
;
}
catch
(
e
)
{
// ignore
}
}
getServeDir
(
)
{
return
this
.
adminforth
.
config
.
customization
.
spaServeDir
||
path
.
join
(
this
.
getSpaDir
(
)
,
'dist'
)
;
}
/**
* serveDir is removed before every rebuild, so a user-configured spaServeDir which points to a folder with
* other files must not be wiped: only an empty folder or one created by AdminForth (it has the marker) is cleared.
* The default serveDir lives inside the AdminForth package, so it is always ours.
*/
private
async
assertServeDirCanBeCleared
(
serveDir
:
string
)
:
Promise
<
void
>
{
if
(
!
this
.
adminforth
.
config
.
customization
.
spaServeDir
)
{
return
;
}
let
entries
:
string
[
]
;
try
{
entries
=
await
fs
.
promises
.
readdir
(
serveDir
)
;
}
catch
(
e
)
{
if
(
e
.
code
===
'ENOENT'
)
{
return
;
}
throw
e
;
}
if
(
entries
.
length
&&
!
entries
.
includes
(
SERVE_DIR_MARKER
)
)
{
throw
new
Error
(
`customization.spaServeDir "
${
serveDir
}
" is not empty and was not created by AdminForth. `
+
`Its content is removed on every SPA rebuild, so please point spaServeDir to a dedicated directory.`
)
;
}
}
async
parsePackageLockPackages
(
dir
:
string
,
packageContent
:
{
dependencies
:
any
,
devDependencies
:
any
}
)
:
Promise
<
[
string
,
string
[
]
]
>
{
const
npmLockPath
=
path
.
join
(
dir
,
'package-lock.json'
)
;
let
npmLock
:
any
=
null
;
try
{
npmLock
=
JSON
.
parse
(
await
fs
.
promises
.
readFile
(
npmLockPath
,
'utf-8'
)
)
;
}
catch
(
npmLockError
)
{
throw
new
Error
(
`Custom pnpm-lock.yaml or package-lock.json does not exist in
${
dir
}
, but package.json does.
We can't determine version of packages without pnpm-lock.yaml or package-lock.json. Please run pnpm install or npm install in
${
dir
}
`
)
;
}
const
lockHash
=
hashify
(
npmLock
)
;
const
packages
=
[
...
Object
.
keys
(
packageContent
.
dependencies
||
{
}
)
,
...
Object
.
keys
(
packageContent
.
devDependencies
||
{
}
)
]
.
reduce
(
(
acc
,
packageName
)
=>
{
const
pack
=
npmLock
?.
packages
?.
[
`node_modules/
${
packageName
}
`
]
;
if
(
!
pack
?.
version
)
{
throw
new
Error
(
`Package
${
packageName
}
is not in package-lock.json but is in package.json. Please run 'npm install' in
${
dir
}
`
)
;
}
acc
.
push
(
`
${
packageName
}
@
${
pack
.
version
}
`
)
;
return
acc
;
}
,
[
]
)
;
return
[
lockHash
,
packages
]
;
}
async
packagesFromPnpm
(
dir
:
string
)
:
Promise
<
[
string
,
string
[
]
]
>
{
const
usersPackagePath
=
path
.
join
(
dir
,
'package.json'
)
;
let
packageContent
:
{
dependencies
:
any
,
devDependencies
:
any
}
=
null
;
let
lockHash
:
string
=
''
;
let
packages
:
string
[
]
=
[
]
;
try
{
packageContent
=
JSON
.
parse
(
await
fs
.
promises
.
readFile
(
usersPackagePath
,
'utf-8'
)
)
;
}
catch
(
e
)
{
// user package.json does not exist, user does not have custom components
}
if
(
packageContent
)
{
const
lockPath
=
path
.
join
(
dir
,
'pnpm-lock.yaml'
)
;
let
lock
:
any
=
null
;
try
{
lock
=
yaml
.
parse
(
await
fs
.
promises
.
readFile
(
lockPath
,
'utf-8'
)
)
;
}
catch
(
e
)
{
return
await
this
.
parsePackageLockPackages
(
dir
,
packageContent
)
;
}
lockHash
=
hashify
(
lock
)
;
const
importer
=
lock
?.
importers
?.
[
'.'
]
;
if
(
!
importer
)
{
throw
new
Error
(
`pnpm-lock.yaml in
${
dir
}
does not contain importer ".". Please run pnpm install in
${
dir
}
`
)
;
}
const
importerDeps
=
{
...
(
importer
.
dependencies
||
{
}
)
,
...
(
importer
.
devDependencies
||
{
}
)
,
...
(
importer
.
optionalDependencies
||
{
}
)
,
}
;
try
{
packages
=
[
...
Object
.
keys
(
packageContent
.
dependencies
||
{
}
)
,
...
Object
.
keys
(
packageContent
.
devDependencies
||
{
}
)
]
.
reduce
(
(
acc
,
packageName
)
=>
{
const
depInfo
=
importerDeps
[
packageName
]
;
const
raw
=
typeof
depInfo
===
'string'
?
depInfo
:
(
depInfo
?.
version
||
depInfo
?.
specifier
)
;
if
(
!
raw
)
{
throw
new
Error
(
`Package
${
packageName
}
is not in pnpm-lock.yaml but is in package.json. Please run 'pnpm install' in
${
dir
}
`
)
;
}
const
cleaned
=
raw
.
includes
(
'('
)
?
raw
.
split
(
'('
)
[
0
]
:
raw
;
acc
.
push
(
`
${
packageName
}
@
${
cleaned
}
`
)
;
return
acc
;
}
,
[
]
)
;
}
catch
(
e
)
{
console
.
log
(
`Error while parsing pnpm-lock.yaml:
${
e
.
message
}
. Falling back to package-lock.json parsing.`
)
;
// if there there is no sync between package.json and pnpm-lock.yaml - fallback to the package-lock.json parsing
return
await
this
.
parsePackageLockPackages
(
dir
,
packageContent
)
;
}
}
return
[
lockHash
,
packages
]
;
}
async
allowBuildsFromWorkspaceFile
(
dir
:
string
,
sourceName
:
string
)
:
Promise
<
{
[
packageName
:
string
]
:
boolean
}
>
{
const
content
=
await
this
.
tryReadFile
(
path
.
join
(
dir
,
'pnpm-workspace.yaml'
)
)
;
if
(
!
content
)
{
return
{
}
;
}
let
parsed
:
any
=
null
;
try
{
parsed
=
yaml
.
parse
(
content
)
;
}
catch
(
e
)
{
afLogger
.
warn
(
`Could not parse pnpm-workspace.yaml in
${
dir
}
, ignoring its allowBuilds:
${
e
.
message
}
`
)
;
return
{
}
;
}
const
allowBuilds
:
{
[
packageName
:
string
]
:
boolean
}
=
{
}
;
for
(
const
[
packageName
,
allowed
]
of
Object
.
entries
(
parsed
?.
allowBuilds
||
{
}
)
)
{
if
(
typeof
allowed
!==
'boolean'
)
{
afLogger
.
warn
(
`Ignoring allowBuilds."
${
packageName
}
" declared by
${
sourceName
}
: expected true or false, got
${
JSON
.
stringify
(
allowed
)
}
`
)
;
continue
;
}
allowBuilds
[
packageName
]
=
allowed
;
}
return
allowBuilds
;
}
async
syncAllowBuildsToSpaTmp
(
)
:
Promise
<
{
[
packageName
:
string
]
:
boolean
}
>
{
const
sources
:
{
name
:
string
,
dir
:
string
}
[
]
=
[
]
;
const
customComponentsDir
=
this
.
adminforth
.
config
.
customization
?.
customComponentsDir
;
if
(
customComponentsDir
)
{
sources
.
push
(
{
name
:
'customComponentsDir'
,
dir
:
path
.
resolve
(
customComponentsDir
)
}
)
;
}
for
(
const
plugin
of
this
.
adminforth
.
activatedPlugins
)
{
sources
.
push
(
{
name
:
plugin
.
constructor
.
name
,
dir
:
plugin
.
customFolderPath
}
)
;
}
const
merged
:
{
[
packageName
:
string
]
:
boolean
}
=
{
}
;
for
(
const
{
name
,
dir
}
of
sources
)
{
const
allowBuilds
=
await
this
.
allowBuildsFromWorkspaceFile
(
dir
,
name
)
;
for
(
const
[
packageName
,
allowed
]
of
Object
.
entries
(
allowBuilds
)
)
{
if
(
merged
[
packageName
]
!==
undefined
&&
merged
[
packageName
]
!==
allowed
)
{
afLogger
.
warn
(
`Conflicting allowBuilds for "
${
packageName
}
", denying the build. Last source:
${
name
}
`
)
;
merged
[
packageName
]
=
false
;
continue
;
}
merged
[
packageName
]
=
allowed
;
}
}
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲 allowBuilds collected from plugins/custom dir:
${
JSON
.
stringify
(
merged
)
}
`
)
;
if
(
!
Object
.
keys
(
merged
)
.
length
)
{
return
merged
;
}
const
workspacePath
=
path
.
join
(
this
.
spaTmpPath
(
)
,
'pnpm-workspace.yaml'
)
;
const
workspaceContent
=
await
this
.
tryReadFile
(
workspacePath
)
;
const
workspace
=
workspaceContent
?
(
yaml
.
parse
(
workspaceContent
)
||
{
}
)
:
{
}
;
workspace
.
allowBuilds
=
{
...
merged
,
...
(
workspace
.
allowBuilds
||
{
}
)
}
;
await
fs
.
promises
.
writeFile
(
workspacePath
,
yaml
.
stringify
(
workspace
)
)
;
return
merged
;
}
getSpaDir
(
)
{
let
spaDir
=
path
.
join
(
ADMIN_FORTH_ABSOLUTE_PATH
,
'spa'
)
;
if
(
!
fs
.
existsSync
(
spaDir
)
)
{
spaDir
=
path
.
join
(
ADMIN_FORTH_ABSOLUTE_PATH
,
'dist'
,
'spa'
)
;
}
return
spaDir
;
}
registerPluginPublicFoldersToSync
(
)
{
this
.
publicFoldersToSync
=
{
}
;
for
(
const
plugin
of
this
.
adminforth
.
activatedPlugins
)
{
const
pluginPublicFolderPath
=
path
.
join
(
plugin
.
customFolderPath
,
'public'
)
;
if
(
fs
.
existsSync
(
pluginPublicFolderPath
)
)
{
this
.
publicFoldersToSync
[
pluginPublicFolderPath
]
=
`./plugins/
${
plugin
.
className
}
/`
;
}
}
}
async
updatePartials
(
{
filesUpdated
}
:
{
filesUpdated
:
string
[
]
}
)
{
const
spaDir
=
this
.
getSpaDir
(
)
;
// copy only updated files
await
Promise
.
all
(
filesUpdated
.
map
(
async
(
file
)
=>
{
const
src
=
path
.
join
(
spaDir
,
file
)
;
const
dest
=
path
.
join
(
this
.
spaTmpPath
(
)
,
file
)
;
// atomic: a hot reload copy must never leave dest missing for a reader (vite / computeSourcesHash)
await
copyFileAtomic
(
src
,
dest
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲⚙️ copyFileAtomic copy single file,
${
src
}
,
${
dest
}
`
)
;
}
)
)
;
}
async
migrateLegacyCustomLayout
(
oldMeta
)
{
if
(
oldMeta
.
customLayout
===
true
)
{
oldMeta
.
sidebarAndHeader
=
"none"
;
}
return
oldMeta
;
}
async
prepareSources
(
)
:
Promise
<
SpaDependencies
>
{
// collects all files and folders into SPA_TMP_DIR
// check spa tmp folder exists and create if not
try
{
await
fs
.
promises
.
access
(
this
.
spaTmpPath
(
)
,
fs
.
constants
.
F_OK
)
;
}
catch
(
e
)
{
await
fs
.
promises
.
mkdir
(
this
.
spaTmpPath
(
)
,
{
recursive
:
true
}
)
;
}
await
this
.
claimSpaTmp
(
)
;
// leftovers of deleted sources would stay in the sources hash, so a build made in a reused spa_tmp
// (e.g. docker build with a cache mount) would never match a clean spa_tmp of the same sources at runtime
const
spaTmpEntries
=
await
fs
.
promises
.
readdir
(
this
.
spaTmpPath
(
)
)
;
await
Promise
.
all
(
spaTmpEntries
.
filter
(
(
entry
)
=>
!
SPA_TMP_KEPT_ENTRIES
.
includes
(
entry
)
)
.
map
(
(
entry
)
=>
fs
.
promises
.
rm
(
path
.
join
(
this
.
spaTmpPath
(
)
,
entry
)
,
{
recursive
:
true
,
force
:
true
}
)
)
)
;
const
icons
=
[
]
;
let
routes
=
''
;
let
routerComponents
=
''
;
const
collectAssetsFromMenu
=
(
menu
)
=>
{
menu
.
forEach
(
(
item
)
=>
{
if
(
item
.
icon
)
{
icons
.
push
(
item
.
icon
)
;
}
if
(
item
.
component
)
{
if
(
Object
.
keys
(
item
)
.
includes
(
'isStaticRoute'
)
)
{
if
(
!
item
.
isStaticRoute
)
{
routes
+=
`{
path: '
${
item
.
path
}
',
name: '
${
item
.
path
}
',
component: () => import('
${
item
.
component
}
'),
meta: { title: '
${
item
?.
meta
?.
title
||
item
?.
label
||
item
.
path
.
replace
(
'/'
,
''
)
}
'}
},\n`
}
else
{
routes
+=
`{
path: '
${
item
.
path
}
',
name: '
${
item
.
path
}
',
component:
${
getComponentNameFromPath
(
item
.
component
)
}
,
meta: { title: '
${
item
?.
meta
?.
title
||
item
?.
label
||
item
.
path
.
replace
(
'/'
,
''
)
}
'}
},\n`
const
componentName
=
`
${
getComponentNameFromPath
(
item
.
component
)
}
`
;
routerComponents
+=
`import
${
componentName
}
from '
${
item
.
component
}
';\n`
;
}
}
else
{
if
(
item
.
homepage
)
{
routes
+=
`{
path: '
${
item
.
path
}
',
name: '
${
item
.
path
}
',
component:
${
getComponentNameFromPath
(
item
.
component
)
}
,
meta: { title: '
${
item
?.
meta
?.
title
||
item
?.
label
||
item
.
path
.
replace
(
'/'
,
''
)
}
'}
},\n`
const
componentName
=
`
${
getComponentNameFromPath
(
item
.
component
)
}
`
;
routerComponents
+=
`import
${
componentName
}
from '
${
item
.
component
}
';\n`
;
}
else
{
routes
+=
`{
path: '
${
item
.
path
}
',
name: '
${
item
.
path
}
',
component: () => import('
${
item
.
component
}
'),
meta: { title: '
${
item
?.
meta
?.
title
||
item
.
path
.
replace
(
'/'
,
''
)
}
'}
},\n`
}
}
}
if
(
item
.
children
)
{
collectAssetsFromMenu
(
item
.
children
)
;
}
}
)
;
}
;
const
registerCustomPages
=
(
config
)
=>
{
if
(
config
.
customization
.
customPages
)
{
config
.
customization
.
customPages
.
forEach
(
async
(
page
)
=>
{
const
newMeta
=
await
this
.
migrateLegacyCustomLayout
(
page
?.
component
?.
meta
||
{
}
)
;
routes
+=
`{
path: '
${
page
.
path
}
',
name: '
${
page
.
path
}
',
component: () => import('
${
page
?.
component
?.
file
||
page
.
component
}
'),
meta:
${
JSON
.
stringify
(
{
...
newMeta
,
title
:
page
.
meta
?.
title
||
page
.
path
.
replace
(
'/'
,
''
)
}
)
}
},`
}
)
}
}
const
registerSettingPages
=
(
settingPage
)
=>
{
if
(
!
settingPage
)
{
return
;
}
for
(
const
page
of
settingPage
)
{
if
(
page
.
icon
)
{
icons
.
push
(
page
.
icon
)
;
}
}
}
registerCustomPages
(
this
.
adminforth
.
config
)
;
const
menuWithContributions
=
await
this
.
adminforth
.
getMenuWithContributions
(
)
;
collectAssetsFromMenu
(
menuWithContributions
)
;
registerSettingPages
(
this
.
adminforth
.
config
.
auth
.
userMenuSettingsPages
)
;
const
spaDir
=
this
.
getSpaDir
(
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲⚙️ copyTreeAtomic from
${
spaDir
}
->
${
this
.
spaTmpPath
(
)
}
`
)
;
// overwrite can't be used to not destroy cache
await
copyTreeAtomic
(
spaDir
,
this
.
spaTmpPath
(
)
,
{
filter
:
(
src
)
=>
{
// /adminforth/* used for local development and /dist/* used for production
const
filterPasses
=
!
src
.
includes
(
`
${
path
.
sep
}
adminforth
${
path
.
sep
}
spa
${
path
.
sep
}
node_modules`
)
&&
!
src
.
includes
(
`
${
path
.
sep
}
adminforth
${
path
.
sep
}
spa
${
path
.
sep
}
dist`
)
&&
!
src
.
includes
(
`
${
path
.
sep
}
dist
${
path
.
sep
}
spa
${
path
.
sep
}
node_modules`
)
&&
!
src
.
includes
(
`
${
path
.
sep
}
dist
${
path
.
sep
}
spa
${
path
.
sep
}
dist`
)
;
return
filterPasses
}
,
}
)
;
// copy whole custom directory
if
(
this
.
adminforth
.
config
.
customization
?.
customComponentsDir
)
{
// resolve customComponentsDir to absolute path, so ./aa will be resolved to /path/to/current/dir/aa
const
customCompAbsPath
=
path
.
resolve
(
this
.
adminforth
.
config
.
customization
.
customComponentsDir
)
;
this
.
srcFoldersToSync
[
customCompAbsPath
]
=
'./'
}
this
.
registerPluginPublicFoldersToSync
(
)
;
// if this.adminforth.config.customization.favicon is set, copy it to assets
const
customFav
=
this
.
adminforth
.
config
.
customization
?.
favicon
;
if
(
customFav
)
{
const
faviconPath
=
path
.
join
(
this
.
adminforth
.
config
.
customization
?.
customComponentsDir
,
customFav
.
replace
(
'@@/'
,
''
)
)
;
const
dest
=
path
.
join
(
this
.
spaTmpPath
(
)
,
'public'
,
'assets'
,
customFav
.
replace
(
'@@/'
,
''
)
)
;
// copyFileAtomic creates all folders in dest itself
await
copyFileAtomic
(
faviconPath
,
dest
)
;
}
for
(
const
[
src
,
dest
]
of
Object
.
entries
(
this
.
srcFoldersToSync
)
)
{
const
to
=
path
.
join
(
this
.
spaTmpPath
(
)
,
'src'
,
'custom'
,
dest
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲⚙️ srcFoldersToSync: copyTreeAtomic from
${
src
}
,
${
to
}
`
)
;
await
copyTreeAtomic
(
src
,
to
,
{
// exclude if node_modules comes after /custom/ in path
filter
:
(
src
)
=>
!
src
.
includes
(
path
.
join
(
'custom'
,
'node_modules'
)
)
,
}
)
;
}
for
(
const
[
src
,
dest
]
of
Object
.
entries
(
this
.
publicFoldersToSync
)
)
{
const
to
=
path
.
join
(
this
.
spaTmpPath
(
)
,
'public'
,
dest
)
;
process
.
env
.
HEAVY_DEBUG
&&
console
.
log
(
`🪲⚙️ publicFoldersToSync: copyTreeAtomic from
${
src
}
,
${
to
}
`
)
;
await
copyTreeAtomic
(
src
,
to
)
;
}
//collect all 'icon' fields from resources bulkActions
this
.
adminforth
.
config
.
resources
.
forEach
(
(
resource
)
=>
{
if
(
resource
.
options
?.
bulkActions
)
{
resource
.
options
.
bulkActions
.
forEach
(
(
action
)
=>
{
if
(
action
.
icon
)
{
icons
.
push
(
action
.
icon
)
;
}
}
)
;
}
if
(
resource
.
options
?.
actions
)
{
resource
.
options
.
actions
.
forEach
(
(
action
)
=>
{
if
(
action
.
icon
)
{
icons
.
push
(
action
.
icon
)
;
}
}
)
;
}
}
)
;
const
uniqueIcons
=
Array
.
from
(
new
Set
(
icons
)
)
;
// icons are collectionName:iconName. Get list of all unique collection names:
const
collections
=
new
Set
(
icons
.
map
(
(
icon
)
=>
icon
.
split
(
':'
)
[
0
]
)
)
;
// package names
@iconify
-prerendered/vue-<collection name>
const
iconPackageNames
=
Array
.
from
(
collections
)
.
map
(
(
collection
)
=>
`@iconify-prerendered/vue-
${
collection
}
`
)
;
// for each icon generate import statement
const
iconImports
=
uniqueIcons
.
map
(
(
icon
)
=>
{
const
[
collection
,
iconName
]
=
icon
.
split
(
':'
)
;
const
PascalIconName
=
'Icon'
+
iconName
.
split
(
'-'
)
.
map
(
(
part
,
index
)
=>
{
return
part
[
0
]
.
toUpperCase
(
)
+
part
.
slice
(
1
)
;
}
)
.
join
(
''
)
;
return
`import {
${
PascalIconName
}
} from '@iconify-prerendered/vue-
${
collection
}
';`
;
}
)
.
join
(
'\n'
)
;
// for each custom component generate import statement
const
customResourceComponents
=
[
]
;
function
checkInjections
(
filePathes
)
{
filePathes
.
forEach
(
(
{
file
}
)
=>
{
if
(
!
customResourceComponents
.
includes
(
file
)
)
{
if
(
file
===
undefined
)
{
throw
new
Error
(
'file is undefined'
)
;
}
customResourceComponents
.
push
(
file
)
;
}
}
)
;
}
this
.
adminforth
.
config
.
resources
.
forEach
(
(
resource
)
=>
{
resource
.
columns
.
forEach
(
(
column
)
=>
{
if
(
column
.
components
)
{
Object
.
values
(
column
.
components
)
.
forEach
(
(
{
file
}
:
{
file
:
string
}
)
=>
{
if
(
!
customResourceComponents
.
includes
(
file
)
)
{
if
(
file
===
undefined
)
{
throw
new
Error
(
'file is undefined from field.components, field:'
+
JSON
.
stringify
(
column
)
)
;
}
customResourceComponents
.
push
(
file
)
;
}
}
)
;
}
}
)
;
resource
.
options
.
actions
.
forEach
(
(
action
)
=>
{
const
cc
=
action
.
customComponent
;
if
(
!
cc
)
return
;
const
file
=
(
typeof
cc
===
'string'
)
?
cc
:
cc
.
file
;
if
(
!
file
)
{
throw
new
Error
(
'customComponent.file is missing for action: '
+
JSON
.
stringify
(
{
id
:
action
.
id
,
name
:
action
.
name
}
)
)
;
}
if
(
!
customResourceComponents
.
includes
(
file
)
)
{
customResourceComponents
.
push
(
file
)
;
}
}
)
;
(
Object
.
values
(
resource
.
options
?.
pageInjections
||
{
}
)
)
.
forEach
(
(
injection
)
=>
{
Object
.
values
(
injection
)
.
forEach
(
(
filePathes
:
{
file
:
string
}
[
]
)
=>
{
checkInjections
(
filePathes
)
;
}
)
;
}
)
;
}
)
;
if
(
this
.
adminforth
.
config
.
customization
?.
globalInjections
)
{
Object
.
values
(
this
.
adminforth
.
config
.
customization
.
globalInjections
)
.
forEach
(
(
injection
)
=>
{
checkInjections
(
injection
)
;
}
)
;
}
if
(
this
.
adminforth
.
config
.
customization
?.
loginPageInjections
)
{
Object
.
values
(
this
.
adminforth
.
config
.
customization
.
loginPageInjections
)
.
forEach
(
(
injection
)
=>
{
checkInjections
(
injection
)
;
}
)
;
}
if
(
this
.
adminforth
.
config
.
auth
.
userMenuSettingsPages
)
{
for
(
const
settingPage
of
this
.
adminforth
.
config
.
auth
.
userMenuSettingsPages
)
{
checkInjections
(
[
{
file
:
settingPage
.
component
}
]
)
;
}
}
if
(
this
.
adminforth
.
config
.
componentsToExplicitRegister
)
{
this
.
adminforth
.
config
.
componentsToExplicitRegister
.
forEach
(
(
component
)
=>
{
if
(
!
customResourceComponents
.
includes
(
component
)
)
{
customResourceComponents
.
push
(
component
.
file
)
;
}
}
)
;
}
customResourceComponents
.
forEach
(
(
filePath
)
=>
{
const
componentName
=
getComponentNameFromPath
(
filePath
)
;
this
.
allComponentNames
[
filePath
]
=
componentName
;
}
)
;
let
customComponentsImports
=
''
;
for
(
const
[
targetPath
,
component
]
of
Object
.
entries
(
this
.
allComponentNames
)
)
{
customComponentsImports
+=
`import
${
component
}
from '
${
targetPath
}
';\n`
;
}
// Generate Vue.component statements for each icon
const
iconComponents
=
uniqueIcons
.
map
(
(
icon
)
=>
{
const
[
collection
,
iconName
]
=
icon
.
split
(
':'
)
;
const
PascalIconName
=
'Icon'
+
iconName
.
split
(
'-'
)
.
map
(
(
part
,
index
)
=>
{
return
part
[
0
]
.
toUpperCase
(
)
+
part
.
slice
(
1
)
;
}
)
.
join
(
''
)
;
return
`app.component('
${
PascalIconName
}
',
${
PascalIconName
}
);`
;
}
)
.
join
(
'\n'
)
;
// Generate Vue.component statements for each custom component
let
customComponentsComponents
=
''
;
for
(
const
name
of
Object
.
values
(
this
.
allComponentNames
)
)
{
customComponentsComponents
+=
`app.component('
${
name
}
',
${
name
}
);\n`
;
}
let
imports
=
iconImports
+
'\n'
;
imports
+=
customComponentsImports
+
'\n'
;
if
(
this
.
adminforth
.
config
.
customization
?.
vueUsesFile
)
{
imports
+=
`import addCustomUses from '
${
this
.
adminforth
.
config
.
customization
.
vueUsesFile
}
';\n`
;
}
// inject that code into spa_tmp/src/App.vue
const
appVuePath
=
path
.
join
(
this
.
spaTmpPath
(
)
,
'src'
,
'main.ts'
)
;
let
appVueContent
=
await
fs
.
promises
.
readFile
(
appVuePath
,
'utf-8'
)
;
appVueContent
=
appVueContent
.
replace
(
'/* IMPORTANT:ADMINFORTH IMPORTS */'
,
imports
)
;
appVueContent
=
appVueContent
.
replace
(
'/* IMPORTANT:ADMINFORTH COMPONENT REGISTRATIONS */'
,
iconComponents
+
'\n'
+
customComponentsComponents
+
'\n'
)
;
if
(
this
.
adminforth
.
config
.
customization
?.
vueUsesFile
)
{
appVueContent
=
appVueContent
.
replace
(
'/* IMPORTANT:ADMINFORTH CUSTOM USES */'
,
'addCustomUses(app);'
)
;
}
await
fs
.
promises
.
writeFile
(
appVuePath
,
appVueContent
)
;
// generate tailwind extend styles
const
stylesGenerator
=
new
StylesGenerator
(
this
.
adminforth
.
config
.
customization
?.
styles
)
;
const
stylesText
=
JSON
.
stringify
(
stylesGenerator
.
mergeStyles
(
)
,
null
,
2
)
.
slice
(
1
,
-
1
)
;
const
safelistText
=
JSON
.
stringify
(
this
.
collectTailwindSafelist
(
)
,
null
,
2
)
.
slice
(
1
,
-
1
)
;
let
tailwindConfigPath
=
path
.
join
(
this
.
spaTmpPath
(
)
,
'tailwind.config.js'
)
;
let
tailwindConfigContent
=
await
fs
.
promises
.
readFile
(
tailwindConfigPath
,
'utf-8'
)
;
tailwindConfigContent
=
tailwindConfigContent
.
replace
(
'/* IMPORTANT:ADMINFORTH TAILWIND STYLES */'
,
stylesText
)
;
tailwindConfigContent
=
tailwindConfigContent
.
replace
(
'/* IMPORTANT:ADMINFORTH TAILWIND SAFELIST */'
,
safelistText
)
;
await
fs
.
promises
.
writeFile
(
tailwindConfigPath
,
tailwindConfigContent
)
;
const
routerVuePath
=
path
.
join
(
this
.
spaTmpPath
(
)
,
'src'
,
'router'
,
'index.ts'
)
;
let
routerVueContent
=
await
fs
.
promises
.
readFile
(
routerVuePath
,
'utf-8'
)
;
routerVueContent
=
routerVueContent
.
replace
(
'/* IMPORTANT:ADMINFORTH ROUTES IMPORTS */'
,
routerComponents
)
;
const
loginPage
=
this
.
adminforth
.
config
.
customization
.
loginPage
;
if
(
loginPage
)
{
// path, name and beforeEnter of the built-in route are kept, so all redirects to { name: 'login' } still work
routerVueContent
=
routerVueContent
.
replace
(
LOGIN_PAGE_ROUTE_PART_RE
,
`component: () => import('
${
loginPage
.
file
}
'),
meta:
${
JSON
.
stringify
(
{
title
:
'Login'
,
...
loginPage
.
meta
}
)
}
,`
)
;
}
// inject title to index.html
const
indexHtmlPath
=
path
.
join
(
this
.
spaTmpPath
(
)
,
'index.html'
)
;
let
indexHtmlContent
=
await
fs
.
promises
.
readFile
(
indexHtmlPath
,
'utf-8'
)
;
indexHtmlContent
=
indexHtmlContent
.
replace
(
'/* IMPORTANT:ADMINFORTH TITLE */'
,
`
${
this
.
adminforth
.
config
.
customization
?.
title
||
this
.
adminforth
.
config
.
customization
?.
brandName
||
'AdminForth'
}
`
)
;
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL