@stackbit/cms-core 0.0.17 → 0.0.19-alpha.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 (59) hide show
  1. package/dist/annotator/html.d.ts +1 -0
  2. package/dist/annotator/html.d.ts.map +1 -0
  3. package/dist/annotator/index.d.ts +3 -2
  4. package/dist/annotator/index.d.ts.map +1 -0
  5. package/dist/annotator/react.d.ts +1 -0
  6. package/dist/annotator/react.d.ts.map +1 -0
  7. package/dist/common/common-schema.d.ts +3 -10
  8. package/dist/common/common-schema.d.ts.map +1 -0
  9. package/dist/common/common-schema.js +3 -4
  10. package/dist/common/common-schema.js.map +1 -1
  11. package/dist/consts.d.ts +1 -0
  12. package/dist/consts.d.ts.map +1 -0
  13. package/dist/content-source-interface.d.ts +324 -0
  14. package/dist/content-source-interface.d.ts.map +1 -0
  15. package/dist/content-source-interface.js +28 -0
  16. package/dist/content-source-interface.js.map +1 -0
  17. package/dist/content-store-types.d.ts +328 -0
  18. package/dist/content-store-types.d.ts.map +1 -0
  19. package/dist/content-store-types.js +3 -0
  20. package/dist/content-store-types.js.map +1 -0
  21. package/dist/content-store.d.ts +207 -0
  22. package/dist/content-store.d.ts.map +1 -0
  23. package/dist/content-store.js +1743 -0
  24. package/dist/content-store.js.map +1 -0
  25. package/dist/encoder.d.ts +36 -7
  26. package/dist/encoder.d.ts.map +1 -0
  27. package/dist/encoder.js +63 -40
  28. package/dist/encoder.js.map +1 -1
  29. package/dist/index.d.ts +11 -6
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +37 -11
  32. package/dist/index.js.map +1 -1
  33. package/dist/stackbit/index.d.ts +7 -3
  34. package/dist/stackbit/index.d.ts.map +1 -0
  35. package/dist/stackbit/index.js +13 -10
  36. package/dist/stackbit/index.js.map +1 -1
  37. package/dist/utils/index.d.ts +8 -7
  38. package/dist/utils/index.d.ts.map +1 -0
  39. package/dist/utils/schema-utils.d.ts +3 -2
  40. package/dist/utils/schema-utils.d.ts.map +1 -0
  41. package/dist/utils/timer.d.ts +18 -0
  42. package/dist/utils/timer.d.ts.map +1 -0
  43. package/dist/utils/timer.js +36 -0
  44. package/dist/utils/timer.js.map +1 -0
  45. package/package.json +8 -4
  46. package/src/common/common-schema.ts +12 -0
  47. package/src/content-source-interface.ts +468 -0
  48. package/src/content-store-types.ts +416 -0
  49. package/src/content-store.ts +2233 -0
  50. package/src/{encoder.js → encoder.ts} +55 -17
  51. package/src/index.ts +10 -0
  52. package/src/stackbit/{index.js → index.ts} +5 -9
  53. package/src/utils/timer.ts +42 -0
  54. package/dist/utils/lazy-poller.d.ts +0 -21
  55. package/dist/utils/lazy-poller.js +0 -56
  56. package/dist/utils/lazy-poller.js.map +0 -1
  57. package/src/common/common-schema.js +0 -14
  58. package/src/index.js +0 -13
  59. package/src/utils/lazy-poller.ts +0 -74
