@esri/solution-deployer 6.0.2-alpha.23 → 6.0.2-alpha.250423

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