adminforth 1.6.2-next.3 → 1.6.2-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/index.d.ts.map +1 -1
  2. package/dist/index.js +22 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/spa/.eslintrc.cjs +14 -0
  5. package/dist/spa/README.md +39 -0
  6. package/dist/spa/env.d.ts +1 -0
  7. package/dist/spa/index.html +23 -0
  8. package/dist/spa/package-lock.json +5062 -0
  9. package/dist/spa/package.json +58 -0
  10. package/dist/spa/postcss.config.js +6 -0
  11. package/dist/spa/public/assets/favicon.png +0 -0
  12. package/dist/spa/src/App.vue +432 -0
  13. package/dist/spa/src/adminforth.ts +160 -0
  14. package/dist/spa/src/afcl/AreaChart.vue +160 -0
  15. package/dist/spa/src/afcl/BarChart.vue +170 -0
  16. package/dist/spa/src/afcl/Button.vue +27 -0
  17. package/dist/spa/src/afcl/Checkbox.vue +24 -0
  18. package/dist/spa/src/afcl/Dropzone.vue +128 -0
  19. package/dist/spa/src/afcl/Input.vue +41 -0
  20. package/dist/spa/src/afcl/Link.vue +17 -0
  21. package/dist/spa/src/afcl/LinkButton.vue +25 -0
  22. package/dist/spa/src/afcl/PieChart.vue +175 -0
  23. package/dist/spa/src/afcl/ProgressBar.vue +57 -0
  24. package/dist/spa/src/afcl/Select.vue +246 -0
  25. package/dist/spa/src/afcl/Skeleton.vue +26 -0
  26. package/dist/spa/src/afcl/Spinner.vue +9 -0
  27. package/dist/spa/src/afcl/Table.vue +116 -0
  28. package/dist/spa/src/afcl/Tooltip.vue +43 -0
  29. package/dist/spa/src/afcl/VerticalTabs.vue +49 -0
  30. package/dist/spa/src/afcl/index.ts +20 -0
  31. package/dist/spa/src/assets/base.css +2 -0
  32. package/dist/spa/src/assets/logo.svg +19 -0
  33. package/dist/spa/src/components/AcceptModal.vue +44 -0
  34. package/dist/spa/src/components/Breadcrumbs.vue +41 -0
  35. package/dist/spa/src/components/BreadcrumbsWithButtons.vue +25 -0
  36. package/dist/spa/src/components/CustomDatePicker.vue +180 -0
  37. package/dist/spa/src/components/CustomDateRangePicker.vue +218 -0
  38. package/dist/spa/src/components/CustomRangePicker.vue +156 -0
  39. package/dist/spa/src/components/Filters.vue +232 -0
  40. package/dist/spa/src/components/GroupsTable.vue +218 -0
  41. package/dist/spa/src/components/HelloWorld.vue +17 -0
  42. package/dist/spa/src/components/MenuLink.vue +41 -0
  43. package/dist/spa/src/components/ResourceForm.vue +260 -0
  44. package/dist/spa/src/components/ResourceListTable.vue +486 -0
  45. package/dist/spa/src/components/ShowTable.vue +81 -0
  46. package/dist/spa/src/components/SingleSkeletLoader.vue +13 -0
  47. package/dist/spa/src/components/SkeleteLoader.vue +18 -0
  48. package/dist/spa/src/components/ThreeDotsMenu.vue +43 -0
  49. package/dist/spa/src/components/Toast.vue +78 -0
  50. package/dist/spa/src/components/ValueRenderer.vue +141 -0
  51. package/dist/spa/src/components/icons/IconCalendar.vue +5 -0
  52. package/dist/spa/src/components/icons/IconCommunity.vue +7 -0
  53. package/dist/spa/src/components/icons/IconDocumentation.vue +7 -0
  54. package/dist/spa/src/components/icons/IconEcosystem.vue +7 -0
  55. package/dist/spa/src/components/icons/IconSupport.vue +7 -0
  56. package/dist/spa/src/components/icons/IconTime.vue +5 -0
  57. package/dist/spa/src/components/icons/IconTooling.vue +19 -0
  58. package/dist/spa/src/composables/useFrontendApi.ts +28 -0
  59. package/dist/spa/src/i18n.ts +54 -0
  60. package/dist/spa/src/index.scss +34 -0
  61. package/dist/spa/src/main.ts +22 -0
  62. package/dist/spa/src/renderers/CompactField.vue +46 -0
  63. package/dist/spa/src/renderers/CompactUUID.vue +46 -0
  64. package/dist/spa/src/renderers/CountryFlag.vue +65 -0
  65. package/dist/spa/src/renderers/HumanNumber.vue +58 -0
  66. package/dist/spa/src/renderers/RelativeTime.vue +42 -0
  67. package/dist/spa/src/renderers/URL.vue +18 -0
  68. package/dist/spa/src/router/index.ts +70 -0
  69. package/dist/spa/src/spa_types/core.ts +51 -0
  70. package/dist/spa/src/stores/core.ts +228 -0
  71. package/dist/spa/src/stores/filters.ts +27 -0
  72. package/dist/spa/src/stores/modal.ts +48 -0
  73. package/dist/spa/src/stores/toast.ts +30 -0
  74. package/dist/spa/src/stores/user.ts +79 -0
  75. package/dist/spa/src/types/Adapters.ts +26 -0
  76. package/dist/spa/src/types/Back.ts +1344 -0
  77. package/dist/spa/src/types/Common.ts +940 -0
  78. package/dist/spa/src/types/FrontendAPI.ts +189 -0
  79. package/dist/spa/src/utils.ts +184 -0
  80. package/dist/spa/src/views/CreateView.vue +167 -0
  81. package/dist/spa/src/views/EditView.vue +171 -0
  82. package/dist/spa/src/views/ListView.vue +442 -0
  83. package/dist/spa/src/views/LoginView.vue +199 -0
  84. package/dist/spa/src/views/PageNotFound.vue +20 -0
  85. package/dist/spa/src/views/ResourceParent.vue +50 -0
  86. package/dist/spa/src/views/ShowView.vue +209 -0
  87. package/dist/spa/src/websocket.ts +129 -0
  88. package/dist/spa/tailwind.config.js +19 -0
  89. package/dist/spa/tsconfig.app.json +14 -0
  90. package/dist/spa/tsconfig.json +11 -0
  91. package/dist/spa/tsconfig.node.json +19 -0
  92. package/dist/spa/vite.config.ts +52 -0
  93. package/package.json +1 -1
