@esri/solution-workflow 5.2.1 → 5.2.3

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 (53) hide show
  1. package/README.md +3 -6
  2. package/dist/esm/index.js.map +1 -0
  3. package/dist/esm/{workflow/src/workflow.d.ts → workflow.d.ts} +12 -3
  4. package/dist/esm/workflow.js +112 -0
  5. package/dist/esm/workflow.js.map +1 -0
  6. package/package.json +3 -3
  7. package/dist/cjs/common/src/generalHelpers.d.ts +0 -400
  8. package/dist/cjs/common/src/generalHelpers.js +0 -877
  9. package/dist/cjs/common/src/generalHelpers.js.map +0 -1
  10. package/dist/cjs/common/src/getItemTypeAbbrev.d.ts +0 -19
  11. package/dist/cjs/common/src/getItemTypeAbbrev.js +0 -186
  12. package/dist/cjs/common/src/getItemTypeAbbrev.js.map +0 -1
  13. package/dist/cjs/common/src/interfaces.d.ts +0 -1344
  14. package/dist/cjs/common/src/interfaces.js +0 -77
  15. package/dist/cjs/common/src/interfaces.js.map +0 -1
  16. package/dist/cjs/common/src/libConnectors.d.ts +0 -73
  17. package/dist/cjs/common/src/libConnectors.js +0 -115
  18. package/dist/cjs/common/src/libConnectors.js.map +0 -1
  19. package/dist/cjs/common/test/mocks/templates.d.ts +0 -71
  20. package/dist/cjs/common/test/mocks/templates.js +0 -1220
  21. package/dist/cjs/common/test/mocks/templates.js.map +0 -1
  22. package/dist/cjs/common/test/mocks/utils.d.ts +0 -605
  23. package/dist/cjs/common/test/mocks/utils.js +0 -1222
  24. package/dist/cjs/common/test/mocks/utils.js.map +0 -1
  25. package/dist/cjs/workflow/src/index.js +0 -25
  26. package/dist/cjs/workflow/src/index.js.map +0 -1
  27. package/dist/cjs/workflow/src/workflow.d.ts +0 -32
  28. package/dist/cjs/workflow/src/workflow.js +0 -51
  29. package/dist/cjs/workflow/src/workflow.js.map +0 -1
  30. package/dist/esm/common/src/generalHelpers.d.ts +0 -400
  31. package/dist/esm/common/src/generalHelpers.js +0 -829
  32. package/dist/esm/common/src/generalHelpers.js.map +0 -1
  33. package/dist/esm/common/src/getItemTypeAbbrev.d.ts +0 -19
  34. package/dist/esm/common/src/getItemTypeAbbrev.js +0 -182
  35. package/dist/esm/common/src/getItemTypeAbbrev.js.map +0 -1
  36. package/dist/esm/common/src/interfaces.d.ts +0 -1344
  37. package/dist/esm/common/src/interfaces.js +0 -72
  38. package/dist/esm/common/src/interfaces.js.map +0 -1
  39. package/dist/esm/common/src/libConnectors.d.ts +0 -73
  40. package/dist/esm/common/src/libConnectors.js +0 -105
  41. package/dist/esm/common/src/libConnectors.js.map +0 -1
  42. package/dist/esm/common/test/mocks/templates.d.ts +0 -71
  43. package/dist/esm/common/test/mocks/templates.js +0 -1195
  44. package/dist/esm/common/test/mocks/templates.js.map +0 -1
  45. package/dist/esm/common/test/mocks/utils.d.ts +0 -605
  46. package/dist/esm/common/test/mocks/utils.js +0 -1177
  47. package/dist/esm/common/test/mocks/utils.js.map +0 -1
  48. package/dist/esm/workflow/src/index.d.ts +0 -21
  49. package/dist/esm/workflow/src/index.js.map +0 -1
  50. package/dist/esm/workflow/src/workflow.js +0 -45
  51. package/dist/esm/workflow/src/workflow.js.map +0 -1
  52. /package/dist/{cjs/workflow/src → esm}/index.d.ts +0 -0
  53. /package/dist/esm/{workflow/src/index.js → index.js} +0 -0
