@webiny/api-file-manager 0.0.0-ee-vpcs.549378cf03

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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -0
  3. package/handlers/download/index.d.ts +3 -0
  4. package/handlers/download/index.js +132 -0
  5. package/handlers/download/index.js.map +1 -0
  6. package/handlers/manage/index.d.ts +5 -0
  7. package/handlers/manage/index.js +71 -0
  8. package/handlers/manage/index.js.map +1 -0
  9. package/handlers/transform/index.d.ts +2 -0
  10. package/handlers/transform/index.js +91 -0
  11. package/handlers/transform/index.js.map +1 -0
  12. package/handlers/transform/loaders/imageLoader.d.ts +30 -0
  13. package/handlers/transform/loaders/imageLoader.js +105 -0
  14. package/handlers/transform/loaders/imageLoader.js.map +1 -0
  15. package/handlers/transform/loaders/index.d.ts +8 -0
  16. package/handlers/transform/loaders/index.js +13 -0
  17. package/handlers/transform/loaders/index.js.map +1 -0
  18. package/handlers/transform/loaders/sanitizeImageTransformations.d.ts +11 -0
  19. package/handlers/transform/loaders/sanitizeImageTransformations.js +58 -0
  20. package/handlers/transform/loaders/sanitizeImageTransformations.js.map +1 -0
  21. package/handlers/transform/managers/imageManager.d.ts +15 -0
  22. package/handlers/transform/managers/imageManager.js +63 -0
  23. package/handlers/transform/managers/imageManager.js.map +1 -0
  24. package/handlers/transform/managers/index.d.ts +5 -0
  25. package/handlers/transform/managers/index.js +13 -0
  26. package/handlers/transform/managers/index.js.map +1 -0
  27. package/handlers/transform/optimizeImage.d.ts +3 -0
  28. package/handlers/transform/optimizeImage.js +48 -0
  29. package/handlers/transform/optimizeImage.js.map +1 -0
  30. package/handlers/transform/transformImage.d.ts +10 -0
  31. package/handlers/transform/transformImage.js +30 -0
  32. package/handlers/transform/transformImage.js.map +1 -0
  33. package/handlers/transform/utils.d.ts +12 -0
  34. package/handlers/transform/utils.js +46 -0
  35. package/handlers/transform/utils.js.map +1 -0
  36. package/handlers/types.d.ts +8 -0
  37. package/handlers/types.js +5 -0
  38. package/handlers/types.js.map +1 -0
  39. package/handlers/utils/getEnvironment.d.ts +5 -0
  40. package/handlers/utils/getEnvironment.js +13 -0
  41. package/handlers/utils/getEnvironment.js.map +1 -0
  42. package/handlers/utils/getObjectParams.d.ts +9 -0
  43. package/handlers/utils/getObjectParams.js +25 -0
  44. package/handlers/utils/getObjectParams.js.map +1 -0
  45. package/handlers/utils/index.d.ts +2 -0
  46. package/handlers/utils/index.js +23 -0
  47. package/handlers/utils/index.js.map +1 -0
  48. package/package.json +76 -0
  49. package/plugins/crud/files/validation.d.ts +3 -0
  50. package/plugins/crud/files/validation.js +41 -0
  51. package/plugins/crud/files/validation.js.map +1 -0
  52. package/plugins/crud/files.crud.d.ts +4 -0
  53. package/plugins/crud/files.crud.js +431 -0
  54. package/plugins/crud/files.crud.js.map +1 -0
  55. package/plugins/crud/settings.crud.d.ts +5 -0
  56. package/plugins/crud/settings.crud.js +116 -0
  57. package/plugins/crud/settings.crud.js.map +1 -0
  58. package/plugins/crud/system.crud.d.ts +4 -0
  59. package/plugins/crud/system.crud.js +153 -0
  60. package/plugins/crud/system.crud.js.map +1 -0
  61. package/plugins/crud/utils/checkBasePermissions.d.ts +5 -0
  62. package/plugins/crud/utils/checkBasePermissions.js +33 -0
  63. package/plugins/crud/utils/checkBasePermissions.js.map +1 -0
  64. package/plugins/crud/utils/createFileModel.d.ts +5 -0
  65. package/plugins/crud/utils/createFileModel.js +77 -0
  66. package/plugins/crud/utils/createFileModel.js.map +1 -0
  67. package/plugins/crud/utils/lifecycleEvents.d.ts +6 -0
  68. package/plugins/crud/utils/lifecycleEvents.js +38 -0
  69. package/plugins/crud/utils/lifecycleEvents.js.map +1 -0
  70. package/plugins/definitions/FilePhysicalStoragePlugin.d.ts +21 -0
  71. package/plugins/definitions/FilePhysicalStoragePlugin.js +42 -0
  72. package/plugins/definitions/FilePhysicalStoragePlugin.js.map +1 -0
  73. package/plugins/definitions/FilePlugin.d.ts +136 -0
  74. package/plugins/definitions/FilePlugin.js +70 -0
  75. package/plugins/definitions/FilePlugin.js.map +1 -0
  76. package/plugins/definitions/FileStorageTransformPlugin.d.ts +34 -0
  77. package/plugins/definitions/FileStorageTransformPlugin.js +51 -0
  78. package/plugins/definitions/FileStorageTransformPlugin.js.map +1 -0
  79. package/plugins/definitions/FilesStorageOperationsProviderPlugin.d.ts +9 -0
  80. package/plugins/definitions/FilesStorageOperationsProviderPlugin.js +17 -0
  81. package/plugins/definitions/FilesStorageOperationsProviderPlugin.js.map +1 -0
  82. package/plugins/definitions/InstallationPlugin.d.ts +19 -0
  83. package/plugins/definitions/InstallationPlugin.js +42 -0
  84. package/plugins/definitions/InstallationPlugin.js.map +1 -0
  85. package/plugins/definitions/SettingsStorageOperationsProviderPlugin.d.ts +9 -0
  86. package/plugins/definitions/SettingsStorageOperationsProviderPlugin.js +17 -0
  87. package/plugins/definitions/SettingsStorageOperationsProviderPlugin.js.map +1 -0
  88. package/plugins/definitions/SystemStorageOperationsProviderPlugin.d.ts +9 -0
  89. package/plugins/definitions/SystemStorageOperationsProviderPlugin.js +17 -0
  90. package/plugins/definitions/SystemStorageOperationsProviderPlugin.js.map +1 -0
  91. package/plugins/graphql.d.ts +4 -0
  92. package/plugins/graphql.js +290 -0
  93. package/plugins/graphql.js.map +1 -0
  94. package/plugins/index.d.ts +2 -0
  95. package/plugins/index.js +24 -0
  96. package/plugins/index.js.map +1 -0
  97. package/plugins/storage/FileStorage.d.ts +30 -0
  98. package/plugins/storage/FileStorage.js +103 -0
  99. package/plugins/storage/FileStorage.js.map +1 -0
  100. package/plugins/storage/index.d.ts +4 -0
  101. package/plugins/storage/index.js +26 -0
  102. package/plugins/storage/index.js.map +1 -0
  103. package/types.d.ts +361 -0
  104. package/types.js +5 -0
  105. package/types.js.map +1 -0
  106. package/utils.d.ts +4 -0
  107. package/utils.js +16 -0
  108. package/utils.js.map +1 -0