@@ -0,0 +1,1743 @@
1
+ "use strict";
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.getContentSourceId = exports.ContentStore = void 0;
7
+ const lodash_1 = __importDefault(require("lodash"));
8
+ const slugify_1 = __importDefault(require("slugify"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const sanitize_filename_1 = __importDefault(require("sanitize-filename"));
11
+ const sdk_1 = require("@stackbit/sdk");
12
+ const utils_1 = require("@stackbit/utils");
13
+ const content_source_interface_1 = require("./content-source-interface");
14
+ const common_schema_1 = require("./common/common-schema");
15
+ const timer_1 = require("./utils/timer");
16
+ class ContentStore {
17
+ constructor(options) {
18
+ this.contentSourceDataById = {};
19
+ this.logger = options.logger.createLogger({ label: 'content-store' });
20
+ this.userLogger = options.userLogger.createLogger({ label: 'content-store' });
21
+ this.localDev = options.localDev;
22
+ this.stackbitYamlDir = options.stackbitYamlDir; // TODO: remove stackbitYamlDir, ContentStore should not be aware of filesystem, instead pass autoreloading Config object
23
+ this.contentSources = options.contentSources;
24
+ this.onSchemaChangeCallback = options.onSchemaChangeCallback;
25
+ this.onContentChangeCallback = options.onContentChangeCallback;
26
+ this.handleConfigAssets = options.handleConfigAssets;
27
+ this.contentUpdatesWatchTimer = new timer_1.Timer({ timerCallback: () => this.handleTimerTimeout(), logger: this.logger });
28
+ }
29
+ async init() {
30
+ this.logger.debug('init');
31
+ this.rawStackbitConfig = await this.loadStackbitConfig();
32
+ this.logger.debug('init => load content source data');
33
+ for (const contentSourceInstance of this.contentSources) {
34
+ await this.loadContentSourceData({ contentSourceInstance, init: true });
35
+ }
36
+ this.contentUpdatesWatchTimer.startTimer();
37
+ }
38
+ async reset() {
39
+ this.logger.debug('reset');
40
+ this.contentUpdatesWatchTimer.stopTimer();
41
+ this.rawStackbitConfig = await this.loadStackbitConfig();
42
+ this.logger.debug('reset => load content source data');
43
+ for (const contentSourceInstance of this.contentSources) {
44
+ await this.loadContentSourceData({ contentSourceInstance, init: false });
45
+ }
46
+ this.contentUpdatesWatchTimer.startTimer();
47
+ }
48
+ /**
49
+ * This method is called when contentUpdatesWatchTimer receives timeout.
50
+ * It then notifies all content sources to stop watching for content changes.
51
+ */
52
+ handleTimerTimeout() {
53
+ for (const contentSourceInstance of this.contentSources) {
54
+ contentSourceInstance.stopWatchingContentUpdates();
55
+ }
56
+ }
57
+ /**
58
+ * This method is called when user interacts with Stackbit application.
59
+ * It is used to reset contentUpdatesWatchTimer. When the timer is over
60
+ * all content sources are notified to stop watching for content updates.
61
+ */
62
+ async keepAlive() {
63
+ if (!this.contentUpdatesWatchTimer.isRunning()) {
64
+ this.logger.debug('keepAlive => contentUpdatesWatchTimer is not running => load content source data');
65
+ for (const contentSourceInstance of this.contentSources) {
66
+ await this.loadContentSourceData({ contentSourceInstance, init: false });
67
+ }
68
+ }
69
+ this.contentUpdatesWatchTimer.resetTimer();
70
+ }
71
+ /**
72
+ * This method is called when a content source notifies Stackbit of models
73
+ * changes via webhook. When this happens, all content source data
74
+ *
75
+ * For example, Contentful notifies Stackbit of any content-type changes via
76
+ * special webhook.
77
+ *
78
+ * @param contentSourceId
79
+ */
80
+ async onContentSourceSchemaChange({ contentSourceId }) {
81
+ this.logger.debug('onContentSourceSchemaChange', { contentSourceId });
82
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
83
+ await this.loadContentSourceData({
84
+ contentSourceInstance: contentSourceData.instance,
85
+ init: false
86
+ });
87
+ this.onSchemaChangeCallback();
88
+ }
89
+ async onFilesChange(updatedFiles) {
90
+ var _a, _b;
91
+ this.logger.debug('onFilesChange');
92
+ const stackbitConfigUpdated = lodash_1.default.some(updatedFiles, (filePath) => isStackbitConfigFile(filePath));
93
+ this.logger.debug(`stackbitConfigUpdated: ${stackbitConfigUpdated}`);
94
+ if (stackbitConfigUpdated) {
95
+ this.rawStackbitConfig = await this.loadStackbitConfig();
96
+ }
97
+ let someContentSourceSchemaUpdated = false;
98
+ const contentChanges = {
99
+ updatedDocuments: [],
100
+ updatedAssets: [],
101
+ deletedDocuments: [],
102
+ deletedAssets: []
103
+ };
104
+ for (const contentSourceInstance of this.contentSources) {
105
+ const contentSourceId = getContentSourceIdForContentSource(contentSourceInstance);
106
+ this.logger.debug(`call onFilesChange for contentSource: ${contentSourceId}`);
107
+ const { schemaChanged, contentChangeEvent } = (_b = (_a = contentSourceInstance.onFilesChange) === null || _a === void 0 ? void 0 : _a.call(contentSourceInstance, { updatedFiles: updatedFiles })) !== null && _b !== void 0 ? _b : {};
108
+ this.logger.debug(`schemaChanged: ${schemaChanged}, has contentChangeEvent: ${!!contentChangeEvent}`);
109
+ // if schema is changed, there is no need to return contentChanges
110
+ // because schema changes reloads everything and implies content changes
111
+ if (stackbitConfigUpdated || schemaChanged) {
112
+ if (schemaChanged) {
113
+ someContentSourceSchemaUpdated = true;
114
+ }
115
+ await this.loadContentSourceData({ contentSourceInstance, init: false });
116
+ }
117
+ else if (contentChangeEvent) {
118
+ const contentChangeResult = this.onContentChange(contentSourceId, contentChangeEvent);
119
+ contentChanges.updatedDocuments = contentChanges.updatedDocuments.concat(contentChangeResult.updatedDocuments);
120
+ contentChanges.updatedAssets = contentChanges.updatedAssets.concat(contentChangeResult.updatedAssets);
121
+ contentChanges.deletedDocuments = contentChanges.deletedDocuments.concat(contentChangeResult.deletedDocuments);
122
+ contentChanges.deletedAssets = contentChanges.deletedAssets.concat(contentChangeResult.deletedAssets);
123
+ }
124
+ }
125
+ return {
126
+ stackbitConfigUpdated,
127
+ schemaChanged: someContentSourceSchemaUpdated || stackbitConfigUpdated,
128
+ contentChanges: contentChanges
129
+ };
130
+ }
131
+ async loadStackbitConfig() {
132
+ this.logger.debug('loadStackbitConfig');
133
+ // TODO: use esbuild to watch for stackbit.config.js changes and notify
134
+ // the content-store via onStackbitConfigChange with updated rawConfig
135
+ const { config, errors } = await (0, sdk_1.loadConfigFromDir)({ dirPath: this.stackbitYamlDir });
136
+ for (const error of errors) {
137
+ this.userLogger.warn(error.message);
138
+ }
139
+ if (!config) {
140
+ this.userLogger.error(`could not load stackbit config`);
141
+ }
142
+ return config;
143
+ }
144
+ async loadContentSourceData({ contentSourceInstance, init }) {
145
+ // TODO: defer loading content if content is already loading for a specific content source
146
+ var _a;
147
+ // TODO: optimize: cache raw responses from contentSource
148
+ // e.g.: getModels(), getDocuments(), getAssets()
149
+ // ana use the cached response to remap documents when only stackbitConfig changes
150
+ const contentSourceId = getContentSourceIdForContentSource(contentSourceInstance);
151
+ this.logger.debug('loadContentSourceData', { contentSourceId, init });
152
+ if (init) {
153
+ await contentSourceInstance.init({
154
+ logger: this.logger,
155
+ userLogger: this.userLogger,
156
+ localDev: this.localDev
157
+ });
158
+ }
159
+ else {
160
+ contentSourceInstance.stopWatchingContentUpdates();
161
+ await contentSourceInstance.reset();
162
+ }
163
+ const csModels = await contentSourceInstance.getModels();
164
+ const locales = await (contentSourceInstance === null || contentSourceInstance === void 0 ? void 0 : contentSourceInstance.getLocales());
165
+ const result = await (0, sdk_1.extendConfig)({ dirPath: this.stackbitYamlDir, config: this.rawStackbitConfig, externalModels: csModels });
166
+ const config = await this.handleConfigAssets(result.config);
167
+ const models = config.models;
168
+ const modelMap = lodash_1.default.keyBy(models, 'name');
169
+ const defaultLocaleCode = (_a = locales === null || locales === void 0 ? void 0 : locales.find((locale) => locale.default)) === null || _a === void 0 ? void 0 : _a.code;
170
+ for (const error of result.errors) {
171
+ this.userLogger.warn(error.message);
172
+ }
173
+ // TODO: load presets externally from config, and create additional map
174
+ // that maps presetIds by model name instead of storing that map inside every model
175
+ this.presets = config.presets;
176
+ const csiDocuments = await contentSourceInstance.getDocuments({ modelMap });
177
+ const csiAssets = await contentSourceInstance.getAssets();
178
+ const csiDocumentMap = lodash_1.default.keyBy(csiDocuments, 'id');
179
+ const csiAssetMap = lodash_1.default.keyBy(csiAssets, 'id');
180
+ const contentStoreDocuments = mapCSIDocumentsToStoreDocuments({
181
+ csiDocuments,
182
+ contentSourceInstance,
183
+ modelMap,
184
+ defaultLocaleCode
185
+ });
186
+ const contentStoreAssets = mapCSIAssetsToStoreAssets({
187
+ csiAssets,
188
+ contentSourceInstance,
189
+ defaultLocaleCode
190
+ });
191
+ const documentMap = lodash_1.default.keyBy(contentStoreDocuments, 'srcObjectId');
192
+ const assetMap = lodash_1.default.keyBy(contentStoreAssets, 'srcObjectId');
193
+ this.logger.debug('loaded content source data', {
194
+ contentSourceId,
195
+ locales,
196
+ defaultLocaleCode,
197
+ modelCount: models.length,
198
+ documentCount: contentStoreDocuments.length,
199
+ assetCount: contentStoreAssets.length
200
+ });
201
+ this.contentSourceDataById[contentSourceId] = {
202
+ id: contentSourceId,
203
+ type: contentSourceInstance.getContentSourceType(),
204
+ projectId: contentSourceInstance.getProjectId(),
205
+ instance: contentSourceInstance,
206
+ locales: locales,
207
+ defaultLocaleCode: defaultLocaleCode,
208
+ models: models,
209
+ modelMap: modelMap,
210
+ csiDocuments: csiDocuments,
211
+ csiDocumentMap: csiDocumentMap,
212
+ documents: contentStoreDocuments,
213
+ documentMap: documentMap,
214
+ csiAssets: csiAssets,
215
+ csiAssetMap: csiAssetMap,
216
+ assets: contentStoreAssets,
217
+ assetMap: assetMap
218
+ };
219
+ contentSourceInstance.startWatchingContentUpdates({
220
+ getModelMap: () => {
221
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
222
+ return contentSourceData.modelMap;
223
+ },
224
+ getDocument({ documentId }) {
225
+ return csiDocumentMap[documentId];
226
+ },
227
+ getAsset({ assetId }) {
228
+ return csiAssetMap[assetId];
229
+ },
230
+ onContentChange: (contentChangeEvent) => {
231
+ this.logger.debug('content source called onContentChange', { contentSourceId });
232
+ const result = this.onContentChange(contentSourceId, contentChangeEvent);
233
+ this.onContentChangeCallback(result);
234
+ },
235
+ onSchemaChange: async () => {
236
+ this.logger.debug('content source called onSchemaChange', { contentSourceId });
237
+ await this.loadContentSourceData({
238
+ contentSourceInstance: contentSourceInstance,
239
+ init: false
240
+ });
241
+ this.onSchemaChangeCallback();
242
+ }
243
+ });
244
+ }
245
+ onContentChange(contentSourceId, contentChangeEvent) {
246
+ // TODO: prevent content change process for contentSourceId if loading content is in progress
247
+ this.logger.debug('onContentChange', {
248
+ contentSourceId,
249
+ documentCount: contentChangeEvent.documents.length,
250
+ assetCount: contentChangeEvent.assets.length,
251
+ deletedDocumentCount: contentChangeEvent.deletedDocumentIds.length,
252
+ deletedAssetCount: contentChangeEvent.deletedAssetIds.length
253
+ });
254
+ const result = {
255
+ updatedDocuments: [],
256
+ updatedAssets: [],
257
+ deletedDocuments: [],
258
+ deletedAssets: []
259
+ };
260
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
261
+ // update contentSourceData with deleted documents
262
+ contentChangeEvent.deletedDocumentIds.forEach((docId) => {
263
+ // delete document from documents map
264
+ delete contentSourceData.documentMap[docId];
265
+ delete contentSourceData.csiDocumentMap[docId];
266
+ // delete document from document array
267
+ const index = contentSourceData.documents.findIndex((document) => document.srcObjectId === docId);
268
+ if (index !== -1) {
269
+ // the indexes of documents and csiDocuments are always the same as they are always updated at the same time
270
+ contentSourceData.documents.splice(index, 1);
271
+ contentSourceData.csiDocuments.splice(index, 1);
272
+ }
273
+ result.deletedDocuments.push({
274
+ srcType: contentSourceData.type,
275
+ srcProjectId: contentSourceData.projectId,
276
+ srcObjectId: docId
277
+ });
278
+ });
279
+ // update contentSourceData with deleted assets
280
+ contentChangeEvent.deletedAssetIds.forEach((assetId) => {
281
+ // delete document from asset map
282
+ delete contentSourceData.assetMap[assetId];
283
+ delete contentSourceData.csiAssetMap[assetId];
284
+ // delete document from asset array
285
+ const index = contentSourceData.assets.findIndex((asset) => asset.srcObjectId === assetId);
286
+ if (index !== -1) {
287
+ // the indexes of assets and csiAssets are always the same as they are always updated at the same time
288
+ contentSourceData.assets.splice(index, 1);
289
+ contentSourceData.csiAssets.splice(index, 1);
290
+ }
291
+ result.deletedAssets.push({
292
+ srcType: contentSourceData.type,
293
+ srcProjectId: contentSourceData.projectId,
294
+ srcObjectId: assetId
295
+ });
296
+ });
297
+ // map csi documents and assets to content store documents and assets
298
+ const documents = mapCSIDocumentsToStoreDocuments({
299
+ csiDocuments: contentChangeEvent.documents,
300
+ contentSourceInstance: contentSourceData.instance,
301
+ modelMap: contentSourceData.modelMap,
302
+ defaultLocaleCode: contentSourceData.defaultLocaleCode
303
+ });
304
+ const assets = mapCSIAssetsToStoreAssets({
305
+ csiAssets: contentChangeEvent.assets,
306
+ contentSourceInstance: contentSourceData.instance,
307
+ defaultLocaleCode: contentSourceData.defaultLocaleCode
308
+ });
309
+ // update contentSourceData with new or updated documents and assets
310
+ Object.assign(contentSourceData.csiDocumentMap, lodash_1.default.keyBy(contentChangeEvent.documents, 'id'));
311
+ Object.assign(contentSourceData.csiAssets, lodash_1.default.keyBy(contentChangeEvent.assets, 'id'));
312
+ Object.assign(contentSourceData.documentMap, lodash_1.default.keyBy(documents, 'srcObjectId'));
313
+ Object.assign(contentSourceData.assetMap, lodash_1.default.keyBy(assets, 'srcObjectId'));
314
+ for (let idx = 0; idx < documents.length; idx++) {
315
+ // the indexes of mapped documents and documents from changeEvent are the same
316
+ const document = documents[idx];
317
+ const csiDocument = contentChangeEvent.documents[idx];
318
+ const dataIndex = contentSourceData.documents.findIndex((existingDoc) => existingDoc.srcObjectId === document.srcObjectId);
319
+ if (dataIndex === -1) {
320
+ contentSourceData.documents.push(document);
321
+ contentSourceData.csiDocuments.push(csiDocument);
322
+ }
323
+ else {
324
+ // the indexes of documents and csiDocuments are always the same as they are always updated at the same time
325
+ contentSourceData.documents.splice(dataIndex, 1, document);
326
+ contentSourceData.csiDocuments.splice(dataIndex, 1, csiDocument);
327
+ }
328
+ result.updatedDocuments.push({
329
+ srcType: contentSourceData.type,
330
+ srcProjectId: contentSourceData.projectId,
331
+ srcObjectId: document.srcObjectId
332
+ });
333
+ }
334
+ for (let idx = 0; idx < assets.length; idx++) {
335
+ // the indexes of mapped assets and assets from changeEvent are the same
336
+ const asset = assets[idx];
337
+ const csiAsset = contentChangeEvent.assets[idx];
338
+ const index = contentSourceData.assets.findIndex((existingAsset) => existingAsset.srcObjectId === asset.srcObjectId);
339
+ if (index === -1) {
340
+ contentSourceData.assets.push(asset);
341
+ contentSourceData.csiAssets.push(csiAsset);
342
+ }
343
+ else {
344
+ // the indexes of assets and csiAssets are always the same as they are always updated at the same time
345
+ contentSourceData.assets.splice(index, 1, asset);
346
+ contentSourceData.csiAssets.splice(index, 1, csiAsset);
347
+ }
348
+ result.updatedAssets.push({
349
+ srcType: contentSourceData.type,
350
+ srcProjectId: contentSourceData.projectId,
351
+ srcObjectId: asset.srcObjectId
352
+ });
353
+ }
354
+ return result;
355
+ }
356
+ getModels() {
357
+ return lodash_1.default.reduce(this.contentSourceDataById, (result, contentSourceData) => {
358
+ const contentSourceType = contentSourceData.instance.getContentSourceType();
359
+ const srcProjectId = contentSourceData.instance.getProjectId();
360
+ lodash_1.default.set(result, [contentSourceType, srcProjectId], contentSourceData.modelMap);
361
+ return result;
362
+ }, {});
363
+ }
364
+ getLocales() {
365
+ return lodash_1.default.reduce(this.contentSourceDataById, (result, contentSourceData) => {
366
+ var _a;
367
+ const locales = ((_a = contentSourceData.locales) !== null && _a !== void 0 ? _a : []).map((locale) => locale.code);
368
+ return result.concat(locales);
369
+ }, []);
370
+ }
371
+ getPresets() {
372
+ var _a;
373
+ return (_a = this.presets) !== null && _a !== void 0 ? _a : {};
374
+ }
375
+ getContentSourceEnvironment({ srcProjectId, srcType }) {
376
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
377
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
378
+ return contentSourceData.instance.getProjectEnvironment();
379
+ }
380
+ hasAccess({ srcType, srcProjectId, user }) {
381
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
382
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
383
+ const userContext = getUserContextForSrcType(srcType, user);
384
+ return contentSourceData.instance.hasAccess({ userContext });
385
+ }
386
+ hasChanges({ srcType, srcProjectId, documents }) {
387
+ let result;
388
+ if (srcType && srcProjectId) {
389
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
390
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
391
+ result = [...contentSourceData.documents, ...contentSourceData.assets];
392
+ }
393
+ else if (documents && documents.length > 0) {
394
+ const documentsBySourceId = lodash_1.default.groupBy(documents, (document) => getContentSourceId(document.srcType, document.srcProjectId));
395
+ result = lodash_1.default.reduce(documentsBySourceId, (result, documents, contentSourceId) => {
396
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
397
+ for (const document of documents) {
398
+ if (document.srcObjectId in contentSourceData.documentMap) {
399
+ result.push(contentSourceData.documentMap[document.srcObjectId]);
400
+ }
401
+ else if (document.srcObjectId in contentSourceData.assetMap) {
402
+ result.push(contentSourceData.assetMap[document.srcObjectId]);
403
+ }
404
+ }
405
+ return result;
406
+ }, []);
407
+ }
408
+ else {
409
+ result = lodash_1.default.reduce(this.contentSourceDataById, (result, contentSourceData) => {
410
+ return result.concat(contentSourceData.documents, contentSourceData.assets);
411
+ }, []);
412
+ }
413
+ const changedDocuments = result.filter((document) => document.status === 'added' || document.status === 'modified');
414
+ return {
415
+ hasChanges: !lodash_1.default.isEmpty(changedDocuments),
416
+ changedObjects: changedDocuments.map((item) => ({
417
+ srcType: item.srcType,
418
+ srcProjectId: item.srcProjectId,
419
+ srcObjectId: item.srcObjectId
420
+ }))
421
+ };
422
+ }
423
+ getDocument({ srcDocumentId, srcProjectId, srcType }) {
424
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
425
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
426
+ return contentSourceData.documentMap[srcDocumentId];
427
+ }
428
+ getDocuments() {
429
+ return lodash_1.default.reduce(this.contentSourceDataById, (documents, contentSourceData) => {
430
+ return documents.concat(contentSourceData.documents);
431
+ }, []);
432
+ }
433
+ getAsset({ srcAssetId, srcProjectId, srcType }) {
434
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
435
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
436
+ return contentSourceData.assetMap[srcAssetId];
437
+ }
438
+ getAssets() {
439
+ return lodash_1.default.reduce(this.contentSourceDataById, (assets, contentSourceData) => {
440
+ return assets.concat(contentSourceData.assets);
441
+ }, []);
442
+ }
443
+ getLocalizedApiObjects({ locale }) {
444
+ return lodash_1.default.reduce(this.contentSourceDataById, (objects, contentSourceData) => {
445
+ locale = locale !== null && locale !== void 0 ? locale : contentSourceData.defaultLocaleCode;
446
+ const documentObjects = mapDocumentsToLocalizedApiObjects(contentSourceData.documents, locale);
447
+ const imageObjects = mapAssetsToLocalizedApiImages(contentSourceData.assets, locale);
448
+ return objects.concat(documentObjects, imageObjects);
449
+ }, []);
450
+ }
451
+ getApiAssets({ srcType, srcProjectId, pageSize = 20, pageNum = 1, searchQuery } = {}) {
452
+ let assets;
453
+ if (srcProjectId && srcType) {
454
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
455
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
456
+ assets = mapStoreAssetsToAPIAssets(contentSourceData.assets, contentSourceData.defaultLocaleCode);
457
+ }
458
+ else {
459
+ assets = lodash_1.default.reduce(this.contentSourceDataById, (result, contentSourceData) => {
460
+ const assets = mapStoreAssetsToAPIAssets(contentSourceData.assets, contentSourceData.defaultLocaleCode);
461
+ return result.concat(assets);
462
+ }, []);
463
+ }
464
+ let filteredFiles = assets;
465
+ if (searchQuery) {
466
+ const sanitizedSearchQuery = (0, sanitize_filename_1.default)(searchQuery).toLowerCase();
467
+ filteredFiles = assets.filter((asset) => asset.fileName && path_1.default.basename(asset.fileName).toLowerCase().includes(sanitizedSearchQuery));
468
+ }
469
+ const sortedAssets = lodash_1.default.orderBy(filteredFiles, ['fileName'], ['asc']);
470
+ const skip = (pageNum - 1) * pageSize;
471
+ const totalPages = Math.ceil(filteredFiles.length / pageSize);
472
+ const pagesAssets = sortedAssets.slice(skip, skip + pageSize);
473
+ return {
474
+ assets: pagesAssets,
475
+ pageSize: pageSize,
476
+ pageNum: pageNum,
477
+ totalPages: totalPages
478
+ };
479
+ }
480
+ async createAndLinkDocument({ srcType, srcProjectId, srcDocumentId, fieldPath, modelName, object, index, locale, user }) {
481
+ this.logger.debug('createAndLinkDocument', { srcType, srcProjectId, srcDocumentId, fieldPath, modelName, index, locale });
482
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
483
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
484
+ // get the document that is being updated
485
+ const document = contentSourceData.documentMap[srcDocumentId];
486
+ const csiDocument = contentSourceData.csiDocumentMap[srcDocumentId];
487
+ if (!document || !csiDocument) {
488
+ throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
489
+ }
490
+ // get the document model
491
+ const documentModelName = document.srcModelName;
492
+ const modelMap = contentSourceData.modelMap;
493
+ const model = modelMap[documentModelName];
494
+ if (!model) {
495
+ throw new Error(`error updating document, could not find document model: '${documentModelName}'`);
496
+ }
497
+ // get the 'reference' model field in the updated document that will be used to link the new document
498
+ locale = locale !== null && locale !== void 0 ? locale : contentSourceData.defaultLocaleCode;
499
+ const modelField = getModelFieldForFieldAtPath(document, model, fieldPath, modelMap, locale);
500
+ if (!modelField) {
501
+ throw Error(`the "fieldPath" points to non existing model field: ${fieldPath.join('.')}`);
502
+ }
503
+ const fieldProps = modelField.type === 'list' ? modelField.items : modelField;
504
+ if (fieldProps.type !== 'reference') {
505
+ throw Error(`error in "createAndLinkDocument", this operation can only be used on reference field: ${fieldPath.join('.')}`);
506
+ }
507
+ // get the model name for the new document
508
+ if (!modelName && fieldProps.models.length === 1) {
509
+ modelName = fieldProps.models[0];
510
+ }
511
+ if (!modelName) {
512
+ throw Error(`error in "createAndLinkDocument", missing "modelName": ${fieldPath.join('.')}`);
513
+ }
514
+ // create the new document
515
+ const result = await this.createDocument({
516
+ object: object,
517
+ srcProjectId: srcProjectId,
518
+ srcType: srcType,
519
+ modelName: modelName,
520
+ locale: locale,
521
+ user: user
522
+ });
523
+ // update the document by linking the field to the created document
524
+ const userContext = getUserContextForSrcType(srcType, user);
525
+ const field = {
526
+ type: 'reference',
527
+ refType: 'document',
528
+ refId: result.srcDocumentId
529
+ };
530
+ const updatedDocument = await contentSourceData.instance.updateDocument({
531
+ document: csiDocument,
532
+ modelMap: modelMap,
533
+ userContext: userContext,
534
+ operations: [
535
+ modelField.type === 'list'
536
+ ? {
537
+ opType: 'insert',
538
+ fieldPath: fieldPath,
539
+ modelField: modelField,
540
+ locale: locale,
541
+ index: index,
542
+ item: field
543
+ }
544
+ : {
545
+ opType: 'set',
546
+ fieldPath: fieldPath,
547
+ modelField: modelField,
548
+ locale: locale,
549
+ field: field
550
+ }
551
+ ]
552
+ });
553
+ return { srcDocumentId: updatedDocument.id };
554
+ }
555
+ async uploadAndLinkAsset({ srcType, srcProjectId, srcDocumentId, fieldPath, asset, index, locale, user }) {
556
+ this.logger.debug('uploadAndLinkAsset', { srcType, srcProjectId, srcDocumentId, fieldPath, index, locale });
557
+ // get the document that is being updated
558
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
559
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
560
+ const document = contentSourceData.documentMap[srcDocumentId];
561
+ const csiDocument = contentSourceData.csiDocumentMap[srcDocumentId];
562
+ if (!document || !csiDocument) {
563
+ throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
564
+ }
565
+ // get the document model
566
+ const documentModelName = document.srcModelName;
567
+ const modelMap = contentSourceData.modelMap;
568
+ const model = modelMap[documentModelName];
569
+ if (!model) {
570
+ throw new Error(`error updating document, could not find document model: '${documentModelName}'`);
571
+ }
572
+ // get the 'reference' model field in the updated document that will be used to link the new asset
573
+ locale = locale !== null && locale !== void 0 ? locale : contentSourceData.defaultLocaleCode;
574
+ const modelField = getModelFieldForFieldAtPath(document, model, fieldPath, modelMap, locale);
575
+ if (!modelField) {
576
+ throw Error(`the "fieldPath" points to non existing model field: ${fieldPath.join('.')}`);
577
+ }
578
+ const fieldProps = modelField.type === 'list' ? modelField.items : modelField;
579
+ if (fieldProps.type !== 'reference' && fieldProps.type !== 'image') {
580
+ throw Error(`error in "uploadAndLinkAsset", this operation can only be used on reference and image fields: ${fieldPath.join('.')}`);
581
+ }
582
+ // upload the new asset
583
+ const userContext = getUserContextForSrcType(srcType, user);
584
+ const result = await contentSourceData.instance.uploadAsset({
585
+ url: asset.url,
586
+ fileName: asset.metadata.name,
587
+ mimeType: asset.metadata.type,
588
+ locale: locale,
589
+ userContext: userContext
590
+ });
591
+ // update the document by linking the field to the created asset
592
+ const field = {
593
+ type: 'reference',
594
+ refType: 'asset',
595
+ refId: result.id
596
+ };
597
+ const updatedDocument = await contentSourceData.instance.updateDocument({
598
+ document: csiDocument,
599
+ modelMap: modelMap,
600
+ userContext: userContext,
601
+ operations: [
602
+ modelField.type === 'list'
603
+ ? {
604
+ opType: 'insert',
605
+ fieldPath: fieldPath,
606
+ modelField: modelField,
607
+ locale: locale,
608
+ index: index,
609
+ item: field
610
+ }
611
+ : {
612
+ opType: 'set',
613
+ fieldPath: fieldPath,
614
+ modelField: modelField,
615
+ locale: locale,
616
+ field: field
617
+ }
618
+ ]
619
+ });
620
+ return { srcDocumentId: updatedDocument.id };
621
+ }
622
+ async createDocument({ srcType, srcProjectId, modelName, object, locale, user }) {
623
+ this.logger.debug('createDocument', { srcType, srcProjectId, modelName, locale });
624
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
625
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
626
+ const modelMap = contentSourceData.modelMap;
627
+ const model = modelMap[modelName];
628
+ if (!model) {
629
+ throw new Error(`no model with name '${modelName}' was found`);
630
+ }
631
+ locale = locale !== null && locale !== void 0 ? locale : contentSourceData.defaultLocaleCode;
632
+ const userContext = getUserContextForSrcType(srcType, user);
633
+ const result = await createDocumentRecursively({
634
+ object,
635
+ model,
636
+ modelMap,
637
+ locale,
638
+ userContext,
639
+ contentSourceInstance: contentSourceData.instance
640
+ });
641
+ this.logger.debug('created document', { srcType, srcProjectId, srcDocumentId: result.document.id, modelName });
642
+ // do not update cache in contentSourceData.documents and documentMap,
643
+ // instead wait for contentSource to call onContentChange(contentChangeEvent)
644
+ // and use data from contentChangeEvent to update the cache
645
+ // const newDocuments = [result.document, ...result.referencedDocuments];
646
+ // contentSourceData.documentMap = Object.assign(contentSourceData.documentMap, _.keyBy(newDocuments, 'srcObjectId'));
647
+ return { srcDocumentId: result.document.id };
648
+ }
649
+ async updateDocument({ srcType, srcProjectId, srcDocumentId, updateOperations, user }) {
650
+ this.logger.debug('updateDocument');
651
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
652
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
653
+ const userContext = getUserContextForSrcType(srcType, user);
654
+ const document = contentSourceData.documentMap[srcDocumentId];
655
+ const csiDocument = contentSourceData.csiDocumentMap[srcDocumentId];
656
+ if (!document || !csiDocument) {
657
+ throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
658
+ }
659
+ const modelMap = contentSourceData.modelMap;
660
+ const documentModelName = document.srcModelName;
661
+ const model = modelMap[documentModelName];
662
+ if (!model) {
663
+ throw new Error(`error updating document, could not find document model: '${documentModelName}'`);
664
+ }
665
+ const operations = await (0, utils_1.mapPromise)(updateOperations, async (updateOperation) => {
666
+ var _a;
667
+ const locale = (_a = updateOperation.locale) !== null && _a !== void 0 ? _a : contentSourceData.defaultLocaleCode;
668
+ const modelField = getModelFieldForFieldAtPath(document, model, updateOperation.fieldPath, modelMap, locale);
669
+ switch (updateOperation.opType) {
670
+ case 'set':
671
+ const field = await convertOperationField({
672
+ operationField: updateOperation.field,
673
+ fieldPath: updateOperation.fieldPath,
674
+ locale: updateOperation.locale,
675
+ modelField,
676
+ modelMap,
677
+ userContext,
678
+ contentSourceInstance: contentSourceData.instance
679
+ });
680
+ return {
681
+ ...updateOperation,
682
+ modelField,
683
+ field
684
+ };
685
+ case 'unset':
686
+ return { ...updateOperation, modelField };
687
+ case 'insert':
688
+ const item = await convertOperationField({
689
+ operationField: updateOperation.item,
690
+ fieldPath: updateOperation.fieldPath,
691
+ locale: updateOperation.locale,
692
+ modelField,
693
+ modelMap,
694
+ userContext,
695
+ contentSourceInstance: contentSourceData.instance
696
+ });
697
+ return {
698
+ ...updateOperation,
699
+ modelField,
700
+ item
701
+ };
702
+ case 'remove':
703
+ return { ...updateOperation, modelField };
704
+ case 'reorder':
705
+ return { ...updateOperation, modelField };
706
+ }
707
+ });
708
+ const updatedDocumentResult = await contentSourceData.instance.updateDocument({
709
+ document: csiDocument,
710
+ modelMap,
711
+ userContext,
712
+ operations
713
+ });
714
+ // do not update cache in contentSourceData.documents and documentMap,
715
+ // instead wait for contentSource to call onContentChange(contentChangeEvent)
716
+ // and use data from contentChangeEvent to update the cache
717
+ // contentSourceData.documentMap = Object.assign(contentSourceData.documentMap, { [document.srcObjectId]: document });
718
+ return { srcDocumentId: updatedDocumentResult.id };
719
+ }
720
+ async duplicateDocument({ srcType, srcProjectId, srcDocumentId, object, user }) {
721
+ this.logger.debug('duplicateDocument');
722
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
723
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
724
+ const document = contentSourceData.documentMap[srcDocumentId];
725
+ if (!document) {
726
+ throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
727
+ }
728
+ const modelMap = contentSourceData.modelMap;
729
+ const model = modelMap[document.srcModelName];
730
+ if (!model) {
731
+ throw new Error(`no model with name '${document.srcModelName}' was found`);
732
+ }
733
+ const userContext = getUserContextForSrcType(srcType, user);
734
+ // TODO: handle duplicatable and non duplicatable models
735
+ // TODO: handle fields from the provided object
736
+ const documentResult = await contentSourceData.instance.createDocument({
737
+ documentFields: mapStoreFieldsToSourceFields({
738
+ documentFields: document.fields,
739
+ modelFields: model.fields,
740
+ modelMap: contentSourceData.modelMap
741
+ }),
742
+ model,
743
+ modelMap,
744
+ locale: contentSourceData.defaultLocaleCode,
745
+ userContext
746
+ });
747
+ return { srcDocumentId: documentResult.id };
748
+ }
749
+ async uploadAssets({ srcType, srcProjectId, assets, locale, user }) {
750
+ this.logger.debug('uploadAssets');
751
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
752
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
753
+ const sourceAssets = [];
754
+ const userContext = getUserContextForSrcType(srcType, user);
755
+ locale = locale !== null && locale !== void 0 ? locale : contentSourceData.defaultLocaleCode;
756
+ for (const asset of assets) {
757
+ let base64 = undefined;
758
+ if (asset.data) {
759
+ const matchResult = asset.data.match(/;base64,([\s\S]+)$/);
760
+ if (matchResult) {
761
+ base64 = matchResult[1];
762
+ }
763
+ }
764
+ const sourceAsset = await contentSourceData.instance.uploadAsset({
765
+ url: asset.url,
766
+ base64: base64,
767
+ fileName: asset.metadata.name,
768
+ mimeType: asset.metadata.type,
769
+ locale: locale,
770
+ userContext: userContext
771
+ });
772
+ sourceAssets.push(sourceAsset);
773
+ }
774
+ const storeAssets = mapCSIAssetsToStoreAssets({
775
+ csiAssets: sourceAssets,
776
+ contentSourceInstance: contentSourceData.instance,
777
+ defaultLocaleCode: contentSourceData.defaultLocaleCode
778
+ });
779
+ return mapStoreAssetsToAPIAssets(storeAssets, locale);
780
+ }
781
+ async deleteDocument({ srcType, srcProjectId, srcDocumentId, user }) {
782
+ this.logger.debug('deleteDocument');
783
+ const userContext = getUserContextForSrcType(srcType, user);
784
+ const contentSourceId = getContentSourceId(srcType, srcProjectId);
785
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
786
+ const csiDocument = contentSourceData.csiDocumentMap[srcDocumentId];
787
+ if (!csiDocument) {
788
+ throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
789
+ }
790
+ await contentSourceData.instance.deleteDocument({ document: csiDocument, userContext });
791
+ // do not update cache in contentSourceData.documents and documentMap,
792
+ // instead wait for contentSource to call onContentChange(contentChangeEvent)
793
+ // and use data from contentChangeEvent to update the cache
794
+ // delete contentSourceData.documentMap[srcDocumentId];
795
+ }
796
+ async validateDocuments({ objects, locale, user }) {
797
+ this.logger.debug('validateDocuments');
798
+ const objectsBySourceId = lodash_1.default.groupBy(objects, (object) => getContentSourceId(object.srcType, object.srcProjectId));
799
+ let errors = [];
800
+ for (const [contentSourceId, contentSourceObjects] of Object.entries(objectsBySourceId)) {
801
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
802
+ locale = locale !== null && locale !== void 0 ? locale : contentSourceData.defaultLocaleCode;
803
+ const { documents, assets } = getCSIDocumentsAndAssetsFromContentSourceDataByIds(contentSourceData, contentSourceObjects);
804
+ const userContext = getUserContextForSrcType(contentSourceData.type, user);
805
+ const validationResult = await contentSourceData.instance.validateDocuments({ documents, assets, locale, userContext });
806
+ errors = errors.concat(validationResult.errors.map((validationError) => ({
807
+ message: validationError.message,
808
+ srcType: contentSourceData.type,
809
+ srcProjectId: contentSourceData.projectId,
810
+ srcObjectType: validationError.objectType,
811
+ srcObjectId: validationError.objectId,
812
+ fieldPath: validationError.fieldPath,
813
+ isUniqueValidation: validationError.isUniqueValidation
814
+ })));
815
+ }
816
+ return { errors };
817
+ /* validate for multiple sources
818
+ const objectsBySourceId = _.groupBy(objects, (document) => getContentSourceId(document.srcType, document.srcProjectId));
819
+ const contentSourceIds = Object.keys(objectsBySourceId);
820
+ return reducePromise(
821
+ contentSourceIds,
822
+ async (result: ContentStoreTypes.ValidationError[], contentSourceId) => {
823
+ const documents = documentsBySourceId[contentSourceId]!;
824
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
825
+ const validationErrors = await contentSourceData.instance.validateDocuments({ documentIds: documents.map((document) => document.srcObjectId) });
826
+ return result.concat(validationErrors);
827
+ },
828
+ []
829
+ );
830
+ */
831
+ }
832
+ async publishDocuments({ objects, user }) {
833
+ this.logger.debug('publishDocuments');
834
+ const objectsBySourceId = lodash_1.default.groupBy(objects, (object) => getContentSourceId(object.srcType, object.srcProjectId));
835
+ for (const [contentSourceId, contentSourceObjects] of Object.entries(objectsBySourceId)) {
836
+ const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
837
+ const userContext = getUserContextForSrcType(contentSourceData.type, user);
838
+ const { documents, assets } = getCSIDocumentsAndAssetsFromContentSourceDataByIds(contentSourceData, contentSourceObjects);
839
+ await contentSourceData.instance.publishDocuments({ documents, assets, userContext });
840
+ }
841
+ }
842
+ getContentSourceDataByIdOrThrow(contentSourceId) {
843
+ const contentSourceData = this.contentSourceDataById[contentSourceId];
844
+ if (!contentSourceData) {
845
+ throw new Error(`no content source for id '${contentSourceId}' was found`);
846
+ }
847
+ return contentSourceData;
848
+ }
849
+ }
850
+ exports.ContentStore = ContentStore;
851
+ function getContentSourceId(contentSourceType, srcProjectId) {
852
+ return contentSourceType + ':' + srcProjectId;
853
+ }
854
+ exports.getContentSourceId = getContentSourceId;
855
+ function getUserContextForSrcType(srcType, user) {
856
+ var _a;
857
+ return (_a = user === null || user === void 0 ? void 0 : user.connections) === null || _a === void 0 ? void 0 : _a.find((connection) => connection.type === srcType);
858
+ }
859
+ function mapCSIAssetsToStoreAssets({ csiAssets, contentSourceInstance, defaultLocaleCode }) {
860
+ const extra = {
861
+ srcType: contentSourceInstance.getContentSourceType(),
862
+ srcProjectId: contentSourceInstance.getProjectId(),
863
+ srcProjectUrl: contentSourceInstance.getProjectManageUrl(),
864
+ srcEnvironment: contentSourceInstance.getProjectEnvironment()
865
+ };
866
+ return csiAssets.map((csiAsset) => sourceAssetToStoreAsset({ csiAsset, defaultLocaleCode, extra }));
867
+ }
868
+ function sourceAssetToStoreAsset({ csiAsset, defaultLocaleCode, extra }) {
869
+ return {
870
+ type: 'asset',
871
+ ...extra,
872
+ srcObjectId: csiAsset.id,
873
+ srcObjectUrl: csiAsset.manageUrl,
874
+ srcObjectLabel: getObjectLabel(csiAsset.fields, common_schema_1.IMAGE_MODEL, defaultLocaleCode),
875
+ srcModelName: common_schema_1.IMAGE_MODEL.name,
876
+ srcModelLabel: common_schema_1.IMAGE_MODEL.label,
877
+ isChanged: csiAsset.status === 'added' || csiAsset.status === 'modified',
878
+ status: csiAsset.status,
879
+ createdAt: csiAsset.createdAt,
880
+ createdBy: csiAsset.createdBy,
881
+ updatedAt: csiAsset.updatedAt,
882
+ updatedBy: csiAsset.updatedBy,
883
+ fields: {
884
+ title: {
885
+ label: 'Title',
886
+ ...csiAsset.fields.title
887
+ },
888
+ file: {
889
+ label: 'File',
890
+ ...csiAsset.fields.file
891
+ }
892
+ }
893
+ };
894
+ }
895
+ function mapCSIDocumentsToStoreDocuments({ csiDocuments, contentSourceInstance, modelMap, defaultLocaleCode }) {
896
+ const extra = {
897
+ srcType: contentSourceInstance.getContentSourceType(),
898
+ srcProjectId: contentSourceInstance.getProjectId(),
899
+ srcProjectUrl: contentSourceInstance.getProjectManageUrl(),
900
+ srcEnvironment: contentSourceInstance.getProjectEnvironment()
901
+ };
902
+ return csiDocuments.map((csiDocument) => mapCSIDocumentToStoreDocument({ csiDocument, model: modelMap[csiDocument.modelName], modelMap, defaultLocaleCode, extra }));
903
+ }
904
+ function mapCSIDocumentToStoreDocument({ csiDocument, model, modelMap, defaultLocaleCode, extra }) {
905
+ var _a, _b;
906
+ return {
907
+ type: 'document',
908
+ ...extra,
909
+ srcObjectId: csiDocument.id,
910
+ srcObjectUrl: csiDocument.manageUrl,
911
+ srcObjectLabel: getObjectLabel(csiDocument.fields, model, defaultLocaleCode),
912
+ srcModelLabel: (_a = model.label) !== null && _a !== void 0 ? _a : lodash_1.default.startCase(csiDocument.modelName),
913
+ srcModelName: csiDocument.modelName,
914
+ isChanged: csiDocument.status === 'added' || csiDocument.status === 'modified',
915
+ status: csiDocument.status,
916
+ createdAt: csiDocument.createdAt,
917
+ createdBy: csiDocument.createdBy,
918
+ updatedAt: csiDocument.updatedAt,
919
+ updatedBy: csiDocument.updatedBy,
920
+ fields: mapCSIFieldsToStoreFields({
921
+ csiDocumentFields: csiDocument.fields,
922
+ modelFields: (_b = model.fields) !== null && _b !== void 0 ? _b : [],
923
+ context: {
924
+ modelMap,
925
+ defaultLocaleCode
926
+ }
927
+ })
928
+ };
929
+ }
930
+ function mapCSIFieldsToStoreFields({ csiDocumentFields, modelFields, context }) {
931
+ return modelFields.reduce((result, modelField) => {
932
+ const csiDocumentField = csiDocumentFields[modelField.name];
933
+ const docField = mapCSIFieldToStoreField({
934
+ csiDocumentField,
935
+ modelField,
936
+ context
937
+ });
938
+ docField.label = modelField.label;
939
+ result[modelField.name] = docField;
940
+ return result;
941
+ }, {});
942
+ }
943
+ function mapCSIFieldToStoreField({ csiDocumentField, modelField, context }) {
944
+ if (!csiDocumentField) {
945
+ const isUnset = ['object', 'model', 'reference', 'richText', 'markdown', 'image', 'file', 'json'].includes(modelField.type);
946
+ return {
947
+ type: modelField.type,
948
+ ...(isUnset ? { isUnset } : null),
949
+ ...(modelField.type === 'list' ? { items: [] } : null)
950
+ };
951
+ }
952
+ // TODO: check if need to add "options" to "enum" and subtype/min/max to "number"
953
+ switch (modelField.type) {
954
+ case 'object':
955
+ return mapObjectField(csiDocumentField, modelField, context);
956
+ case 'model':
957
+ return mapModelField(csiDocumentField, modelField, context);
958
+ case 'list':
959
+ return mapListField(csiDocumentField, modelField, context);
960
+ case 'richText':
961
+ return mapRichTextField(csiDocumentField);
962
+ case 'markdown':
963
+ return mapMarkdownField(csiDocumentField);
964
+ default:
965
+ return csiDocumentField;
966
+ }
967
+ }
968
+ function mapObjectField(csiDocumentField, modelField, context) {
969
+ var _a, _b, _c;
970
+ if (!(0, content_source_interface_1.isLocalizedField)(csiDocumentField)) {
971
+ return {
972
+ type: csiDocumentField.type,
973
+ srcObjectLabel: getObjectLabel((_a = csiDocumentField.fields) !== null && _a !== void 0 ? _a : {}, modelField !== null && modelField !== void 0 ? modelField : [], context.defaultLocaleCode),
974
+ fields: mapCSIFieldsToStoreFields({
975
+ csiDocumentFields: (_b = csiDocumentField.fields) !== null && _b !== void 0 ? _b : {},
976
+ modelFields: (_c = modelField.fields) !== null && _c !== void 0 ? _c : [],
977
+ context
978
+ })
979
+ };
980
+ }
981
+ return {
982
+ type: csiDocumentField.type,
983
+ localized: true,
984
+ locales: lodash_1.default.mapValues(csiDocumentField.locales, (locale) => {
985
+ var _a, _b, _c;
986
+ return {
987
+ locale: locale.locale,
988
+ srcObjectLabel: getObjectLabel((_a = locale.fields) !== null && _a !== void 0 ? _a : {}, modelField, locale.locale),
989
+ fields: mapCSIFieldsToStoreFields({
990
+ csiDocumentFields: (_b = locale.fields) !== null && _b !== void 0 ? _b : {},
991
+ modelFields: (_c = modelField.fields) !== null && _c !== void 0 ? _c : [],
992
+ context
993
+ })
994
+ };
995
+ })
996
+ };
997
+ }
998
+ function mapModelField(csiDocumentField, modelField, context) {
999
+ var _a, _b, _c, _d;
1000
+ if (!(0, content_source_interface_1.isLocalizedField)(csiDocumentField)) {
1001
+ const model = context.modelMap[csiDocumentField.modelName];
1002
+ return {
1003
+ type: csiDocumentField.type,
1004
+ srcObjectLabel: getObjectLabel((_a = csiDocumentField.fields) !== null && _a !== void 0 ? _a : {}, model, context.defaultLocaleCode),
1005
+ srcModelName: csiDocumentField.modelName,
1006
+ srcModelLabel: (_b = model.label) !== null && _b !== void 0 ? _b : lodash_1.default.startCase(model.name),
1007
+ fields: mapCSIFieldsToStoreFields({
1008
+ csiDocumentFields: (_c = csiDocumentField.fields) !== null && _c !== void 0 ? _c : {},
1009
+ modelFields: (_d = model.fields) !== null && _d !== void 0 ? _d : [],
1010
+ context
1011
+ })
1012
+ };
1013
+ }
1014
+ return {
1015
+ type: csiDocumentField.type,
1016
+ localized: true,
1017
+ locales: lodash_1.default.mapValues(csiDocumentField.locales, (locale) => {
1018
+ var _a, _b, _c, _d;
1019
+ const model = context.modelMap[locale.modelName];
1020
+ return {
1021
+ locale: locale.locale,
1022
+ srcObjectLabel: getObjectLabel((_a = locale.fields) !== null && _a !== void 0 ? _a : {}, model, locale.locale),
1023
+ srcModelName: locale.modelName,
1024
+ srcModelLabel: (_b = model.label) !== null && _b !== void 0 ? _b : lodash_1.default.startCase(model.name),
1025
+ fields: mapCSIFieldsToStoreFields({
1026
+ csiDocumentFields: (_c = locale.fields) !== null && _c !== void 0 ? _c : {},
1027
+ modelFields: (_d = model.fields) !== null && _d !== void 0 ? _d : [],
1028
+ context
1029
+ })
1030
+ };
1031
+ })
1032
+ };
1033
+ }
1034
+ function mapListField(csiDocumentField, modelField, context) {
1035
+ if (!(0, content_source_interface_1.isLocalizedField)(csiDocumentField)) {
1036
+ return {
1037
+ type: csiDocumentField.type,
1038
+ items: csiDocumentField.items.map((item) => {
1039
+ var _a;
1040
+ return mapCSIFieldToStoreField({
1041
+ csiDocumentField: item,
1042
+ modelField: (_a = modelField.items) !== null && _a !== void 0 ? _a : { type: 'string' },
1043
+ context
1044
+ });
1045
+ })
1046
+ };
1047
+ }
1048
+ return {
1049
+ type: csiDocumentField.type,
1050
+ localized: true,
1051
+ locales: lodash_1.default.mapValues(csiDocumentField.locales, (locale) => {
1052
+ var _a;
1053
+ return {
1054
+ locale: locale.locale,
1055
+ items: ((_a = locale.items) !== null && _a !== void 0 ? _a : []).map((item) => {
1056
+ var _a;
1057
+ return mapCSIFieldToStoreField({
1058
+ csiDocumentField: item,
1059
+ modelField: (_a = modelField.items) !== null && _a !== void 0 ? _a : { type: 'string' },
1060
+ context
1061
+ });
1062
+ })
1063
+ };
1064
+ })
1065
+ };
1066
+ }
1067
+ function mapRichTextField(csiDocumentField) {
1068
+ if (!(0, content_source_interface_1.isLocalizedField)(csiDocumentField)) {
1069
+ return {
1070
+ ...csiDocumentField,
1071
+ multiElement: true
1072
+ };
1073
+ }
1074
+ return {
1075
+ type: csiDocumentField.type,
1076
+ localized: true,
1077
+ locales: lodash_1.default.mapValues(csiDocumentField.locales, (locale) => {
1078
+ return {
1079
+ ...locale,
1080
+ multiElement: true
1081
+ };
1082
+ })
1083
+ };
1084
+ }
1085
+ function mapMarkdownField(csiDocumentField) {
1086
+ if (!(0, content_source_interface_1.isLocalizedField)(csiDocumentField)) {
1087
+ return {
1088
+ type: 'markdown',
1089
+ value: csiDocumentField.value,
1090
+ multiElement: true
1091
+ };
1092
+ }
1093
+ return {
1094
+ type: 'markdown',
1095
+ localized: true,
1096
+ locales: lodash_1.default.mapValues(csiDocumentField.locales, (locale) => {
1097
+ return {
1098
+ ...locale,
1099
+ multiElement: true
1100
+ };
1101
+ })
1102
+ };
1103
+ }
1104
+ function mapStoreFieldsToSourceFields({ documentFields, modelFields, modelMap }) {
1105
+ // TODO: implement
1106
+ throw new Error(`duplicateDocument not implemented yet`);
1107
+ }
1108
+ function getContentSourceIdForContentSource(contentSource) {
1109
+ return getContentSourceId(contentSource.getContentSourceType(), contentSource.getProjectId());
1110
+ }
1111
+ function extractTokensFromString(input) {
1112
+ return input.match(/(?<={)[^}]+(?=})/g) || [];
1113
+ }
1114
+ function sanitizeSlug(slug) {
1115
+ return slug
1116
+ .split('/')
1117
+ .map((part) => (0, slugify_1.default)(part, { lower: true }))
1118
+ .join('/');
1119
+ }
1120
+ function getObjectLabel(documentFields, modelOrObjectField, locale) {
1121
+ const labelField = modelOrObjectField.labelField;
1122
+ let label = null;
1123
+ if (labelField) {
1124
+ const field = lodash_1.default.get(documentFields, labelField, null);
1125
+ if (field && ['string', 'url', 'slug', 'text', 'markdown', 'number', 'enum', 'date', 'datetime', 'color', 'image', 'file'].includes(field.type)) {
1126
+ if ((0, content_source_interface_1.isLocalizedField)(field) && locale) {
1127
+ label = lodash_1.default.get(field, ['locales', locale, 'value'], null);
1128
+ }
1129
+ else if (!(0, content_source_interface_1.isLocalizedField)(field)) {
1130
+ label = lodash_1.default.get(field, 'value', null);
1131
+ }
1132
+ }
1133
+ }
1134
+ if (!label) {
1135
+ label = lodash_1.default.get(modelOrObjectField, 'label');
1136
+ }
1137
+ if (!label && lodash_1.default.has(modelOrObjectField, 'name')) {
1138
+ label = lodash_1.default.startCase(lodash_1.default.get(modelOrObjectField, 'name'));
1139
+ }
1140
+ return label;
1141
+ }
1142
+ function mapDocumentsToLocalizedApiObjects(documents, locale) {
1143
+ return documents.map((document) => documentToLocalizedApiObject(document, locale));
1144
+ }
1145
+ function documentToLocalizedApiObject(document, locale) {
1146
+ const { type, fields, ...rest } = document;
1147
+ return {
1148
+ type: 'object',
1149
+ ...rest,
1150
+ fields: toLocalizedAPIFields(fields, locale)
1151
+ };
1152
+ }
1153
+ function toLocalizedAPIFields(docFields, locale) {
1154
+ return lodash_1.default.mapValues(docFields, (docField) => toLocalizedAPIField(docField, locale));
1155
+ }
1156
+ function toLocalizedAPIField(docField, locale, isListItem = false) {
1157
+ const hasUnsetFlag = ['object', 'model', 'reference', 'richText', 'markdown', 'image', 'file', 'json'].includes(docField.type);
1158
+ let docFieldLocalized;
1159
+ let unset = false;
1160
+ if (docField.localized) {
1161
+ const { locales, localized, ...base } = docField;
1162
+ const localeProps = locale ? locales[locale] : undefined;
1163
+ docFieldLocalized = {
1164
+ ...base,
1165
+ ...localeProps,
1166
+ ...(hasUnsetFlag && !localeProps ? { isUnset: true } : null)
1167
+ };
1168
+ }
1169
+ else {
1170
+ docFieldLocalized = docField;
1171
+ }
1172
+ locale = locale !== null && locale !== void 0 ? locale : docFieldLocalized.locale;
1173
+ const commonProps = isListItem
1174
+ ? null
1175
+ : {
1176
+ localized: !!docField.localized,
1177
+ ...(locale ? { locale } : null)
1178
+ };
1179
+ if (docFieldLocalized.type === 'object' || docFieldLocalized.type === 'model') {
1180
+ return {
1181
+ ...docFieldLocalized,
1182
+ ...commonProps,
1183
+ ...(docFieldLocalized.isUnset
1184
+ ? null
1185
+ : {
1186
+ fields: toLocalizedAPIFields(docFieldLocalized.fields, locale)
1187
+ })
1188
+ };
1189
+ }
1190
+ else if (docFieldLocalized.type === 'reference') {
1191
+ const { type, refType, ...rest } = docFieldLocalized;
1192
+ // if reference field isUnset === true, it behaves like a regular object
1193
+ if (rest.isUnset) {
1194
+ return {
1195
+ type: 'object',
1196
+ ...rest,
1197
+ ...commonProps
1198
+ };
1199
+ }
1200
+ return {
1201
+ type: 'unresolved_reference',
1202
+ refType: refType === 'asset' ? 'image' : 'object',
1203
+ ...rest,
1204
+ ...commonProps
1205
+ };
1206
+ }
1207
+ else if (docFieldLocalized.type === 'list') {
1208
+ const { items, ...rest } = docFieldLocalized;
1209
+ return {
1210
+ ...rest,
1211
+ ...commonProps,
1212
+ items: items.map((field) => toLocalizedAPIField(field, locale, true))
1213
+ };
1214
+ }
1215
+ else {
1216
+ return {
1217
+ ...docFieldLocalized,
1218
+ ...commonProps
1219
+ };
1220
+ }
1221
+ }
1222
+ function mapAssetsToLocalizedApiImages(assets, locale) {
1223
+ return assets.map((asset) => assetToLocalizedApiImage(asset, locale));
1224
+ }
1225
+ function assetToLocalizedApiImage(asset, locale) {
1226
+ const { type, fields, ...rest } = asset;
1227
+ return {
1228
+ type: 'image',
1229
+ ...rest,
1230
+ fields: localizeAssetFields(fields, locale)
1231
+ };
1232
+ }
1233
+ function localizeAssetFields(assetFields, locale) {
1234
+ var _a, _b;
1235
+ const fields = {
1236
+ title: {
1237
+ type: 'string',
1238
+ value: null
1239
+ },
1240
+ url: {
1241
+ type: 'string',
1242
+ value: null
1243
+ }
1244
+ };
1245
+ const titleFieldNonLocalized = getDocumentFieldForLocale(assetFields.title, locale);
1246
+ fields.title.value = titleFieldNonLocalized === null || titleFieldNonLocalized === void 0 ? void 0 : titleFieldNonLocalized.value;
1247
+ fields.title.locale = locale !== null && locale !== void 0 ? locale : titleFieldNonLocalized === null || titleFieldNonLocalized === void 0 ? void 0 : titleFieldNonLocalized.locale;
1248
+ const assetFileField = assetFields.file;
1249
+ if (assetFileField.localized) {
1250
+ if (locale) {
1251
+ fields.url.value = (_b = (_a = assetFileField.locales[locale]) === null || _a === void 0 ? void 0 : _a.url) !== null && _b !== void 0 ? _b : null;
1252
+ fields.url.locale = locale;
1253
+ }
1254
+ }
1255
+ else {
1256
+ fields.url.value = assetFileField.url;
1257
+ fields.url.locale = assetFileField.locale;
1258
+ }
1259
+ return fields;
1260
+ }
1261
+ function mapStoreAssetsToAPIAssets(assets, locale) {
1262
+ return assets.map((asset) => storeAssetToAPIAsset(asset, locale));
1263
+ }
1264
+ function storeAssetToAPIAsset(asset, locale) {
1265
+ var _a, _b;
1266
+ const assetTitleField = asset.fields.title;
1267
+ const localizedTitleField = assetTitleField.localized ? assetTitleField.locales[locale] : assetTitleField;
1268
+ const assetFileField = asset.fields.file;
1269
+ const localizedFileField = assetFileField.localized ? assetFileField.locales[locale] : assetFileField;
1270
+ return {
1271
+ objectId: asset.srcObjectId,
1272
+ createdAt: asset.createdAt,
1273
+ url: localizedFileField.url,
1274
+ ...(0, utils_1.omitByNil)({
1275
+ title: localizedTitleField.value,
1276
+ fileName: localizedFileField.fileName,
1277
+ contentType: localizedFileField.contentType,
1278
+ size: localizedFileField.size,
1279
+ width: (_a = localizedFileField.dimensions) === null || _a === void 0 ? void 0 : _a.width,
1280
+ height: (_b = localizedFileField.dimensions) === null || _b === void 0 ? void 0 : _b.height
1281
+ })
1282
+ };
1283
+ }
1284
+ /**
1285
+ * Iterates recursively objects with $$type and $$ref, creating nested objects
1286
+ * as needed and returns standard ContentSourceInterface Documents
1287
+ */
1288
+ async function createDocumentRecursively({ object, model, modelMap, locale, userContext, contentSourceInstance }) {
1289
+ var _a;
1290
+ if (model.type === 'page') {
1291
+ const tokens = extractTokensFromString(String(model.urlPath));
1292
+ const slugField = lodash_1.default.last(tokens);
1293
+ if (object && slugField && slugField in object) {
1294
+ const slugFieldValue = object[slugField];
1295
+ object[slugField] = sanitizeSlug(slugFieldValue);
1296
+ }
1297
+ }
1298
+ const nestedResult = await createNestedObjectRecursively({
1299
+ object,
1300
+ modelFields: (_a = model.fields) !== null && _a !== void 0 ? _a : [],
1301
+ fieldPath: [],
1302
+ modelMap,
1303
+ locale,
1304
+ userContext,
1305
+ contentSourceInstance
1306
+ });
1307
+ const document = await contentSourceInstance.createDocument({
1308
+ documentFields: nestedResult.fields,
1309
+ model,
1310
+ modelMap,
1311
+ locale,
1312
+ userContext
1313
+ });
1314
+ return {
1315
+ document: document,
1316
+ newRefDocuments: nestedResult.newRefDocuments
1317
+ };
1318
+ }
1319
+ async function createNestedObjectRecursively({ object, modelFields, fieldPath, modelMap, locale, userContext, contentSourceInstance }) {
1320
+ object = object !== null && object !== void 0 ? object : {};
1321
+ const result = {
1322
+ fields: {},
1323
+ newRefDocuments: []
1324
+ };
1325
+ const objectFieldNames = Object.keys(object);
1326
+ for (const modelField of modelFields) {
1327
+ const fieldName = modelField.name;
1328
+ let value;
1329
+ if (fieldName in object) {
1330
+ value = object[fieldName];
1331
+ lodash_1.default.pull(objectFieldNames, fieldName);
1332
+ }
1333
+ else if (modelField.const) {
1334
+ value = modelField.const;
1335
+ }
1336
+ else if (!lodash_1.default.isNil(modelField.default)) {
1337
+ value = modelField.default;
1338
+ }
1339
+ if (!lodash_1.default.isNil(value)) {
1340
+ const fieldResult = await createNestedField({
1341
+ value,
1342
+ modelField,
1343
+ fieldPath: fieldPath.concat(fieldName),
1344
+ modelMap,
1345
+ locale,
1346
+ userContext,
1347
+ contentSourceInstance
1348
+ });
1349
+ result.fields[fieldName] = fieldResult.field;
1350
+ result.newRefDocuments = result.newRefDocuments.concat(fieldResult.newRefDocuments);
1351
+ }
1352
+ }
1353
+ if (objectFieldNames.length > 0) {
1354
+ throw new Error(`no model fields found when creating a document with fields: '${objectFieldNames.join(', ')}'`);
1355
+ }
1356
+ return result;
1357
+ }
1358
+ async function createNestedField({ value, modelField, fieldPath, modelMap, locale, userContext, contentSourceInstance }) {
1359
+ var _a;
1360
+ if (modelField.type === 'object') {
1361
+ const result = await createNestedObjectRecursively({
1362
+ object: value,
1363
+ modelFields: modelField.fields,
1364
+ fieldPath,
1365
+ modelMap,
1366
+ locale,
1367
+ userContext,
1368
+ contentSourceInstance
1369
+ });
1370
+ return {
1371
+ field: {
1372
+ type: 'object',
1373
+ fields: result.fields
1374
+ },
1375
+ newRefDocuments: result.newRefDocuments
1376
+ };
1377
+ }
1378
+ else if (modelField.type === 'model') {
1379
+ let { $$type, ...rest } = value;
1380
+ const modelNames = modelField.models;
1381
+ // for backward compatibility check if the object has 'type' instead of '$$type' because older projects use
1382
+ // the 'type' property in default values
1383
+ if (!$$type && 'type' in rest) {
1384
+ $$type = rest.type;
1385
+ rest = lodash_1.default.omit(rest, 'type');
1386
+ }
1387
+ const modelName = $$type !== null && $$type !== void 0 ? $$type : (modelNames.length === 1 ? modelNames[0] : null);
1388
+ if (!modelName) {
1389
+ throw new Error(`no $$type was specified for nested model`);
1390
+ }
1391
+ const model = modelMap[modelName];
1392
+ if (!model) {
1393
+ throw new Error(`no model with name '${modelName}' was found`);
1394
+ }
1395
+ const result = await createNestedObjectRecursively({
1396
+ object: rest,
1397
+ modelFields: (_a = model.fields) !== null && _a !== void 0 ? _a : [],
1398
+ fieldPath,
1399
+ modelMap,
1400
+ locale,
1401
+ userContext,
1402
+ contentSourceInstance
1403
+ });
1404
+ return {
1405
+ field: {
1406
+ type: 'model',
1407
+ modelName: modelName,
1408
+ fields: result.fields
1409
+ },
1410
+ newRefDocuments: result.newRefDocuments
1411
+ };
1412
+ }
1413
+ else if (modelField.type === 'image') {
1414
+ let refId;
1415
+ if (lodash_1.default.isPlainObject(value)) {
1416
+ refId = value.$$ref;
1417
+ }
1418
+ else {
1419
+ refId = value;
1420
+ }
1421
+ if (!refId) {
1422
+ throw new Error(`reference field must specify a value`);
1423
+ }
1424
+ return {
1425
+ field: {
1426
+ type: 'reference',
1427
+ refType: 'asset',
1428
+ refId: refId
1429
+ },
1430
+ newRefDocuments: []
1431
+ };
1432
+ }
1433
+ else if (modelField.type === 'reference') {
1434
+ let { $$ref: refId = null, $$type: modelName = null, ...rest } = lodash_1.default.isPlainObject(value) ? value : { $$ref: value };
1435
+ if (refId) {
1436
+ return {
1437
+ field: {
1438
+ type: 'reference',
1439
+ refType: 'document',
1440
+ refId: refId
1441
+ },
1442
+ newRefDocuments: []
1443
+ };
1444
+ }
1445
+ else {
1446
+ const modelNames = modelField.models;
1447
+ if (!modelName) {
1448
+ // for backward compatibility check if the object has 'type' instead of '$$type' because older projects use
1449
+ // the 'type' property in default values
1450
+ if ('type' in rest) {
1451
+ modelName = rest.type;
1452
+ rest = lodash_1.default.omit(rest, 'type');
1453
+ }
1454
+ else if (modelNames.length === 1) {
1455
+ modelName = modelNames[0];
1456
+ }
1457
+ }
1458
+ const model = modelMap[modelName];
1459
+ if (!model) {
1460
+ throw new Error(`no model with name '${modelName}' was found`);
1461
+ }
1462
+ const { document, newRefDocuments } = await createDocumentRecursively({
1463
+ object: rest,
1464
+ model: model,
1465
+ modelMap,
1466
+ locale,
1467
+ userContext,
1468
+ contentSourceInstance
1469
+ });
1470
+ return {
1471
+ field: {
1472
+ type: 'reference',
1473
+ refType: 'document',
1474
+ refId: document.id
1475
+ },
1476
+ newRefDocuments: [document, ...newRefDocuments]
1477
+ };
1478
+ }
1479
+ }
1480
+ else if (modelField.type === 'list') {
1481
+ if (!Array.isArray(value)) {
1482
+ throw new Error(`value for list field must be array`);
1483
+ }
1484
+ const itemsField = modelField.items;
1485
+ if (!itemsField) {
1486
+ throw new Error(`list field does not define items`);
1487
+ }
1488
+ const arrayResult = await (0, utils_1.mapPromise)(value, async (item, index) => {
1489
+ return createNestedField({
1490
+ value: item,
1491
+ modelField: itemsField,
1492
+ fieldPath: fieldPath.concat(index),
1493
+ modelMap,
1494
+ locale,
1495
+ userContext,
1496
+ contentSourceInstance
1497
+ });
1498
+ });
1499
+ return {
1500
+ field: {
1501
+ type: 'list',
1502
+ items: arrayResult.map((result) => result.field)
1503
+ },
1504
+ newRefDocuments: arrayResult.reduce((result, { newRefDocuments }) => result.concat(newRefDocuments), [])
1505
+ };
1506
+ }
1507
+ return {
1508
+ field: {
1509
+ type: modelField.type,
1510
+ value: value
1511
+ },
1512
+ newRefDocuments: []
1513
+ };
1514
+ }
1515
+ function getModelFieldForFieldAtPath(document, model, fieldPath, modelMap, locale) {
1516
+ if (lodash_1.default.isEmpty(fieldPath)) {
1517
+ throw new Error('the fieldPath can not be empty');
1518
+ }
1519
+ function getField(docField, modelField, fieldPath) {
1520
+ const fieldName = lodash_1.default.head(fieldPath);
1521
+ if (typeof fieldName === 'undefined') {
1522
+ throw new Error('the first fieldPath item must be string');
1523
+ }
1524
+ const childFieldPath = lodash_1.default.tail(fieldPath);
1525
+ let childDocField;
1526
+ let childModelField;
1527
+ switch (docField.type) {
1528
+ case 'object':
1529
+ const localizedObjectField = getDocumentFieldForLocale(docField, locale);
1530
+ if (!localizedObjectField) {
1531
+ throw new Error(`locale for field was not found`);
1532
+ }
1533
+ if (localizedObjectField.isUnset) {
1534
+ throw new Error(`field is not set`);
1535
+ }
1536
+ childDocField = localizedObjectField.fields[fieldName];
1537
+ childModelField = lodash_1.default.find(modelField.fields, (field) => field.name === fieldName);
1538
+ if (!childDocField || !childModelField) {
1539
+ throw new Error(`field ${fieldName} doesn't exist`);
1540
+ }
1541
+ if (childFieldPath.length === 0) {
1542
+ return childModelField;
1543
+ }
1544
+ return getField(childDocField, childModelField, childFieldPath);
1545
+ case 'model':
1546
+ const localizedModelField = getDocumentFieldForLocale(docField, locale);
1547
+ if (!localizedModelField) {
1548
+ throw new Error(`locale for field was not found`);
1549
+ }
1550
+ if (localizedModelField.isUnset) {
1551
+ throw new Error(`field is not set`);
1552
+ }
1553
+ const modelName = localizedModelField.srcModelName;
1554
+ const childModel = modelMap[modelName];
1555
+ if (!childModel) {
1556
+ throw new Error(`model ${modelName} doesn't exist`);
1557
+ }
1558
+ childModelField = lodash_1.default.find(childModel.fields, (field) => field.name === fieldName);
1559
+ childDocField = localizedModelField.fields[fieldName];
1560
+ if (!childDocField || !childModelField) {
1561
+ throw new Error(`field ${fieldName} doesn't exist`);
1562
+ }
1563
+ if (childFieldPath.length === 0) {
1564
+ return childModelField;
1565
+ }
1566
+ return getField(childDocField, childModelField, childFieldPath);
1567
+ case 'list':
1568
+ const localizedListField = getDocumentFieldForLocale(docField, locale);
1569
+ if (!localizedListField) {
1570
+ throw new Error(`locale for field was not found`);
1571
+ }
1572
+ const listItem = localizedListField.items && localizedListField.items[fieldName];
1573
+ const listItemsModel = modelField.items;
1574
+ if (!listItem || !listItemsModel) {
1575
+ throw new Error(`field ${fieldName} doesn't exist`);
1576
+ }
1577
+ if (childFieldPath.length === 0) {
1578
+ return modelField;
1579
+ }
1580
+ if (!Array.isArray(listItemsModel)) {
1581
+ return getField(listItem, listItemsModel, childFieldPath);
1582
+ }
1583
+ else {
1584
+ const fieldListItems = listItemsModel.find((listItemsModel) => listItemsModel.type === listItem.type);
1585
+ if (!fieldListItems) {
1586
+ throw new Error('cannot find matching field model');
1587
+ }
1588
+ return getField(listItem, fieldListItems, childFieldPath);
1589
+ }
1590
+ default:
1591
+ if (!lodash_1.default.isEmpty(childFieldPath)) {
1592
+ throw new Error('illegal fieldPath');
1593
+ }
1594
+ return modelField;
1595
+ }
1596
+ }
1597
+ const fieldName = lodash_1.default.head(fieldPath);
1598
+ const childFieldPath = lodash_1.default.tail(fieldPath);
1599
+ if (typeof fieldName !== 'string') {
1600
+ throw new Error('the first fieldPath item must be string');
1601
+ }
1602
+ const childDocField = document.fields[fieldName];
1603
+ const childModelField = lodash_1.default.find(model.fields, { name: fieldName });
1604
+ if (!childDocField || !childModelField) {
1605
+ throw new Error(`field ${fieldName} doesn't exist`);
1606
+ }
1607
+ if (childFieldPath.length === 0) {
1608
+ return childModelField;
1609
+ }
1610
+ return getField(childDocField, childModelField, childFieldPath);
1611
+ }
1612
+ async function convertOperationField({ operationField, fieldPath, modelField, modelMap, locale, userContext, contentSourceInstance }) {
1613
+ // for insert operations, the modelField will be of the list, so get the modelField of the list items
1614
+ const modelFieldOrListItems = modelField.type === 'list' ? modelField.items : modelField;
1615
+ switch (operationField.type) {
1616
+ case 'object': {
1617
+ const result = await createNestedObjectRecursively({
1618
+ object: operationField.object,
1619
+ modelFields: modelFieldOrListItems.fields,
1620
+ fieldPath: fieldPath,
1621
+ modelMap,
1622
+ locale,
1623
+ userContext,
1624
+ contentSourceInstance
1625
+ });
1626
+ return {
1627
+ type: operationField.type,
1628
+ fields: result.fields
1629
+ };
1630
+ }
1631
+ case 'model': {
1632
+ const model = modelMap[operationField.modelName];
1633
+ if (!model) {
1634
+ throw new Error(`error updating document, could not find document model: '${operationField.modelName}'`);
1635
+ }
1636
+ const result = await createNestedObjectRecursively({
1637
+ object: operationField.object,
1638
+ modelFields: model.fields,
1639
+ fieldPath,
1640
+ modelMap,
1641
+ locale,
1642
+ userContext,
1643
+ contentSourceInstance
1644
+ });
1645
+ return {
1646
+ type: operationField.type,
1647
+ modelName: operationField.modelName,
1648
+ fields: result.fields
1649
+ };
1650
+ }
1651
+ case 'list': {
1652
+ if (modelField.type !== 'list') {
1653
+ throw new Error(`'the operation field type '${operationField.type}' does not match the model field type '${modelField.type}'`);
1654
+ }
1655
+ const result = await (0, utils_1.mapPromise)(operationField.items, async (item, index) => {
1656
+ const result = await createNestedField({
1657
+ value: item,
1658
+ modelField: modelField.items,
1659
+ fieldPath,
1660
+ modelMap,
1661
+ locale,
1662
+ userContext,
1663
+ contentSourceInstance
1664
+ });
1665
+ return result.field;
1666
+ });
1667
+ return {
1668
+ type: operationField.type,
1669
+ items: result
1670
+ };
1671
+ }
1672
+ case 'string':
1673
+ if (typeof operationField.value !== 'string') {
1674
+ return {
1675
+ type: operationField.type,
1676
+ value: ''
1677
+ };
1678
+ }
1679
+ return operationField;
1680
+ case 'enum':
1681
+ if (typeof operationField.value !== 'string') {
1682
+ if (modelFieldOrListItems.type !== 'enum') {
1683
+ throw new Error(`'the operation field type 'enum' does not match the model field type '${modelFieldOrListItems.type}'`);
1684
+ }
1685
+ const option = modelFieldOrListItems.options[0];
1686
+ const optionValue = typeof option === 'object' ? option.value : option;
1687
+ return {
1688
+ type: operationField.type,
1689
+ value: optionValue
1690
+ };
1691
+ }
1692
+ return operationField;
1693
+ case 'image':
1694
+ if (typeof operationField.value !== 'string') {
1695
+ throw new Error('image value was not specified');
1696
+ }
1697
+ return operationField;
1698
+ default:
1699
+ return operationField;
1700
+ }
1701
+ }
1702
+ function getDocumentFieldForLocale(docField, locale) {
1703
+ if (docField.localized) {
1704
+ if (!locale) {
1705
+ return null;
1706
+ }
1707
+ const { localized, locales, ...base } = docField;
1708
+ const localizedField = locales[locale];
1709
+ if (!localizedField) {
1710
+ return null;
1711
+ }
1712
+ return {
1713
+ ...base,
1714
+ ...localizedField
1715
+ };
1716
+ }
1717
+ else {
1718
+ return docField;
1719
+ }
1720
+ }
1721
+ function isStackbitConfigFile(filePath) {
1722
+ const pathObject = path_1.default.parse(filePath);
1723
+ const isInDotStackbitFolder = pathObject.dir.startsWith('.stackbit');
1724
+ const isMainStackbitConfigFile = pathObject.name === 'stackbit' && ['yaml', 'yml'].includes(pathObject.ext.substring(1));
1725
+ return isMainStackbitConfigFile || isInDotStackbitFolder;
1726
+ }
1727
+ function getCSIDocumentsAndAssetsFromContentSourceDataByIds(contentSourceData, objects) {
1728
+ const documents = [];
1729
+ const assets = [];
1730
+ for (const object of objects) {
1731
+ if (object.srcObjectId in contentSourceData.csiDocumentMap) {
1732
+ documents.push(contentSourceData.csiDocumentMap[object.srcObjectId]);
1733
+ }
1734
+ else if (object.srcObjectId in contentSourceData.csiAssetMap) {
1735
+ assets.push(contentSourceData.csiAssetMap[object.srcObjectId]);
1736
+ }
1737
+ }
1738
+ return {
1739
+ documents,
1740
+ assets
1741
+ };
1742
+ }
1743
+ //# sourceMappingURL=content-store.js.map