-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathconfigValidator.ts
More file actions
1317 lines (1144 loc) · 57.5 KB
/
Copy pathconfigValidator.ts
File metadata and controls
1317 lines (1144 loc) · 57.5 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
import {
AdminForthConfig,
AdminForthResource,
IAdminForth, IConfigValidator,
AdminForthBulkAction,
AdminForthActionInput,
AdminForthInputConfig,
AdminForthConfigCustomization,
AdminForthResourceInput,
AdminForthResourceColumnInput,
AdminForthResourceColumn,
AllowedActions,
ShowIn,
ShowInInput,
ShowInLegacyInput,
ShowInModernInput,
RateLimitString,
} from "../types/Back.js";
import fs from 'fs';
import path from 'path';
import { guessLabelFromName, md5hash, RateLimiter, suggestIfTypo, slugifyString } from './utils.js';
import {
AdminForthSortDirections,
type AdminForthComponentDeclarationFull,
AllowedActionsEnum,
AdminForthComponentDeclaration ,
AdminForthResourcePages,
AdminForthDataTypes,
Predicate,
AdminUser,
} from "../types/Common.js";
import AdminForth from "adminforth";
import { AdminForthConfigMenuItem } from "adminforth";
import { afLogger } from "./logger.js";
import {cascadeChildrenDelete} from './utils.js'
const DEBOUNCE_TIME_MS = 300;
const DEFAULT_AUTH_RATE_LIMIT: RateLimitString[] = ['500/5m', '5000/1h', '10000/1d'];
export default class ConfigValidator implements IConfigValidator {
customComponentsDir: string | undefined;
private static readonly LOGIN_INJECTION_KEYS = ['underInputs', 'underLoginButton', 'panelHeader'];
private static readonly GLOBAL_INJECTION_KEYS = ['userMenu', 'header', 'sidebar', 'sidebarTop', 'everyPageBottom'];
private static readonly PAGE_INJECTION_KEYS = ['beforeBreadcrumbs', 'beforeActionButtons', 'afterBreadcrumbs', 'bottom', 'threeDotsDropdownItems', 'customActionIcons', 'customActionIconsThreeDotsMenuItems'];
constructor(private adminforth: IAdminForth, private inputConfig: AdminForthInputConfig) {
this.adminforth = adminforth;
this.inputConfig = inputConfig;
}
validateAndListifyInjection(obj, key, errors) {
if (key.includes('tableRowReplace')) {
if (obj[key].length > 1) {
throw new Error(`tableRowReplace injection supports only one element, but received ${obj[key].length}.`);
}
}
if (!Array.isArray(obj[key])) {
// not array
obj[key] = [obj[key]];
}
obj[key].forEach((target, i) => {
obj[key][i] = this.validateComponent(target, errors);
});
}
validateAndListifyInjectionNew(obj: Record<string, any>, key: string, errors: Array<string>): Array<AdminForthComponentDeclarationFull> {
let injections: AdminForthComponentDeclarationFull[] = obj[key];
if (!Array.isArray(injections)) {
// not array
injections = [injections];
}
injections.forEach((target, i) => {
injections[i] = this.validateComponent(target, errors);
});
return injections;
}
checkCustomFileExists(filePath: string): Array<string> {
if (filePath.startsWith('@@/')) {
const checkPath = path.join(this.customComponentsDir, filePath.replace('@@/', ''));
if (!fs.existsSync(checkPath)) {
return [`File file ${filePath} does not exist in ${this.customComponentsDir}`];
}
}
return [];
}
validateComponent(component: AdminForthComponentDeclaration, errors: Array<string>): AdminForthComponentDeclarationFull {
if (!component) {
throw new Error('Component is missing during validation');
}
let obj: AdminForthComponentDeclarationFull;
if (typeof component === 'string') {
obj = { file: component, meta: {} };
} else {
obj = component;
}
let ignoreExistsCheck = false;
if (
this.adminforth.codeInjector.allComponentNames.hasOwnProperty(
(component as AdminForthComponentDeclarationFull).file)
) {
// not obvious, but if we are in this if, it means that this is plugin component
// if component is plugin component, we don't need to check if it exists in users folder
ignoreExistsCheck = true;
}
if (!ignoreExistsCheck) {
errors.push(...this.checkCustomFileExists(obj.file));
}
return obj;
}
validateAndNormalizeCustomization(errors: string[]): AdminForthConfigCustomization {
this.customComponentsDir = this.inputConfig.customization?.customComponentsDir;
if (!this.customComponentsDir) {
this.customComponentsDir = './custom';
}
try {
// check customComponentsDir exists
fs.accessSync(this.customComponentsDir, fs.constants.R_OK);
} catch (e) {
this.customComponentsDir = undefined;
}
const loginPageInjections: AdminForthConfigCustomization['loginPageInjections'] = {
underInputs: [],
underLoginButton: [],
panelHeader: [],
};
if (this.inputConfig.customization?.loginPageInjections) {
Object.keys(this.inputConfig.customization.loginPageInjections).forEach((injection) => {
if (ConfigValidator.LOGIN_INJECTION_KEYS.includes(injection)) {
loginPageInjections[injection] = this.validateAndListifyInjectionNew(this.inputConfig.customization.loginPageInjections, injection, errors);
} else {
const similar = suggestIfTypo(ConfigValidator.LOGIN_INJECTION_KEYS, injection);
errors.push(`Login page injection key "${injection}" is not allowed. Allowed keys are ${ConfigValidator.LOGIN_INJECTION_KEYS.join(', ')}. ${similar ? `Did you mean "${similar}"?` : ''}`);
}
});
}
const globalInjections: AdminForthConfigCustomization['globalInjections'] = {
userMenu: [],
header: [],
sidebar: [],
sidebarTop: [],
everyPageBottom: [],
};
if (this.inputConfig.customization?.globalInjections) {
Object.keys(this.inputConfig.customization.globalInjections).forEach((injection) => {
if (ConfigValidator.GLOBAL_INJECTION_KEYS.includes(injection)) {
globalInjections[injection] = this.validateAndListifyInjectionNew(this.inputConfig.customization.globalInjections, injection, errors);
} else {
const similar = suggestIfTypo(ConfigValidator.GLOBAL_INJECTION_KEYS, injection);
errors.push(`Global injection key "${injection}" is not allowed. Allowed keys are ${ConfigValidator.GLOBAL_INJECTION_KEYS.join(', ')}. ${similar ? `Did you mean "${similar}"?` : ''}`);
}
});
}
const customization: Partial<AdminForthConfigCustomization> = {
...(this.inputConfig.customization || {}),
customComponentsDir: this.customComponentsDir,
loginPageInjections,
globalInjections,
};
if (!customization.customPages) {
customization.customPages = [];
}
customization.customPages.forEach((page) => {
page.component = this.validateComponent(page.component, errors);
const meta = page.component.meta || {};
if (meta.sidebarAndHeader === undefined) {
meta.sidebarAndHeader = meta.customLayout === true ? 'none' : 'default';
}
delete meta.customLayout;
page.component.meta = meta;
});
if (!customization.brandName) { //} === undefined) {
customization.brandName = 'AdminForth';
}
// slug should have only lowercase letters, dashes and numbers
customization.brandNameSlug = slugifyString(customization.brandName);
if (customization.brandLogo) {
errors.push(...this.checkCustomFileExists(customization.brandLogo));
}
if (customization.iconOnlySidebar && customization.iconOnlySidebar.logo) {
errors.push(...this.checkCustomFileExists(customization.iconOnlySidebar.logo));
}
if (customization.showBrandNameInSidebar === undefined) {
customization.showBrandNameInSidebar = true;
}
if (customization.showBrandLogoInSidebar === undefined) {
customization.showBrandLogoInSidebar = true;
}
if (customization.favicon) {
errors.push(...this.checkCustomFileExists(customization.favicon));
}
if (!customization.datesFormat) {
customization.datesFormat = 'MMM D, YYYY';
}
if (!customization.timeFormat) {
customization.timeFormat = 'HH:mm:ss';
}
return customization as AdminForthConfigCustomization;
}
validateAndNormalizeAllowedActions(resInput: AdminForthResourceInput, errors: string[]): AllowedActions {
const allowedActions = resInput.options?.allowedActions || { all: true };
if (Object.keys(allowedActions).includes('all')) {
if (Object.keys(allowedActions).length > 1) {
errors.push(`Resource "${resInput.resourceId || resInput.table}" allowedActions cannot have "all" and other keys at same time: ${Object.keys(allowedActions).join(', ')}`);
}
for (const key of Object.keys(AllowedActionsEnum)) {
if (key !== 'all') {
allowedActions[key] = allowedActions.all;
}
}
delete allowedActions.all;
} else {
// by default allow all actions
for (const key of Object.keys(AllowedActionsEnum)) {
if (!Object.keys(allowedActions).includes(key)) {
allowedActions[key] = true;
}
}
}
return allowedActions as AllowedActions;
}
validateAndNormalizeBulkActions(resInput: AdminForthResourceInput, res: Partial<AdminForthResource>, errors: string[]): AdminForthBulkAction[] {
//check if resource has bulkActions
let bulkActions: AdminForthBulkAction[] = resInput?.options?.bulkActions || [];
if (!Array.isArray(bulkActions)) {
errors.push(`Resource "${res.resourceId}" bulkActions must be an array`);
bulkActions = [];
}
bulkActions.push({
label: `Delete checked`,
icon: 'flowbite:trash-bin-outline',
confirm: {
title: 'Are you sure you want to delete selected items?',
message: 'Deleting {count} item. This process is irreversible. | Deleting {count} items. This process is irreversible.',
},
dangerous: true,
allowed: async ({ resource, adminUser, allowedActions }) => { return allowedActions.delete },
action: async ({ selectedIds, adminUser, response }) => {
const connector = this.adminforth.connectors[res.dataSource];
// for now if at least one error, stop and return error
let error = null;
await Promise.all(
selectedIds.map(async (recordId) => {
const record = await connector.getRecordByPrimaryKey(res as AdminForthResource, recordId);
await Promise.all(
(res.hooks.delete.beforeSave).map(
async (hook) => {
const resp = await hook({
recordId: recordId,
resource: res as AdminForthResource,
record,
adminUser,
response,
adminforth: this.adminforth
});
if (!error && resp.error) {
error = resp.error;
}
}
)
)
if (error) {
return;
}
await cascadeChildrenDelete(res as AdminForthResource, recordId, { adminUser, response}, this.adminforth);
await connector.deleteRecord({ resource: res as AdminForthResource, recordId });
await Promise.all(
(res.hooks.delete.afterSave).map(
async (hook) => {
await hook({
resource: res as AdminForthResource,
record,
adminUser,
recordId: recordId,
response,
adminforth: this.adminforth,
});
}
)
)
})
);
if (error) {
return { error, ok: false };
}
return { ok: true, successMessage: `${selectedIds.length} item${selectedIds.length > 1 ? 's' : ''} deleted` };
}
});
bulkActions.map((action) => {
if (!action.id) {
action.id = md5hash(action.label);
}
});
return bulkActions;
}
validateAndNormalizeShowIn(resInput: AdminForthResourceInput, column: AdminForthResourceColumnInput, errors: string[], warnings: string[]): ShowIn {
if (column.showIn && !Array.isArray(column.showIn) && typeof column.showIn !== 'object') {
errors.push(`Resource "${resInput.resourceId || resInput.table}" column "${column.name}" showIn must be an object`);
return;
}
let showIn: ShowInInput = column.showIn || { all: true };
if (column.showIn && Array.isArray(column.showIn)) {
showIn = Object.values(AdminForthResourcePages).reduce((acc, key) => {
return {
...acc,
[key]: (column.showIn as ShowInLegacyInput).includes(key),
}
}, {} as ShowInInput);
if (warnings.filter((w) => w.includes('showIn should be an object, array is deprecated')).length === 0) {
warnings.push(`Resource "${resInput.resourceId || resInput.table}" column "${column.name}" showIn should be an object, array is deprecated`);
}
}
const showInTransformedToObject: ShowInModernInput = showIn as ShowInModernInput;
// by default copy from 'all' key if present or show on all pages
for (const key of Object.keys(AdminForthResourcePages)) {
if (!Object.keys(showInTransformedToObject).includes(key)) {
showInTransformedToObject[key] = showInTransformedToObject.all !== undefined ? showInTransformedToObject.all : true;
}
}
if (showInTransformedToObject.all !== undefined) {
delete showInTransformedToObject.all;
}
return showInTransformedToObject as ShowIn;
}
validateFieldGroups(fieldGroups: { groupName: string; columns: string[] }[], allColumnsList: string[]): string[] {
if (!fieldGroups) return allColumnsList;
const columnPositions = new Map<string, number>();
let position = 0;
fieldGroups.forEach((group) => {
group.columns.forEach((col) => {
if (!allColumnsList.includes(col)) {
const similar = suggestIfTypo(allColumnsList, col);
throw new Error(
`Group '${group.groupName}' has an unknown column '${col}'. ${
similar ? `Did you mean '${similar}'?` : ''
}`
);
}
if (!columnPositions.has(col)) {
columnPositions.set(col, position++);
}
});
});
allColumnsList.forEach((col) => {
if (!columnPositions.has(col)) {
columnPositions.set(col, position++);
}
});
return allColumnsList.sort((a, b) => {
const posA = columnPositions.get(a);
const posB = columnPositions.get(b);
return posA - posB;
});
}
validateAndNormalizeCustomActions(resInput: AdminForthResourceInput, res: Partial<AdminForthResource>, errors: string[]): AdminForthActionInput[] {
if (!resInput.options?.actions) {
return [];
}
const actions = [...resInput.options.actions];
actions.forEach((action) => {
if (!action.name) {
errors.push(`Resource "${res.resourceId}" has action without name`);
}
if (!action.action && !action.bulkHandler && !action.url) {
errors.push(`Resource "${res.resourceId}" action "${action.name}" must have action, bulkHandler or url`);
}
if ((action.action && action.url) || (action.bulkHandler && action.url)) {
errors.push(`Resource "${res.resourceId}" action "${action.name}" cannot combine url with action or bulkHandler`);
}
if (action.customComponent) {
action.customComponent = this.validateComponent(action.customComponent as any, errors);
}
// Generate ID if not present
if (!action.id) {
action.id = md5hash(action.name);
}
const defaultListValue = !!(action.action || action.url);
if (!action.showIn) {
action.showIn = {
list: defaultListValue,
listThreeDotsMenu: false,
showButton: false,
showThreeDotsMenu: false,
}
} else {
action.showIn.list = action.showIn.list ?? defaultListValue;
action.showIn.listThreeDotsMenu = action.showIn.listThreeDotsMenu ?? false;
action.showIn.showButton = action.showIn.showButton ?? false;
action.showIn.showThreeDotsMenu = action.showIn.showThreeDotsMenu ?? false;
}
if (typeof action.allowed === 'boolean') {
const val = action.allowed;
action.allowed = () => val;
}
const shownInNonBulk = action.showIn.list || action.showIn.listThreeDotsMenu || action.showIn.showButton || action.showIn.showThreeDotsMenu;
if (shownInNonBulk && !action.action && !action.url) {
errors.push(`Resource "${res.resourceId}" action "${action.name}" has showIn enabled for non-bulk locations (list, listThreeDotsMenu, showButton, showThreeDotsMenu) but has no "action" or "url" handler. Either add an "action" handler or set those showIn flags to false.`);
}
});
return actions as AdminForthActionInput[];
}
validateAndNormalizeResources(errors: string[], warnings: string[]): AdminForthResource[] {
if (!this.inputConfig.resources) {
errors.push('No resources defined, at least one resource must be defined');
return [];
}
return this.inputConfig.resources.map((resInput: AdminForthResourceInput) => {
const res: Partial<AdminForthResource> = { ...resInput, columns: undefined, options: undefined, hooks: undefined, };
if (!res.table) {
errors.push(`Resource in "${res.dataSource}" is missing table`);
}
res.resourceId = res.resourceId || res.table;
// if recordLabel is not callable, throw error
if (res.recordLabel && typeof res.recordLabel !== 'function') {
errors.push(`Resource "${res.resourceId}" recordLabel is not a function`);
}
if (!res.recordLabel) {
res.recordLabel = (item) => {
const pkVal = item[res.columns.find((col) => col.primaryKey).name];
return `${res.label} ${pkVal}`;
}
}
// as fallback value, capitalize and then replace _ with space
res.label = res.label || res.resourceId.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
if (!res.dataSource) {
errors.push(`Resource "${res.resourceId}" is missing dataSource`);
}
if (!res.columns) {
res.columns = [];
}
res.columns = resInput.columns.map((inCol: AdminForthResourceColumnInput, inColIndex) => {
const col: Partial<AdminForthResourceColumn> = {
...inCol, showIn: undefined, editingNote: undefined, required: undefined,
};
col.required = typeof inCol.required === 'boolean' ? { create: inCol.required, edit: inCol.required } : inCol.required;
if (col.name.trim() !== col.name) {
errors.push(`Resource "${res.resourceId}" column name "${col.name}" must not have leading or trailing spaces`);
}
// check for duplicate column names
if (resInput.columns.findIndex((c) => c.name === col.name) !== inColIndex) {
errors.push(`Resource "${res.resourceId}" has duplicate column name "${col.name}"`);
}
col.label = col.label || guessLabelFromName(col.name);
//define default sortable
if (!Object.keys(col).includes('sortable')) { col.sortable = !col.virtual; }
// define default filter options
if (!Object.keys(col).includes('filterOptions')) {
col.filterOptions = {
debounceTimeMs: DEBOUNCE_TIME_MS,
substringSearch: true,
};
if (col.enum || col.foreignResource || col.type === AdminForthDataTypes.BOOLEAN) {
col.filterOptions.multiselect = true;
}
} else {
if (col.filterOptions.debounceTimeMs !== undefined) {
if (typeof col.filterOptions.debounceTimeMs !== 'number') {
errors.push(`Resource "${res.resourceId}" column "${col.name}" filterOptions.debounceTimeMs must be a number`);
}
} else {
col.filterOptions.debounceTimeMs = DEBOUNCE_TIME_MS;
}
if (col.filterOptions.substringSearch !== undefined) {
if (typeof col.filterOptions.substringSearch !== 'boolean') {
errors.push(`Resource "${res.resourceId}" column "${col.name}" filterOptions.substringSearch must be a boolean`);
}
} else {
col.filterOptions.substringSearch = true;
}
if (col.filterOptions.multiselect !== undefined) {
if (typeof col.filterOptions.multiselect !== 'boolean') {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has multiselectFilter in filterOptions that is not boolean`);
}
if (!col.enum && !col.foreignResource && col.type !== AdminForthDataTypes.BOOLEAN) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" multiselectFilter in filterOptions should be set only for enum, foreign resource or boolean columns`);
}
} else if (col.enum || col.foreignResource) {
col.filterOptions.multiselect = true;
}
}
col.showIn = this.validateAndNormalizeShowIn(resInput, inCol, errors, warnings);
if (col.showIn.create && inCol.fillOnCreate !== undefined) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" is shown on create page but has fillOnCreate. FillOnCreate is not allowed for columns shown on create page. Please either set showIn.create to false or remove fillOnCreate`);
}
// check col.required is boolean or object
if (inCol.required && !((typeof inCol.required === 'boolean') || (typeof inCol.required === 'object'))) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" required must be a boolean or object`);
}
// if it is object check the keys are one of ['create', 'edit']
if (typeof inCol.required === 'object') {
const wrongRequiredOn = Object.keys(inCol.required).find((c) => !['create', 'edit'].includes(c));
if (wrongRequiredOn) {
errors.push(`Resource "${res.resourceId}" column "${inCol.name}" has invalid required value "${wrongRequiredOn}", allowed keys are 'create', 'edit']`);
}
}
// same for editingNote
if (inCol.editingNote && !((typeof inCol.editingNote === 'string') || (typeof inCol.editingNote === 'object'))) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" editingNote must be a string or object`);
}
if (typeof inCol.editingNote === 'object') {
const wrongEditingNoteOn = Object.keys(inCol.editingNote).find((c) => !['create', 'edit'].includes(c));
if (wrongEditingNoteOn) {
errors.push(`Resource "${res.resourceId}" column "${inCol.name}" has invalid editingNote value "${wrongEditingNoteOn}", allowed keys are 'create', 'edit']`);
}
}
col.editingNote = typeof inCol.editingNote === 'string' ? { create: inCol.editingNote, edit: inCol.editingNote } : inCol.editingNote;
if (col.isArray !== undefined) {
if (typeof col.isArray !== 'object') {
errors.push(`Resource "${res.resourceId}" column "${col.name}" isArray must be an object`);
} else if (col.isArray.enabled) {
if (col.primaryKey) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" isArray cannot be used for a primary key columns`);
}
if (col.masked) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" isArray cannot be used for a masked column`);
}
if (col.foreignResource && col.foreignResource.polymorphicResources) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" isArray cannot be used for a polymorphic foreignResource column`);
}
if (!col.type || col.type !== AdminForthDataTypes.JSON) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" isArray can be used only with column type JSON`);
}
if (col.isArray.itemType === undefined) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" isArray must have itemType`);
}
if (col.isArray.itemType === AdminForthDataTypes.JSON) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" isArray itemType cannot be JSON`);
}
}
}
// check suggestOnCreate types
if (inCol.suggestOnCreate !== undefined && typeof inCol.suggestOnCreate !== 'function') {
if (!col.showIn.create) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" suggestOnCreate is present, while column is hidden on create page`);
}
if (inCol.suggestOnCreate === '' || inCol.suggestOnCreate === null) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" suggestOnCreate must not be empty`);
}
if (!['string', 'number', 'boolean', 'object'].includes(typeof inCol.suggestOnCreate)) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" suggestOnCreate must be a string, number, boolean or object`);
}
// if suggestOnCreate is string, column should be one of the types with text inputs
if (typeof inCol.suggestOnCreate === 'string' && ![AdminForthDataTypes.STRING, AdminForthDataTypes.DATE, AdminForthDataTypes.DATETIME, AdminForthDataTypes.TIME, AdminForthDataTypes.TEXT, undefined].includes(inCol.type)) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" suggestOnCreate value does not match type of a column`);
}
if (typeof inCol.suggestOnCreate === 'number' && ![AdminForthDataTypes.INTEGER, AdminForthDataTypes.FLOAT, AdminForthDataTypes.DECIMAL].includes(inCol.type)) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" suggestOnCreate value does not match type of a column`);
}
if (typeof inCol.suggestOnCreate === 'boolean' && inCol.type !== AdminForthDataTypes.BOOLEAN) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" suggestOnCreate value does not match type of a column`);
}
if (inCol.enum && !inCol.enum.map((ei) => ei.value).includes(inCol.suggestOnCreate)) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" suggestOnCreate value is not in enum`);
}
if (typeof inCol.suggestOnCreate === 'object' && inCol.type !== AdminForthDataTypes.JSON) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" suggestOnCreate value does not match type of a column`);
}
if (inCol.isArray?.enabled && !Array.isArray(inCol.suggestOnCreate)) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" isArray is enabled but suggestOnCreate is not an array`);
}
}
if (col.foreignResource) {
if (col.foreignResource.onDelete && (col.foreignResource.onDelete !== 'cascade' && col.foreignResource.onDelete !== 'setNull')){
errors.push (`Resource "${res.resourceId}" column "${col.name}" has wrong delete strategy, you can use 'setNull' or 'cascade'`);
}
if (col.foreignResource.onDelete === 'setNull' && col.required) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" cannot use onDelete 'setNull' because column is required (non-nullable).`);
}
if (!col.foreignResource.resourceId) {
// resourceId is absent or empty
if (!col.foreignResource.polymorphicResources && !col.foreignResource.polymorphicOn) {
// foreignResource is present but no specifying fields
errors.push(`Resource "${res.resourceId}" column "${col.name}" has foreignResource without resourceId`);
} else if (!col.foreignResource.polymorphicResources || !col.foreignResource.polymorphicOn) {
// some polymorphic fields are present but not all
if (!col.foreignResource.polymorphicResources) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" polymorphic foreign resource requires polymorphicResources field`);
} else {
errors.push(`Resource "${res.resourceId}" column "${col.name}" polymorphic foreign resource requires polymorphicOn field`);
}
} else {
// correct polymorphic structure
if (!col.foreignResource.polymorphicResources.length) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" polymorphicResources `);
}
// we do || here because 'resourceId' might yet not be assigned from 'table'
col.foreignResource.polymorphicResources.forEach((polymorphicResource, polymorphicResourceIndex) => {
if (polymorphicResource.resourceId === undefined) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has polymorphic foreign resource without resourceId`);
} else if (!polymorphicResource.whenValue) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has polymorphic foreign resource without whenValue`);
} else if (polymorphicResource.resourceId !== null) {
const resource = this.inputConfig.resources.find((r) => r.resourceId === polymorphicResource.resourceId || r.table === polymorphicResource.resourceId);
if (!resource) {
const similar = suggestIfTypo(this.inputConfig.resources.map((r) => r.resourceId || r.table), polymorphicResource.resourceId);
errors.push(`Resource "${res.resourceId}" column "${col.name}" has foreignResource polymorphicResource resourceId which is not in resources: "${polymorphicResource.resourceId}".
${similar ? `Did you mean "${similar}" instead of "${polymorphicResource.resourceId}"?` : ''}`);
}
if (col.foreignResource.polymorphicResources.findIndex((pr) => pr.resourceId === polymorphicResource.resourceId) !== polymorphicResourceIndex) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" polymorphicResource resourceId should be unique`);
}
}
if (col.foreignResource.polymorphicResources.findIndex((pr) => pr.whenValue === polymorphicResource.whenValue) !== polymorphicResourceIndex) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" polymorphicResource whenValue should be unique`);
}
});
const polymorphicOnInCol = resInput.columns.find((c) => c.name === col.foreignResource.polymorphicOn);
if (!polymorphicOnInCol) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" polymorphicOn links to an unknown column`);
} else if (polymorphicOnInCol.type && polymorphicOnInCol.type !== AdminForthDataTypes.STRING) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" polymorphicOn links to an column that is not of type string`);
} else {
const polymorphicOnColShowIn = this.validateAndNormalizeShowIn(resInput, polymorphicOnInCol, errors, warnings);
if (typeof polymorphicOnColShowIn.create !== 'function' && typeof polymorphicOnColShowIn.edit !== 'function') {
if (polymorphicOnColShowIn.create || polymorphicOnColShowIn.edit) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" polymorphicOn column should not be changeable manually`);
}
}
}
}
} else if (col.foreignResource.polymorphicResources || col.foreignResource.polymorphicOn) {
// both resourceId and polymorphic fields
errors.push(`Resource "${res.resourceId}" column "${col.name}" has foreignResource cannot have resourceId and be polymorphic at the same time`);
} else {
// non empty resourceId and no polymorphic fields
// we do || here because 'resourceId' might yet not be assigned from 'table'
const resource = this.inputConfig.resources.find((r) => r.resourceId === col.foreignResource.resourceId || r.table === col.foreignResource.resourceId);
if (!resource) {
const similar = suggestIfTypo(this.inputConfig.resources.map((r) => r.resourceId || r.table), col.foreignResource.resourceId);
errors.push(`Resource "${res.resourceId}" column "${col.name}" has foreignResource resourceId which is not in resources: "${col.foreignResource.resourceId}".
${similar ? `Did you mean "${similar}" instead of "${col.foreignResource.resourceId}"?` : ''}`);
}
}
if (col.foreignResource.searchableFields) {
const searchableFields = Array.isArray(col.foreignResource.searchableFields)
? col.foreignResource.searchableFields
: [col.foreignResource.searchableFields];
searchableFields.forEach((fieldName) => {
if (typeof fieldName !== 'string') {
errors.push(`Resource "${res.resourceId}" column "${col.name}" foreignResource.searchableFields must contain only strings`);
return;
}
if (col.foreignResource.resourceId) {
const targetResource = this.inputConfig.resources.find((r) => r.resourceId === col.foreignResource.resourceId || r.table === col.foreignResource.resourceId);
if (targetResource) {
const targetColumn = targetResource.columns.find((targetCol) => targetCol.name === fieldName);
if (!targetColumn) {
const similar = suggestIfTypo(targetResource.columns.map((c) => c.name), fieldName);
errors.push(`Resource "${res.resourceId}" column "${col.name}" foreignResource.searchableFields contains field "${fieldName}" which does not exist in target resource "${targetResource.resourceId || targetResource.table}". ${similar ? `Did you mean "${similar}"?` : ''}`);
}
}
} else if (col.foreignResource.polymorphicResources) {
let hasFieldInAnyResource = false;
for (const pr of col.foreignResource.polymorphicResources) {
if (pr.resourceId) {
const targetResource = this.inputConfig.resources.find((r) => r.resourceId === pr.resourceId || r.table === pr.resourceId);
if (targetResource) {
const hasField = targetResource.columns.some((targetCol) => targetCol.name === fieldName);
if (hasField) {
hasFieldInAnyResource = true;
}
}
}
}
if (!hasFieldInAnyResource) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" foreignResource.searchableFields contains field "${fieldName}" which does not exist in any of the polymorphic target resources`);
}
}
});
}
if (col.foreignResource.unsetLabel) {
if (typeof col.foreignResource.unsetLabel !== 'string') {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has foreignResource unsetLabel which is not a string`);
}
} else {
// set default unset label
col.foreignResource.unsetLabel = 'Unset';
}
// Set default searchIsCaseSensitive
if (col.foreignResource.searchIsCaseSensitive === undefined) {
col.foreignResource.searchIsCaseSensitive = false;
}
const befHook = col.foreignResource.hooks?.dropdownList?.beforeDatasourceRequest;
if (befHook) {
if (!Array.isArray(befHook)) {
col.foreignResource.hooks.dropdownList.beforeDatasourceRequest = [befHook];
}
}
const aftHook = col.foreignResource.hooks?.dropdownList?.afterDatasourceResponse;
if (aftHook) {
if (!Array.isArray(aftHook)) {
col.foreignResource.hooks.dropdownList.afterDatasourceResponse = [aftHook];
}
}
}
if (inCol.inputPrefix || inCol.inputSuffix) {
if (![AdminForthDataTypes.DECIMAL, AdminForthDataTypes.FLOAT, AdminForthDataTypes.INTEGER, AdminForthDataTypes.STRING, undefined].includes(col.type)) {
if (inCol.type === AdminForthDataTypes.JSON) {
if (inCol.isArray && inCol.isArray.enabled && ![AdminForthDataTypes.DECIMAL, AdminForthDataTypes.FLOAT, AdminForthDataTypes.INTEGER, AdminForthDataTypes.STRING].includes(inCol.isArray.itemType)) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has input${inCol.inputPrefix ? 'Prefix': 'Suffix'} but it is not supported for array columns item type: ${inCol.isArray.itemType}`);
} else if (!inCol.isArray || !inCol.isArray.enabled) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has input${inCol.inputPrefix ? 'Prefix' : 'Suffix'} but it is not supported for this column type: ${col.type}`);
}
} else {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has input${inCol.inputPrefix ? 'Prefix' : 'Suffix'} but it is not supported for this column type: ${col.type}`);
}
}
if (inCol.enum) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has input${inCol.inputPrefix ? 'Prefix' : 'Suffix'} but it is not supported for enum columns`);
}
if (inCol.foreignResource) {
errors.push(`Resource "${res.resourceId}" column "${col.name}" has input${inCol.inputPrefix ? 'Prefix' : 'Suffix'} but it is not supported for foreignResource columns`);
}
}
// check is all custom components files exists
if (col.components) {
for (const [key, comp] of Object.entries(col.components as Record<string, AdminForthComponentDeclarationFull>)) {
col.components[key] = this.validateComponent(comp, errors);
}
}
// fixes issues after discover when result of this validation applied to discovered column
Object.keys(col).forEach((key) => {
if (col[key] === undefined) {
delete col[key];
}
});
return col as AdminForthResourceColumn;
})
// Check for multiple sticky columns
if (res.columns.filter(c => c.listSticky).length > 1) {
errors.push(`Resource "${res.resourceId}" has more than one listSticky column. Only one column can be sticky in the list view.`);
}
const conditionalColumns = res.columns.filter(c => c.showIf);
if (conditionalColumns.length) {
const checkConditionArrays = (predicate: Predicate, column: AdminForthResourceColumn) => {
if ("$and" in predicate && !Array.isArray(predicate.$and)) {
errors.push(`Resource "${res.resourceId}" column "${column.name}" has showIf with $and that is not an array`);
} else if ("$and" in predicate && Array.isArray(predicate.$and)) {
predicate.$and.forEach((item) => checkConditionArrays(item, column));
}
if ("$or" in predicate && !Array.isArray(predicate.$or)) {
errors.push(`Resource "${res.resourceId}" column "${column.name}" has showIf with $or that is not an array`);
} else if ("$or" in predicate && Array.isArray(predicate.$or)) {
predicate.$or.forEach((item) => checkConditionArrays(item, column));
}
const fieldEntries = Object.entries(predicate).filter(([key]) => !key.startsWith('$'));
if (fieldEntries.length > 0) {
fieldEntries.forEach(([field, condition]) => {
if (typeof condition !== 'object') {
return;
}
const relatedColumn = res.columns.find((c) => c.name === field);
if (!relatedColumn) {
const similar = suggestIfTypo(res.columns.map((c) => c.name), field);
errors.push(`Resource "${res.resourceId}" column "${column.name}" has showIf on unknown column "${field}". ${similar ? `Did you mean "${similar}"?` : ''}`);
return;
}
if ("$in" in condition && !Array.isArray(condition.$in)) {
errors.push(`Resource "${res.resourceId}" column "${column.name}" has showIf with $in that is not an array`);
}
if ("$nin" in condition && !Array.isArray(condition.$nin)) {
errors.push(`Resource "${res.resourceId}" column "${column.name}" has showIf with $nin that is not an array`);
}
if ("$includes" in condition && !relatedColumn.isArray?.enabled) {
errors.push(`Resource "${res.resourceId}" has showIf with $includes on non-array column "${relatedColumn.name}"`);
}
if ("$nincludes" in condition && !relatedColumn.isArray?.enabled) {
errors.push(`Resource "${res.resourceId}" has showIf with $nincludes on non-array column "${relatedColumn.name}"`);
}
});
}
};
conditionalColumns.forEach((column) => {
checkConditionArrays(column.showIf, column);
});
}
const options: Partial<AdminForthResource['options']> = {...resInput.options, bulkActions: undefined, allowedActions: undefined};
options.allowedActions = this.validateAndNormalizeAllowedActions(resInput, errors);
if (options.defaultSort) {
const colName = options.defaultSort.columnName;
const col = res.columns.find((c) => c.name === colName);
if (!col) {
const similar = suggestIfTypo(res.columns.map((c) => c.name), colName);
errors.push(`Resource "${res.resourceId}" defaultSort.columnName column "${colName}" not found in columns. ${similar ? `Did you mean "${similar}"?` : ''}`);
}
const dir = options.defaultSort.direction;
if (!dir) {
errors.push(`Resource "${res.resourceId}" defaultSort.direction is missing`);
}
// AdminForthSortDirections is enum
if (!(Object.values(AdminForthSortDirections) as string[]).includes(dir)) {
errors.push(`Resource "${res.resourceId}" defaultSort.direction "${dir}" is invalid, allowed values are ${Object.values(AdminForthSortDirections).join(', ')}`);
}
}
if (resInput?.options?.bulkActions?.length) {
warnings.push(`Resource "${res.resourceId}" uses deprecated \`bulkActions\`. Please migrate to \`actions\` instead. \`bulkActions\` will be removed in 3.0.0.`);
}
options.bulkActions = this.validateAndNormalizeBulkActions(resInput, res, errors);
options.actions = this.validateAndNormalizeCustomActions(resInput, res, errors);
const allColumnsList = res.columns.map((col) => col.name);
const sortedColumns = this.validateFieldGroups(options.fieldGroups, allColumnsList);
res.columns = res.columns.sort((a, b) => {
return sortedColumns.indexOf(a.name) - sortedColumns.indexOf(b.name);
});
// if pageInjection is a string, make array with one element. Also check file exists
// Validate page-specific allowed injection keys
const possiblePages = ['list', 'show', 'create', 'edit'];
const allowedInjectionsByPage: Record<string, string[]> = {
list: ['beforeBreadcrumbs', 'afterBreadcrumbs', 'beforeActionButtons', 'bottom', 'threeDotsDropdownItems', 'customActionIcons', 'customActionIconsThreeDotsMenuItems', 'tableBodyStart', 'tableRowReplace'],
show: ['beforeBreadcrumbs', 'afterBreadcrumbs', 'bottom', 'threeDotsDropdownItems'],
edit: ['beforeBreadcrumbs', 'afterBreadcrumbs', 'bottom', 'threeDotsDropdownItems'],
create: ['beforeBreadcrumbs', 'afterBreadcrumbs', 'bottom', 'threeDotsDropdownItems'],
};
if (options.pageInjections) {
Object.entries(options.pageInjections).map(([pageKey, value]) => {
if (!possiblePages.includes(pageKey)) {
const similar = suggestIfTypo(possiblePages, pageKey);
errors.push(`Resource "${res.resourceId}" has invalid pageInjection page "${pageKey}", allowed pages are ${possiblePages.join(', ')}. ${similar ? `Did you mean "${similar}"?` : ''}`);
return;
}
const allowedForThisPage = allowedInjectionsByPage[pageKey];
Object.entries(value).map(([injection, _target]) => {
if (allowedForThisPage.includes(injection)) {
this.validateAndListifyInjection(options.pageInjections[pageKey], injection, errors);
} else {
const similar = suggestIfTypo(allowedForThisPage, injection);
errors.push(`Resource "${res.resourceId}" has invalid pageInjection key "${injection}" for page "${pageKey}", supported keys are ${allowedForThisPage.join(', ')}. ${similar ? `Did you mean "${similar}"?` : ''}`);
}
});
})
}
res.options = options as AdminForthResource['options'];
// transform all hooks Functions to array of functions
res.hooks = {};
for (const hookName of ['show', 'list']) {
res.hooks[hookName] = {};
res.hooks[hookName].beforeDatasourceRequest = [];
const bdr = resInput.hooks?.[hookName]?.beforeDatasourceRequest;
if (!Array.isArray(bdr)) {
if (bdr) {
res.hooks[hookName].beforeDatasourceRequest = [bdr];
} else {
res.hooks[hookName].beforeDatasourceRequest = [];
}
} else {
res.hooks[hookName].beforeDatasourceRequest = bdr;
}
res.hooks[hookName].afterDatasourceResponse = [];
const adr = resInput.hooks?.[hookName]?.afterDatasourceResponse;
if (!Array.isArray(adr)) {
if (adr) {
res.hooks[hookName].afterDatasourceResponse = [adr];
} else {
res.hooks[hookName].afterDatasourceResponse = [];
}
} else {
res.hooks[hookName].afterDatasourceResponse = adr;
}
}
for (const hookName of ['create', 'edit', 'delete']) {
res.hooks[hookName] = {};
res.hooks[hookName].beforeSave = [];
const bs = resInput.hooks?.[hookName]?.beforeSave;
if (!Array.isArray(bs)) {
if (bs) {
res.hooks[hookName].beforeSave = [bs];
} else {
res.hooks[hookName].beforeSave = [];
}
} else {
res.hooks[hookName].beforeSave = bs;
}
res.hooks[hookName].afterSave = [];
const as = resInput.hooks?.[hookName]?.afterSave;