@@ -0,0 +1,431 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.default = void 0;
9
+
10
+ var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
11
+
12
+ var _mdbid = _interopRequireDefault(require("mdbid"));
13
+
14
+ var _handlerGraphql = require("@webiny/handler-graphql");
15
+
16
+ var _apiSecurity = require("@webiny/api-security");
17
+
18
+ var _checkBasePermissions = _interopRequireDefault(require("./utils/checkBasePermissions"));
19
+
20
+ var _api = require("@webiny/api");
21
+
22
+ var _FilePlugin = require("../definitions/FilePlugin");
23
+
24
+ var _FilesStorageOperationsProviderPlugin = require("../definitions/FilesStorageOperationsProviderPlugin");
25
+
26
+ var _error = _interopRequireDefault(require("@webiny/error"));
27
+
28
+ var _lifecycleEvents = require("./utils/lifecycleEvents");
29
+
30
+ /**
31
+ * Package mdbid does not have types.
32
+ */
33
+ // @ts-ignore
34
+ const BATCH_CREATE_MAX_FILES = 20;
35
+ /**
36
+ * If permission is limited to "own" files only, check that current identity owns the file.
37
+ */
38
+
39
+ const checkOwnership = (file, permission, context) => {
40
+ if ((permission === null || permission === void 0 ? void 0 : permission.own) === true) {
41
+ const identity = context.security.getIdentity();
42
+
43
+ if (file.createdBy.id !== identity.id) {
44
+ throw new _apiSecurity.NotAuthorizedError();
45
+ }
46
+ }
47
+ };
48
+
49
+ const getLocaleCode = context => {
50
+ if (!context.i18n) {
51
+ throw new _error.default("Missing i18n on the FileManagerContext.", "MISSING_I18N");
52
+ }
53
+
54
+ const locale = context.i18n.getContentLocale();
55
+
56
+ if (!locale) {
57
+ throw new _error.default("Missing content locale on the FileManagerContext.", "MISSING_I18N_CONTENT_LOCALE");
58
+ }
59
+
60
+ if (!locale.code) {
61
+ throw new _error.default("Missing content locale code on the FileManagerContext.", "MISSING_I18N_CONTENT_LOCALE_CODE");
62
+ }
63
+
64
+ return locale.code;
65
+ };
66
+
67
+ const filesContextCrudPlugin = new _api.ContextPlugin(async context => {
68
+ const pluginType = _FilesStorageOperationsProviderPlugin.FilesStorageOperationsProviderPlugin.type;
69
+ const providerPlugin = context.plugins.byType(pluginType).find(() => true);
70
+
71
+ if (!providerPlugin) {
72
+ throw new _error.default(`Missing "${pluginType}" plugin.`, "PLUGIN_NOT_FOUND", {
73
+ type: pluginType
74
+ });
75
+ }
76
+
77
+ const storageOperations = await providerPlugin.provide({
78
+ context
79
+ });
80
+
81
+ if (!context.fileManager) {
82
+ context.fileManager = {};
83
+ }
84
+
85
+ const filePlugins = context.plugins.byType(_FilePlugin.FilePlugin.type);
86
+ context.fileManager.files = {
87
+ async getFile(id) {
88
+ const permission = await (0, _checkBasePermissions.default)(context, {
89
+ rwd: "r"
90
+ });
91
+ const file = await storageOperations.get({
92
+ where: {
93
+ id,
94
+ tenant: context.tenancy.getCurrentTenant().id,
95
+ locale: getLocaleCode(context)
96
+ }
97
+ });
98
+
99
+ if (!file) {
100
+ throw new _handlerGraphql.NotFoundError(`File with id "${id}" does not exists.`);
101
+ }
102
+
103
+ checkOwnership(file, permission, context);
104
+ return file;
105
+ },
106
+
107
+ async createFile(input) {
108
+ await (0, _checkBasePermissions.default)(context, {
109
+ rwd: "w"
110
+ });
111
+ const identity = context.security.getIdentity();
112
+ const tenant = context.tenancy.getCurrentTenant();
113
+ const id = (0, _mdbid.default)();
114
+ const file = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, input), {}, {
115
+ tags: Array.isArray(input.tags) ? input.tags : [],
116
+ id,
117
+ meta: (0, _objectSpread2.default)({
118
+ private: false
119
+ }, input.meta || {}),
120
+ tenant: tenant.id,
121
+ createdOn: new Date().toISOString(),
122
+ createdBy: {
123
+ id: identity.id,
124
+ displayName: identity.displayName,
125
+ type: identity.type
126
+ },
127
+ locale: getLocaleCode(context),
128
+ webinyVersion: context.WEBINY_VERSION
129
+ });
130
+
131
+ try {
132
+ await (0, _lifecycleEvents.runLifecycleEvent)("beforeCreate", {
133
+ context,
134
+ plugins: filePlugins,
135
+ data: file
136
+ });
137
+ const result = await storageOperations.create({
138
+ file
139
+ });
140
+ await (0, _lifecycleEvents.runLifecycleEvent)("afterCreate", {
141
+ context,
142
+ plugins: filePlugins,
143
+ data: file,
144
+ file: result
145
+ });
146
+ return result;
147
+ } catch (ex) {
148
+ throw new _error.default(ex.message || "Could not create a file.", ex.code || "CREATE_FILE_ERROR", (0, _objectSpread2.default)((0, _objectSpread2.default)({}, ex.data || {}), {}, {
149
+ file
150
+ }));
151
+ }
152
+ },
153
+
154
+ async updateFile(id, input) {
155
+ const permission = await (0, _checkBasePermissions.default)(context, {
156
+ rwd: "w"
157
+ });
158
+ const original = await storageOperations.get({
159
+ where: {
160
+ id,
161
+ tenant: context.tenancy.getCurrentTenant().id,
162
+ locale: getLocaleCode(context)
163
+ }
164
+ });
165
+
166
+ if (!original) {
167
+ throw new _handlerGraphql.NotFoundError(`File with id "${id}" does not exists.`);
168
+ }
169
+
170
+ checkOwnership(original, permission, context);
171
+ const file = (0, _objectSpread2.default)((0, _objectSpread2.default)((0, _objectSpread2.default)({}, original), input), {}, {
172
+ tags: Array.isArray(input.tags) ? input.tags : Array.isArray(original.tags) ? original.tags : [],
173
+ id: original.id,
174
+ webinyVersion: context.WEBINY_VERSION
175
+ });
176
+
177
+ try {
178
+ await (0, _lifecycleEvents.runLifecycleEvent)("beforeUpdate", {
179
+ context,
180
+ plugins: filePlugins,
181
+ original,
182
+ data: file
183
+ });
184
+ const result = await storageOperations.update({
185
+ original,
186
+ file
187
+ });
188
+ await (0, _lifecycleEvents.runLifecycleEvent)("afterUpdate", {
189
+ context,
190
+ plugins: filePlugins,
191
+ original,
192
+ data: file,
193
+ file: result
194
+ });
195
+ return result;
196
+ } catch (ex) {
197
+ throw new _error.default(ex.message || "Could not update a file.", ex.code || "UPDATE_FILE_ERROR", (0, _objectSpread2.default)((0, _objectSpread2.default)({}, ex.data || {}), {}, {
198
+ original,
199
+ file
200
+ }));
201
+ }
202
+ },
203
+
204
+ async deleteFile(id) {
205
+ const permission = await (0, _checkBasePermissions.default)(context, {
206
+ rwd: "d"
207
+ });
208
+ const file = await storageOperations.get({
209
+ where: {
210
+ id,
211
+ tenant: context.tenancy.getCurrentTenant().id,
212
+ locale: getLocaleCode(context)
213
+ }
214
+ });
215
+
216
+ if (!file) {
217
+ throw new _handlerGraphql.NotFoundError(`File with id "${id}" does not exists.`);
218
+ }
219
+
220
+ checkOwnership(file, permission, context);
221
+
222
+ try {
223
+ await (0, _lifecycleEvents.runLifecycleEvent)("beforeDelete", {
224
+ context,
225
+ plugins: filePlugins,
226
+ file
227
+ });
228
+ await storageOperations.delete({
229
+ file
230
+ });
231
+ await (0, _lifecycleEvents.runLifecycleEvent)("afterDelete", {
232
+ context,
233
+ plugins: filePlugins,
234
+ file
235
+ });
236
+ } catch (ex) {
237
+ throw new _error.default(ex.message || "Could not delete a file.", ex.code || "DELETE_FILE_ERROR", (0, _objectSpread2.default)((0, _objectSpread2.default)({}, ex.data || {}), {}, {
238
+ id,
239
+ file
240
+ }));
241
+ }
242
+
243
+ return true;
244
+ },
245
+
246
+ async createFilesInBatch(inputs) {
247
+ if (!Array.isArray(inputs)) {
248
+ throw new _error.default(`"data" must be an array.`, "CREATE_FILES_NON_ARRAY");
249
+ }
250
+
251
+ if (inputs.length === 0) {
252
+ throw new _error.default(`"data" argument must contain at least one file.`, "CREATE_FILES_MIN_FILES");
253
+ }
254
+
255
+ if (inputs.length > BATCH_CREATE_MAX_FILES) {
256
+ throw new _error.default(`"data" argument must not contain more than ${BATCH_CREATE_MAX_FILES} files.`, "CREATE_FILES_MAX_FILES");
257
+ }
258
+
259
+ await (0, _checkBasePermissions.default)(context, {
260
+ rwd: "w"
261
+ });
262
+ const identity = context.security.getIdentity();
263
+ const tenant = context.tenancy.getCurrentTenant();
264
+ const createdBy = {
265
+ id: identity.id,
266
+ displayName: identity.displayName,
267
+ type: identity.type
268
+ };
269
+ const files = inputs.map(input => {
270
+ return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, input), {}, {
271
+ tags: Array.isArray(input.tags) ? input.tags : [],
272
+ meta: (0, _objectSpread2.default)({
273
+ private: false
274
+ }, input.meta || {}),
275
+ id: (0, _mdbid.default)(),
276
+ tenant: tenant.id,
277
+ createdOn: new Date().toISOString(),
278
+ createdBy,
279
+ locale: getLocaleCode(context),
280
+ webinyVersion: context.WEBINY_VERSION
281
+ });
282
+ });
283
+
284
+ try {
285
+ await (0, _lifecycleEvents.runLifecycleEvent)("beforeBatchCreate", {
286
+ context,
287
+ plugins: filePlugins,
288
+ data: files
289
+ });
290
+ const results = await storageOperations.createBatch({
291
+ files
292
+ });
293
+ await (0, _lifecycleEvents.runLifecycleEvent)("afterBatchCreate", {
294
+ context,
295
+ plugins: filePlugins,
296
+ data: files,
297
+ files: results
298
+ });
299
+ return results;
300
+ } catch (ex) {
301
+ throw new _error.default(ex.message || "Could not create a batch of files.", ex.code || "CREATE_FILES_ERROR", (0, _objectSpread2.default)((0, _objectSpread2.default)({}, ex.data || {}), {}, {
302
+ files
303
+ }));
304
+ }
305
+ },
306
+
307
+ async listFiles(params = {}) {
308
+ const permission = await (0, _checkBasePermissions.default)(context, {
309
+ rwd: "r"
310
+ });
311
+ const {
312
+ limit = 40,
313
+ search = "",
314
+ types = [],
315
+ tags = [],
316
+ ids = [],
317
+ after = null,
318
+ where: initialWhere,
319
+ sort: initialSort
320
+ } = params;
321
+ const where = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, initialWhere), {}, {
322
+ private: false,
323
+ locale: getLocaleCode(context),
324
+ tenant: context.tenancy.getCurrentTenant().id
325
+ });
326
+ /**
327
+ * Always override the createdBy received from the user, if any.
328
+ */
329
+
330
+ if (permission.own === true) {
331
+ const identity = context.security.getIdentity();
332
+ where.createdBy = identity.id;
333
+ }
334
+ /**
335
+ * We need to map the old GraphQL definition to the new one.
336
+ * That GQL definition is marked as deprecated.
337
+ */
338
+
339
+ /**
340
+ * To have standardized where objects across the applications, we transform the types into type_in.
341
+ */
342
+
343
+
344
+ if (Array.isArray(types) && types.length > 0 && !where.type_in) {
345
+ where.type_in = types;
346
+ }
347
+ /**
348
+ * We are assigning search to tag and name search.
349
+ * This should be treated as OR condition in the storage operations.
350
+ */
351
+
352
+
353
+ if (search && !where.search) {
354
+ where.search = search;
355
+ }
356
+ /**
357
+ * Same as on types/type_in.
358
+ */
359
+
360
+
361
+ if (Array.isArray(tags) && tags.length > 0 && !where.tag_in) {
362
+ where.tag_in = tags.map(tag => tag.toLowerCase());
363
+ }
364
+ /**
365
+ * Same as on types/type_in.
366
+ */
367
+
368
+
369
+ if (Array.isArray(ids) && ids.length > 0 && !where.id_in) {
370
+ where.id_in = ids;
371
+ }
372
+
373
+ const sort = Array.isArray(initialSort) && initialSort.length > 0 ? initialSort : ["id_DESC"];
374
+
375
+ try {
376
+ return await storageOperations.list({
377
+ where,
378
+ after,
379
+ limit,
380
+ sort
381
+ });
382
+ } catch (ex) {
383
+ throw new _error.default(ex.message || "Could not list files by given parameters.", ex.code || "FILE_TAG_SEARCH_ERROR", (0, _objectSpread2.default)((0, _objectSpread2.default)({}, ex.data || {}), {}, {
384
+ where,
385
+ after,
386
+ limit,
387
+ sort
388
+ }));
389
+ }
390
+ },
391
+
392
+ async listTags({
393
+ where: initialWhere,
394
+ after,
395
+ limit
396
+ }) {
397
+ await (0, _checkBasePermissions.default)(context);
398
+ const where = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, initialWhere), {}, {
399
+ tenant: context.tenancy.getCurrentTenant().id,
400
+ locale: getLocaleCode(context)
401
+ });
402
+ const params = {
403
+ where,
404
+ limit: limit || 100000,
405
+ after
406
+ };
407
+
408
+ try {
409
+ const [tags] = await storageOperations.tags(params);
410
+
411
+ if (Array.isArray(tags) === false) {
412
+ return [];
413
+ }
414
+ /**
415
+ * just to keep it standardized, sort by the tag ASC
416
+ */
417
+
418
+
419
+ return tags.sort();
420
+ } catch (ex) {
421
+ throw new _error.default(ex.message || "Could not search for tags.", ex.code || "FILE_TAG_SEARCH_ERROR", (0, _objectSpread2.default)((0, _objectSpread2.default)({}, ex.data || {}), {}, {
422
+ params
423
+ }));
424
+ }
425
+ }
426
+
427
+ };
428
+ });
429
+ filesContextCrudPlugin.name = "FileManagerFilesCrud";
430
+ var _default = filesContextCrudPlugin;
431
+ exports.default = _default;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["BATCH_CREATE_MAX_FILES","checkOwnership","file","permission","context","own","identity","security","getIdentity","createdBy","id","NotAuthorizedError","getLocaleCode","i18n","WebinyError","locale","getContentLocale","code","filesContextCrudPlugin","ContextPlugin","pluginType","FilesStorageOperationsProviderPlugin","type","providerPlugin","plugins","byType","find","storageOperations","provide","fileManager","filePlugins","FilePlugin","files","getFile","checkBasePermissions","rwd","get","where","tenant","tenancy","getCurrentTenant","NotFoundError","createFile","input","mdbid","tags","Array","isArray","meta","private","createdOn","Date","toISOString","displayName","webinyVersion","WEBINY_VERSION","runLifecycleEvent","data","result","create","ex","message","updateFile","original","update","deleteFile","delete","createFilesInBatch","inputs","length","map","results","createBatch","listFiles","params","limit","search","types","ids","after","initialWhere","sort","initialSort","type_in","tag_in","tag","toLowerCase","id_in","list","listTags","name"],"sources":["files.crud.ts"],"sourcesContent":["/**\n * Package mdbid does not have types.\n */\n// @ts-ignore\nimport mdbid from \"mdbid\";\nimport { NotFoundError } from \"@webiny/handler-graphql\";\nimport { NotAuthorizedError } from \"@webiny/api-security\";\nimport {\n CreatedBy,\n File,\n FileManagerContext,\n FileManagerFilesStorageOperationsListParamsWhere,\n FileManagerFilesStorageOperationsTagsParamsWhere,\n FilePermission,\n FilesListOpts\n} from \"~/types\";\nimport checkBasePermissions from \"./utils/checkBasePermissions\";\nimport { ContextPlugin } from \"@webiny/api\";\nimport { FilePlugin } from \"~/plugins/definitions/FilePlugin\";\nimport { FilesStorageOperationsProviderPlugin } from \"~/plugins/definitions/FilesStorageOperationsProviderPlugin\";\nimport WebinyError from \"@webiny/error\";\nimport { runLifecycleEvent } from \"~/plugins/crud/utils/lifecycleEvents\";\n\nconst BATCH_CREATE_MAX_FILES = 20;\n\n/**\n * If permission is limited to \"own\" files only, check that current identity owns the file.\n */\nconst checkOwnership = (file: File, permission: FilePermission, context: FileManagerContext) => {\n if (permission?.own === true) {\n const identity = context.security.getIdentity();\n if (file.createdBy.id !== identity.id) {\n throw new NotAuthorizedError();\n }\n }\n};\n\nconst getLocaleCode = (context: FileManagerContext): string => {\n if (!context.i18n) {\n throw new WebinyError(\"Missing i18n on the FileManagerContext.\", \"MISSING_I18N\");\n }\n\n const locale = context.i18n.getContentLocale();\n if (!locale) {\n throw new WebinyError(\n \"Missing content locale on the FileManagerContext.\",\n \"MISSING_I18N_CONTENT_LOCALE\"\n );\n }\n\n if (!locale.code) {\n throw new WebinyError(\n \"Missing content locale code on the FileManagerContext.\",\n \"MISSING_I18N_CONTENT_LOCALE_CODE\"\n );\n }\n return locale.code;\n};\n\nconst filesContextCrudPlugin = new ContextPlugin<FileManagerContext>(async context => {\n const pluginType = FilesStorageOperationsProviderPlugin.type;\n\n const providerPlugin = context.plugins\n .byType<FilesStorageOperationsProviderPlugin>(pluginType)\n .find(() => true);\n\n if (!providerPlugin) {\n throw new WebinyError(`Missing \"${pluginType}\" plugin.`, \"PLUGIN_NOT_FOUND\", {\n type: pluginType\n });\n }\n\n const storageOperations = await providerPlugin.provide({\n context\n });\n\n if (!context.fileManager) {\n context.fileManager = {} as any;\n }\n\n const filePlugins = context.plugins.byType<FilePlugin>(FilePlugin.type);\n\n context.fileManager.files = {\n async getFile(id: string) {\n const permission = await checkBasePermissions(context, { rwd: \"r\" });\n\n const file = await storageOperations.get({\n where: {\n id,\n tenant: context.tenancy.getCurrentTenant().id,\n locale: getLocaleCode(context)\n }\n });\n\n if (!file) {\n throw new NotFoundError(`File with id \"${id}\" does not exists.`);\n }\n\n checkOwnership(file, permission, context);\n\n return file;\n },\n async createFile(input) {\n await checkBasePermissions(context, { rwd: \"w\" });\n const identity = context.security.getIdentity();\n const tenant = context.tenancy.getCurrentTenant();\n\n const id = mdbid();\n\n const file: File = {\n ...input,\n tags: Array.isArray(input.tags) ? input.tags : [],\n id,\n meta: {\n private: false,\n ...(input.meta || {})\n },\n tenant: tenant.id,\n createdOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n },\n locale: getLocaleCode(context),\n webinyVersion: context.WEBINY_VERSION\n };\n\n try {\n await runLifecycleEvent(\"beforeCreate\", {\n context,\n plugins: filePlugins,\n data: file\n });\n const result = await storageOperations.create({\n file\n });\n await runLifecycleEvent(\"afterCreate\", {\n context,\n plugins: filePlugins,\n data: file,\n file: result\n });\n return result;\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not create a file.\",\n ex.code || \"CREATE_FILE_ERROR\",\n {\n ...(ex.data || {}),\n file\n }\n );\n }\n },\n async updateFile(id, input) {\n const permission = await checkBasePermissions(context, { rwd: \"w\" });\n\n const original = await storageOperations.get({\n where: {\n id,\n tenant: context.tenancy.getCurrentTenant().id,\n locale: getLocaleCode(context)\n }\n });\n\n if (!original) {\n throw new NotFoundError(`File with id \"${id}\" does not exists.`);\n }\n\n checkOwnership(original, permission, context);\n\n const file: File = {\n ...original,\n ...input,\n tags: Array.isArray(input.tags)\n ? input.tags\n : Array.isArray(original.tags)\n ? original.tags\n : [],\n id: original.id,\n webinyVersion: context.WEBINY_VERSION\n };\n\n try {\n await runLifecycleEvent(\"beforeUpdate\", {\n context,\n plugins: filePlugins,\n original,\n data: file\n });\n const result = await storageOperations.update({\n original,\n file\n });\n await runLifecycleEvent(\"afterUpdate\", {\n context,\n plugins: filePlugins,\n original,\n data: file,\n file: result\n });\n return result;\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not update a file.\",\n ex.code || \"UPDATE_FILE_ERROR\",\n {\n ...(ex.data || {}),\n original,\n file\n }\n );\n }\n },\n async deleteFile(id) {\n const permission = await checkBasePermissions(context, { rwd: \"d\" });\n\n const file = await storageOperations.get({\n where: {\n id,\n tenant: context.tenancy.getCurrentTenant().id,\n locale: getLocaleCode(context)\n }\n });\n if (!file) {\n throw new NotFoundError(`File with id \"${id}\" does not exists.`);\n }\n\n checkOwnership(file, permission, context);\n\n try {\n await runLifecycleEvent(\"beforeDelete\", {\n context,\n plugins: filePlugins,\n file\n });\n await storageOperations.delete({\n file\n });\n await runLifecycleEvent(\"afterDelete\", {\n context,\n plugins: filePlugins,\n file\n });\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not delete a file.\",\n ex.code || \"DELETE_FILE_ERROR\",\n {\n ...(ex.data || {}),\n id,\n file\n }\n );\n }\n\n return true;\n },\n async createFilesInBatch(inputs) {\n if (!Array.isArray(inputs)) {\n throw new WebinyError(`\"data\" must be an array.`, \"CREATE_FILES_NON_ARRAY\");\n }\n\n if (inputs.length === 0) {\n throw new WebinyError(\n `\"data\" argument must contain at least one file.`,\n \"CREATE_FILES_MIN_FILES\"\n );\n }\n\n if (inputs.length > BATCH_CREATE_MAX_FILES) {\n throw new WebinyError(\n `\"data\" argument must not contain more than ${BATCH_CREATE_MAX_FILES} files.`,\n \"CREATE_FILES_MAX_FILES\"\n );\n }\n\n await checkBasePermissions(context, { rwd: \"w\" });\n\n const identity = context.security.getIdentity();\n const tenant = context.tenancy.getCurrentTenant();\n const createdBy: CreatedBy = {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n };\n\n const files: File[] = inputs.map(input => {\n return {\n ...input,\n tags: Array.isArray(input.tags) ? input.tags : [],\n meta: {\n private: false,\n ...(input.meta || {})\n },\n id: mdbid(),\n tenant: tenant.id,\n createdOn: new Date().toISOString(),\n createdBy,\n locale: getLocaleCode(context),\n webinyVersion: context.WEBINY_VERSION\n };\n });\n\n try {\n await runLifecycleEvent(\"beforeBatchCreate\", {\n context,\n plugins: filePlugins,\n data: files\n });\n const results = await storageOperations.createBatch({\n files\n });\n await runLifecycleEvent(\"afterBatchCreate\", {\n context,\n plugins: filePlugins,\n data: files,\n files: results\n });\n return results;\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not create a batch of files.\",\n ex.code || \"CREATE_FILES_ERROR\",\n {\n ...(ex.data || {}),\n files\n }\n );\n }\n },\n async listFiles(params: FilesListOpts = {}) {\n const permission = await checkBasePermissions(context, { rwd: \"r\" });\n\n const {\n limit = 40,\n search = \"\",\n types = [],\n tags = [],\n ids = [],\n after = null,\n where: initialWhere,\n sort: initialSort\n } = params;\n\n const where: FileManagerFilesStorageOperationsListParamsWhere = {\n ...initialWhere,\n private: false,\n locale: getLocaleCode(context),\n tenant: context.tenancy.getCurrentTenant().id\n };\n /**\n * Always override the createdBy received from the user, if any.\n */\n if (permission.own === true) {\n const identity = context.security.getIdentity();\n where.createdBy = identity.id;\n }\n /**\n * We need to map the old GraphQL definition to the new one.\n * That GQL definition is marked as deprecated.\n */\n /**\n * To have standardized where objects across the applications, we transform the types into type_in.\n */\n if (Array.isArray(types) && types.length > 0 && !where.type_in) {\n where.type_in = types;\n }\n /**\n * We are assigning search to tag and name search.\n * This should be treated as OR condition in the storage operations.\n */\n if (search && !where.search) {\n where.search = search;\n }\n /**\n * Same as on types/type_in.\n */\n if (Array.isArray(tags) && tags.length > 0 && !where.tag_in) {\n where.tag_in = tags.map(tag => tag.toLowerCase());\n }\n /**\n * Same as on types/type_in.\n */\n if (Array.isArray(ids) && ids.length > 0 && !where.id_in) {\n where.id_in = ids;\n }\n\n const sort =\n Array.isArray(initialSort) && initialSort.length > 0 ? initialSort : [\"id_DESC\"];\n try {\n return await storageOperations.list({\n where,\n after,\n limit,\n sort\n });\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not list files by given parameters.\",\n ex.code || \"FILE_TAG_SEARCH_ERROR\",\n {\n ...(ex.data || {}),\n where,\n after,\n limit,\n sort\n }\n );\n }\n },\n async listTags({ where: initialWhere, after, limit }) {\n await checkBasePermissions(context);\n\n const where: FileManagerFilesStorageOperationsTagsParamsWhere = {\n ...initialWhere,\n tenant: context.tenancy.getCurrentTenant().id,\n locale: getLocaleCode(context)\n };\n\n const params = {\n where,\n limit: limit || 100000,\n after\n };\n\n try {\n const [tags] = await storageOperations.tags(params);\n if (Array.isArray(tags) === false) {\n return [];\n }\n /**\n * just to keep it standardized, sort by the tag ASC\n */\n return tags.sort();\n } catch (ex) {\n throw new WebinyError(\n ex.message || \"Could not search for tags.\",\n ex.code || \"FILE_TAG_SEARCH_ERROR\",\n {\n ...(ex.data || {}),\n params\n }\n );\n }\n }\n };\n});\n\nfilesContextCrudPlugin.name = \"FileManagerFilesCrud\";\n\nexport default filesContextCrudPlugin;\n"],"mappings":";;;;;;;;;;;AAIA;;AACA;;AACA;;AAUA;;AACA;;AACA;;AACA;;AACA;;AACA;;AArBA;AACA;AACA;AACA;AAoBA,MAAMA,sBAAsB,GAAG,EAA/B;AAEA;AACA;AACA;;AACA,MAAMC,cAAc,GAAG,CAACC,IAAD,EAAaC,UAAb,EAAyCC,OAAzC,KAAyE;EAC5F,IAAI,CAAAD,UAAU,SAAV,IAAAA,UAAU,WAAV,YAAAA,UAAU,CAAEE,GAAZ,MAAoB,IAAxB,EAA8B;IAC1B,MAAMC,QAAQ,GAAGF,OAAO,CAACG,QAAR,CAAiBC,WAAjB,EAAjB;;IACA,IAAIN,IAAI,CAACO,SAAL,CAAeC,EAAf,KAAsBJ,QAAQ,CAACI,EAAnC,EAAuC;MACnC,MAAM,IAAIC,+BAAJ,EAAN;IACH;EACJ;AACJ,CAPD;;AASA,MAAMC,aAAa,GAAIR,OAAD,IAAyC;EAC3D,IAAI,CAACA,OAAO,CAACS,IAAb,EAAmB;IACf,MAAM,IAAIC,cAAJ,CAAgB,yCAAhB,EAA2D,cAA3D,CAAN;EACH;;EAED,MAAMC,MAAM,GAAGX,OAAO,CAACS,IAAR,CAAaG,gBAAb,EAAf;;EACA,IAAI,CAACD,MAAL,EAAa;IACT,MAAM,IAAID,cAAJ,CACF,mDADE,EAEF,6BAFE,CAAN;EAIH;;EAED,IAAI,C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0C,KANF;UAOEJ,KAPF;UAQEM;QARF,GAAN;MAWH;IACJ,CAzUuB;;IA0UxB,MAAMQ,QAAN,CAAe;MAAEpD,KAAK,EAAE2C,YAAT;MAAuBD,KAAvB;MAA8BJ;IAA9B,CAAf,EAAsD;MAClD,MAAM,IAAAzC,6BAAA,EAAqB9B,OAArB,CAAN;MAEA,MAAMiC,KAAuD,+DACtD2C,YADsD;QAEzD1C,MAAM,EAAElC,OAAO,CAACmC,OAAR,CAAgBC,gBAAhB,GAAmC9B,EAFc;QAGzDK,MAAM,EAAEH,aAAa,CAACR,OAAD;MAHoC,EAA7D;MAMA,MAAMsE,MAAM,GAAG;QACXrC,KADW;QAEXsC,KAAK,EAAEA,KAAK,IAAI,MAFL;QAGXI;MAHW,CAAf;;MAMA,IAAI;QACA,MAAM,CAAClC,IAAD,IAAS,MAAMlB,iBAAiB,CAACkB,IAAlB,CAAuB6B,MAAvB,CAArB;;QACA,IAAI5B,KAAK,CAACC,OAAN,CAAcF,IAAd,MAAwB,KAA5B,EAAmC;UAC/B,OAAO,EAAP;QACH;QACD;AAChB;AACA;;;QACgB,OAAOA,IAAI,CAACoC,IAAL,EAAP;MACH,CATD,CASE,OAAOrB,EAAP,EAAW;QACT,MAAM,IAAI9C,cAAJ,CACF8C,EAAE,CAACC,OAAH,IAAc,4BADZ,EAEFD,EAAE,CAAC3C,IAAH,IAAW,uBAFT,8DAIM2C,EAAE,CAACH,IAAH,IAAW,EAJjB;UAKEiB;QALF,GAAN;MAQH;IACJ;;EA5WuB,CAA5B;AA8WH,CArY8B,CAA/B;AAuYAxD,sBAAsB,CAACwE,IAAvB,GAA8B,sBAA9B;eAEexE,sB"}
@@ -0,0 +1,5 @@
1
+ import { FileManagerContext } from "../../types";
2
+ import { ContextPlugin } from "@webiny/api";
3
+ export declare const SETTINGS_KEY = "file-manager";
4
+ declare const settingsCrudContextPlugin: ContextPlugin<FileManagerContext>;
5
+ export default settingsCrudContextPlugin;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.default = exports.SETTINGS_KEY = void 0;
9
+
10
+ var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
11
+
12
+ var _fields = require("@commodo/fields");
13
+
14
+ var _validation = require("@webiny/validation");
15
+
16
+ var _SettingsStorageOperationsProviderPlugin = require("../definitions/SettingsStorageOperationsProviderPlugin");
17
+
18
+ var _error = _interopRequireDefault(require("@webiny/error"));
19
+
20
+ var _api = require("@webiny/api");
21
+
22
+ /**
23
+ * Package @commodo/fields does not have types.
24
+ */
25
+ // @ts-ignore
26
+ // TODO @ts-refactor verify that this is not used and remove it
27
+ const SETTINGS_KEY = "file-manager";
28
+ exports.SETTINGS_KEY = SETTINGS_KEY;
29
+ const CreateDataModel = (0, _fields.withFields)({
30
+ uploadMinFileSize: (0, _fields.number)({
31
+ value: 0,
32
+ validation: _validation.validation.create("gte:0")
33
+ }),
34
+ uploadMaxFileSize: (0, _fields.number)({
35
+ value: 26214401
36
+ }),
37
+ srcPrefix: (0, _fields.onSet)(value => {
38
+ // Make sure srcPrefix always ends with forward slash.
39
+ if (typeof value === "string") {
40
+ return value.endsWith("/") ? value : value + "/";
41
+ }
42
+
43
+ return value;
44
+ })((0, _fields.string)({
45
+ value: "/files/"
46
+ }))
47
+ })();
48
+ const UpdateDataModel = (0, _fields.withFields)({
49
+ uploadMinFileSize: (0, _fields.number)({
50
+ validation: _validation.validation.create("gte:0")
51
+ }),
52
+ uploadMaxFileSize: (0, _fields.number)(),
53
+ srcPrefix: (0, _fields.onSet)(value => {
54
+ // Make sure srcPrefix always ends with forward slash.
55
+ if (typeof value === "string") {
56
+ return value.endsWith("/") ? value : value + "/";
57
+ }
58
+
59
+ return value;
60
+ })((0, _fields.string)())
61
+ })();
62
+ const settingsCrudContextPlugin = new _api.ContextPlugin(async context => {
63
+ const pluginType = _SettingsStorageOperationsProviderPlugin.SettingsStorageOperationsProviderPlugin.type;
64
+ const providerPlugin = context.plugins.byType(pluginType).find(() => true);
65
+
66
+ if (!providerPlugin) {
67
+ throw new _error.default(`Missing "${pluginType}" plugin.`, "PLUGIN_NOT_FOUND", {
68
+ type: pluginType
69
+ });
70
+ }
71
+
72
+ const storageOperations = await providerPlugin.provide({
73
+ context
74
+ });
75
+
76
+ if (!context.fileManager) {
77
+ context.fileManager = {};
78
+ }
79
+
80
+ context.fileManager.settings = {
81
+ async getSettings() {
82
+ return storageOperations.get();
83
+ },
84
+
85
+ async createSettings(data) {
86
+ const settings = new CreateDataModel().populate(data);
87
+ await settings.validate();
88
+ const settingsData = await settings.toJSON();
89
+ return storageOperations.create({
90
+ data: settingsData
91
+ });
92
+ },
93
+
94
+ async updateSettings(data) {
95
+ const updatedValue = new UpdateDataModel().populate(data);
96
+ await updatedValue.validate();
97
+ const existingSettings = await storageOperations.get();
98
+ const updatedSettings = await updatedValue.toJSON({
99
+ onlyDirty: true
100
+ });
101
+ return storageOperations.update({
102
+ original: existingSettings,
103
+ data: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, existingSettings), updatedSettings)
104
+ });
105
+ },
106
+
107
+ async deleteSettings() {
108
+ await storageOperations.delete();
109
+ return true;
110
+ }
111
+
112
+ };
113
+ });
114
+ settingsCrudContextPlugin.name = "FileMangerSettingsCrud";
115
+ var _default = settingsCrudContextPlugin;
116
+ exports.default = _default;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["SETTINGS_KEY","CreateDataModel","withFields","uploadMinFileSize","number","value","validation","create","uploadMaxFileSize","srcPrefix","onSet","endsWith","string","UpdateDataModel","settingsCrudContextPlugin","ContextPlugin","context","pluginType","SettingsStorageOperationsProviderPlugin","type","providerPlugin","plugins","byType","find","WebinyError","storageOperations","provide","fileManager","settings","getSettings","get","createSettings","data","populate","validate","settingsData","toJSON","updateSettings","updatedValue","existingSettings","updatedSettings","onlyDirty","update","original","deleteSettings","delete","name"],"sources":["settings.crud.ts"],"sourcesContent":["/**\n * Package @commodo/fields does not have types.\n */\n// @ts-ignore\nimport { withFields, string, number, onSet } from \"@commodo/fields\";\nimport { validation } from \"@webiny/validation\";\nimport { FileManagerContext, FileManagerSettings } from \"~/types\";\nimport { SettingsStorageOperationsProviderPlugin } from \"~/plugins/definitions/SettingsStorageOperationsProviderPlugin\";\nimport WebinyError from \"@webiny/error\";\nimport { ContextPlugin } from \"@webiny/api\";\n\n// TODO @ts-refactor verify that this is not used and remove it\nexport const SETTINGS_KEY = \"file-manager\";\n\nconst CreateDataModel = withFields({\n uploadMinFileSize: number({ value: 0, validation: validation.create(\"gte:0\") }),\n uploadMaxFileSize: number({ value: 26214401 }),\n srcPrefix: onSet((value?: string) => {\n // Make sure srcPrefix always ends with forward slash.\n if (typeof value === \"string\") {\n return value.endsWith(\"/\") ? value : value + \"/\";\n }\n return value;\n })(string({ value: \"/files/\" }))\n})();\n\nconst UpdateDataModel = withFields({\n uploadMinFileSize: number({\n validation: validation.create(\"gte:0\")\n }),\n uploadMaxFileSize: number(),\n srcPrefix: onSet((value?: string) => {\n // Make sure srcPrefix always ends with forward slash.\n if (typeof value === \"string\") {\n return value.endsWith(\"/\") ? value : value + \"/\";\n }\n return value;\n })(string())\n})();\n\nconst settingsCrudContextPlugin = new ContextPlugin<FileManagerContext>(async context => {\n const pluginType = SettingsStorageOperationsProviderPlugin.type;\n\n const providerPlugin = context.plugins\n .byType<SettingsStorageOperationsProviderPlugin>(pluginType)\n .find(() => true);\n\n if (!providerPlugin) {\n throw new WebinyError(`Missing \"${pluginType}\" plugin.`, \"PLUGIN_NOT_FOUND\", {\n type: pluginType\n });\n }\n\n const storageOperations = await providerPlugin.provide({\n context\n });\n\n if (!context.fileManager) {\n context.fileManager = {} as any;\n }\n\n context.fileManager.settings = {\n async getSettings() {\n return storageOperations.get();\n },\n async createSettings(data) {\n const settings = new CreateDataModel().populate(data);\n await settings.validate();\n\n const settingsData: FileManagerSettings = await settings.toJSON();\n\n return storageOperations.create({\n data: settingsData\n });\n },\n async updateSettings(data) {\n const updatedValue = new UpdateDataModel().populate(data);\n await updatedValue.validate();\n\n const existingSettings = (await storageOperations.get()) as FileManagerSettings;\n\n const updatedSettings: Partial<FileManagerSettings> = await updatedValue.toJSON({\n onlyDirty: true\n });\n\n return storageOperations.update({\n original: existingSettings,\n data: {\n ...existingSettings,\n ...updatedSettings\n }\n });\n },\n async deleteSettings() {\n await storageOperations.delete();\n\n return true;\n }\n };\n});\n\nsettingsCrudContextPlugin.name = \"FileMangerSettingsCrud\";\n\nexport default settingsCrudContextPlugin;\n"],"mappings":";;;;;;;;;;;AAIA;;AACA;;AAEA;;AACA;;AACA;;AATA;AACA;AACA;AACA;AAQA;AACO,MAAMA,YAAY,GAAG,cAArB;;AAEP,MAAMC,eAAe,GAAG,IAAAC,kBAAA,EAAW;EAC/BC,iBAAiB,EAAE,IAAAC,cAAA,EAAO;IAAEC,KAAK,EAAE,CAAT;IAAYC,UAAU,EAAEA,sBAAA,CAAWC,MAAX,CAAkB,OAAlB;EAAxB,CAAP,CADY;EAE/BC,iBAAiB,EAAE,IAAAJ,cAAA,EAAO;IAAEC,KAAK,EAAE;EAAT,CAAP,CAFY;EAG/BI,SAAS,EAAE,IAAAC,aAAA,EAAOL,KAAD,IAAoB;IACjC;IACA,IAAI,OAAOA,KAAP,KAAiB,QAArB,EAA+B;MAC3B,OAAOA,KAAK,CAACM,QAAN,CAAe,GAAf,IAAsBN,KAAtB,GAA8BA,KAAK,GAAG,GAA7C;IACH;;IACD,OAAOA,KAAP;EACH,CANU,EAMR,IAAAO,cAAA,EAAO;IAAEP,KAAK,EAAE;EAAT,CAAP,CANQ;AAHoB,CAAX,GAAxB;AAYA,MAAMQ,eAAe,GAAG,IAAAX,kBAAA,EAAW;EAC/BC,iBAAiB,EAAE,IAAAC,cAAA,EAAO;IACtBE,UAAU,EAAEA,sBAAA,CAAWC,MAAX,CAAkB,OAAlB;EADU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,MAAT,EAAhD;MAEA,OAAOX,iBAAiB,CAAClB,MAAlB,CAAyB;QAC5ByB,IAAI,EAAEG;MADsB,CAAzB,CAAP;IAGH,CAb0B;;IAc3B,MAAME,cAAN,CAAqBL,IAArB,EAA2B;MACvB,MAAMM,YAAY,GAAG,IAAIzB,eAAJ,GAAsBoB,QAAtB,CAA+BD,IAA/B,CAArB;MACA,MAAMM,YAAY,CAACJ,QAAb,EAAN;MAEA,MAAMK,gBAAgB,GAAI,MAAMd,iBAAiB,CAACK,GAAlB,EAAhC;MAEA,MAAMU,eAA6C,GAAG,MAAMF,YAAY,CAACF,MAAb,CAAoB;QAC5EK,SAAS,EAAE;MADiE,CAApB,CAA5D;MAIA,OAAOhB,iBAAiB,CAACiB,MAAlB,CAAyB;QAC5BC,QAAQ,EAAEJ,gBADkB;QAE5BP,IAAI,8DACGO,gBADH,GAEGC,eAFH;MAFwB,CAAzB,CAAP;IAOH,CA/B0B;;IAgC3B,MAAMI,cAAN,GAAuB;MACnB,MAAMnB,iBAAiB,CAACoB,MAAlB,EAAN;MAEA,OAAO,IAAP;IACH;;EApC0B,CAA/B;AAsCH,CA3DiC,CAAlC;AA6DA/B,yBAAyB,CAACgC,IAA1B,GAAiC,wBAAjC;eAEehC,yB"}
@@ -0,0 +1,4 @@
1
+ import { FileManagerContext } from "../../types";
2
+ import { ContextPlugin } from "@webiny/api";
3
+ declare const systemCrudContextPlugin: ContextPlugin<FileManagerContext>;
4
+ export default systemCrudContextPlugin;