@webiny/api-page-builder-import-export 0.0.0-mt-1

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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -0
  3. package/exportPages/combine/index.d.ts +19 -0
  4. package/exportPages/combine/index.js +88 -0
  5. package/exportPages/process/index.d.ts +26 -0
  6. package/exportPages/process/index.js +204 -0
  7. package/exportPages/s3Stream.d.ts +29 -0
  8. package/exportPages/s3Stream.js +106 -0
  9. package/exportPages/utils.d.ts +13 -0
  10. package/exportPages/utils.js +113 -0
  11. package/exportPages/zipper.d.ts +35 -0
  12. package/exportPages/zipper.js +137 -0
  13. package/graphql/crud/pageImportExportTasks.crud.d.ts +5 -0
  14. package/graphql/crud/pageImportExportTasks.crud.js +394 -0
  15. package/graphql/crud/pages.crud.d.ts +4 -0
  16. package/graphql/crud/pages.crud.js +162 -0
  17. package/graphql/crud.d.ts +3 -0
  18. package/graphql/crud.js +16 -0
  19. package/graphql/graphql/pageImportExportTasks.gql.d.ts +4 -0
  20. package/graphql/graphql/pageImportExportTasks.gql.js +80 -0
  21. package/graphql/graphql/pages.gql.d.ts +4 -0
  22. package/graphql/graphql/pages.gql.js +72 -0
  23. package/graphql/graphql/utils/resolve.d.ts +3 -0
  24. package/graphql/graphql/utils/resolve.js +18 -0
  25. package/graphql/graphql.d.ts +3 -0
  26. package/graphql/graphql.js +15 -0
  27. package/graphql/index.d.ts +3 -0
  28. package/graphql/index.js +16 -0
  29. package/graphql/types.d.ts +63 -0
  30. package/graphql/types.js +5 -0
  31. package/importPages/client.d.ts +7 -0
  32. package/importPages/client.js +40 -0
  33. package/importPages/create/index.d.ts +27 -0
  34. package/importPages/create/index.js +109 -0
  35. package/importPages/process/index.d.ts +25 -0
  36. package/importPages/process/index.js +183 -0
  37. package/importPages/utils.d.ts +43 -0
  38. package/importPages/utils.js +539 -0
  39. package/mockSecurity.d.ts +2 -0
  40. package/mockSecurity.js +13 -0
  41. package/package.json +80 -0
  42. package/types.d.ts +192 -0
  43. package/types.js +42 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Webiny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @webiny/api-page-builder-import-export
