contentful-import 9.0.21 → 9.1.0

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.
@@ -1,81 +1,57 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = getDestinationData;
7
- var _bluebird = _interopRequireDefault(require("bluebird"));
8
- var _logging = require("contentful-batch-libs/dist/logging");
9
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
11
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
12
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
14
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const bluebird_1 = __importDefault(require("bluebird"));
7
+ const logging_1 = require("contentful-batch-libs/dist/logging");
15
8
  const BATCH_CHAR_LIMIT = 1990;
16
9
  const BATCH_SIZE_LIMIT = 100;
17
10
  const METHODS = {
18
- contentTypes: {
19
- name: 'content types',
20
- method: 'getContentTypes'
21
- },
22
- locales: {
23
- name: 'locales',
24
- method: 'getLocales'
25
- },
26
- entries: {
27
- name: 'entries',
28
- method: 'getEntries'
29
- },
30
- assets: {
31
- name: 'assets',
32
- method: 'getAssets'
33
- }
11
+ contentTypes: { name: 'content types', method: 'getContentTypes' },
12
+ locales: { name: 'locales', method: 'getLocales' },
13
+ entries: { name: 'entries', method: 'getEntries' },
14
+ assets: { name: 'assets', method: 'getAssets' }
34
15
  };
35
- async function batchedIdQuery({
36
- environment,
37
- type,
38
- ids,
39
- requestQueue
40
- }) {
41
- const method = METHODS[type].method;
42
- const entityTypeName = METHODS[type].name;
43
- const batches = getIdBatches(ids);
44
- let totalFetched = 0;
45
- const allPendingResponses = batches.map(idBatch => {
46
- // TODO: add batch count to indicate that it's running
47
- return requestQueue.add(async () => {
48
- const response = await environment[method]({
49
- 'sys.id[in]': idBatch,
50
- limit: idBatch.split(',').length
51
- });
52
- totalFetched = totalFetched + response.items.length;
53
- _logging.logEmitter.emit('info', `Fetched ${totalFetched} of ${response.total} ${entityTypeName}`);
54
- return response.items;
16
+ async function batchedIdQuery({ environment, type, ids, requestQueue }) {
17
+ const method = METHODS[type].method;
18
+ const entityTypeName = METHODS[type].name;
19
+ const batches = getIdBatches(ids);
20
+ let totalFetched = 0;
21
+ const allPendingResponses = batches.map((idBatch) => {
22
+ // TODO: add batch count to indicate that it's running
23
+ return requestQueue.add(async () => {
24
+ const response = await environment[method]({
25
+ 'sys.id[in]': idBatch,
26
+ limit: idBatch.split(',').length
27
+ });
28
+ totalFetched = totalFetched + response.items.length;
29
+ logging_1.logEmitter.emit('info', `Fetched ${totalFetched} of ${response.total} ${entityTypeName}`);
30
+ return response.items;
31
+ });
55
32
  });
56
- });
57
- const responses = await _bluebird.default.all(allPendingResponses);
58
- return responses.flat();
33
+ const responses = await bluebird_1.default.all(allPendingResponses);
34
+ return responses.flat();
59
35
  }
60
36
  function getIdBatches(ids) {
61
- const batches = [];
62
- let currentBatch = '';
63
- let currentSize = 0;
64
- while (ids.length > 0) {
65
- const id = ids.splice(0, 1);
66
- currentBatch += id;
67
- currentSize = currentSize + 1;
68
- if (currentSize === BATCH_SIZE_LIMIT || currentBatch.length > BATCH_CHAR_LIMIT || ids.length === 0) {
69
- batches.push(currentBatch);
70
- currentBatch = '';
71
- currentSize = 0;
72
- } else {
73
- currentBatch += ',';
37
+ const batches = [];
38
+ let currentBatch = '';
39
+ let currentSize = 0;
40
+ while (ids.length > 0) {
41
+ const id = ids.splice(0, 1);
42
+ currentBatch += id;
43
+ currentSize = currentSize + 1;
44
+ if (currentSize === BATCH_SIZE_LIMIT || currentBatch.length > BATCH_CHAR_LIMIT || ids.length === 0) {
45
+ batches.push(currentBatch);
46
+ currentBatch = '';
47
+ currentSize = 0;
48
+ }
49
+ else {
50
+ currentBatch += ',';
51
+ }
74
52
  }
75
- }
76
- return batches;
53
+ return batches;
77
54
  }
78
-
79
55
  /**
80
56
  * Gets content from a space which will have content copied to it, based on a
81
57
  * collection of existing content.
@@ -84,72 +60,63 @@ function getIdBatches(ids) {
84
60
  * All tags will be retrieved.
85
61
  *
86
62
  */
87
-
88
- async function getDestinationData({
89
- client,
90
- spaceId,
91
- environmentId,
92
- sourceData,
93
- contentModelOnly,
94
- skipLocales,
95
- skipContentModel,
96
- requestQueue
97
- }) {
98
- const space = await client.getSpace(spaceId);
99
- const environment = await space.getEnvironment(environmentId);
100
- const result = {
101
- contentTypes: [],
102
- tags: [],
103
- locales: [],
104
- entries: [],
105
- assets: []
106
- };
107
-
108
- // Make sure all required properties are available and at least an empty array
109
- sourceData = _objectSpread(_objectSpread({}, result), sourceData);
110
- if (!skipContentModel) {
111
- const contentTypeIds = sourceData.contentTypes.map(e => e.sys.id);
112
- result.contentTypes = batchedIdQuery({
113
- environment,
114
- type: 'contentTypes',
115
- ids: contentTypeIds,
116
- requestQueue
63
+ async function getDestinationData({ client, spaceId, environmentId, sourceData, contentModelOnly, skipLocales, skipContentModel, requestQueue }) {
64
+ const space = await client.getSpace(spaceId);
65
+ const environment = await space.getEnvironment(environmentId);
66
+ const result = {
67
+ contentTypes: [],
68
+ tags: [],
69
+ locales: [],
70
+ entries: [],
71
+ assets: []
72
+ };
73
+ // Make sure all required properties are available and at least an empty array
74
+ sourceData = {
75
+ ...result,
76
+ ...sourceData
77
+ };
78
+ if (!skipContentModel) {
79
+ const contentTypeIds = sourceData.contentTypes.map((e) => e.sys.id);
80
+ result.contentTypes = batchedIdQuery({
81
+ environment,
82
+ type: 'contentTypes',
83
+ ids: contentTypeIds,
84
+ requestQueue
85
+ });
86
+ if (!skipLocales) {
87
+ const localeIds = sourceData.locales.map((e) => e.sys.id);
88
+ result.locales = batchedIdQuery({
89
+ environment,
90
+ type: 'locales',
91
+ ids: localeIds,
92
+ requestQueue
93
+ });
94
+ }
95
+ }
96
+ // include tags even if contentModelOnly = true
97
+ result.tags = environment.getTags().then(response => response.items).catch((e) => {
98
+ // users without access to Tags will get 404
99
+ // if they dont have access, remove tags array so they're not handled in future steps
100
+ delete result.tags;
117
101
  });
118
- if (!skipLocales) {
119
- const localeIds = sourceData.locales.map(e => e.sys.id);
120
- result.locales = batchedIdQuery({
102
+ if (contentModelOnly) {
103
+ return bluebird_1.default.props(result);
104
+ }
105
+ const entryIds = sourceData.entries.map((e) => e.sys.id);
106
+ const assetIds = sourceData.assets.map((e) => e.sys.id);
107
+ result.entries = batchedIdQuery({
121
108
  environment,
122
- type: 'locales',
123
- ids: localeIds,
109
+ type: 'entries',
110
+ ids: entryIds,
124
111
  requestQueue
125
- });
126
- }
127
- }
128
-
129
- // include tags even if contentModelOnly = true
130
- result.tags = environment.getTags().then(response => response.items).catch(e => {
131
- // users without access to Tags will get 404
132
- // if they dont have access, remove tags array so they're not handled in future steps
133
- delete result.tags;
134
- });
135
- if (contentModelOnly) {
136
- return _bluebird.default.props(result);
137
- }
138
- const entryIds = sourceData.entries.map(e => e.sys.id);
139
- const assetIds = sourceData.assets.map(e => e.sys.id);
140
- result.entries = batchedIdQuery({
141
- environment,
142
- type: 'entries',
143
- ids: entryIds,
144
- requestQueue
145
- });
146
- result.assets = batchedIdQuery({
147
- environment,
148
- type: 'assets',
149
- ids: assetIds,
150
- requestQueue
151
- });
152
- result.webhooks = [];
153
- return _bluebird.default.props(result);
112
+ });
113
+ result.assets = batchedIdQuery({
114
+ environment,
115
+ type: 'assets',
116
+ ids: assetIds,
117
+ requestQueue
118
+ });
119
+ result.webhooks = [];
120
+ return bluebird_1.default.props(result);
154
121
  }
155
- module.exports = exports.default;
122
+ exports.default = getDestinationData;
@@ -1,25 +1,19 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = initClient;
7
- var _contentfulManagement = require("contentful-management");
8
- var _logging = require("contentful-batch-libs/dist/logging");
9
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
10
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
11
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
13
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const contentful_management_1 = require("contentful-management");
4
+ const logging_1 = require("contentful-batch-libs/dist/logging");
14
5
  function logHandler(level, data) {
15
- _logging.logEmitter.emit(level, data);
6
+ logging_1.logEmitter.emit(level, data);
16
7
  }
17
8
  function initClient(opts) {
18
- const defaultOpts = {
19
- timeout: 30000,
20
- logHandler
21
- };
22
- const config = _objectSpread(_objectSpread({}, defaultOpts), opts);
23
- return (0, _contentfulManagement.createClient)(config);
9
+ const defaultOpts = {
10
+ timeout: 30000,
11
+ logHandler
12
+ };
13
+ const config = {
14
+ ...defaultOpts,
15
+ ...opts
16
+ };
17
+ return (0, contentful_management_1.createClient)(config);
24
18
  }
25
- module.exports = exports.default;
19
+ exports.default = initClient;
@@ -1,83 +1,75 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.getAssetStreamForURL = getAssetStreamForURL;
7
- exports.processAssets = processAssets;
8
- var _fs = _interopRequireDefault(require("fs"));
9
- var _path = require("path");
10
- var _util = require("util");
11
- var _getEntityName = _interopRequireDefault(require("contentful-batch-libs/dist/get-entity-name"));
12
- var _logging = require("contentful-batch-libs/dist/logging");
13
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
- const stat = (0, _util.promisify)(_fs.default.stat);
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.processAssets = exports.getAssetStreamForURL = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = require("path");
9
+ const util_1 = require("util");
10
+ const get_entity_name_1 = __importDefault(require("contentful-batch-libs/dist/get-entity-name"));
11
+ const logging_1 = require("contentful-batch-libs/dist/logging");
12
+ const stat = (0, util_1.promisify)(fs_1.default.stat);
15
13
  async function getAssetStreamForURL(url, assetsDirectory) {
16
- const [, assetPath] = url.split('//');
17
- const filePath = (0, _path.join)(assetsDirectory, assetPath);
18
- try {
19
- await stat(filePath);
20
- return _fs.default.createReadStream(filePath);
21
- } catch (err) {
22
- const error = new Error('Cannot open asset from filesystem');
23
- error.filePath = filePath;
24
- throw error;
25
- }
14
+ const [, assetPath] = url.split('//');
15
+ const filePath = (0, path_1.join)(assetsDirectory, assetPath);
16
+ try {
17
+ await stat(filePath);
18
+ return fs_1.default.createReadStream(filePath);
19
+ }
20
+ catch (err) {
21
+ const error = new Error('Cannot open asset from filesystem');
22
+ error.filePath = filePath;
23
+ throw error;
24
+ }
26
25
  }
26
+ exports.getAssetStreamForURL = getAssetStreamForURL;
27
27
  async function processAssetForLocale(locale, asset, processingOptions) {
28
- try {
29
- return await asset.processForLocale(locale, processingOptions);
30
- } catch (err) {
31
- err.entity = asset;
32
- _logging.logEmitter.emit('error', err);
33
- throw err;
34
- }
28
+ try {
29
+ return await asset.processForLocale(locale, processingOptions);
30
+ }
31
+ catch (err) {
32
+ err.entity = asset;
33
+ logging_1.logEmitter.emit('error', err);
34
+ throw err;
35
+ }
35
36
  }
36
-
37
37
  // From
38
38
  // https://stackoverflow.com/questions/67339630/how-to-get-last-resolved-promise-from-a-list-of-resolved-promises-in-javascript
39
39
  async function lastResult(promises) {
40
- if (!promises.length) throw new RangeError('No last result from no promises');
41
- const results = [];
42
- await Promise.all(promises.map(p => p.then(v => {
43
- results.push(v);
44
- })));
45
- return results[results.length - 1];
40
+ if (!promises.length)
41
+ throw new RangeError('No last result from no promises');
42
+ const results = [];
43
+ await Promise.all(promises.map((p) => p.then((v) => {
44
+ results.push(v);
45
+ })));
46
+ return results[results.length - 1];
46
47
  }
47
- async function processAssets({
48
- assets,
49
- timeout,
50
- retryLimit,
51
- requestQueue
52
- }) {
53
- const processingOptions = Object.assign({}, timeout && {
54
- processingCheckWait: timeout
55
- }, retryLimit && {
56
- processingCheckRetry: retryLimit
57
- });
58
- const pendingProcessingAssets = assets.map(async asset => {
59
- _logging.logEmitter.emit('info', `Processing Asset ${(0, _getEntityName.default)(asset)}`);
60
-
61
- // We want to do what processForAllLocale does, but as the rate
62
- // limit is only enforced if we have a dedicated requestQueue item
63
- // for every processForLocale call, we need to duplicate the logic
64
- // here
65
- const locales = Object.keys(asset.fields.file || {});
66
- let latestAssetVersion = asset;
67
- try {
68
- // The last resolved promise will return the most up to date asset
69
- // version which we need for next import steps (e.g. publishing)
70
- latestAssetVersion = await lastResult(locales.map(locale => {
71
- return requestQueue.add(() => processAssetForLocale(locale, asset, processingOptions));
72
- }));
73
- } catch (err) {
74
- // Handle any error that arises during the processing of any locale
75
- return null;
76
- }
77
- return latestAssetVersion;
78
- });
79
- const potentiallyProcessedAssets = await Promise.all(pendingProcessingAssets);
80
-
81
- // This filters out all process attempts which failed
82
- return potentiallyProcessedAssets.filter(asset => asset);
83
- }
48
+ async function processAssets({ assets, timeout, retryLimit, requestQueue }) {
49
+ const processingOptions = Object.assign({}, timeout && { processingCheckWait: timeout }, retryLimit && { processingCheckRetry: retryLimit });
50
+ const pendingProcessingAssets = assets.map(async (asset) => {
51
+ logging_1.logEmitter.emit('info', `Processing Asset ${(0, get_entity_name_1.default)(asset)}`);
52
+ // We want to do what processForAllLocale does, but as the rate
53
+ // limit is only enforced if we have a dedicated requestQueue item
54
+ // for every processForLocale call, we need to duplicate the logic
55
+ // here
56
+ const locales = Object.keys(asset.fields.file || {});
57
+ let latestAssetVersion = asset;
58
+ try {
59
+ // The last resolved promise will return the most up to date asset
60
+ // version which we need for next import steps (e.g. publishing)
61
+ latestAssetVersion = await lastResult(locales.map((locale) => {
62
+ return requestQueue.add(() => processAssetForLocale(locale, asset, processingOptions));
63
+ }));
64
+ }
65
+ catch (err) {
66
+ // Handle any error that arises during the processing of any locale
67
+ return null;
68
+ }
69
+ return latestAssetVersion;
70
+ });
71
+ const potentiallyProcessedAssets = await Promise.all(pendingProcessingAssets);
72
+ // This filters out all process attempts which failed
73
+ return potentiallyProcessedAssets.filter((asset) => asset);
74
+ }
75
+ exports.processAssets = processAssets;