@@ -1,877 +0,0 @@
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._padPositiveNum = exports._getRandomNumberInRange = exports.regExTest = exports.getTemplateById = exports.cleanLayerId = exports.cleanLayerBasedItemId = exports.cleanItemId = exports.hasDatasource = exports.globalStringReplace = exports.getUniqueTitle = exports.hasTypeKeyword = exports.hasAnyKeyword = exports.getUTCTimestamp = exports.setProp = exports.setCreateProp = exports.idTest = exports.getPropWithDefault = exports.getProps = exports.getProp = exports.getIDs = exports.getSubgroupIds = exports.failWithIds = exports.fail = exports.deleteProps = exports.deleteProp = exports.deleteItemProps = exports.sanitizeJSONAndReportChanges = exports.compareJSONProperties = exports.compareJSONNoEmptyStrings = exports.compareJSON = exports.cloneObject = exports.saveBlobAsFile = exports.jsonToJson = exports.jsonToFile = exports.jsonToBlob = exports.generateEmptyCreationResponse = exports.dedupe = exports.createShortId = exports.createLongId = exports.convertIModel = exports.checkUrlPathTermination = exports.blobToText = exports.blobToFile = exports.blobToJson = exports.appendQueryParam = void 0;
19
- /**
20
- * Provides general helper functions.
21
- *
22
- * @module generalHelpers
23
- */
24
- const hub_common_1 = require("@esri/hub-common");
25
- const libConnectors_1 = require("./libConnectors");
26
- // ------------------------------------------------------------------------------------------------------------------ //
27
- /**
28
- * Returns a URL with a query parameter appended
29
- *
30
- * @param url URL to append to
31
- * @param parameter Query parameter to append, prefixed with "?" or "&" as appropriate to what url already has
32
- * @returns New URL combining url and parameter
33
- */
34
- function appendQueryParam(url, parameter) {
35
- return url + (url.indexOf("?") === -1 ? "?" : "&") + parameter;
36
- }
37
- exports.appendQueryParam = appendQueryParam;
38
- /**
39
- * Extracts JSON from a Blob.
40
- *
41
- * @param blob Blob to use as source
42
- * @returns A promise that will resolve with JSON or null
43
- */
44
- function blobToJson(blob) {
45
- return new Promise(resolve => {
46
- blobToText(blob).then(blobContents => {
47
- try {
48
- resolve(JSON.parse(blobContents));
49
- }
50
- catch (err) {
51
- resolve(null);
52
- }
53
- }, () => resolve(null));
54
- });
55
- }
56
- exports.blobToJson = blobToJson;
57
- /**
58
- * Converts a Blob to a File.
59
- *
60
- * @param blob Blob to use as source
61
- * @param filename Name to use for file
62
- * @param mimeType MIME type to override blob's MIME type
63
- * @returns File created out of Blob and filename
64
- */
65
- function blobToFile(blob, filename, mimeType) {
66
- return new File([blob], filename ? filename : "", {
67
- type: mimeType ?? blob.type // Blobs default to type=""
68
- });
69
- }
70
- exports.blobToFile = blobToFile;
71
- /**
72
- * Extracts text from a Blob.
73
- *
74
- * @param blob Blob to use as source
75
- * @returns A promise that will resolve with text read from blob
76
- */
77
- function blobToText(blob) {
78
- return new Promise(resolve => {
79
- const reader = new FileReader();
80
- reader.onload = function (evt) {
81
- // Disable needed because Node requires cast
82
- const blobContents = evt.target.result;
83
- resolve(blobContents ? blobContents : ""); // not handling ArrayContents variant
84
- };
85
- reader.readAsText(blob);
86
- });
87
- }
88
- exports.blobToText = blobToText;
89
- /**
90
- * Checks that a URL path ends with a slash.
91
- *
92
- * @param url URL to check
93
- * @returns URL, appended with slash if missing
94
- */
95
- function checkUrlPathTermination(url) {
96
- return url ? (url.endsWith("/") ? url : url + "/") : url;
97
- }
98
- exports.checkUrlPathTermination = checkUrlPathTermination;
99
- /**
100
- * Converts a hub-style item into a solutions-style item, the difference being handling of resources.
101
- *
102
- * @param hubModel Hub-style item
103
- * @return solutions-style item
104
- */
105
- function convertIModel(hubModel) {
106
- const item = {
107
- ...hubModel
108
- };
109
- item.resources = hubModel?.resources ? Object.values(hubModel.resources) : [];
110
- return item;
111
- }
112
- exports.convertIModel = convertIModel;
113
- /**
114
- * Creates a random 32-character alphanumeric string.
115
- *
116
- * @returns A lowercase 32-char alphanumeric string
117
- * @internal
118
- */
119
- function createLongId() {
120
- // createId gets a random number, converts it to base 36 representation, then grabs chars 2-8
121
- return (0, hub_common_1.createId)("") + (0, hub_common_1.createId)("") + (0, hub_common_1.createId)("") + (0, hub_common_1.createId)("");
122
- }
123
- exports.createLongId = createLongId;
124
- /**
125
- * Creates a random 8-character alphanumeric string that begins with an alphabetic character.
126
- *
127
- * @returns An alphanumeric string in the range [a0000000..zzzzzzzz]
128
- */
129
- function createShortId() {
130
- // Return a random number, but beginning with an alphabetic character so that it can be used as a valid
131
- // dotable property name. Used for unique identifiers that do not require the rigor of a full UUID -
132
- // i.e. node ids, process ids, etc.
133
- const min = 0.2777777777777778; // 0.a in base 36
134
- const max = 0.9999999999996456; // 0.zzzzzzzz in base 36
135
- return (_getRandomNumberInRange(min, max).toString(36) + "0000000").substr(2, 8);
136
- }
137
- exports.createShortId = createShortId;
138
- /**
139
- * Copies an input list removing duplicates.
140
- *
141
- * @param input List to be deduped
142
- * @returns Deduped list; order of items in input is not maintained
143
- */
144
- function dedupe(input = []) {
145
- if (input.length === 0) {
146
- return [];
147
- }
148
- const dedupedList = new Set(input);
149
- const output = [];
150
- dedupedList.forEach((value) => output.push(value));
151
- return output;
152
- }
153
- exports.dedupe = dedupe;
154
- /**
155
- * Flags a failure to create an item from a template.
156
- *
157
- * @param itemType The AGO item type
158
- * @param id Item id to include in response
159
- * @returns Empty creation response
160
- */
161
- function generateEmptyCreationResponse(itemType, id = "") {
162
- return {
163
- item: null,
164
- id,
165
- type: itemType,
166
- postProcess: false
167
- };
168
- }
169
- exports.generateEmptyCreationResponse = generateEmptyCreationResponse;
170
- /**
171
- * Converts JSON to a Blob.
172
- *
173
- * @param json JSON to use as source
174
- * @returns A blob from the source JSON
175
- */
176
- function jsonToBlob(json) {
177
- const uint8array = new TextEncoder().encode(JSON.stringify(json));
178
- const blobOptions = { type: "application/octet-stream" };
179
- return new Blob([uint8array], blobOptions);
180
- }
181
- exports.jsonToBlob = jsonToBlob;
182
- /**
183
- * Converts JSON to a File.
184
- *
185
- * @param json JSON to use as source
186
- * @param filename Name to use for file
187
- * @param mimeType MIME type to override blob's MIME type
188
- * @returns File created out of JSON and filename
189
- */
190
- function jsonToFile(json, filename, mimeType = "application/json") {
191
- return blobToFile(jsonToBlob(json), filename, mimeType);
192
- }
193
- exports.jsonToFile = jsonToFile;
194
- /**
195
- * Makes a unique copy of JSON by stringifying and parsing.
196
- *
197
- * @param json JSON to use as source
198
- * @returns A JSON object from the source JSON
199
- */
200
- function jsonToJson(json) {
201
- return JSON.parse(JSON.stringify(json));
202
- }
203
- exports.jsonToJson = jsonToJson;
204
- /**
205
- * Saves a blob to a file.
206
- *
207
- * @param filename Name to give file
208
- * @param blob Blob to save
209
- * @returns Promise resolving when operation is complete
210
- */
211
- // Function is only used for live testing, so excluding it from coverage for now
212
- /* istanbul ignore next */
213
- function saveBlobAsFile(filename, blob) {
214
- return new Promise(resolve => {
215
- const dataUrl = URL.createObjectURL(blob);
216
- const linkElement = document.createElement("a");
217
- linkElement.setAttribute("href", dataUrl);
218
- linkElement.setAttribute("download", filename);
219
- linkElement.style.display = "none";
220
- document.body.appendChild(linkElement);
221
- linkElement.click();
222
- document.body.removeChild(linkElement);
223
- setTimeout(() => {
224
- URL.revokeObjectURL(dataUrl);
225
- resolve(null);
226
- }, 500);
227
- });
228
- }
229
- exports.saveBlobAsFile = saveBlobAsFile;
230
- /**
231
- * Makes a deep clone, including arrays but not functions.
232
- *
233
- * @param obj Object to be cloned
234
- * @returns Clone of obj
235
- * @example
236
- * ```js
237
- * import { cloneObject } from "utils/object-helpers";
238
- * const original = { foo: "bar" }
239
- * const copy = cloneObject(original)
240
- * copy.foo // "bar"
241
- * copy === original // false
242
- * ```
243
- */
244
- function cloneObject(obj) {
245
- let clone = {};
246
- // first check array
247
- if (Array.isArray(obj)) {
248
- clone = obj.map(cloneObject);
249
- }
250
- else if (typeof obj === "object") {
251
- if (obj instanceof File) {
252
- const fileOptions = obj.type ? { type: obj.type } : undefined;
253
- clone = new File([obj], obj.name, fileOptions);
254
- }
255
- else {
256
- for (const i in obj) {
257
- if (obj[i] != null && typeof obj[i] === "object") {
258
- clone[i] = cloneObject(obj[i]);
259
- }
260
- else {
261
- clone[i] = obj[i];
262
- }
263
- }
264
- }
265
- }
266
- else {
267
- clone = obj;
268
- }
269
- return clone;
270
- }
271
- exports.cloneObject = cloneObject;
272
- /**
273
- * Compares two JSON objects using JSON.stringify.
274
- *
275
- * @param json1 First object
276
- * @param json2 Second object
277
- * @returns True if objects are the same
278
- */
279
- function compareJSON(json1, json2) {
280
- return JSON.stringify(json1) === JSON.stringify(json2);
281
- }
282
- exports.compareJSON = compareJSON;
283
- /**
284
- * Compares two JSON objects using JSON.stringify, converting empty strings to nulls.
285
- *
286
- * @param json1 First object
287
- * @param json2 Second object
288
- * @returns True if objects are the same
289
- */
290
- function compareJSONNoEmptyStrings(json1, json2) {
291
- const jsonStr1 = JSON.stringify(json1).replace(/":""/g, '":null');
292
- const jsonStr2 = JSON.stringify(json2).replace(/":""/g, '":null');
293
- return jsonStr1 === jsonStr2;
294
- }
295
- exports.compareJSONNoEmptyStrings = compareJSONNoEmptyStrings;
296
- /**
297
- * Compares two JSON objects property by property and reports each mismatch.
298
- *
299
- * @param json1 First object
300
- * @param json2 Second object
301
- * @returns A list of mismatch report strings
302
- */
303
- function compareJSONProperties(json1, json2) {
304
- let mismatches = [];
305
- const type1 = _typeof_null(json1);
306
- const type2 = _typeof_null(json2);
307
- if (type1 !== type2) {
308
- // Ignore "undefined" vs. "null" and vice versa
309
- /* istanbul ignore else */
310
- if ((type1 !== "undefined" && type1 !== "null") ||
311
- (type2 !== "null" && type2 !== "undefined")) {
312
- mismatches.push("Type difference: " + type1 + " vs. " + type2);
313
- }
314
- }
315
- else {
316
- if (json1 !== json2) {
317
- switch (type1) {
318
- case "boolean":
319
- mismatches.push("Value difference: " + json1 + " vs. " + json2);
320
- break;
321
- case "number":
322
- mismatches.push("Value difference: " + json1 + " vs. " + json2);
323
- break;
324
- case "string":
325
- mismatches.push('String difference: "' + json1 + '" vs. "' + json2 + '"');
326
- break;
327
- case "object":
328
- const keys1 = Object.keys(json1);
329
- const keys2 = Object.keys(json2);
330
- if (keys1.length !== keys2.length ||
331
- JSON.stringify(keys1) !== JSON.stringify(keys2)) {
332
- if (Array.isArray(json1) && Array.isArray(json2)) {
333
- mismatches.push("Array length difference: [" +
334
- keys1.length +
335
- "] vs. [" +
336
- keys2.length +
337
- "]");
338
- }
339
- else {
340
- mismatches.push("Props difference: " +
341
- JSON.stringify(keys1) +
342
- " vs. " +
343
- JSON.stringify(keys2));
344
- }
345
- }
346
- else {
347
- for (let k = 0; k < keys1.length; ++k) {
348
- const submismatches = compareJSONProperties(json1[keys1[k]], json2[keys2[k]]);
349
- if (submismatches.length > 0) {
350
- mismatches = mismatches.concat(submismatches);
351
- }
352
- }
353
- }
354
- break;
355
- }
356
- }
357
- }
358
- return mismatches;
359
- }
360
- exports.compareJSONProperties = compareJSONProperties;
361
- /**
362
- * Sanitizes JSON and echoes changes to console.
363
- *
364
- * @param json JSON to sanitize
365
- * @param sanitizer Instance of Sanitizer class
366
- * @returns Sanitized version of `json`
367
- * @see https://github.com/esri/arcgis-html-sanitizer#sanitize-json
368
- */
369
- function sanitizeJSONAndReportChanges(json, sanitizer) {
370
- const sanitizedJSON = (0, libConnectors_1.sanitizeJSON)(json, sanitizer);
371
- const mismatches = compareJSONProperties(json, sanitizedJSON);
372
- if (mismatches.length > 0) {
373
- console.warn("Changed " +
374
- mismatches.length +
375
- (mismatches.length === 1 ? " property" : " properties"));
376
- mismatches.forEach(mismatch => console.warn(" " + mismatch));
377
- }
378
- return sanitizedJSON;
379
- }
380
- exports.sanitizeJSONAndReportChanges = sanitizeJSONAndReportChanges;
381
- function deleteItemProps(itemTemplate) {
382
- const propsToRetain = [
383
- "accessInformation",
384
- "appCategories",
385
- "banner",
386
- "categories",
387
- "culture",
388
- "description",
389
- "documentation",
390
- "extent",
391
- "groupDesignations",
392
- "industries",
393
- "languages",
394
- "licenseInfo",
395
- "listed",
396
- "name",
397
- "properties",
398
- "proxyFilter",
399
- "screenshots",
400
- "size",
401
- "snippet",
402
- "spatialReference",
403
- "tags",
404
- "title",
405
- "type",
406
- "typeKeywords",
407
- "url"
408
- ];
409
- const propsToDelete = Object.keys(itemTemplate).filter(k => propsToRetain.indexOf(k) < 0);
410
- deleteProps(itemTemplate, propsToDelete);
411
- return itemTemplate;
412
- }
413
- exports.deleteItemProps = deleteItemProps;
414
- /**
415
- * Deletes a property from an object.
416
- *
417
- * @param obj Object with property to delete
418
- * @param path Path into an object to property, e.g., "data.values.webmap", where "data" is a top-level property
419
- * in obj
420
- */
421
- function deleteProp(obj, path) {
422
- const pathParts = path.split(".");
423
- if (Array.isArray(obj)) {
424
- obj.forEach((child) => deleteProp(child, path));
425
- }
426
- else {
427
- const subpath = pathParts.slice(1).join(".");
428
- if (typeof obj[pathParts[0]] !== "undefined") {
429
- if (pathParts.length === 1) {
430
- delete obj[path];
431
- }
432
- else {
433
- deleteProp(obj[pathParts[0]], subpath);
434
- }
435
- }
436
- }
437
- }
438
- exports.deleteProp = deleteProp;
439
- /**
440
- * Deletes properties from an object.
441
- *
442
- * @param obj Object with properties to delete
443
- * @param props Array of properties on object that should be deleted
444
- */
445
- function deleteProps(obj, props) {
446
- props.forEach(prop => {
447
- deleteProp(obj, prop);
448
- });
449
- }
450
- exports.deleteProps = deleteProps;
451
- /**
452
- * Creates an AGO-style JSON failure response with success property.
453
- *
454
- * @param e Optional error information
455
- * @returns JSON structure with property success set to false and optionally including `e`
456
- */
457
- function fail(e) {
458
- if (e) {
459
- return { success: false, error: e.response?.error || e.error || e };
460
- }
461
- else {
462
- return { success: false };
463
- }
464
- }
465
- exports.fail = fail;
466
- /**
467
- * Creates an AGO-style JSON failure response with success property and extended with ids list.
468
- *
469
- * @param ids List of ids
470
- * @param e Optional error information
471
- * @returns JSON structure with property success set to false and optionally including `e`
472
- */
473
- function failWithIds(itemIds, e) {
474
- if (e) {
475
- return { success: false, itemIds, error: e.error || e };
476
- }
477
- else {
478
- return { success: false, itemIds };
479
- }
480
- }
481
- exports.failWithIds = failWithIds;
482
- /**
483
- * Extracts subgroup ids from item tags
484
- *
485
- * @param tags Tags in an item
486
- * @returns List of subgroup ids; subgroups are identified using tags that begin with "group." and end with a group id,
487
- * e.g., "group.8d515625ee9f49d7b4f6c6cb2a389151"; non-matching tags are ignored
488
- */
489
- function getSubgroupIds(tags) {
490
- if (tags) {
491
- const containedGroupPrefix = "group.";
492
- return tags
493
- .filter(tag => tag.startsWith(containedGroupPrefix))
494
- .map(tag => tag.substring(containedGroupPrefix.length));
495
- }
496
- else {
497
- return [];
498
- }
499
- }
500
- exports.getSubgroupIds = getSubgroupIds;
501
- /**
502
- * Extracts the ids from a string
503
- *
504
- * @param v String to examine
505
- * @returns List of id strings found
506
- * @example
507
- * get id from
508
- * bad3483e025c47338d43df308c117308
509
- * {bad3483e025c47338d43df308c117308
510
- * =bad3483e025c47338d43df308c117308
511
- * do not get id from
512
- * http: *something/name_bad3483e025c47338d43df308c117308
513
- * {{bad3483e025c47338d43df308c117308.itemId}}
514
- * bad3483e025c47338d43df308c117308bad3483e025c47338d43df308c117308
515
- */
516
- function getIDs(v) {
517
- // lookbehind is not supported in safari
518
- // cannot use /(?<!_)(?<!{{)\b[0-9A-F]{32}/gi
519
- // use groups and filter out the ids that start with {{
520
- return regExTest(v, /({*)(\b[0-9A-F]{32}\b)/gi).reduce(function (acc, _v) {
521
- /* istanbul ignore else */
522
- if (_v.indexOf("{{") < 0) {
523
- acc.push(_v.replace("{", ""));
524
- }
525
- return acc;
526
- }, []);
527
- }
528
- exports.getIDs = getIDs;
529
- /**
530
- * Gets a property out of a deeply nested object.
531
- * Does not handle anything but nested object graph
532
- *
533
- * @param obj Object to retrieve value from
534
- * @param path Path into an object, e.g., "data.values.webmap", where "data" is a top-level property
535
- * in obj
536
- * @returns Value at end of path
537
- */
538
- function getProp(obj, path) {
539
- return path.split(".").reduce(function (prev, curr) {
540
- /* istanbul ignore next no need to test undefined scenario */
541
- return prev ? prev[curr] : undefined;
542
- }, obj);
543
- }
544
- exports.getProp = getProp;
545
- /**
546
- * Returns an array of values from an object based on an array of property paths.
547
- *
548
- * @param obj Object to retrieve values from
549
- * @param props Array of paths into the object e.g., "data.values.webmap", where "data" is a top-level property
550
- * @returns Array of the values plucked from the object; only defined values are returned
551
- */
552
- function getProps(obj, props) {
553
- return props.reduce((a, p) => {
554
- const v = getProp(obj, p);
555
- if (v) {
556
- a.push(v);
557
- }
558
- return a;
559
- }, []);
560
- }
561
- exports.getProps = getProps;
562
- /**
563
- * Get a property out of a deeply nested object
564
- * Does not handle anything but nested object graph
565
- *
566
- * @param obj Object to retrieve value from
567
- * @param path Path into an object, e.g., "data.values.webmap", where "data" is a top-level property
568
- * in obj
569
- * @param defaultV Optional value to use if any part of path--including final value--is undefined
570
- * @returns Value at end of path
571
- */
572
- function getPropWithDefault(obj, path, defaultV) {
573
- const value = path.split(".").reduce(function (prev, curr) {
574
- /* istanbul ignore next no need to test undefined scenario */
575
- return prev ? prev[curr] : undefined;
576
- }, obj);
577
- if (typeof value === "undefined") {
578
- return defaultV;
579
- }
580
- else {
581
- return value;
582
- }
583
- }
584
- exports.getPropWithDefault = getPropWithDefault;
585
- /**
586
- * Updates a list of the items dependencies if more are found in the
587
- * provided value.
588
- *
589
- * @param v a string value to check for ids
590
- * @param deps a list of the items dependencies
591
- */
592
- function idTest(v, deps) {
593
- const ids = getIDs(v);
594
- ids.forEach(id => {
595
- /* istanbul ignore else */
596
- if (deps.indexOf(id) === -1) {
597
- deps.push(id);
598
- }
599
- });
600
- }
601
- exports.idTest = idTest;
602
- /**
603
- * Sets a deeply nested property of an object.
604
- * Creates the full path if it does not exist.
605
- *
606
- * @param obj Object to set value of
607
- * @param path Path into an object, e.g., "data.values.webmap", where "data" is a top-level property in obj
608
- * @param value The value to set at the end of the path
609
- */
610
- function setCreateProp(obj, path, value) {
611
- const pathParts = path.split(".");
612
- pathParts.reduce((a, b, c) => {
613
- if (c === pathParts.length - 1) {
614
- a[b] = value;
615
- return value;
616
- }
617
- else {
618
- if (!a[b]) {
619
- a[b] = {};
620
- }
621
- return a[b];
622
- }
623
- }, obj);
624
- }
625
- exports.setCreateProp = setCreateProp;
626
- /**
627
- * Sets a deeply nested property of an object.
628
- * Does nothing if the full path does not exist.
629
- *
630
- * @param obj Object to set value of
631
- * @param path Path into an object, e.g., "data.values.webmap", where "data" is a top-level property in obj
632
- * @param value The value to set at the end of the path
633
- */
634
- function setProp(obj, path, value) {
635
- if (getProp(obj, path)) {
636
- const pathParts = path.split(".");
637
- pathParts.reduce((a, b, c) => {
638
- if (c === pathParts.length - 1) {
639
- a[b] = value;
640
- return value;
641
- }
642
- else {
643
- return a[b];
644
- }
645
- }, obj);
646
- }
647
- }
648
- exports.setProp = setProp;
649
- /**
650
- * Creates a timestamp string using the current UTC date and time.
651
- *
652
- * @returns Timestamp formatted as YYYYMMDD_hhmm_ssmmm, with month one-based and all values padded with zeroes on the
653
- * left as needed (`ssmmm` stands for seconds from 0..59 and milliseconds from 0..999)
654
- * @private
655
- */
656
- function getUTCTimestamp() {
657
- const now = new Date();
658
- return (_padPositiveNum(now.getUTCFullYear(), 4) +
659
- _padPositiveNum(now.getUTCMonth() + 1, 2) +
660
- _padPositiveNum(now.getUTCDate(), 2) +
661
- "_" +
662
- _padPositiveNum(now.getUTCHours(), 2) +
663
- _padPositiveNum(now.getUTCMinutes(), 2) +
664
- "_" +
665
- _padPositiveNum(now.getUTCSeconds(), 2) +
666
- _padPositiveNum(now.getUTCMilliseconds(), 3));
667
- }
668
- exports.getUTCTimestamp = getUTCTimestamp;
669
- /**
670
- * Tests if an object's `item.typeKeywords` or `typeKeywords` properties has any of a set of keywords.
671
- *
672
- * @param jsonObj Object to test
673
- * @param keywords List of keywords to look for in jsonObj
674
- * @returns Boolean indicating result
675
- */
676
- function hasAnyKeyword(jsonObj, keywords) {
677
- const typeKeywords = getProp(jsonObj, "item.typeKeywords") || jsonObj.typeKeywords || [];
678
- return keywords.reduce((a, kw) => {
679
- if (!a) {
680
- a = typeKeywords.includes(kw);
681
- }
682
- return a;
683
- }, false);
684
- }
685
- exports.hasAnyKeyword = hasAnyKeyword;
686
- /**
687
- * Tests if an object's `item.typeKeywords` or `typeKeywords` properties has a specific keyword.
688
- *
689
- * @param jsonObj Object to test
690
- * @param keyword Keyword to look for in jsonObj
691
- * @returns Boolean indicating result
692
- */
693
- function hasTypeKeyword(jsonObj, keyword) {
694
- const typeKeywords = getProp(jsonObj, "item.typeKeywords") || jsonObj.typeKeywords || [];
695
- return typeKeywords.includes(keyword);
696
- }
697
- exports.hasTypeKeyword = hasTypeKeyword;
698
- /**
699
- * Will return the provided title if it does not exist as a property
700
- * in one of the objects at the defined path. Otherwise the title will
701
- * have a numerical value attached.
702
- *
703
- * @param title The root title to test
704
- * @param templateDictionary Hash of the facts
705
- * @param path to the objects to evaluate for potantial name clashes
706
- * @returns string The unique title to use
707
- */
708
- function getUniqueTitle(title, templateDictionary, path) {
709
- title = title ? title.trim() : "_";
710
- const objs = getProp(templateDictionary, path) || [];
711
- const titles = objs.map(obj => {
712
- return obj.title;
713
- });
714
- let newTitle = title;
715
- let i = 0;
716
- while (titles.indexOf(newTitle) > -1) {
717
- i++;
718
- newTitle = title + " " + i;
719
- }
720
- return newTitle;
721
- }
722
- exports.getUniqueTitle = getUniqueTitle;
723
- /**
724
- * Performs string replacement on every string in an object.
725
- *
726
- * @param obj Object to scan and to modify
727
- * @param pattern Search pattern in each string
728
- * @param replacement Replacement for matches to search pattern
729
- * @returns Modified obj is returned
730
- */
731
- function globalStringReplace(obj, pattern, replacement) {
732
- if (obj) {
733
- Object.keys(obj).forEach(prop => {
734
- const propObj = obj[prop];
735
- if (propObj) {
736
- /* istanbul ignore else */
737
- if (typeof propObj === "object") {
738
- globalStringReplace(propObj, pattern, replacement);
739
- }
740
- else if (typeof propObj === "string") {
741
- obj[prop] = obj[prop].replace(pattern, replacement);
742
- }
743
- }
744
- });
745
- }
746
- return obj;
747
- }
748
- exports.globalStringReplace = globalStringReplace;
749
- /**
750
- * Tests if an array of DatasourceInfos has a given item and layer id already.
751
- *
752
- * @param datasourceInfos Array of DatasourceInfos to evaluate
753
- * @param itemId The items id to check for
754
- * @param layerId The layers id to check for
755
- * @returns Boolean indicating result
756
- */
757
- function hasDatasource(datasourceInfos, itemId, layerId) {
758
- return datasourceInfos.some(ds => ds.itemId === itemId && ds.layerId === layerId);
759
- }
760
- exports.hasDatasource = hasDatasource;
761
- /**
762
- * remove templatization from item id to compare
763
- *
764
- * @example
765
- * \{\{934a9ef8efa7448fa8ddf7b13cef0240.itemId\}\}
766
- * returns 934a9ef8efa7448fa8ddf7b13cef0240
767
- */
768
- function cleanItemId(id) {
769
- return id ? id.replace("{{", "").replace(".itemId}}", "") : id;
770
- }
771
- exports.cleanItemId = cleanItemId;
772
- /**
773
- * remove templatization from layer based item id to compare
774
- *
775
- * @example
776
- * \{\{934a9ef8efa7448fa8ddf7b13cef0240.layer0.itemId\}\}
777
- * returns 934a9ef8efa7448fa8ddf7b13cef0240
778
- */
779
- function cleanLayerBasedItemId(id) {
780
- return id
781
- ? id
782
- .replace("{{", "")
783
- .replace(/([.]layer([0-9]|[1-9][0-9])[.](item|layer)Id)[}]{2}/, "")
784
- : id;
785
- }
786
- exports.cleanLayerBasedItemId = cleanLayerBasedItemId;
787
- /**
788
- * remove templatization from layer id to compare
789
- *
790
- * @example
791
- * \{\{934a9ef8efa7448fa8ddf7b13cef0240.layer0.layerId\}\}
792
- * returns 0
793
- */
794
- function cleanLayerId(id) {
795
- return id?.toString()
796
- ? parseInt(id
797
- .toString()
798
- .replace(/[{]{2}.{32}[.]layer/, "")
799
- .replace(/[.]layerId[}]{2}/, ""), 10)
800
- : id;
801
- }
802
- exports.cleanLayerId = cleanLayerId;
803
- /**
804
- * Get template from list of templates by ID
805
- *
806
- * @param templates Array of item templates to search
807
- * @param id of template we are searching for
808
- *
809
- * @returns Template associated with the user provided id argument
810
- */
811
- function getTemplateById(templates, id) {
812
- let template;
813
- templates.some(_template => {
814
- if (_template.itemId === id) {
815
- template = _template;
816
- return true;
817
- }
818
- return false;
819
- });
820
- return template;
821
- }
822
- exports.getTemplateById = getTemplateById;
823
- /**
824
- * Evaluates a value with a regular expression
825
- *
826
- * @param v a string value to test with the expression
827
- * @param ex the regular expresion to test with
828
- * @returns an array of matches
829
- */
830
- function regExTest(v, ex) {
831
- return v && ex.test(v) ? v.match(ex) : [];
832
- }
833
- exports.regExTest = regExTest;
834
- // ------------------------------------------------------------------------------------------------------------------ //
835
- /**
836
- * Creates a random number between two values.
837
- *
838
- * @param min Inclusive minimum desired value
839
- * @param max Non-inclusive maximum desired value
840
- * @returns Random number in the range [min, max)
841
- */
842
- function _getRandomNumberInRange(min, max) {
843
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_number_between_two_values
844
- // © 2006 IvanWills
845
- // MIT license https://opensource.org/licenses/mit-license.php
846
- return Math.random() * (max - min) + min;
847
- }
848
- exports._getRandomNumberInRange = _getRandomNumberInRange;
849
- /**
850
- * Pads the string representation of a number to a minimum width. Requires modern browser.
851
- *
852
- * @param n Number to pad
853
- * @param totalSize Desired *minimum* width of number after padding with zeroes
854
- * @returns Number converted to string and padded on the left as needed
855
- * @private
856
- */
857
- function _padPositiveNum(n, totalSize) {
858
- let numStr = n.toString();
859
- const numPads = totalSize - numStr.length;
860
- if (numPads > 0) {
861
- numStr = "0".repeat(numPads) + numStr; // TODO IE11 does not support repeat()
862
- }
863
- return numStr;
864
- }
865
- exports._padPositiveNum = _padPositiveNum;
866
- /**
867
- * Implements rejected ECMA proposal to change `typeof null` from "object" to "null".
868
- *
869
- * @param value Value whose type is sought
870
- * @returns "null" if `value` is null; `typeof value` otherwise
871
- * @see https://web.archive.org/web/20160331031419/http://wiki.ecmascript.org:80/doku.php?id=harmony:typeof_null
872
- * @private
873
- */
874
- function _typeof_null(value) {
875
- return value === null ? "null" : typeof value;
876
- }
877
- //# sourceMappingURL=generalHelpers.js.map