2
+ [![](https://img.shields.io/npm/dw/@webiny/api-page-builder.svg)](https://www.npmjs.com/package/@webiny/api-page-builder)
3
+ [![](https://img.shields.io/npm/v/@webiny/api-page-builder.svg)](https://www.npmjs.com/package/@webiny/api-page-builder)
4
+ [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
5
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
6
+
7
+ The API for the [Webiny Page Builder (@webiny/app-page-builder)](../app-page-builder) app.
8
+
9
+ ## Install
10
+ ```
11
+ npm install --save @webiny/api-page-builder-import-export
12
+ ```
13
+
14
+ Or if you prefer yarn:
15
+ ```
16
+ yarn add @webiny/api-page-builder-import-export
17
+ ```
@@ -0,0 +1,19 @@
1
+ import { HandlerPlugin } from "@webiny/handler/types";
2
+ import { ArgsContext } from "@webiny/handler-args/types";
3
+ import { PbPageImportExportContext } from "../../types";
4
+ import { SecurityIdentity } from "@webiny/api-security/types";
5
+ export declare type HandlerArgs = {
6
+ taskId: string;
7
+ identity: SecurityIdentity;
8
+ };
9
+ export declare type HandlerResponse = {
10
+ data: string;
11
+ error: {
12
+ message: string;
13
+ };
14
+ };
15
+ declare const _default: () => HandlerPlugin<PbPageImportExportContext, ArgsContext<HandlerArgs>>;
16
+ /**
17
+ * Handles the export pages combine workflow.
18
+ */
19
+ export default _default;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+
8
+ var _types = require("../../types");
9
+
10
+ var _s3Stream = require("../s3Stream");
11
+
12
+ var _zipper = require("../zipper");
13
+
14
+ var _mockSecurity = require("../../mockSecurity");
15
+
16
+ /**
17
+ * Handles the export pages combine workflow.
18
+ */
19
+ var _default = () => ({
20
+ type: "handler",
21
+
22
+ async handle(context) {
23
+ const log = console.log;
24
+ log("RUNNING Export Pages Combine Handler");
25
+ const {
26
+ invocationArgs: args,
27
+ pageBuilder
28
+ } = context;
29
+ const {
30
+ taskId,
31
+ identity
32
+ } = args;
33
+ (0, _mockSecurity.mockSecurity)(identity, context);
34
+
35
+ try {
36
+ const task = await pageBuilder.pageImportExportTask.getTask(taskId);
37
+ const {
38
+ exportPagesDataKey
39
+ } = task.input; // Get all files (zip) from given key
40
+
41
+ const listObjectResponse = await _s3Stream.s3Stream.listObject(exportPagesDataKey);
42
+ const zipFileKeys = listObjectResponse.Contents.filter(file => file.Key !== exportPagesDataKey).map(file => file.Key); // Prepare zip of all zips
43
+
44
+ const zipOfZip = new _zipper.ZipOfZip(zipFileKeys); // Upload
45
+
46
+ const pageExportUpload = await zipOfZip.process();
47
+ log(`Done uploading... File is located at ${pageExportUpload.Location} `); // Update task status and save export page data key
48
+
49
+ await pageBuilder.pageImportExportTask.updateTask(taskId, {
50
+ status: _types.PageImportExportTaskStatus.COMPLETED,
51
+ data: {
52
+ message: `Finish uploading page export.`,
53
+ key: pageExportUpload.Key,
54
+ url: pageExportUpload.Location
55
+ }
56
+ }); // Remove individual zip files from storage
57
+
58
+ const deleteFilePromises = zipFileKeys.map(key => _s3Stream.s3Stream.deleteObject(key));
59
+ await Promise.all(deleteFilePromises);
60
+ log(`Successfully deleted ${deleteFilePromises.length} zip files.`);
61
+ } catch (e) {
62
+ log("[EXPORT_PAGES_COMBINE] Error => ", e);
63
+ /**
64
+ * In case of error, we'll update the task status to "failed",
65
+ * so that, client can show notify the user appropriately.
66
+ */
67
+
68
+ await pageBuilder.pageImportExportTask.updateTask(taskId, {
69
+ status: _types.PageImportExportTaskStatus.FAILED,
70
+ error: {
71
+ name: e.name,
72
+ message: e.message,
73
+ stack: e.stack,
74
+ code: "IMPORT_FAILED"
75
+ }
76
+ });
77
+ return {
78
+ data: null,
79
+ error: {
80
+ message: e.message
81
+ }
82
+ };
83
+ }
84
+ }
85
+
86
+ });
87
+
88
+ exports.default = _default;
@@ -0,0 +1,26 @@
1
+ import { HandlerPlugin } from "@webiny/handler/types";
2
+ import { ArgsContext } from "@webiny/handler-args/types";
3
+ import { PbPageImportExportContext } from "../../types";
4
+ import { SecurityIdentity } from "@webiny/api-security/types";
5
+ export declare type HandlerArgs = {
6
+ taskId: string;
7
+ subTaskIndex: number;
8
+ identity?: SecurityIdentity;
9
+ };
10
+ export declare type HandlerResponse = {
11
+ data: string;
12
+ error: {
13
+ message: string;
14
+ };
15
+ };
16
+ interface Configuration {
17
+ handlers: {
18
+ process: string;
19
+ combine: string;
20
+ };
21
+ }
22
+ declare const _default: (configuration: Configuration) => HandlerPlugin<PbPageImportExportContext, ArgsContext<HandlerArgs>>;
23
+ /**
24
+ * Handles the export pages process workflow.
25
+ */
26
+ export default _default;
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+
8
+ var _types = require("../../types");
9
+
10
+ var _utils = require("../../importPages/utils");
11
+
12
+ var _client = require("../../importPages/client");
13
+
14
+ var _handlerGraphql = require("@webiny/handler-graphql");
15
+
16
+ var _utils2 = require("../utils");
17
+
18
+ var _mockSecurity = require("../../mockSecurity");
19
+
20
+ /**
21
+ * Handles the export pages process workflow.
22
+ */
23
+ var _default = configuration => ({
24
+ type: "handler",
25
+
26
+ async handle(context) {
27
+ const log = console.log;
28
+ let subTask;
29
+ let noPendingTask = true;
30
+ let prevStatusOfSubTask = _types.PageImportExportTaskStatus.PENDING;
31
+ log("RUNNING Export Pages Process Handler");
32
+ const {
33
+ invocationArgs: args,
34
+ pageBuilder,
35
+ fileManager
36
+ } = context;
37
+ const {
38
+ taskId,
39
+ subTaskIndex,
40
+ identity
41
+ } = args; // Disable authorization; this is necessary because we call Page Builder CRUD methods which include authorization checks
42
+ // and this Lambda is invoked internally, without credentials.
43
+
44
+ (0, _mockSecurity.mockSecurity)(identity, context);
45
+
46
+ try {
47
+ /*
48
+ * Note: We're not going to DB for finding the next sub-task to process,
49
+ * because the data might be out of sync due to GSI eventual consistency.
50
+ */
51
+ subTask = await pageBuilder.pageImportExportTask.getSubTask(taskId, (0, _utils.zeroPad)(subTaskIndex));
52
+ /**
53
+ * Base condition!!
54
+ * Bail out early, if task not found or task's status is not "pending".
55
+ */
56
+
57
+ if (!subTask || subTask.status !== _types.PageImportExportTaskStatus.PENDING) {
58
+ noPendingTask = true;
59
+ return;
60
+ } else {
61
+ noPendingTask = false;
62
+ }
63
+
64
+ log(`Fetched sub task => ${subTask.id}`);
65
+ const {
66
+ input
67
+ } = subTask;
68
+ const {
69
+ pageId,
70
+ exportPagesDataKey,
71
+ revisionType
72
+ } = input;
73
+ /**
74
+ * At the moment, we only export a single revision of the page.
75
+ * It could be "published" or "latest" depending upon user input.
76
+ *
77
+ * Note: In case of no "published" revision available, we use the latest revision.
78
+ */
79
+
80
+ let page;
81
+
82
+ try {
83
+ if (revisionType === _types.PageExportRevisionType.PUBLISHED) {
84
+ // Get "published" page.
85
+ page = await pageBuilder.pages.getPublishedById({
86
+ id: pageId
87
+ });
88
+ } else {
89
+ // Get "latest" page.
90
+ page = await pageBuilder.pages.get(pageId);
91
+ }
92
+ } catch (e) {
93
+ // If we're looking for "published" page and doesn't found it, get latest page.
94
+ if (revisionType === _types.PageExportRevisionType.PUBLISHED && e instanceof _handlerGraphql.NotFoundError) {
95
+ page = await pageBuilder.pages.get(pageId);
96
+ } else {
97
+ throw e;
98
+ }
99
+ }
100
+
101
+ if (!page) {
102
+ log(`Unable to load page "${pageId}"`);
103
+ throw new _handlerGraphql.NotFoundError(`Unable to load page "${pageId}"`);
104
+ }
105
+
106
+ log(`Processing page key "${pageId}" | version ${page.version} | ${page.status}`); // Mark task status as PROCESSING
107
+
108
+ subTask = await pageBuilder.pageImportExportTask.updateSubTask(taskId, subTask.id, {
109
+ status: _types.PageImportExportTaskStatus.PROCESSING
110
+ }); // Update stats in main task
111
+
112
+ await pageBuilder.pageImportExportTask.updateStats(taskId, {
113
+ prevStatus: prevStatusOfSubTask,
114
+ nextStatus: _types.PageImportExportTaskStatus.PROCESSING
115
+ });
116
+ prevStatusOfSubTask = subTask.status;
117
+ log(`Extracting page data and uploading to storage...`); // Extract Page
118
+
119
+ const pageDataZip = await (0, _utils2.exportPage)(page, exportPagesDataKey, fileManager);
120
+ log(`Finish uploading zip...`); // Update task record in DB
121
+
122
+ subTask = await pageBuilder.pageImportExportTask.updateSubTask(taskId, subTask.id, {
123
+ status: _types.PageImportExportTaskStatus.COMPLETED,
124
+ data: {
125
+ message: `Finish uploading data for page "${page.id}" v${page.version} (${page.status}).`,
126
+ key: pageDataZip.Key
127
+ }
128
+ }); // Update stats in main task
129
+
130
+ await pageBuilder.pageImportExportTask.updateStats(taskId, {
131
+ prevStatus: prevStatusOfSubTask,
132
+ nextStatus: _types.PageImportExportTaskStatus.COMPLETED
133
+ });
134
+ prevStatusOfSubTask = subTask.status;
135
+ } catch (e) {
136
+ log("[EXPORT_PAGES_PROCESS] Error => ", e);
137
+
138
+ if (subTask && subTask.id) {
139
+ /**
140
+ * In case of error, we'll update the task status to "failed",
141
+ * so that, client can show notify the user appropriately.
142
+ */
143
+ const {
144
+ invocationArgs: args,
145
+ pageBuilder
146
+ } = context;
147
+ const {
148
+ taskId
149
+ } = args;
150
+ subTask = await pageBuilder.pageImportExportTask.updateSubTask(taskId, subTask.id, {
151
+ status: _types.PageImportExportTaskStatus.FAILED,
152
+ error: {
153
+ name: e.name,
154
+ message: e.message,
155
+ stack: e.stack,
156
+ code: "IMPORT_FAILED"
157
+ }
158
+ }); // Update stats in main task
159
+
160
+ await pageBuilder.pageImportExportTask.updateStats(taskId, {
161
+ prevStatus: prevStatusOfSubTask,
162
+ nextStatus: _types.PageImportExportTaskStatus.FAILED
163
+ });
164
+ prevStatusOfSubTask = subTask.status;
165
+ }
166
+
167
+ return {
168
+ data: null,
169
+ error: {
170
+ message: e.message
171
+ }
172
+ };
173
+ } finally {
174
+ // Base condition!
175
+ if (noPendingTask) {
176
+ log(`No pending sub-task for task ${taskId}`); // Combine individual page zip files.
177
+
178
+ await (0, _client.invokeHandlerClient)({
179
+ context,
180
+ name: configuration.handlers.combine,
181
+ payload: {
182
+ taskId,
183
+ identity: context.security.getIdentity()
184
+ }
185
+ });
186
+ } else {
187
+ console.log(`Invoking PROCESS for task "${subTaskIndex + 1}"`); // We want to continue with Self invocation no matter if current page error out.
188
+
189
+ await (0, _client.invokeHandlerClient)({
190
+ context,
191
+ name: configuration.handlers.process,
192
+ payload: {
193
+ taskId,
194
+ subTaskIndex: subTaskIndex + 1,
195
+ identity: context.security.getIdentity()
196
+ }
197
+ });
198
+ }
199
+ }
200
+ }
201
+
202
+ });
203
+
204
+ exports.default = _default;
@@ -0,0 +1,29 @@
1
+ /// <reference types="node" />
2
+ import { PassThrough, Readable } from "stream";
3
+ import S3 from "aws-sdk/clients/s3";
4
+ declare class S3Stream {
5
+ s3: S3;
6
+ bucket: string;
7
+ constructor();
8
+ /**
9
+ * We're checking if the file is accessible on S3 by getting object meta data.
10
+ * It help us to filter files that we need to download as part of export data.
11
+ * @param Key {string}
12
+ */
13
+ isFileAccessible(Key: string): Promise<boolean>;
14
+ getObjectHead(Key: string): Promise<S3.HeadObjectOutput>;
15
+ readStream(Key: string): Readable;
16
+ writeStream(Key: string, contentType?: string): {
17
+ streamPassThrough: PassThrough;
18
+ streamPassThroughUploadPromise: Promise<S3.ManagedUpload.SendData>;
19
+ };
20
+ upload(params: {
21
+ Key: string;
22
+ ContentType: string;
23
+ Body: Buffer;
24
+ }): Promise<S3.ManagedUpload.SendData>;
25
+ listObject(prefix: string): Promise<S3.ListObjectsOutput>;
26
+ deleteObject(key: string): Promise<S3.DeleteObjectOutput>;
27
+ }
28
+ export declare const s3Stream: S3Stream;
29
+ export {};
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.s3Stream = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _stream = require("stream");
13
+
14
+ var _s = _interopRequireDefault(require("aws-sdk/clients/s3"));
15
+
16
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
17
+
18
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
19
+
20
+ const ARCHIVE_CONTENT_TYPE = "application/zip";
21
+
22
+ class S3Stream {
23
+ constructor() {
24
+ (0, _defineProperty2.default)(this, "s3", void 0);
25
+ (0, _defineProperty2.default)(this, "bucket", void 0);
26
+ this.s3 = new _s.default({
27
+ region: process.env.AWS_REGION
28
+ });
29
+ this.bucket = process.env.S3_BUCKET;
30
+ }
31
+ /**
32
+ * We're checking if the file is accessible on S3 by getting object meta data.
33
+ * It help us to filter files that we need to download as part of export data.
34
+ * @param Key {string}
35
+ */
36
+
37
+
38
+ async isFileAccessible(Key) {
39
+ try {
40
+ await this.getObjectHead(Key);
41
+ return true;
42
+ } catch (error) {
43
+ console.warn(`Error while fetching meta data for file "${Key}"`);
44
+ console.log(error);
45
+ return false;
46
+ }
47
+ }
48
+
49
+ getObjectHead(Key) {
50
+ return this.s3.headObject({
51
+ Bucket: this.bucket,
52
+ Key
53
+ }).promise();
54
+ }
55
+
56
+ readStream(Key) {
57
+ return this.s3.getObject({
58
+ Bucket: this.bucket,
59
+ Key
60
+ }).createReadStream();
61
+ }
62
+
63
+ writeStream(Key, contentType = ARCHIVE_CONTENT_TYPE) {
64
+ const streamPassThrough = new _stream.Stream.PassThrough();
65
+ const params = {
66
+ ACL: "public-read",
67
+ Body: streamPassThrough,
68
+ Bucket: this.bucket,
69
+ ContentType: contentType,
70
+ Key
71
+ };
72
+ return {
73
+ streamPassThrough: streamPassThrough,
74
+
75
+ /**
76
+ * We're not using the `FileManager` storage plugin here because it currently doesn't support streams.
77
+ */
78
+ streamPassThroughUploadPromise: this.s3.upload(params).promise()
79
+ };
80
+ }
81
+
82
+ upload(params) {
83
+ return this.s3.upload(_objectSpread({
84
+ ACL: "private",
85
+ Bucket: this.bucket
86
+ }, params)).promise();
87
+ }
88
+
89
+ listObject(prefix) {
90
+ return this.s3.listObjects({
91
+ Bucket: this.bucket,
92
+ Prefix: prefix
93
+ }).promise();
94
+ }
95
+
96
+ deleteObject(key) {
97
+ return this.s3.deleteObject({
98
+ Key: key,
99
+ Bucket: this.bucket
100
+ }).promise();
101
+ }
102
+
103
+ }
104
+
105
+ const s3Stream = new S3Stream();
106
+ exports.s3Stream = s3Stream;
@@ -0,0 +1,13 @@
1
+ import S3 from "aws-sdk/clients/s3";
2
+ import { Page, File } from "@webiny/api-page-builder/types";
3
+ import { FileManagerContext } from "@webiny/api-file-manager/types";
4
+ export declare const EXPORT_PAGES_FOLDER_KEY = "WEBINY_PB_EXPORT_PAGES";
5
+ export interface ExportedPageData {
6
+ page: Pick<Page, "content" | "title" | "version" | "status" | "settings" | "path">;
7
+ files: ImageFile[];
8
+ }
9
+ export declare function exportPage(page: Page, exportPagesDataKey: string, fileManager: FileManagerContext["fileManager"]): Promise<S3.ManagedUpload.SendData>;
10
+ export interface ImageFile extends File {
11
+ key: string;
12
+ }
13
+ export declare function extractFilesFromPageData(data: Record<string, any>, files?: any[]): ImageFile[];
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.EXPORT_PAGES_FOLDER_KEY = void 0;
9
+ exports.exportPage = exportPage;
10
+ exports.extractFilesFromPageData = extractFilesFromPageData;
11
+
12
+ var _get = _interopRequireDefault(require("lodash/get"));
13
+
14
+ var _s3Stream = require("./s3Stream");
15
+
16
+ var _zipper = _interopRequireDefault(require("./zipper"));
17
+
18
+ const EXPORT_PAGES_FOLDER_KEY = "WEBINY_PB_EXPORT_PAGES";
19
+ exports.EXPORT_PAGES_FOLDER_KEY = EXPORT_PAGES_FOLDER_KEY;
20
+
21
+ async function getFilteredFiles(files) {
22
+ const uniqueFileKeys = new Map();
23
+ const promises = files.map(file => _s3Stream.s3Stream.isFileAccessible(file.key));
24
+ const isFileAvailableResults = await Promise.all(promises);
25
+ const filesAvailableForDownload = []; // Filter files
26
+
27
+ for (let i = 0; i < files.length; i++) {
28
+ const file = files[i]; // Check file accessibility
29
+
30
+ if (isFileAvailableResults[i] && !uniqueFileKeys.has(file.key)) {
31
+ filesAvailableForDownload.push(file);
32
+ uniqueFileKeys.set(file.key, true);
33
+ }
34
+ }
35
+
36
+ return filesAvailableForDownload;
37
+ }
38
+
39
+ async function exportPage(page, exportPagesDataKey, fileManager) {
40
+ // Extract all files
41
+ const files = extractFilesFromPageData(page.content); // Filter files
42
+
43
+ const filesAvailableForDownload = await getFilteredFiles(files); // Extract images from page settings
44
+
45
+ const pageSettingsImages = [(0, _get.default)(page, "settings.general.image"), (0, _get.default)(page, "settings.social.image")].filter(image => image && image.src);
46
+ const pageSettingsImagesData = []; // Get file data for all images inside "page.settings"
47
+
48
+ for (let i = 0; i < pageSettingsImages.length; i++) {
49
+ const {
50
+ id
51
+ } = pageSettingsImages[i];
52
+ const file = await fileManager.files.getFile(id);
53
+ pageSettingsImagesData.push(file);
54
+ } // Extract the page data in a json file and upload it to S3
55
+
56
+
57
+ const pageData = {
58
+ page: {
59
+ content: page.content,
60
+ title: page.title,
61
+ path: page.path,
62
+ version: page.version,
63
+ status: page.status,
64
+ settings: page.settings
65
+ },
66
+ files: [...filesAvailableForDownload, ...pageSettingsImagesData]
67
+ };
68
+ const pageDataBuffer = Buffer.from(JSON.stringify(pageData));
69
+ const zipper = new _zipper.default({
70
+ exportInfo: {
71
+ files: [...filesAvailableForDownload, ...pageSettingsImagesData],
72
+ pageTitle: page.title,
73
+ pageDataBuffer
74
+ },
75
+ archiveFileKey: exportPagesDataKey
76
+ });
77
+ return zipper.process();
78
+ }
79
+
80
+ function extractFilesFromPageData(data, files = []) {
81
+ // Base case: termination
82
+ if (!data || typeof data !== "object") {
83
+ return files;
84
+ } // Recursively call function for each element
85
+
86
+
87
+ if (Array.isArray(data)) {
88
+ for (let i = 0; i < data.length; i++) {
89
+ const element = data[i];
90
+ extractFilesFromPageData(element, files);
91
+ }
92
+
93
+ return files;
94
+ } // Main
95
+
96
+
97
+ const tuple = Object.entries(data);
98
+
99
+ for (let i = 0; i < tuple.length; i++) {
100
+ const [key, value] = tuple[i]; // TODO: @ashutosh extract it to plugins, so that, we can handle cases for other components too.
101
+
102
+ if (key === "file" && value) {
103
+ files.push(value);
104
+ } else if (key === "images" && Array.isArray(value)) {
105
+ // Handle case for "images-list" component
106
+ files.push(...value);
107
+ } else {
108
+ extractFilesFromPageData(value, files);
109
+ }
110
+ }
111
+
112
+ return files;
113
+ }
@@ -0,0 +1,35 @@
1
+ /// <reference types="node" />
2
+ import S3 from "aws-sdk/clients/s3";
3
+ import { Readable } from "stream";
4
+ import { ImageFile } from "./utils";
5
+ interface FileStreamDetails {
6
+ stream: Readable;
7
+ filename: string;
8
+ }
9
+ interface ExportInfo {
10
+ files: ImageFile[];
11
+ pageTitle: string;
12
+ pageDataBuffer: Buffer;
13
+ }
14
+ export interface ZipperConfig {
15
+ exportInfo: ExportInfo;
16
+ archiveFileKey: string;
17
+ }
18
+ export default class Zipper {
19
+ private readonly archiveFormat;
20
+ private readonly filesDirName;
21
+ private readonly archiveFileName;
22
+ config: ZipperConfig;
23
+ constructor(config: ZipperConfig);
24
+ s3DownloadStreams(): FileStreamDetails[];
25
+ process(): Promise<S3.ManagedUpload.SendData>;
26
+ }
27
+ export declare class ZipOfZip {
28
+ private readonly archiveFormat;
29
+ private readonly archiveFileName;
30
+ keys: string[];
31
+ constructor(keys: string[]);
32
+ getFileStreams(): FileStreamDetails[];
33
+ process(): Promise<S3.ManagedUpload.SendData>;
34
+ }
35
+ export {};