@@ -0,0 +1,1344 @@
1
+ import type { Express } from 'express';
2
+ import type { Writable } from 'stream';
3
+
4
+ import { ActionCheckSource, AdminForthFilterOperators, AdminForthSortDirections, AllowedActionsEnum,
5
+ type AdminForthComponentDeclaration,
6
+ type AdminForthResourceCommon,
7
+ type AdminUser, type AllowedActionsResolved,
8
+ type AdminForthBulkActionCommon,
9
+ type AdminForthForeignResourceCommon,
10
+ type AdminForthResourceColumnCommon,
11
+ AdminForthResourceInputCommon,
12
+ AdminForthComponentDeclarationFull,
13
+ AdminForthConfigMenuItem,
14
+ AnnouncementBadgeResponse
15
+ } from './Common.js';
16
+ import { AnyCnameRecord } from 'dns';
17
+
18
+ export interface ICodeInjector {
19
+ srcFoldersToSync: Object;
20
+ allComponentNames: Object;
21
+ devServerPort: number;
22
+
23
+ getServeDir(): string;
24
+
25
+ spaTmpPath(): string;
26
+ }
27
+
28
+ export interface IConfigValidator {
29
+ validateConfig(): void;
30
+ postProcessAfterDiscover(resource: AdminForthResource): void;
31
+ }
32
+
33
+ export interface IAdminForthHttpResponse {
34
+ setHeader: (key: string, value: string) => void,
35
+ setStatus: (code: number, message: string) => void,
36
+ blobStream: () => Writable,
37
+ };
38
+
39
+ /**
40
+ * Implement this interface to create custom HTTP server adapter for AdminForth.
41
+ */
42
+ export interface IHttpServer {
43
+
44
+ // constructor(adminforth: IAdminForth): void;
45
+
46
+ /**
47
+ * Sets up HTTP server to serve AdminForth SPA.
48
+ * if hotReload is true, it should proxy all requests and headers to Vite dev server at `http://localhost:5173$\{req.url\}`
49
+ * otherwise it should serve AdminForth SPA from dist folder. See Express for example.
50
+ */
51
+ setupSpaServer(): void;
52
+
53
+ /**
54
+ * Method which should register endpoint in HTTP server.
55
+ *
56
+ * @param options : Object with method, path and handler properties.
57
+ */
58
+ endpoint(options: {
59
+ method: string,
60
+ noAuth?: boolean,
61
+ path: string,
62
+ handler: (
63
+ body: any,
64
+ adminUser: any,
65
+ query: {[key: string]: string},
66
+ headers: {[key: string]: string},
67
+ cookies: {[key: string]: string},
68
+ response: IAdminForthHttpResponse,
69
+ ) => void,
70
+ }): void;
71
+
72
+ }
73
+
74
+
75
+ export interface IExpressHttpServer extends IHttpServer {
76
+
77
+ /**
78
+ * Call this method to serve AdminForth SPA from Express instance.
79
+ * @param app : Express instance
80
+ */
81
+ serve(app: Express): void;
82
+
83
+ /**
84
+ * Method to start listening on port.
85
+ */
86
+ listen(port: number, callback: Function): void;
87
+ listen(port: number, host: string, callback: Function): void;
88
+
89
+ /**
90
+ * Method (middleware) to wrap express endpoints with authorization check.
91
+ * Adds adminUser to request object if user is authorized. Drops request with 401 status if user is not authorized.
92
+ * @param callable : Function which will be called if user is authorized.
93
+ *
94
+ * Example:
95
+ *
96
+ * ```ts
97
+ * expressApp.get('/myApi', authorize((req, res) => \{
98
+ * console.log('User is authorized', req.adminUser);
99
+ * res.json(\{ message: 'Hello World' \});
100
+ * \}));
101
+ * ``
102
+ *
103
+ */
104
+ authorize(callable: Function): void;
105
+ }
106
+
107
+
108
+ export interface IAdminForthFilter {
109
+ field: string;
110
+ operator: AdminForthFilterOperators;
111
+ value: any;
112
+ }
113
+
114
+ export interface IAdminForthSort {
115
+ field: string,
116
+ direction: AdminForthSortDirections
117
+ }
118
+
119
+ export interface IAdminForthDataSourceConnector {
120
+
121
+ /**
122
+ * Optional.
123
+ * You an redefine this function to define how one record should be fetched from database.
124
+ * You you will not redefine it, AdminForth will use {@link IAdminForthDataSourceConnector.getData} with limit 1 and offset 0 and
125
+ * filter by primary key.
126
+ */
127
+ getRecordByPrimaryKeyWithOriginalTypes(resource: AdminForthResource, recordId: string): Promise<any>;
128
+
129
+
130
+ /**
131
+ * Function should go over all columns of table defined in resource.table and try to guess
132
+ * data and constraints for each columns.
133
+ * Type should be saved to:
134
+ * - {@link AdminForthResourceColumn.type}
135
+ * Constraints:
136
+ * - {@link AdminForthResourceColumn.required}
137
+ * - {@link AdminForthResourceColumn.primaryKey}
138
+ * For string fields:
139
+ * - {@link AdminForthResourceColumn.maxLength}
140
+ * For numbers:
141
+ * - {@link AdminForthResourceColumn.min}
142
+ * - {@link AdminForthResourceColumn.max}
143
+ * - {@link AdminForthResourceColumn.minValue}, {@link AdminForthResourceColumn.maxValue}, {@link AdminForthResourceColumn.enum}, {@link AdminForthResourceColumn.foreignResource}, {@link AdminForthResourceColumn.sortable}, {@link AdminForthResourceColumn.backendOnly}, {@link AdminForthResourceColumn.masked}, {@link AdminForthResourceColumn.virtual}, {@link AdminForthResourceColumn.components}, {@link AdminForthResourceColumn.allowMinMaxQuery}, {@link AdminForthResourceColumn.editingNote}, {@link AdminForthResourceColumn.showIn}, {@link AdminForthResourceColumn.isUnique}, {@link AdminForthResourceColumn.validation})
144
+ * Also you can additionally save original column type to {@link AdminForthResourceColumn._underlineType}. This might be later used
145
+ * in {@link IAdminForthDataSourceConnector.getFieldValue} and {@link IAdminForthDataSourceConnector.setFieldValue} methods.
146
+ *
147
+ *
148
+ * @param resource
149
+ */
150
+ discoverFields(resource: AdminForthResource): Promise<{[key: string]: AdminForthResourceColumn}>;
151
+
152
+
153
+ /**
154
+ * Used to transform record after fetching from database.
155
+ * According to AdminForth convention, if {@link AdminForthResourceColumn.type} is set to {@link AdminForthDataTypes.DATETIME} then it should be transformed to ISO string.
156
+ * @param field
157
+ * @param value
158
+ */
159
+ getFieldValue(field: AdminForthResourceColumn, value: any): any;
160
+
161
+ /**
162
+ * Used to transform record before saving to database. Should perform operation inverse to {@link IAdminForthDataSourceConnector.getFieldValue}
163
+ * @param field
164
+ * @param value
165
+ */
166
+ setFieldValue(field: AdminForthResourceColumn, value: any): any;
167
+
168
+ /**
169
+ * Used to fetch data from database.
170
+ * This method is reused both to list records and show one record (by passing limit 1 and offset 0) .
171
+ *
172
+ * Fields are returned from db "as is" then {@link AdminForthBaseConnector.getData} will transform each field using {@link IAdminForthDataSourceConnector.getFieldValue}
173
+ */
174
+ getDataWithOriginalTypes({ resource, limit, offset, sort, filters }: {
175
+ resource: AdminForthResource,
176
+ limit: number,
177
+ offset: number,
178
+ sort: IAdminForthSort[],
179
+ filters: IAdminForthFilter[],
180
+ }): Promise<Array<any>>;
181
+
182
+ /**
183
+ * Used to get count of records in database.
184
+ */
185
+ getCount({ resource, filters }: {
186
+ resource: AdminForthResource,
187
+ filters: IAdminForthFilter[],
188
+ }): Promise<number>;
189
+
190
+ /**
191
+ * Optional method which used to get min and max values for columns in resource.
192
+ * Called only for columns which have {@link AdminForthResourceColumn.allowMinMaxQuery} set to true.
193
+ *
194
+ * Internally should call {@link IAdminForthDataSourceConnector.getFieldValue} for both min and max values.
195
+ */
196
+ getMinMaxForColumnsWithOriginalTypes({ resource, columns }: { resource: AdminForthResource, columns: AdminForthResourceColumn[] }): Promise<{ [key: string]: { min: any, max: any } }>;
197
+
198
+
199
+ /**
200
+ * Used to create record in database.
201
+ */
202
+ createRecordOriginalValues({ resource, record }: { resource: AdminForthResource, record: any }): Promise<void>;
203
+
204
+ /**
205
+ * Update record in database. newValues might have not all fields in record, but only changed ones.
206
+ * recordId is value of field which is marked as {@link AdminForthResourceColumn.primaryKey}
207
+ */
208
+ updateRecordOriginalValues({ resource, recordId, newValues }: { resource: AdminForthResource; recordId: string; newValues: any; }): Promise<void>;
209
+
210
+ /**
211
+ * Used to delete record in database.
212
+ */
213
+ deleteRecord({ resource, recordId }: { resource: AdminForthResource, recordId: any }): Promise<boolean>;
214
+ }
215
+
216
+
217
+ /**
218
+ * Interface that exposes methods to interact with AdminForth in standard way
219
+ */
220
+ export interface IAdminForthDataSourceConnectorBase extends IAdminForthDataSourceConnector {
221
+
222
+ getPrimaryKey(resource: AdminForthResource): string;
223
+
224
+ getData({ resource, limit, offset, sort, filters }: {
225
+ resource: AdminForthResource,
226
+ limit: number,
227
+ offset: number,
228
+ sort: IAdminForthSort[],
229
+ filters: IAdminForthFilter[],
230
+ getTotals?: boolean,
231
+ }): Promise<{ data: Array<any>, total: number }>;
232
+
233
+ getRecordByPrimaryKey(resource: AdminForthResource, recordId: string): Promise<any>;
234
+
235
+ createRecord({ resource, record, adminUser }: {
236
+ resource: AdminForthResource,
237
+ record: any
238
+ adminUser: AdminUser,
239
+ }): Promise<{ok: boolean, error?: string, createdRecord?: any}>;
240
+
241
+ updateRecord({ resource, recordId, newValues }: {
242
+ resource: AdminForthResource,
243
+ recordId: string,
244
+ newValues: any,
245
+ }): Promise<{ok: boolean, error?: string}>;
246
+
247
+ getMinMaxForColumns({ resource, columns }: { resource: AdminForthResource, columns: AdminForthResourceColumn[] }): Promise<{ [key: string]: { min: any, max: any } }>;
248
+ }
249
+
250
+
251
+ export interface IAdminForthDataSourceConnectorConstructor {
252
+ new ({ url }: { url: string }): IAdminForthDataSourceConnectorBase;
253
+ }
254
+
255
+ export interface IAdminForthAuth {
256
+ verify(jwt : string, mustHaveType: string, decodeUser?: boolean): Promise<any>;
257
+
258
+ issueJWT(payload: Object, type: string, expiresIn?: string): string;
259
+
260
+ removeCustomCookie({response, name}: {response: any, name: string}): void;
261
+
262
+ setAuthCookie({expireInDays, response, username, pk,}: {expireInDays?: number, response: any, username: string, pk: string}): void;
263
+
264
+ removeAuthCookie(response: any): void;
265
+
266
+ getClientIp(headers: any): string;
267
+ }
268
+
269
+ export interface IAdminForthRestAPI {
270
+
271
+ /**
272
+ * Called by AdminForth to initialize all endpoints for REST API.
273
+ */
274
+ registerEndpoints(server: IHttpServer): void;
275
+
276
+ /**
277
+ * Called by login endpoint to process login callbacks. Also might be called by plugins, to prevent action if user is not allowed to login.
278
+ * For example signup or login via google might want to check if user is allowed to login by calling this method.
279
+ * @param adminUser - plugin/af pases current adminUser
280
+ * @param toReturn - this is an object which will get status of login process. If at least one callback returns error or redirectTo, login process will be stopped (future callbacks will not be called).
281
+ * @param response - http response object
282
+ */
283
+ processLoginCallbacks(adminUser: AdminUser, toReturn: { redirectTo?: string, allowedLogin: boolean, error?: string }, response: any, extra: HttpExtra): Promise<void>;
284
+ }
285
+
286
+ export interface IAdminForth {
287
+ config: AdminForthConfig;
288
+ codeInjector: ICodeInjector;
289
+ express: IHttpServer;
290
+
291
+ restApi: IAdminForthRestAPI;
292
+ activatedPlugins: Array<IAdminForthPlugin>;
293
+
294
+
295
+ websocket: IWebSocketBroker;
296
+
297
+ statuses: {
298
+ dbDiscover: 'running' | 'done',
299
+ };
300
+
301
+ connectors: {
302
+ [key: string]: IAdminForthDataSourceConnectorBase;
303
+ };
304
+
305
+ formatAdminForth(): string;
306
+
307
+ tr(msg: string, category: string, lang: string, params: any, pluralizationNumber?: number): Promise<string>;
308
+
309
+ createResourceRecord(
310
+ params: { resource: AdminForthResource, record: any, adminUser: AdminUser, extra?: HttpExtra }
311
+ ): Promise<{ error?: string, createdRecord?: any }>;
312
+
313
+ updateResourceRecord(
314
+ params: { resource: AdminForthResource, recordId: any, record: any, oldRecord: any, adminUser: AdminUser, extra?: HttpExtra }
315
+ ): Promise<{ error?: string }>;
316
+
317
+ deleteResourceRecord(
318
+ params: { resource: AdminForthResource, recordId: string, adminUser: AdminUser, record: any, extra?: HttpExtra }
319
+ ): Promise<{ error?: string }>;
320
+
321
+ auth: IAdminForthAuth;
322
+
323
+ /**
324
+ * Internal flag which indicates if AdminForth is running in hot reload mode.
325
+ */
326
+ runningHotReload: boolean;
327
+
328
+ /**
329
+ * Connects to databases defined in datasources and fetches described resource columns to find out data types and constraints.
330
+ * You must call this method as soon as possible after AdminForth class is instantiated.
331
+ */
332
+ discoverDatabases(): Promise<void>;
333
+
334
+ /**
335
+ * Bundles AdminForth SPA by injecting custom components into internal pre-made SPA source code. It generates internally dist which then will be
336
+ * served by AdminForth HTTP adapter.
337
+ * Bundle is generated in /tmp folder so if you have ramfs or tmpfs this operation will be faster.
338
+ *
339
+ * We recommend calling this method from dedicated script which will be run by CI/CD pipeline in build time. This ensures lowest downtime for your users.
340
+ * However for simple setup you can call it from your main script, and users will see some "AdminForth is bundling" message in the admin panel while app is bundling.
341
+ */
342
+ bundleNow({ hotReload, verbose }: { hotReload: boolean, verbose: boolean }): Promise<void>;
343
+
344
+ /**
345
+ * Resource to get access to operational resources for data api fetching and manipulation.
346
+ */
347
+ resource(resourceId: string): IOperationalResource;
348
+
349
+ /**
350
+ * This method will be automatically called from AdminForth HTTP adapter to serve AdminForth SPA.
351
+ */
352
+ setupEndpoints(server: IHttpServer): void;
353
+
354
+ }
355
+
356
+
357
+ export interface IAdminForthPlugin {
358
+ adminforth: IAdminForth;
359
+ pluginDir: string;
360
+ customFolderName: string;
361
+ pluginInstanceId: string;
362
+ customFolderPath: string;
363
+ pluginOptions: any;
364
+ resourceConfig: AdminForthResource;
365
+ className: string;
366
+
367
+ /**
368
+ * Before activating all plugins are sorted by this number and then activated in order.
369
+ * If you want to make sure that your plugin is activated after some other plugin, set this number to higher value. (default is 0)
370
+ */
371
+ activationOrder: number;
372
+
373
+
374
+ /**
375
+ * AdminForth plugins concept is based on modification of full AdminForth configuration
376
+ * to add some custom functionality. For example plugin might simply add custom field to resource by reusing
377
+ * {@link AdminForthResourceColumn.components} object, then add some hook which will modify record before getting or saving it to database.
378
+ *
379
+ * So this method is core of AdminForth plugins. It allows to modify full resource configuration.
380
+ * @param adminforth Instance of IAdminForth
381
+ * @param resourceConfig Resource configuration object which will be modified by plugin
382
+ */
383
+ modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource): void;
384
+ componentPath(componentFile: string): string;
385
+
386
+ /**
387
+ * If plugin should support multiple installations per one resource, this function that should return unique string for each instance of plugin.
388
+ * For example if plugin is installed for one column and this column defined as
389
+ * `targetColumn` in plugin options, then this method should return `${pluginOptions.targetColumn}`.
390
+ *
391
+ * If plugin should support only one installation per resource, option can return 'single'
392
+ * @param pluginOptions - options of plugin
393
+ */
394
+ instanceUniqueRepresentation(pluginOptions: any) : string;
395
+
396
+
397
+ /**
398
+ * Optional method which will be called after AdminForth discovers all resources and their columns.
399
+ * Can be used to validate types of columns, check if some columns are missing, etc.
400
+ */
401
+ validateConfigAfterDiscover?(adminforth: IAdminForth, resourceConfig: AdminForthResource): void;
402
+
403
+ /**
404
+ * Here you can register custom endpoints for your plugin.
405
+ *
406
+ * @param server
407
+ */
408
+ setupEndpoints(server: IHttpServer): void;
409
+ }
410
+
411
+
412
+ /**
413
+ * Modify query to change how data is fetched from database.
414
+ * Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
415
+ */
416
+ export type BeforeDataSourceRequestFunction = (params: {
417
+ resource: AdminForthResource,
418
+ adminUser: AdminUser,
419
+ query: any,
420
+ extra: {
421
+ body: any,
422
+ query: Record<string, string>,
423
+ headers: Record<string, string>,
424
+ cookies: Record<string, string>,
425
+ requestUrl: string,
426
+ },
427
+ adminforth: IAdminForth,
428
+ }) => Promise<{ok: boolean, error?: string}>;
429
+
430
+ /**
431
+ * Modify response to change how data is returned after fetching from database.
432
+ * Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
433
+ */
434
+ export type AfterDataSourceResponseFunction = (params: {
435
+ resource: AdminForthResource,
436
+ adminUser: AdminUser,
437
+ query: any,
438
+ response: any,
439
+ extra: {
440
+ body: any,
441
+ query: Record<string, string>,
442
+ headers: Record<string, string>,
443
+ cookies: { key: string, value: string }[],
444
+ requestUrl: string,
445
+ },
446
+ adminforth: IAdminForth,
447
+ }) => Promise<{ok: boolean, error?: string}>;
448
+
449
+ export interface HttpExtra {
450
+ body: any,
451
+ query: Record<string, string>,
452
+ headers: Record<string, string>,
453
+ cookies: Record<string, string>,
454
+ requestUrl: string,
455
+ }
456
+ /**
457
+ * Modify record to change how data is saved to database.
458
+ * Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
459
+ */
460
+ export type BeforeDeleteSaveFunction = (params: {
461
+ resource: AdminForthResource,
462
+ recordId: any,
463
+ adminUser: AdminUser,
464
+ record: any,
465
+ adminforth: IAdminForth,
466
+ extra?: HttpExtra,
467
+ }) => Promise<{ok: boolean, error?: string}>;
468
+
469
+
470
+ export type BeforeEditSaveFunction = (params: {
471
+ resource: AdminForthResource,
472
+ recordId: any,
473
+ adminUser: AdminUser,
474
+ updates: any,
475
+ record: any, // legacy, 'updates' should be used instead
476
+ oldRecord: any,
477
+ adminforth: IAdminForth,
478
+ extra?: HttpExtra,
479
+ }) => Promise<{ok: boolean, error?: string}>;
480
+
481
+
482
+
483
+ export type BeforeCreateSaveFunction = (params: {
484
+ resource: AdminForthResource,
485
+ adminUser: AdminUser,
486
+ record: any,
487
+ adminforth: IAdminForth,
488
+ extra?: HttpExtra,
489
+ }) => Promise<{ok: boolean, error?: string}>;
490
+
491
+ export type AfterCreateSaveFunction = (params: {
492
+ resource: AdminForthResource,
493
+ recordId: any,
494
+ adminUser: AdminUser,
495
+ record: any,
496
+ adminforth: IAdminForth,
497
+ extra?: HttpExtra,
498
+ }) => Promise<{ok: boolean, error?: string}>;
499
+
500
+ /**
501
+ * Modify record to change how data is saved to database.
502
+ * Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
503
+ */
504
+ export type AfterDeleteSaveFunction = (params: {
505
+ resource: AdminForthResource,
506
+ recordId: any,
507
+ adminUser: AdminUser,
508
+ record: any,
509
+ adminforth: IAdminForth,
510
+ extra?: HttpExtra,
511
+ }) => Promise<{ok: boolean, error?: string}>;
512
+
513
+
514
+ export type AfterEditSaveFunction = (params: {
515
+ resource: AdminForthResource,
516
+ recordId: any,
517
+ adminUser: AdminUser,
518
+ updates: any,
519
+ record: any, // legacy, 'updates' should be used instead
520
+ oldRecord: any,
521
+ adminforth: IAdminForth,
522
+ extra?: HttpExtra,
523
+ }) => Promise<{ok: boolean, error?: string}>;
524
+
525
+ /**
526
+ * Allow to get user data before login confirmation, will triger when user try to login.
527
+ */
528
+ export type BeforeLoginConfirmationFunction = (params?: {
529
+ adminUser: AdminUser,
530
+ response: IAdminForthHttpResponse,
531
+ adminforth: IAdminForth,
532
+ extra?: HttpExtra,
533
+ }) => Promise<{
534
+ error?: string,
535
+ body: {
536
+ redirectTo?: string,
537
+ allowedLogin?: boolean,
538
+ }
539
+ }>;
540
+
541
+
542
+ /**
543
+ * Data source describes database connection which will be used to fetch data for resources.
544
+ * Each resource should use one data source.
545
+ */
546
+ export type AdminForthDataSource = {
547
+ /**
548
+ * ID of datasource which you will use in resources to specify from which database to fetch data from
549
+ */
550
+ id: string,
551
+
552
+ /**
553
+ * URL to database. Examples:
554
+ *
555
+ * - MongoDB: `mongodb://<user>:<password>@<host>:<port>/<database>`
556
+ * - PostgreSQL: `postgresql://<user>:<password>@<host>:<port>/<database>`
557
+ * - SQLite: `sqlite://<path>`
558
+ */
559
+ url: string,
560
+ }
561
+
562
+ type AdminForthPageDeclaration = {
563
+ path: string,
564
+ component: AdminForthComponentDeclaration,
565
+ }
566
+
567
+ interface AdminForthInputConfigCustomization {
568
+ /**
569
+ * Your app name
570
+ */
571
+ brandName?: string,
572
+
573
+ /**
574
+ * Whether to show brand name in sidebar
575
+ * default is true
576
+ */
577
+ showBrandNameInSidebar?: boolean,
578
+
579
+ /**
580
+ * Path to your app logo
581
+ *
582
+ * Example:
583
+ * Place file `logo.svg` to `./custom` folder and set this option:
584
+ *
585
+ * ```ts
586
+ * brandLogo: '@@/logo.svg',
587
+ * ```
588
+ *
589
+ */
590
+ brandLogo?: string,
591
+
592
+ /**
593
+ * Path to your app favicon
594
+ *
595
+ * Example:
596
+ * Place file `favicon.png` to `./custom` folder and set this option:
597
+ *
598
+ * ```ts
599
+ * favicon: '@@/favicon.png',
600
+ * ```
601
+ */
602
+ favicon?: string,
603
+
604
+ /**
605
+ * DayJS format string for all dates in the app.
606
+ * Defaulted to 'MMM D, YYYY'
607
+ */
608
+ datesFormat?: string,
609
+
610
+ /**
611
+ * DayJS format string for all datetimes in the app.
612
+ * Defaulted to 'HH:mm:ss'
613
+ */
614
+ timeFormat?: string,
615
+
616
+ /**
617
+ * HTML title tag value, defaults to brandName
618
+ */
619
+ title?: string,
620
+
621
+ /**
622
+ * Placeholder for empty fields in lists and show views, by default empty string ''
623
+ */
624
+ emptyFieldPlaceholder?: {
625
+ show?: string,
626
+ list?: string,
627
+
628
+ } | string,
629
+
630
+ /**
631
+ * Relative or absolute path to custom components directory
632
+ * By default equals `./custom`.
633
+ *
634
+ * Custom .vue files, images, and any other assets placed in this directory can be accessed in AdminForth components and configs with `@@/`.
635
+ *
636
+ * For example if file path is `./custom/comp/my.vue`, you can use it in AdminForth config like this:
637
+ *
638
+ * ```ts
639
+ * components: {
640
+ * show: '@@/comp/my.vue',
641
+ * }
642
+ * ```
643
+ *
644
+ */
645
+ customComponentsDir?: string,
646
+
647
+ /**
648
+ * Path to custom .ts file which allows to inject custom Vue uses in SPA or add custom imports.
649
+ *
650
+ * Example: Create file: `./custom/vue-uses.ts` with next content:
651
+ *
652
+ * ```ts
653
+ * import HighchartsVue from 'highcharts-vue';
654
+ * // import '@@/custom.scss'; // here is how you can import custom styles
655
+ *
656
+ * export default function (app) {
657
+ * app.use(HighchartsVue);
658
+ * }
659
+ * ```
660
+ *
661
+ * Install HighCharts into custom folder:
662
+ *
663
+ * ```bashcreating rec
664
+ * cd custom
665
+ * npm init -y
666
+ * npm install highcharts highcharts-vue
667
+ * ```
668
+ *
669
+ * And specify vueUsesFile in AdminForth config:
670
+ *
671
+ * ```ts
672
+ * vueUsesFile: '@@/vue-uses.ts',
673
+ * ```
674
+ *
675
+ */
676
+ vueUsesFile?: string,
677
+ /**
678
+ * Object to redefine default styles for AdminForth components. Use this file as reference for all possible adjustments https://github.com/devforth/adminforth/blob/main/adminforth/modules/styles.ts
679
+ */
680
+ styles?: Object,
681
+
682
+ /**
683
+ * Description of custom pages which will let register custom pages for custom routes in AdminForth.
684
+ */
685
+ customPages?: Array<AdminForthPageDeclaration>,
686
+
687
+ /**
688
+ * Function to return custom badge in side bar for users. Can return text or html
689
+ * If function is not passed or returns null, badge will not be shown.
690
+ * Execution is done on admin app load.
691
+ */
692
+ announcementBadge?: (user: AdminUser) => AnnouncementBadgeResponse,
693
+
694
+ /**
695
+ * Custom panel components or array of components which will be displayed in the login form
696
+ * right after the inputs. Use it to add custom authorization methods like social login or other custom fields e.g. 'reset'
697
+ * password link.
698
+ */
699
+ loginPageInjections?: {
700
+ underInputs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
701
+ }
702
+
703
+ /**
704
+ * Custom panel components or array of components which will be displayed in different parts of the admin panel.
705
+ */
706
+ globalInjections?: {
707
+ userMenu?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
708
+ header?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
709
+ sidebar?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
710
+ }
711
+ }
712
+
713
+
714
+ export interface AdminForthResourceInput extends Omit<AdminForthResourceInputCommon, 'columns' | 'hooks' | 'options'> {
715
+
716
+ /**
717
+ * Array of plugins which will be used to modify resource configuration.
718
+ *
719
+ */
720
+ plugins?: Array<IAdminForthPlugin>,
721
+
722
+ /**
723
+ * Hooks allow you to change the data on different stages of resource lifecycle.
724
+ * Hooks are functions which will be called on backend side (only backend side).
725
+ */
726
+ hooks?: {
727
+ show?: {
728
+ /**
729
+ * Typical use-cases:
730
+ * - request additional data from database before returning to frontend for soft-join
731
+ */
732
+ beforeDatasourceRequest?: BeforeDataSourceRequestFunction | Array<BeforeDataSourceRequestFunction>,
733
+
734
+ /**
735
+ * Typical use-cases:
736
+ * - Transform value for some field for record returned from database before returning to frontend (minimize, sanitize, etc)
737
+ * - If some-why you can't use `backendOnly` you can cleanup sensitive fields here
738
+ * - Attach additional data to record before returning to frontend
739
+ */
740
+ afterDatasourceResponse?: AfterDataSourceResponseFunction | Array<AfterDataSourceResponseFunction>,
741
+ },
742
+ list?: {
743
+ /**
744
+ * Typical use-cases:
745
+ * - add additional filters in addition to what user selected before fetching data from database.
746
+ * - same as hooks.show.beforeDatasourceRequest
747
+ */
748
+ beforeDatasourceRequest?: BeforeDataSourceRequestFunction | Array<BeforeDataSourceRequestFunction>,
749
+
750
+ /**
751
+ * Typical use-cases:
752
+ * - Same as hooks.show.afterDatasourceResponse but applied for all records returned from database for
753
+ * showing in list view, e.g. add new field to each record in list view
754
+ */
755
+ afterDatasourceResponse?: AfterDataSourceResponseFunction | Array<AfterDataSourceResponseFunction>,
756
+ },
757
+ create?: {
758
+ /**
759
+ * Typical use-cases:
760
+ * - Validate record before saving to database and interrupt execution if validation failed (`allowedActions.create` should be preferred in most cases)
761
+ * - fill-in adminUser as creator of record
762
+ * - Attach additional data to record before saving to database (mostly fillOnCreate should be used instead)
763
+ */
764
+ beforeSave?: BeforeCreateSaveFunction | Array<BeforeCreateSaveFunction>,
765
+
766
+ /**
767
+ * Typical use-cases:
768
+ * - Initiate some trigger after record saved to database (e.g sync to another datasource)
769
+ */
770
+ afterSave?: AfterCreateSaveFunction | Array<AfterCreateSaveFunction>,
771
+ },
772
+ edit?: {
773
+ /**
774
+ * Typical use-cases:
775
+ * - Same as hooks.create.beforeSave but for edit page
776
+ */
777
+ beforeSave?: BeforeEditSaveFunction | Array<BeforeEditSaveFunction>,
778
+
779
+ /**
780
+ * Typical use-cases:
781
+ * - Same as hooks.create.afterSave but for edit page
782
+ */
783
+ afterSave?: AfterEditSaveFunction | Array<AfterEditSaveFunction>,
784
+ },
785
+ delete?: {
786
+ /**
787
+ * Typical use-cases:
788
+ * - Validate that record can be deleted and interrupt execution if validation failed (`allowedActions.delete` should be preferred in most cases)
789
+ */
790
+ beforeSave?: BeforeDeleteSaveFunction | Array<BeforeDeleteSaveFunction>,
791
+ /**
792
+ * Typical use-cases:
793
+ * - Initiate some trigger after record deleted from database (e.g sync to another datasource)
794
+ */
795
+ afterSave?: BeforeDeleteSaveFunction | Array<BeforeDeleteSaveFunction>,
796
+ },
797
+ },
798
+
799
+ options?: ResourceOptionsInput,
800
+
801
+ columns: Array<AdminForthResourceColumn>,
802
+
803
+ dataSourceColumns?: Array<AdminForthResourceColumn>,
804
+ }
805
+
806
+ /**
807
+ * Main configuration object for AdminForth
808
+ */
809
+ export interface AdminForthInputConfig {
810
+
811
+ /**
812
+ * Authorization module configuration
813
+ */
814
+ auth?: {
815
+ /**
816
+ * Resource ID for resource which stores user table.
817
+ * Resource is a table in database where users will be stored and fetched from. Resources and their ids are defined in resources section of the config.
818
+ * In other words this setting is a reference to a table in database where users will be fetched from on login.
819
+ */
820
+ usersResourceId?: string,
821
+
822
+ /**
823
+ * Legacy field left for backward compatibility. Use usersResourceId instead.
824
+ */
825
+ resourceId?: string,
826
+
827
+ /**
828
+ * Field name (column name) in user resource which will be used as username for searching user in database during login.
829
+ * Can be e.g. 'email' or 'username'
830
+ */
831
+ usernameField: string,
832
+
833
+ /**
834
+ * Field name (column name) in user resource which will be used to get hash of password.
835
+ * Can be e.g. 'passwordHash'
836
+ */
837
+ passwordHashField: string,
838
+
839
+ /**
840
+ * File path to custom background image for login page
841
+ * Example:
842
+ * Place file `login-background.jpg` to `./custom` folder and set this option:
843
+ *
844
+ * ```ts
845
+ * loginBackgroundImage: '@@/login-background.jpg',
846
+ * ```
847
+ */
848
+ loginBackgroundImage?: string,
849
+
850
+
851
+ /**
852
+ * Position of background image on login page
853
+ * 'over' - image will be displayed over full login page under login form
854
+ * '1/2' - image will be displayed on left 1/2 of login page
855
+ *
856
+ * Default: '1/2'
857
+ */
858
+ loginBackgroundPosition?: 'over' | '1/2' | '1/3' | '2/3' | '3/4' | '2/5' | '3/5',
859
+
860
+ /**
861
+ * Function or functions which will be called before user try to login.
862
+ * Each function will resive User object as an argument
863
+ */
864
+ beforeLoginConfirmation?: BeforeLoginConfirmationFunction | Array<BeforeLoginConfirmationFunction>,
865
+
866
+ /**
867
+ * Optionally if your users table has a field(column) with full name, you can set it here.
868
+ * This field will be used to display user name in the top right corner of the admin panel.
869
+ */
870
+ userFullNameField?: string,
871
+
872
+ /**
873
+ * Pair of login and pass substitution for demo mode. Split by ':'
874
+ * ! This option is for demo purposes only, never use it for your projects
875
+ */
876
+ demoCredentials?: string,
877
+
878
+ /**
879
+ * Any prompt to show users on login. Supports HTML.
880
+ */
881
+ loginPromptHTML?: string,
882
+
883
+ /**
884
+ * Remember me days for "Remember Me" checkbox on login page.
885
+ * If not set or set to null/0/undefined, "Remember Me" checkbox will not be displayed.
886
+ * If rememberMeDays is set, then users who check "Remember Me" will be staying logged in for this amount of days.
887
+ */
888
+ rememberMeDays?: number,
889
+
890
+
891
+ /**
892
+ * Can be used to limit user access when subscribing from frontend to websocket topics.
893
+ * @param topic - topic where user is trying to subscribe
894
+ * @param user - user object
895
+ * @returns - boolean, true if user is allowed to subscribe to this topic, false otherwise
896
+ */
897
+ websocketTopicAuth?: (topic: string, user: AdminUser) => Promise<boolean>,
898
+
899
+ /**
900
+ * callback which will be called after user subscribes to websocket topic
901
+ * @param topic - topic on which user subscribed
902
+ * @param user - user object
903
+ * @returns
904
+ */
905
+ websocketSubscribed?: (topic: string, user: AdminUser) => void,
906
+
907
+ /**
908
+ * Client IP header name. If set, AdminForth will use this header to get client IP address.
909
+ * Otherwise it will use first IP address from X-Forwarded-For header.
910
+ * If you are using Cloudflare, set this to 'CF-Connecting-IP'. Case-insensitive.
911
+ */
912
+ clientIpHeader?: string,
913
+ },
914
+
915
+ /**
916
+ * Array of resources which will be displayed in the admin panel.
917
+ * Resource represents one table or collection in database.
918
+ * Each resource has its own configuration.
919
+ */
920
+ resources: Array<AdminForthResourceInput>,
921
+
922
+ /**
923
+ * Array of left sidebar menu items which will be displayed in the admin panel.
924
+ * Menu items can be links to resources or custom pages.
925
+ * Menu items can be grouped.
926
+ *
927
+ */
928
+ menu: Array<AdminForthConfigMenuItem>,
929
+
930
+ /**
931
+ * If you want use custom DataSource which is not supported by AdminForth yet, you can define it's class here
932
+ *
933
+ */
934
+ databaseConnectors?: {
935
+ [key: string]: IAdminForthDataSourceConnectorConstructor,
936
+ },
937
+
938
+ /**
939
+ * List of data sources which will be used to fetch data for resources.
940
+ * Datasource is one database connection
941
+ *
942
+ */
943
+ dataSources: Array<AdminForthDataSource>,
944
+
945
+ /**
946
+ * Settings which allow you to customize AdminForth
947
+ *
948
+ */
949
+ customization?: AdminForthInputConfigCustomization,
950
+
951
+ /**
952
+ * If you want to Serve AdminForth from a subdirectory, e.g. on example.com/backoffice, you can specify it like:
953
+ *
954
+ * ```ts
955
+ * baseUrl: '/backoffice',
956
+ * ```
957
+ *
958
+ */
959
+ baseUrl?: string,
960
+
961
+ }
962
+
963
+
964
+ export interface AdminForthConfigCustomization extends Omit<AdminForthInputConfigCustomization, 'loginPageInjections' | 'globalInjections'> {
965
+ brandName: string,
966
+
967
+ dateFormats: string,
968
+ timeFormat: string,
969
+
970
+ /**
971
+ * Slug which will be used on tech side e.g. to store cookies separately.
972
+ * Created automatically from brandName if not set.
973
+ */
974
+ brandNameSlug: string,
975
+ showBrandNameInSidebar: boolean,
976
+ customPages: Array<AdminForthPageDeclaration>,
977
+
978
+ loginPageInjections: {
979
+ underInputs: Array<AdminForthComponentDeclarationFull>,
980
+ },
981
+
982
+ globalInjections: {
983
+ userMenu: Array<AdminForthComponentDeclarationFull>,
984
+ header: Array<AdminForthComponentDeclarationFull>,
985
+ sidebar: Array<AdminForthComponentDeclarationFull>,
986
+ },
987
+ }
988
+
989
+ export interface AdminForthConfig extends Omit<AdminForthInputConfig, 'customization' | 'resources'> {
990
+ baseUrl: string;
991
+ baseUrlSlashed: string;
992
+
993
+ customization: AdminForthConfigCustomization,
994
+
995
+ resources: Array<AdminForthResource>,
996
+
997
+ }
998
+
999
+
1000
+ // define typescript objects which I can instantiate as Filters.EQ(field, value) and they woudl
1001
+ // return { field: field, operator: 'eq', value: value }. They should be exported with Filters namespace so I can import Filters from this file
1002
+ // and use Filters.EQ(field, value) in my code
1003
+
1004
+ export type FDataFilter = (field: string, value: any) => IAdminForthFilter;
1005
+
1006
+ export class Filters {
1007
+ static EQ(field: string, value: any): IAdminForthFilter {
1008
+ return { field, operator: AdminForthFilterOperators.EQ, value };
1009
+ }
1010
+ static NEQ(field: string, value: any): IAdminForthFilter {
1011
+ return { field, operator: AdminForthFilterOperators.NE, value };
1012
+ }
1013
+ static GT(field: string, value: any): IAdminForthFilter {
1014
+ return { field, operator: AdminForthFilterOperators.GT, value };
1015
+ }
1016
+ static GTE(field: string, value: any): IAdminForthFilter {
1017
+ return { field, operator: AdminForthFilterOperators.GTE, value };
1018
+ }
1019
+ static LT(field: string, value: any): IAdminForthFilter {
1020
+ return { field, operator: AdminForthFilterOperators.LT, value };
1021
+ }
1022
+ static LTE(field: string, value: any): IAdminForthFilter {
1023
+ return { field, operator: AdminForthFilterOperators.LTE, value };
1024
+ }
1025
+ static IN(field: string, value: any): IAdminForthFilter {
1026
+ return { field, operator: AdminForthFilterOperators.IN, value };
1027
+ }
1028
+ static NOT_IN(field: string, value: any): IAdminForthFilter {
1029
+ return { field, operator: AdminForthFilterOperators.NIN, value };
1030
+ }
1031
+ static LIKE(field: string, value: any): IAdminForthFilter {
1032
+ return { field, operator: AdminForthFilterOperators.LIKE, value };
1033
+ }
1034
+ }
1035
+
1036
+ export type FDataSort = (field: string, direction: AdminForthSortDirections) => IAdminForthSort;
1037
+
1038
+ export class Sorts {
1039
+ static ASC(field: string): IAdminForthSort {
1040
+ return { field, direction: AdminForthSortDirections.asc };
1041
+ }
1042
+ static DESC(field: string): IAdminForthSort {
1043
+ return { field, direction: AdminForthSortDirections.desc };
1044
+ }
1045
+ }
1046
+
1047
+ export interface IOperationalResource {
1048
+ get: (filter: IAdminForthFilter | IAdminForthFilter[]) => Promise<any | null>;
1049
+
1050
+ list: (filter: IAdminForthFilter | IAdminForthFilter[], limit?: number, offset?: number, sort?: IAdminForthSort | IAdminForthSort[]) => Promise<any[]>;
1051
+
1052
+ count: (filter: IAdminForthFilter | IAdminForthFilter[] | undefined) => Promise<number>;
1053
+
1054
+ create: (record: any) => Promise<{ ok: boolean; createdRecord: any; error?: string; }>;
1055
+
1056
+ update: (primaryKey: any, record: any) => Promise<any>;
1057
+
1058
+ delete: (primaryKey: any) => Promise<boolean>;
1059
+
1060
+ dataConnector: IAdminForthDataSourceConnectorBase;
1061
+ }
1062
+
1063
+
1064
+
1065
+ /**
1066
+ * Defines whether user has access to an action, can statically be Boolean
1067
+ * or function which returns Boolean or string with error message
1068
+ *
1069
+ */
1070
+ export type AllowedActionValue = boolean | (({adminUser, resource, meta, source, adminforth}: {
1071
+ adminUser: AdminUser,
1072
+ resource: AdminForthResource,
1073
+
1074
+ /**
1075
+ * Meta object which will pass request information just in case
1076
+ */
1077
+ meta: any,
1078
+
1079
+ /**
1080
+ * Source of the check
1081
+ */
1082
+ source: ActionCheckSource,
1083
+
1084
+ /**
1085
+ * Instance of AdminForth, can be used e.g. to call data API adminforth.resource(resourceId)...
1086
+ */
1087
+ adminforth: IAdminForth,
1088
+ }) => Promise<boolean | string>);
1089
+
1090
+
1091
+
1092
+ /**
1093
+ * Object which describes allowed actions for user.
1094
+ */
1095
+ export type AllowedActionsInput = {
1096
+ [key in AllowedActionsEnum]?: AllowedActionValue
1097
+ } & {
1098
+ all?: AllowedActionValue;
1099
+ }
1100
+
1101
+ export type AllowedActions = {
1102
+ [key in AllowedActionsEnum]: AllowedActionValue
1103
+ }
1104
+
1105
+ /**
1106
+ * General options for resource.
1107
+ */
1108
+ export interface ResourceOptionsInput extends Omit<AdminForthResourceCommon['options'], 'allowedActions' | 'bulkActions'> {
1109
+
1110
+ /**
1111
+ * Custom bulk actions list. Bulk actions available in list view when user selects multiple records by
1112
+ * using checkboxes.
1113
+ */
1114
+ bulkActions?: Array<AdminForthBulkAction>,
1115
+
1116
+ /**
1117
+ * Allowed actions for resource.
1118
+ *
1119
+ * Example:
1120
+ *
1121
+ * ```ts
1122
+ * allowedActions: {
1123
+ * create: ({ resource, adminUser }) => {
1124
+ * // Allow only superadmin to create records
1125
+ * return adminUser.dbUser.role === 'superadmin';
1126
+ * },
1127
+ * delete: false, // disable delete action for all users
1128
+ * }
1129
+ * ```
1130
+ *
1131
+ */
1132
+ allowedActions?: AllowedActionsInput,
1133
+ };
1134
+
1135
+ export interface ResourceOptions extends Omit<ResourceOptionsInput, 'allowedActions'> {
1136
+ allowedActions: AllowedActions,
1137
+ }
1138
+
1139
+ /**
1140
+ * Resource describes one table or collection in database.
1141
+ * AdminForth generates set of pages for 'list', 'show', 'edit', 'create', 'filter' operations for each resource.
1142
+ */
1143
+ export interface AdminForthResource extends Omit<AdminForthResourceInput, 'options'> {
1144
+ /**
1145
+ * Array of plugins which will be used to modify resource configuration.
1146
+ *
1147
+ */
1148
+ plugins?: Array<IAdminForthPlugin>,
1149
+
1150
+ /**
1151
+ * Hooks allow you to change the data on different stages of resource lifecycle.
1152
+ * Hooks are functions which will be called on backend side (only backend side).
1153
+ */
1154
+ hooks?: {
1155
+ show?: {
1156
+ /**
1157
+ * Typical use-cases:
1158
+ * - request additional data from database before returning to frontend for soft-join
1159
+ */
1160
+ beforeDatasourceRequest?: Array<BeforeDataSourceRequestFunction>,
1161
+
1162
+ /**
1163
+ * Typical use-cases:
1164
+ * - Transform value for some field for record returned from database before returning to frontend (minimize, sanitize, etc)
1165
+ * - If some-why you can't use `backendOnly` you can cleanup sensitive fields here
1166
+ * - Attach additional data to record before returning to frontend
1167
+ */
1168
+ afterDatasourceResponse?: Array<AfterDataSourceResponseFunction>,
1169
+ },
1170
+ list?: {
1171
+ /**
1172
+ * Typical use-cases:
1173
+ * - add additional filters in addition to what user selected before fetching data from database.
1174
+ * - same as hooks.show.beforeDatasourceRequest
1175
+ */
1176
+ beforeDatasourceRequest?: Array<BeforeDataSourceRequestFunction>,
1177
+
1178
+ /**
1179
+ * Typical use-cases:
1180
+ * - Same as hooks.show.afterDatasourceResponse but applied for all records returned from database for
1181
+ * showing in list view, e.g. add new field to each record in list view
1182
+ */
1183
+ afterDatasourceResponse?: Array<AfterDataSourceResponseFunction>,
1184
+ },
1185
+ create?: {
1186
+ /**
1187
+ * Typical use-cases:
1188
+ * - Validate record before saving to database and interrupt execution if validation failed (`allowedActions.create` should be preferred in most cases)
1189
+ * - fill-in adminUser as creator of record
1190
+ * - Attach additional data to record before saving to database (mostly fillOnCreate should be used instead)
1191
+ */
1192
+ beforeSave?: Array<BeforeCreateSaveFunction>,
1193
+
1194
+ /**
1195
+ * Typical use-cases:
1196
+ * - Initiate some trigger after record saved to database (e.g sync to another datasource)
1197
+ */
1198
+ afterSave?: Array<AfterCreateSaveFunction>,
1199
+ },
1200
+ edit?: {
1201
+ /**
1202
+ * Typical use-cases:
1203
+ * - Same as hooks.create.beforeSave but for edit page
1204
+ */
1205
+ beforeSave?: Array<BeforeEditSaveFunction>,
1206
+
1207
+ /**
1208
+ * Typical use-cases:
1209
+ * - Same as hooks.create.afterSave but for edit page
1210
+ */
1211
+ afterSave?: Array<AfterEditSaveFunction>,
1212
+ },
1213
+ delete?: {
1214
+ /**
1215
+ * Typical use-cases:
1216
+ * - Validate that record can be deleted and interrupt execution if validation failed (`allowedActions.delete` should be preferred in most cases)
1217
+ */
1218
+ beforeSave?: Array<BeforeDeleteSaveFunction>,
1219
+ /**
1220
+ * Typical use-cases:
1221
+ * - Initiate some trigger after record deleted from database (e.g sync to another datasource)
1222
+ */
1223
+ afterSave?: Array<BeforeDeleteSaveFunction>,
1224
+ },
1225
+ },
1226
+
1227
+ options: ResourceOptions,
1228
+
1229
+ columns: Array<AdminForthResourceColumn>,
1230
+
1231
+ dataSourceColumns: Array<AdminForthResourceColumn>,
1232
+
1233
+ recordLabel: (record: any) => string,
1234
+
1235
+ label: string,
1236
+
1237
+ resourceId: string,
1238
+ }
1239
+
1240
+ export interface AdminForthBulkAction extends AdminForthBulkActionCommon {
1241
+
1242
+ /**
1243
+ * Callback which will be called on backend when user clicks on action button.
1244
+ * It should return Promise which will be resolved when action is done.
1245
+ */
1246
+ action: ({ resource, selectedIds, adminUser, tr }: {
1247
+ resource: AdminForthResource, selectedIds: Array<any>, adminUser: AdminUser, tr: (key: string, category?: string, params?: any) => string
1248
+ }) => Promise<{ ok: boolean, error?: string, successMessage?: string }>,
1249
+
1250
+ /**
1251
+ * Allowed callback called to check whether action is allowed for user.
1252
+ * 1. It called first time when user goes to list view. If callback returns false, action button will be hidden on list view.
1253
+ * 2. This same callback called second time when user clicks an action button. If callback returns false, action will not be executed.
1254
+ * In second time selectedIds will be passed to callback (because checkbox for items are selected), so you can use this to make additional
1255
+ * checks ( for example to check if user has permission for certain records ).
1256
+ *
1257
+ * Example:
1258
+ *
1259
+ * ```ts
1260
+ * allowed: async ({ resource, adminUser, selectedIds }) => {
1261
+ * if (adminUser.dbUser.role !== 'superadmin') {
1262
+ * return false;
1263
+ * }
1264
+ * return true;
1265
+ * }
1266
+ * ```
1267
+ *
1268
+ */
1269
+ allowed?: ({ resource, adminUser, selectedIds, allowedActions }: {
1270
+
1271
+ /**
1272
+ * recordIds will be passed only once user tries to perform bulk action by clicking on button
1273
+ */
1274
+ selectedIds?: Array<any>,
1275
+ resource: AdminForthResource,
1276
+
1277
+ /**
1278
+ * Admin user object
1279
+ */
1280
+ adminUser: AdminUser,
1281
+
1282
+ /**
1283
+ * Allowed standard actions for current user resolved by calling allowedActions callbacks if they are passed.
1284
+ * You can use this variable to rely on standard actions permissions. E.g. if you have custom actions "Mark as read", you
1285
+ * might want to allow it only for users who have "edit" action allowed:
1286
+ *
1287
+ * Example:
1288
+ *
1289
+ * ```ts
1290
+ *
1291
+ * options: \{
1292
+ * bulkActions: [
1293
+ * \{
1294
+ * label: 'Mark as read',
1295
+ * action: async (\{ resource, recordIds \}) => \{
1296
+ * await markAsRead(recordIds);
1297
+ * \},
1298
+ * allowed: (\{ allowedActions \}) => allowedActions.edit,
1299
+ * \}
1300
+ * ],
1301
+ * allowedActions: \{
1302
+ * edit: (\{ resource, adminUser, recordIds \}) => \{
1303
+ * return adminUser.dbUser.role === 'superadmin';
1304
+ * \}
1305
+ * \}
1306
+ * \}
1307
+ * ```
1308
+ *
1309
+ */
1310
+ allowedActions: AllowedActionsResolved,
1311
+ }) => Promise<boolean>,
1312
+
1313
+ }
1314
+
1315
+ export interface AdminForthForeignResource extends AdminForthForeignResourceCommon {
1316
+ hooks?: {
1317
+ dropdownList?: {
1318
+ beforeDatasourceRequest?: BeforeDataSourceRequestFunction | Array<BeforeDataSourceRequestFunction>,
1319
+ afterDatasourceResponse?: AfterDataSourceResponseFunction | Array<AfterDataSourceResponseFunction>,
1320
+ },
1321
+ },
1322
+ }
1323
+
1324
+ export interface AdminForthResourceColumn extends AdminForthResourceColumnCommon {
1325
+ foreignResource?: AdminForthForeignResource,
1326
+ }
1327
+
1328
+ export interface IWebSocketClient {
1329
+ id: string;
1330
+ lastPing: number;
1331
+ topics: Set<string>;
1332
+ adminUser: AdminUser;
1333
+
1334
+ send: (message: string) => void;
1335
+ close: () => void;
1336
+ onMessage: (handler: (message: string) => void) => void;
1337
+ onClose: (handler: () => void) => void;
1338
+ }
1339
+
1340
+ export interface IWebSocketBroker {
1341
+ publish: (topic: string, data: any, filterUsers?: (adminUser: AdminUser) => Promise<boolean>) => void;
1342
+
1343
+ registerWsClient: (client: IWebSocketClient) => void;
1344
+ }