@esri/solution-deployer 5.2.3 → 5.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,882 @@
1
+ "use strict";
2
+ /** @license
3
+ * Copyright 2018 Esri
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports._getGroupUpdates = exports._estimateDeploymentCost = exports._createItemFromTemplateWhenReady = exports._findExistingItem = exports._findExistingItemByKeyword = exports._updateTemplateDictionaryById = exports._handleExistingItems = exports._updateTemplateDictionaryForError = exports._setFields = exports._updateTemplateDictionary = exports._setTypekeywordForExisting = exports._useExistingItems = exports._reuseDeployedItems = exports._getViews = exports._getViewHash = exports._updateViewTemplates = exports._evaluateSharedViewSources = exports._flagPatchItemsForPostProcessing = exports.deploySolutionItems = void 0;
19
+ const tslib_1 = require("tslib");
20
+ /**
21
+ * Manages deployment of items via the REST API.
22
+ *
23
+ * @module deployItems
24
+ */
25
+ const common = tslib_1.__importStar(require("@esri/solution-common"));
26
+ const form = tslib_1.__importStar(require("@esri/solution-form"));
27
+ const module_map_1 = require("./module-map");
28
+ const UNSUPPORTED = null;
29
+ // ------------------------------------------------------------------------------------------------------------------ //
30
+ /**
31
+ * Deploys a set of items defined by templates.
32
+ *
33
+ * @param portalSharingUrl Server/sharing
34
+ * @param storageItemId Id of storage item
35
+ * @param templates A collection of AGO item templates
36
+ * @param storageAuthentication Credentials for the organization with the source items
37
+ * @param templateDictionary Hash of facts: org URL, adlib replacements
38
+ * @param deployedSolutionId Id of deployed Solution item
39
+ * @param destinationAuthentication Credentials for the destination organization
40
+ * @param options Options to tune deployment
41
+ * @returns A promise that will resolve with the list of information about the created items
42
+ */
43
+ function deploySolutionItems(portalSharingUrl, storageItemId, templates, storageAuthentication, templateDictionary, deployedSolutionId, destinationAuthentication, options) {
44
+ return new Promise((resolve, reject) => {
45
+ // Prepare feedback mechanism
46
+ const totalEstimatedCost = _estimateDeploymentCost(templates) + 1; // solution items, plus avoid divide by 0
47
+ let percentDone = 10; // allow for previous deployment work
48
+ const progressPercentStep = (99 - percentDone) / totalEstimatedCost; // leave some % for caller for wrapup
49
+ const failedTemplateItemIds = [];
50
+ const deployedItemIds = [];
51
+ let statusOK = true;
52
+ // TODO: move to separate fn
53
+ const itemProgressCallback = (itemId, status, costUsed, createdItemId // supplied when status is EItemProgressStatus.Created or .Finished
54
+ ) => {
55
+ percentDone += progressPercentStep * costUsed;
56
+ /* istanbul ignore else */
57
+ if (options.progressCallback) {
58
+ if (status === common.EItemProgressStatus.Finished) {
59
+ const event = {
60
+ event: common.SItemProgressStatus[status],
61
+ data: itemId
62
+ };
63
+ options.progressCallback(Math.round(percentDone), options.jobId, event);
64
+ }
65
+ else {
66
+ options.progressCallback(Math.round(percentDone), options.jobId);
67
+ }
68
+ }
69
+ /* istanbul ignore if */
70
+ if (options.consoleProgress) {
71
+ console.log(Date.now(), itemId, options.jobId ?? "", common.SItemProgressStatus[status], percentDone.toFixed(0) + "%", costUsed, createdItemId ? "==> " + createdItemId : "");
72
+ }
73
+ if (status === common.EItemProgressStatus.Created) {
74
+ deployedItemIds.push(createdItemId);
75
+ }
76
+ else if (status === common.EItemProgressStatus.Failed) {
77
+ failedTemplateItemIds.push(itemId);
78
+ console.error("Item " + itemId + " has failed");
79
+ statusOK = false;
80
+ }
81
+ return statusOK;
82
+ // ---------------------------------------------------------------------------------------------------------------
83
+ };
84
+ // portal does not allow views of a single source to be created at the same time
85
+ if (common.getProp(templateDictionary, "organization.isPortal")) {
86
+ templates = _evaluateSharedViewSources(templates);
87
+ }
88
+ // Create an ordered graph of the templates so that dependencies are created before the items that need them.
89
+ // Because cycles are permitted, we also keep track of items that need to be patched later because their
90
+ // dependencies are necessarily created after they are created.
91
+ const { buildOrder, itemsToBePatched } = common.topologicallySortItems(templates);
92
+ // For each item in order from no dependencies to dependent on other items,
93
+ // * replace template symbols using template dictionary
94
+ // * create item in destination group
95
+ // * add created item's id into the template dictionary
96
+ const awaitAllItems = [];
97
+ const reuseItemsDef = _reuseDeployedItems(templates, options.enableItemReuse ?? false, templateDictionary, destinationAuthentication);
98
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
99
+ reuseItemsDef.then(() => {
100
+ const useExistingItemsDef = _useExistingItems(templates, common.getProp(templateDictionary, "params.useExisting"), templateDictionary, destinationAuthentication);
101
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
102
+ useExistingItemsDef.then(() => {
103
+ templates = common.setNamesAndTitles(templates, templateDictionary.solutionItemId);
104
+ buildOrder.forEach((id) => {
105
+ // Get the item's template out of the list of templates
106
+ const template = common.findTemplateInList(templates, id);
107
+ if (template.type === "Form") {
108
+ // Flag all forms for post processing of their webhooks
109
+ itemsToBePatched[id] = [];
110
+ }
111
+ else if (template.type === "QuickCapture Project") {
112
+ // Remove qc.project.json files from the resources--we don't use them from solutions
113
+ template.resources = template.resources.filter((filename) => !filename.endsWith("qc.project.json"));
114
+ }
115
+ awaitAllItems.push(_createItemFromTemplateWhenReady(template, common.generateStorageFilePaths(portalSharingUrl, storageItemId, template.resources, options.storageVersion), storageAuthentication, templateDictionary, destinationAuthentication, itemProgressCallback));
116
+ });
117
+ // Wait until all items have been created
118
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
119
+ Promise.all(awaitAllItems).then((clonedSolutionItems) => {
120
+ if (failedTemplateItemIds.length === 0) {
121
+ // Do we have any items to be patched (i.e., they refer to dependencies using the template id rather
122
+ // than the cloned id because the item had to be created before the dependency)? Flag these items
123
+ // for post processing in the list of clones.
124
+ _flagPatchItemsForPostProcessing(itemsToBePatched, templateDictionary, clonedSolutionItems);
125
+ resolve(clonedSolutionItems);
126
+ }
127
+ else {
128
+ // Delete created items
129
+ const progressOptions = {
130
+ consoleProgress: true
131
+ };
132
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
133
+ common
134
+ .deleteSolutionByComponents(deployedSolutionId, deployedItemIds, templates, templateDictionary, destinationAuthentication, progressOptions)
135
+ .then(() => reject(common.failWithIds(failedTemplateItemIds)));
136
+ }
137
+ });
138
+ });
139
+ }, e => {
140
+ console.error(e);
141
+ reject(common.fail(e));
142
+ });
143
+ });
144
+ }
145
+ exports.deploySolutionItems = deploySolutionItems;
146
+ /**
147
+ * For each item to be patched, convert it to its cloned id and mark the item as needing post processing.
148
+ *
149
+ * @param itemsToBePatched List of items that need to have their dependencies patched
150
+ * @param templateDictionary Hash of facts: org URL, adlib replacements
151
+ * @param templates A collection of AGO item templates
152
+ * @private
153
+ */
154
+ function _flagPatchItemsForPostProcessing(itemsToBePatched, templateDictionary, templates) {
155
+ let itemIdsToBePatched = Object.keys(itemsToBePatched);
156
+ /* istanbul ignore else */
157
+ if (itemIdsToBePatched.length > 0) {
158
+ // Replace the ids of the items to be patched (which are template ids) with their cloned versions
159
+ itemIdsToBePatched = itemIdsToBePatched.map(id => templateDictionary[id].itemId);
160
+ // Make sure that the items to be patched are flagged for post processing
161
+ templates.forEach(item => {
162
+ /* istanbul ignore else */
163
+ if (itemIdsToBePatched.includes(item.id)) {
164
+ item.postProcess = true;
165
+ }
166
+ });
167
+ }
168
+ }
169
+ exports._flagPatchItemsForPostProcessing = _flagPatchItemsForPostProcessing;
170
+ /**
171
+ * Portal does not allow views of a single source to be created at the same time.
172
+ *
173
+ * Update view templates with an array of other view template ids that it should wait on.
174
+ *
175
+ * @param templates a collection of AGO item templates
176
+ *
177
+ * @returns An updated array of item templates
178
+ * @private
179
+ */
180
+ function _evaluateSharedViewSources(templates) {
181
+ // update the templates so we can defer the deployment when more than one view shares the same source
182
+ // these are not classic dependencies but are in some ways similar
183
+ const views = _getViews(templates);
184
+ _updateViewTemplates(templates, views);
185
+ const viewHash = _getViewHash(views);
186
+ let processed = [];
187
+ const visited = [];
188
+ Object.keys(viewHash).forEach(k => {
189
+ const _views = viewHash[k];
190
+ _views.forEach(cv => {
191
+ const template = common.findTemplateInList(templates, cv);
192
+ const syncViews = common.getProp(template, "properties.syncViews");
193
+ /* istanbul ignore else */
194
+ if (visited.indexOf(template.itemId) > -1) {
195
+ processed = processed.concat(syncViews);
196
+ }
197
+ /* istanbul ignore else */
198
+ if (syncViews && syncViews.length > 0) {
199
+ // when a view has multiple dependencies we need to retain the syncViews if they have been set already...
200
+ common.setProp(template, "properties.syncViews", common.cloneObject(processed));
201
+ }
202
+ /* istanbul ignore else */
203
+ if (processed.indexOf(cv) < 0) {
204
+ processed.push(cv);
205
+ }
206
+ /* istanbul ignore else */
207
+ if (visited.indexOf(template.itemId) < 0) {
208
+ visited.push(template.itemId);
209
+ }
210
+ });
211
+ processed = [];
212
+ });
213
+ return templates;
214
+ }
215
+ exports._evaluateSharedViewSources = _evaluateSharedViewSources;
216
+ /**
217
+ * Add a syncViews array to each template that will hold all other view ids that
218
+ * have the same FS dependency.
219
+ * These arrays will be processed later to only contain ids that each view will need to wait on.
220
+ *
221
+ * @param templates a collection of AGO item templates
222
+ * @param views an array of view template details
223
+ *
224
+ * @returns An updated array of item templates
225
+ * @private
226
+ */
227
+ function _updateViewTemplates(templates, views) {
228
+ views.forEach(v => {
229
+ v.dependencies.forEach((id) => {
230
+ templates = templates.map(t => {
231
+ /* istanbul ignore else */
232
+ if (common.getProp(t, "properties.service.isView") &&
233
+ t.dependencies.indexOf(id) > -1 &&
234
+ t.itemId !== v.id) {
235
+ /* istanbul ignore else */
236
+ if (!Array.isArray(t.properties.syncViews)) {
237
+ t.properties.syncViews = [];
238
+ }
239
+ /* istanbul ignore else */
240
+ if (t.properties.syncViews.indexOf(v.id) < 0) {
241
+ t.properties.syncViews.push(v.id);
242
+ }
243
+ }
244
+ return t;
245
+ });
246
+ });
247
+ });
248
+ return templates;
249
+ }
250
+ exports._updateViewTemplates = _updateViewTemplates;
251
+ /**
252
+ * Get all view templates from the source templates collection
253
+ *
254
+ * @param views A collection of view ID and dependencies
255
+ *
256
+ * @returns an array of objects with the source FS id as the key and a list of views that are
257
+ * dependant upon it
258
+ *
259
+ * @private
260
+ */
261
+ function _getViewHash(views) {
262
+ const viewHash = {};
263
+ views.forEach(v => {
264
+ v.dependencies.forEach((d) => {
265
+ /* istanbul ignore else */
266
+ if (Object.keys(viewHash).indexOf(d) < 0) {
267
+ viewHash[d] = [v.id];
268
+ }
269
+ else if (viewHash[d].indexOf(v.id) < 0) {
270
+ viewHash[d].push(v.id);
271
+ }
272
+ });
273
+ });
274
+ return viewHash;
275
+ }
276
+ exports._getViewHash = _getViewHash;
277
+ /**
278
+ * Get all view templates from the source templates collection
279
+ *
280
+ * @param templates A collection of AGO item templates
281
+ *
282
+ * @returns an array with the view id and its dependencies
283
+ *
284
+ * @private
285
+ */
286
+ function _getViews(templates) {
287
+ return templates.reduce((acc, v) => {
288
+ /* istanbul ignore else */
289
+ if (common.getProp(v, "properties.service.isView")) {
290
+ acc.push({
291
+ id: v.itemId,
292
+ dependencies: v.dependencies
293
+ });
294
+ }
295
+ return acc;
296
+ }, []);
297
+ }
298
+ exports._getViews = _getViews;
299
+ /**
300
+ * Search for existing items and update the templateDictionary with key details
301
+ *
302
+ * @param templates A collection of AGO item templates
303
+ * @param reuseItems Option to search for existing items
304
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
305
+ * @param authentication Credentials for the requests
306
+ *
307
+ * @returns A Promise that will resolve once existing items have been evaluated
308
+ *
309
+ * @private
310
+ */
311
+ function _reuseDeployedItems(templates, reuseItems, templateDictionary, authentication) {
312
+ return new Promise((resolve, reject) => {
313
+ if (reuseItems) {
314
+ const findItemsByKeywordResponse = _findExistingItemByKeyword(templates, templateDictionary, authentication);
315
+ const existingItemsByKeyword = findItemsByKeywordResponse.existingItemsDefs;
316
+ const existingItemInfos = findItemsByKeywordResponse.existingItemInfos;
317
+ Promise.all(existingItemsByKeyword).then((existingItemsByKeywordResponse) => {
318
+ const findExistingItemsByTag = _handleExistingItems(existingItemsByKeywordResponse, existingItemInfos, templateDictionary, authentication, true);
319
+ const existingItemsByTag = findExistingItemsByTag.existingItemsDefs;
320
+ const existingItemInfosByTag = findExistingItemsByTag.existingItemInfos;
321
+ Promise.all(existingItemsByTag).then(existingItemsByTagResponse => {
322
+ _handleExistingItems(existingItemsByTagResponse, existingItemInfosByTag, templateDictionary, authentication, false);
323
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
324
+ _updateTemplateDictionary(templates, templateDictionary, authentication).then(resolve);
325
+ }, e => reject(common.fail(e)));
326
+ }, e => reject(common.fail(e)));
327
+ }
328
+ else {
329
+ resolve(null);
330
+ }
331
+ });
332
+ }
333
+ exports._reuseDeployedItems = _reuseDeployedItems;
334
+ /**
335
+ * Search for existing items and update the templateDictionary with key details
336
+ *
337
+ * Subtle difference between _reuseDeployedItems and _useExistingItems
338
+ * _reuseDeployedItems: will search all existing items based on specific type keywords
339
+ * that would have been added by a previous deployment
340
+ * _useExistingItems: will search for an existing item that the user provided
341
+ * the item id for while configuring in the deployment app.
342
+ * This type of item would not necessarily have been laid down by a previous deployment and
343
+ * can thus not expect that it will have the type keywords
344
+ *
345
+ * @param templates A collection of AGO item templates
346
+ * @param useExisting Option to search for existing items
347
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
348
+ * @param authentication Credentials for the requests
349
+ *
350
+ * @returns A Promise that will resolve once existing items have been evaluated
351
+ *
352
+ * @private
353
+ */
354
+ function _useExistingItems(templates, useExisting, templateDictionary, authentication) {
355
+ return new Promise(resolve => {
356
+ if (useExisting) {
357
+ const itemDefs = [];
358
+ const sourceIdHash = {};
359
+ const itemIds = [];
360
+ Object.keys(templateDictionary.params).forEach(k => {
361
+ const v = templateDictionary.params[k];
362
+ /* istanbul ignore else */
363
+ if (v.itemId && /[0-9A-F]{32}/i.test(k)) {
364
+ _updateTemplateDictionaryById(templateDictionary, k, v.itemId, v);
365
+ // need to check and set the typeKeyword if it doesn't exist on this service yet
366
+ // when the user has passed in an itemId that does not come from a previous deployment
367
+ itemDefs.push(common.getItemBase(v.itemId, authentication));
368
+ sourceIdHash[v.itemId] = k;
369
+ /* istanbul ignore else */
370
+ if (itemIds.indexOf(k) < 0) {
371
+ itemIds.push(k);
372
+ }
373
+ }
374
+ });
375
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
376
+ _setTypekeywordForExisting(itemDefs, sourceIdHash, authentication).then(() => {
377
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
378
+ _updateTemplateDictionary(itemIds.map(id => common.getTemplateById(templates, id)), templateDictionary, authentication).then(resolve);
379
+ });
380
+ }
381
+ else {
382
+ resolve(null);
383
+ }
384
+ });
385
+ }
386
+ exports._useExistingItems = _useExistingItems;
387
+ /**
388
+ * Verify if the existing item has the source-<itemId> typeKeyword and set it if not
389
+ * This allows items that did not come from deployment to be found for reuse after they
390
+ * have been used once via a custom itemId param
391
+ *
392
+ * @param itemDefs
393
+ * @param sourceIdHash key value pairs..actual itemId is the key and the source itemId is the value
394
+ * @param authentication credentials for the requests
395
+ *
396
+ * @returns a promise to indicate when the requests are complete
397
+ * @private
398
+ */
399
+ function _setTypekeywordForExisting(itemDefs, sourceIdHash, authentication) {
400
+ return new Promise(resolve => {
401
+ if (itemDefs.length > 0) {
402
+ Promise.all(itemDefs).then(results => {
403
+ const itemUpdateDefs = [];
404
+ results.forEach(result => {
405
+ const sourceId = sourceIdHash[result.id];
406
+ /* istanbul ignore else */
407
+ if (result && sourceId && result.typeKeywords) {
408
+ const sourceKeyword = `source-${sourceId}`;
409
+ const typeKeywords = result.typeKeywords;
410
+ /* istanbul ignore else */
411
+ if (typeKeywords.indexOf(sourceKeyword) < 0) {
412
+ typeKeywords.push(sourceKeyword);
413
+ const itemUpdate = { id: result.id, typeKeywords };
414
+ itemUpdateDefs.push(common.updateItem(itemUpdate, authentication));
415
+ }
416
+ }
417
+ });
418
+ // wait for updates to finish before we resolve
419
+ if (itemUpdateDefs.length > 0) {
420
+ Promise.all(itemUpdateDefs).then(resolve, () => resolve(undefined));
421
+ }
422
+ else {
423
+ resolve(undefined);
424
+ }
425
+ }, () => resolve(undefined));
426
+ }
427
+ else {
428
+ resolve(undefined);
429
+ }
430
+ });
431
+ }
432
+ exports._setTypekeywordForExisting = _setTypekeywordForExisting;
433
+ /**
434
+ * Update the templateDictionary with key details by item type
435
+ *
436
+ * @param templates A collection of AGO item templates
437
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
438
+ *
439
+ * @private
440
+ */
441
+ function _updateTemplateDictionary(templates, templateDictionary, authentication) {
442
+ return new Promise(resolve => {
443
+ const defs = [];
444
+ const urls = [];
445
+ const types = [];
446
+ const ids = [];
447
+ templates.forEach(t => {
448
+ const templateInfo = templateDictionary[t.itemId];
449
+ /* istanbul ignore else */
450
+ if (templateInfo && templateInfo.url && templateInfo.itemId) {
451
+ /* istanbul ignore else */
452
+ if (t.item.type === "Feature Service") {
453
+ const enterpriseIDMapping = common.getProp(templateDictionary, `params.${t.itemId}.enterpriseIDMapping`);
454
+ Object.assign(templateDictionary[t.itemId], common.getLayerSettings(common.getLayersAndTables(t), templateInfo.url, templateInfo.itemId, enterpriseIDMapping));
455
+ // if the service has veiws keep track of the fields so we can use them to
456
+ // compare with the view fields
457
+ /* istanbul ignore else */
458
+ if (common.getProp(t, "properties.service.hasViews")) {
459
+ common._updateTemplateDictionaryFields(t, templateDictionary, false);
460
+ }
461
+ }
462
+ // for fs query with its url...for non fs query the item
463
+ // this is to verify situations where we have a stale search index that will
464
+ // say some items exist when they don't really exist
465
+ // searching the services url or with the item id will return an error when this condition occurs
466
+ /* istanbul ignore else */
467
+ if (urls.indexOf(templateInfo.url) < 0) {
468
+ defs.push(t.item.type === "Feature Service"
469
+ ? common.rest_request(templateInfo.url, { authentication })
470
+ : common.getItemBase(templateInfo.itemId, authentication));
471
+ urls.push(templateInfo.url);
472
+ types.push(t.item.type);
473
+ ids.push(templateInfo.itemId);
474
+ }
475
+ }
476
+ });
477
+ if (defs.length > 0) {
478
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
479
+ Promise.all(defs.map(p => p.catch(e => e))).then(results => {
480
+ /* istanbul ignore else */
481
+ if (Array.isArray(results) && results.length > 0) {
482
+ const fieldDefs = [];
483
+ results.forEach((r, i) => {
484
+ // a feature service result will contain a serviceItemId if it was successfully fetched
485
+ if (r.serviceItemId && types[i] === "Feature Service") {
486
+ Object.keys(templateDictionary).forEach(k => {
487
+ const v = templateDictionary[k];
488
+ /* istanbul ignore else */
489
+ if (v.itemId && v.itemId === r.serviceItemId) {
490
+ common.setDefaultSpatialReference(templateDictionary, k, r.spatialReference);
491
+ // keep the extent values from these responses as well
492
+ common.setCreateProp(templateDictionary, `${k}.defaultExtent`, r.fullExtent || r.initialExtent);
493
+ const layerIds = (r.layers || []).map((l) => l.id);
494
+ const tablesIds = (r.tables || []).map((t) => t.id);
495
+ fieldDefs.push(common.getExistingLayersAndTables(urls[i], layerIds.concat(tablesIds), authentication));
496
+ }
497
+ });
498
+ }
499
+ else {
500
+ /* istanbul ignore else */
501
+ if (types[i] === "Feature Service" ||
502
+ common.getProp(r, "response.error")) {
503
+ // if an error is returned we need to clean up the templateDictionary
504
+ templateDictionary = _updateTemplateDictionaryForError(templateDictionary, ids[i]);
505
+ }
506
+ }
507
+ });
508
+ if (fieldDefs.length > 0) {
509
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
510
+ Promise.all(fieldDefs).then(layerTableResult => {
511
+ layerTableResult.forEach(l => {
512
+ l.forEach((ll) => {
513
+ Object.keys(templateDictionary).forEach(k => {
514
+ /* istanbul ignore else */
515
+ if (templateDictionary[k].itemId === ll.serviceItemId) {
516
+ let sourceId = "";
517
+ Object.keys(templateDictionary).some(_k => {
518
+ /* istanbul ignore else */
519
+ if (templateDictionary[_k].itemId === ll.serviceItemId) {
520
+ sourceId = _k;
521
+ return true;
522
+ }
523
+ });
524
+ const enterpriseIDMapping = common.getProp(templateDictionary, `params.${sourceId}.enterpriseIDMapping`);
525
+ if (enterpriseIDMapping) {
526
+ Object.keys(enterpriseIDMapping).forEach(id => {
527
+ if (enterpriseIDMapping[id].toString() ===
528
+ ll.id.toString()) {
529
+ _setFields(templateDictionary, k, id, ll.fields);
530
+ }
531
+ });
532
+ }
533
+ else {
534
+ _setFields(templateDictionary, k, ll.id, ll.fields);
535
+ }
536
+ }
537
+ });
538
+ });
539
+ });
540
+ resolve(null);
541
+ });
542
+ }
543
+ else {
544
+ resolve(null);
545
+ }
546
+ }
547
+ else {
548
+ resolve(null);
549
+ }
550
+ });
551
+ }
552
+ else {
553
+ resolve(null);
554
+ }
555
+ });
556
+ }
557
+ exports._updateTemplateDictionary = _updateTemplateDictionary;
558
+ /**
559
+ * Add the fields from the source layer to the template dictionary for any required replacements
560
+ *
561
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
562
+ * @param itemId the id for the item
563
+ * @param layerId the id for the layer
564
+ * @param fields the fields to transfer
565
+ *
566
+ * @private
567
+ */
568
+ function _setFields(templateDictionary, itemId, layerId, fields) {
569
+ const layerInfo = common.getProp(templateDictionary, `${itemId}.layer${layerId}`);
570
+ /* istanbul ignore else */
571
+ if (layerInfo && fields) {
572
+ layerInfo.fields = fields;
573
+ }
574
+ }
575
+ exports._setFields = _setFields;
576
+ /**
577
+ * In some cases an item id search will return a stale item reference
578
+ * it will subsequently fail when we try to fetch the underlying service.
579
+ *
580
+ * We need to remove the item info that has been added to the template dictionary
581
+ * and treat the item as we do other items that don't already exist on deployment.
582
+ *
583
+ * @param result the service request result
584
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
585
+ *
586
+ * @private
587
+ */
588
+ function _updateTemplateDictionaryForError(templateDictionary, itemId) {
589
+ /* istanbul ignore else */
590
+ if (itemId) {
591
+ let removeKey = "";
592
+ Object.keys(templateDictionary).some(k => {
593
+ /* istanbul ignore else */
594
+ if (templateDictionary[k].itemId === itemId) {
595
+ removeKey = k;
596
+ return true;
597
+ }
598
+ });
599
+ /* istanbul ignore else */
600
+ if (removeKey !== "") {
601
+ delete templateDictionary[removeKey];
602
+ }
603
+ }
604
+ return templateDictionary;
605
+ }
606
+ exports._updateTemplateDictionaryForError = _updateTemplateDictionaryForError;
607
+ /**
608
+ * Optionally search by tags and then update the templateDictionary based on the search results
609
+ *
610
+ * @param existingItemsResponse response object from search by typeKeyword and type
611
+ * @param existingItemIds list of the template ids we have queried
612
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
613
+ * @param authentication Credentials for the request
614
+ * @param addTagQuery Boolean to indicate if a search by tag should happen
615
+ * @returns IFindExistingItemsResponse object with promise that will resolve with an array of results
616
+ * and an array of item ids
617
+ * @private
618
+ */
619
+ function _handleExistingItems(existingItemsResponse, existingItemInfos, templateDictionary, authentication, addTagQuery) {
620
+ // if items are not found by type keyword search by tag
621
+ const existingItemsByTag = [Promise.resolve(null)];
622
+ const existingItemInfosByTag = [undefined];
623
+ /* istanbul ignore else */
624
+ if (existingItemsResponse && Array.isArray(existingItemsResponse)) {
625
+ existingItemsResponse.forEach((existingItem, i) => {
626
+ /* istanbul ignore else */
627
+ if (Array.isArray(existingItem?.results)) {
628
+ let result;
629
+ const results = existingItem.results;
630
+ if (results.length === 1) {
631
+ result = results[0];
632
+ }
633
+ else if (results.length > 1) {
634
+ result = results.reduce((a, b) => a.created > b.created ? a : b);
635
+ }
636
+ else {
637
+ if (addTagQuery && existingItemInfos[i]) {
638
+ const itemInfo = existingItemInfos[i];
639
+ const tagQuery = `tags:source-${itemInfo.itemId} type:${itemInfo.type} owner:${templateDictionary.user.username}`;
640
+ existingItemsByTag.push(_findExistingItem(tagQuery, authentication));
641
+ existingItemInfosByTag.push(existingItemInfos[i]);
642
+ }
643
+ }
644
+ if (result) {
645
+ const sourceId = existingItemInfos[i].itemId;
646
+ /* istanbul ignore else */
647
+ if (sourceId) {
648
+ _updateTemplateDictionaryById(templateDictionary, sourceId, result.id, result);
649
+ }
650
+ }
651
+ }
652
+ });
653
+ }
654
+ return {
655
+ existingItemsDefs: existingItemsByTag,
656
+ existingItemInfos: existingItemInfosByTag
657
+ };
658
+ }
659
+ exports._handleExistingItems = _handleExistingItems;
660
+ //TODO: function doc
661
+ function _updateTemplateDictionaryById(templateDictionary, sourceId, itemId, v) {
662
+ templateDictionary[sourceId] = Object.assign(templateDictionary[sourceId] || {}, {
663
+ def: Promise.resolve(common.generateEmptyCreationResponse(v.type, itemId)),
664
+ itemId,
665
+ name: v.name,
666
+ title: v.title,
667
+ url: v.url
668
+ });
669
+ }
670
+ exports._updateTemplateDictionaryById = _updateTemplateDictionaryById;
671
+ /**
672
+ * Search items based on user query
673
+ *
674
+ * @param templates Templates to examine
675
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
676
+ * @param authentication Credentials for the request
677
+ * @returns IFindExistingItemsResponse object with promise that will resolve with an array of results
678
+ * and an array of item ids
679
+ * @private
680
+ */
681
+ function _findExistingItemByKeyword(templates, templateDictionary, authentication) {
682
+ const existingItemsDefs = [];
683
+ const existingItemInfos = [];
684
+ templates.forEach(template => {
685
+ if (template.item.type === "Group") {
686
+ const userGroups = templateDictionary.user?.groups;
687
+ /* istanbul ignore else */
688
+ if (Array.isArray(userGroups)) {
689
+ existingItemsDefs.push(Promise.resolve({
690
+ results: userGroups
691
+ .filter(g => g.tags.indexOf(`source-${template.itemId}`) > -1 || g.typeKeywords.indexOf(`source-${template.itemId}`) > -1)
692
+ .map(g => {
693
+ g.type = "Group";
694
+ return g;
695
+ }),
696
+ sourceId: template.itemId
697
+ }));
698
+ }
699
+ }
700
+ else {
701
+ existingItemsDefs.push(_findExistingItem(`typekeywords:source-${template.itemId} type:${template.item.type} owner:${templateDictionary.user.username}`, authentication));
702
+ }
703
+ existingItemInfos.push({
704
+ itemId: template.itemId,
705
+ type: template.item.type
706
+ });
707
+ });
708
+ return {
709
+ existingItemsDefs,
710
+ existingItemInfos
711
+ };
712
+ }
713
+ exports._findExistingItemByKeyword = _findExistingItemByKeyword;
714
+ /**
715
+ * Search items based on user query
716
+ *
717
+ * @param query Query string to use
718
+ * @param authentication Credentials for the request
719
+ * @returns A promise that will resolve with an array of results
720
+ * @private
721
+ */
722
+ function _findExistingItem(query, authentication) {
723
+ const searchOptions = {
724
+ q: query,
725
+ authentication: authentication,
726
+ pagingParam: { start: 1, num: 100 }
727
+ };
728
+ return common.searchItems(searchOptions);
729
+ }
730
+ exports._findExistingItem = _findExistingItem;
731
+ /**
732
+ * Creates an item from a template once the item's dependencies have been created.
733
+ *
734
+ * @param template Template of item to deploy
735
+ * @param resourceFilePaths URL, folder, and filename for each item resource/metadata/thumbnail
736
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
737
+ * @param userSession Options for the request
738
+ * @param itemProgressCallback Function for reporting progress updates from type-specific template handlers
739
+ * @returns A promise that will resolve with the id of the deployed item (which is simply returned if it's
740
+ * already in the templates list
741
+ * @private
742
+ */
743
+ function _createItemFromTemplateWhenReady(template, resourceFilePaths, storageAuthentication, templateDictionary, destinationAuthentication, itemProgressCallback) {
744
+ const sourceItemId = template.itemId;
745
+ // ensure this is present
746
+ template.dependencies = template.dependencies || [];
747
+ // if there is no entry in the templateDictionary
748
+ // or if we have a basic entry without the deferred request for its creation, add it
749
+ if (!templateDictionary.hasOwnProperty(template.itemId) ||
750
+ !common.getProp(templateDictionary[template.itemId], "def")) {
751
+ let createResponse;
752
+ let statusCode = common.EItemProgressStatus.Unknown;
753
+ let itemHandler;
754
+ templateDictionary[template.itemId] =
755
+ templateDictionary[template.itemId] || {};
756
+ // Save the deferred for the use of items that depend on this item being created first
757
+ templateDictionary[template.itemId].def = new Promise(resolve => {
758
+ // Wait until all of the item's dependencies are deployed
759
+ const _awaitDependencies = template.dependencies.reduce((acc, id) => {
760
+ const def = common.getProp(templateDictionary, `${id}.def`);
761
+ // can't use maybePush as that clones the object, which does not work for Promises
762
+ /* istanbul ignore else */
763
+ if (def) {
764
+ acc.push(def);
765
+ }
766
+ return acc;
767
+ }, []);
768
+ const syncViews = common.getProp(template, "properties.syncViews");
769
+ const awaitDependencies = syncViews && syncViews.length > 0
770
+ ? syncViews.reduce((acc, v) => {
771
+ const def = common.getProp(templateDictionary, `${v}.def`);
772
+ /* istanbul ignore else */
773
+ if (def) {
774
+ acc.push(def);
775
+ }
776
+ return acc;
777
+ }, _awaitDependencies)
778
+ : _awaitDependencies;
779
+ Promise.all(awaitDependencies)
780
+ .then(() => {
781
+ // Find the conversion handler for this item type
782
+ const templateType = template.type;
783
+ itemHandler = module_map_1.moduleMap[templateType];
784
+ if (!itemHandler || itemHandler === UNSUPPORTED) {
785
+ if (itemHandler === UNSUPPORTED) {
786
+ statusCode = common.EItemProgressStatus.Ignored;
787
+ throw new Error();
788
+ }
789
+ else {
790
+ statusCode = common.EItemProgressStatus.Failed;
791
+ throw new Error();
792
+ }
793
+ }
794
+ // Get the item's thumbnail
795
+ return common.getThumbnailFromStorageItem(storageAuthentication, resourceFilePaths);
796
+ })
797
+ .then(thumbnail => {
798
+ template.item.thumbnail = thumbnail;
799
+ // Delegate the creation of the item to the handler
800
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
801
+ return itemHandler.createItemFromTemplate(template, templateDictionary, destinationAuthentication, itemProgressCallback);
802
+ })
803
+ .then(async (response) => {
804
+ if (response.id === "") {
805
+ statusCode = common.EItemProgressStatus.Failed;
806
+ throw new Error("handled"); // fails to create item
807
+ }
808
+ /* istanbul ignore else */
809
+ createResponse = response;
810
+ if (createResponse.item.item.url) {
811
+ common.setCreateProp(templateDictionary, sourceItemId + ".url", createResponse.item.item.url);
812
+ }
813
+ if (resourceFilePaths.length > 0) {
814
+ const destinationItemId = createResponse.id;
815
+ // Update and copy form resource
816
+ if (template.type === "Form") {
817
+ // Filter out Form zip file
818
+ let formZipFilePath;
819
+ resourceFilePaths = resourceFilePaths.filter((filePath) => {
820
+ if (filePath.filename.endsWith(".zip")) {
821
+ formZipFilePath = filePath;
822
+ return false;
823
+ }
824
+ else {
825
+ return true;
826
+ }
827
+ });
828
+ if (formZipFilePath) {
829
+ // Fetch the form's zip file and detemplatize it
830
+ const zipObject = await common.fetchZipObject(formZipFilePath.url, storageAuthentication);
831
+ const updatedZipObject = await form.swizzleFormObject(zipObject, templateDictionary);
832
+ // Update the new item
833
+ void common.updateItemWithZipObject(updatedZipObject, destinationItemId, destinationAuthentication);
834
+ }
835
+ }
836
+ // Copy resources, metadata
837
+ return common.copyFilesFromStorageItem(storageAuthentication, resourceFilePaths, sourceItemId, templateDictionary.folderId, destinationItemId, destinationAuthentication, createResponse.item);
838
+ }
839
+ else {
840
+ return Promise.resolve(null);
841
+ }
842
+ })
843
+ .then(() => {
844
+ resolve(createResponse);
845
+ })
846
+ .catch(error => {
847
+ if (!error || error.message !== "handled") {
848
+ itemProgressCallback(sourceItemId, statusCode === common.EItemProgressStatus.Unknown
849
+ ? common.EItemProgressStatus.Failed
850
+ : statusCode, 0);
851
+ }
852
+ // Item type not supported or fails to get item dependencies
853
+ resolve(common.generateEmptyCreationResponse(template.type));
854
+ });
855
+ });
856
+ }
857
+ return templateDictionary[sourceItemId].def;
858
+ }
859
+ exports._createItemFromTemplateWhenReady = _createItemFromTemplateWhenReady;
860
+ /**
861
+ * Accumulates the estimated deployment cost of a set of templates.
862
+ *
863
+ * @param templates Templates to examine
864
+ * @returns Sum of estimated deployment costs
865
+ * @private
866
+ */
867
+ function _estimateDeploymentCost(templates) {
868
+ return templates.reduce((accumulatedEstimatedCost, template) => {
869
+ return (accumulatedEstimatedCost + (template.estimatedDeploymentCostFactor || 1));
870
+ }, 0);
871
+ }
872
+ exports._estimateDeploymentCost = _estimateDeploymentCost;
873
+ //TODO: function doc
874
+ // TODO: Return a Promise vs array of promises
875
+ function _getGroupUpdates(template, authentication, templateDictionary) {
876
+ const groups = template.groups || [];
877
+ return groups.map((sourceGroupId) => {
878
+ return common.shareItem(templateDictionary[sourceGroupId].itemId, template.itemId, authentication, common.isTrackingViewTemplate(template) ? templateDictionary.locationTracking.owner : undefined);
879
+ });
880
+ }
881
+ exports._getGroupUpdates = _getGroupUpdates;
882
+ //# sourceMappingURL=deploySolutionItems.js.map