@qikdev/sdk 0.1.168 → 0.1.169

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 (73) hide show
  1. package/dist/sdk.js +2 -0
  2. package/dist/sdk.js.LICENSE.txt +8 -0
  3. package/package.json +12 -2
  4. package/.gitlab-ci.yml +0 -24
  5. package/.husky/pre-commit +0 -5
  6. package/eslint.config.js +0 -6
  7. package/jsdoc.conf +0 -10
  8. package/public/docs/access.html +0 -3826
  9. package/public/docs/api.html +0 -1356
  10. package/public/docs/auth.html +0 -2180
  11. package/public/docs/cache.html +0 -351
  12. package/public/docs/content.html +0 -2560
  13. package/public/docs/files.html +0 -779
  14. package/public/docs/filter.html +0 -1355
  15. package/public/docs/fonts/Montserrat/Montserrat-Bold.eot +0 -0
  16. package/public/docs/fonts/Montserrat/Montserrat-Bold.ttf +0 -0
  17. package/public/docs/fonts/Montserrat/Montserrat-Bold.woff +0 -0
  18. package/public/docs/fonts/Montserrat/Montserrat-Bold.woff2 +0 -0
  19. package/public/docs/fonts/Montserrat/Montserrat-Regular.eot +0 -0
  20. package/public/docs/fonts/Montserrat/Montserrat-Regular.ttf +0 -0
  21. package/public/docs/fonts/Montserrat/Montserrat-Regular.woff +0 -0
  22. package/public/docs/fonts/Montserrat/Montserrat-Regular.woff2 +0 -0
  23. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.eot +0 -0
  24. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.svg +0 -978
  25. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.ttf +0 -0
  26. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.woff +0 -0
  27. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.woff2 +0 -0
  28. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.eot +0 -0
  29. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.svg +0 -1049
  30. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.ttf +0 -0
  31. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.woff +0 -0
  32. package/public/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.woff2 +0 -0
  33. package/public/docs/index.html +0 -96
  34. package/public/docs/qik.access.js.html +0 -790
  35. package/public/docs/qik.api.js.html +0 -511
  36. package/public/docs/qik.auth.js.html +0 -1006
  37. package/public/docs/qik.cache.js.html +0 -131
  38. package/public/docs/qik.content.js.html +0 -918
  39. package/public/docs/qik.core.js.html +0 -301
  40. package/public/docs/qik.files.js.html +0 -219
  41. package/public/docs/qik.filter.js.html +0 -611
  42. package/public/docs/qik.socket.js.html +0 -416
  43. package/public/docs/qik.system.js.html +0 -117
  44. package/public/docs/qik.utils.js.html +0 -1467
  45. package/public/docs/scripts/collapse.js +0 -20
  46. package/public/docs/scripts/linenumber.js +0 -25
  47. package/public/docs/scripts/nav.js +0 -12
  48. package/public/docs/scripts/polyfill.js +0 -4
  49. package/public/docs/scripts/prettify/Apache-License-2.0.txt +0 -202
  50. package/public/docs/scripts/prettify/lang-css.js +0 -2
  51. package/public/docs/scripts/prettify/prettify.js +0 -28
  52. package/public/docs/scripts/search.js +0 -83
  53. package/public/docs/socket.html +0 -810
  54. package/public/docs/styles/jsdoc.css +0 -765
  55. package/public/docs/styles/prettify.css +0 -79
  56. package/public/docs/system.html +0 -197
  57. package/src/api/qik.access.js +0 -825
  58. package/src/api/qik.api.js +0 -431
  59. package/src/api/qik.auth.js +0 -881
  60. package/src/api/qik.cache.js +0 -63
  61. package/src/api/qik.content.js +0 -839
  62. package/src/api/qik.core.js +0 -245
  63. package/src/api/qik.files.js +0 -186
  64. package/src/api/qik.filter.js +0 -543
  65. package/src/api/qik.geo.js +0 -895
  66. package/src/api/qik.socket.js +0 -358
  67. package/src/api/qik.system.js +0 -49
  68. package/src/api/qik.utils.js +0 -1412
  69. package/src/index.js +0 -20
  70. package/src/version.js +0 -1
  71. package/test/index.spec.js +0 -41
  72. package/test/mocha.opts +0 -0
  73. package/yarn-error.log +0 -3598
@@ -1,1412 +0,0 @@
1
- import _get from 'lodash/get.js';
2
- import _isDate from 'lodash/isDate.js';
3
- import _startsWith from 'lodash/startsWith.js';
4
- import _isObject from 'lodash/isObject.js';
5
- import _camelCase from 'lodash/camelCase.js';
6
- import axios from 'axios';
7
- import { isBrowser, isNode } from 'browser-or-node';
8
-
9
-
10
-
11
- ///////////////////////////////////////////////////////////////////////////////
12
-
13
- const service = {};
14
-
15
- ////////////////////////////////////
16
-
17
- const loadedExternalScripts = {}
18
-
19
-
20
- /**
21
- * A function that dynamically include an external javascript resource
22
- * ensuring that it will only be included once
23
- * @alias utils.loadExternalScript
24
- * @param {String} url The url of the external script
25
- * @return {Promise} A promise that will be resolved once the script has been loaded
26
- * @example
27
- *
28
- * await sdk.utils.loadExternalScript('https://cdn.javascript.com/external/script.js');
29
- */
30
-
31
-
32
- service.loadExternalScript = function(url) {
33
-
34
- // If we already have a promise
35
- if (loadedExternalScripts[url]) {
36
- // return the existing promise
37
- return loadedExternalScripts[url];
38
- }
39
-
40
-
41
- // Create a new promise
42
- const promise = loadedExternalScripts[url] = new Promise(createNewScript);
43
-
44
- function createNewScript(resolve, reject) {
45
-
46
- if (!document) {
47
- delete loadedExternalScripts[url];
48
- return reject('document is undefined')
49
- }
50
-
51
- //////////////////////////////////////
52
-
53
- var script = document.createElement('script');
54
- script.type = 'text/javascript';
55
- script.async = true;
56
- script.onload = function() {
57
- console.log('Loaded external script', url);
58
- return resolve(url);
59
- };
60
- script.src = url;
61
-
62
- // Inject it into the document's <head> tag
63
- document.head.appendChild(script);
64
-
65
- }
66
-
67
- return promise;
68
- }
69
-
70
-
71
- const loadedExternalStyles = {}
72
-
73
-
74
- /**
75
- * A function that dynamically include an external css resource
76
- * ensuring that it will only be included once
77
- * @alias utils.loadExternalStyle
78
- * @param {String} url The url of the external css
79
- * @return {Promise} A promise that will be resolved once the css has been loaded
80
- * @example
81
- *
82
- * await sdk.utils.loadExternalStyle('https://cdn.css.com/external/style.css');
83
- */
84
- service.loadExternalStyle = function(url) {
85
-
86
- const promise = new Promise(createNewScript);
87
-
88
- function createNewScript(resolve, reject) {
89
-
90
- if (!document) {
91
- return reject('document is undefined')
92
- }
93
-
94
- if (loadedExternalStyles[url]) {
95
- return resolve(url);
96
- }
97
-
98
- // Avoid duplicate scripts
99
- loadedExternalStyles[url] = true;
100
-
101
- //////////////////////////////////////
102
-
103
- var script = document.createElement('link');
104
- script.setAttribute('rel', 'stylesheet')
105
- script.setAttribute('type', 'text/css')
106
- script.setAttribute('href', url)
107
- script.onload = function() {
108
- console.log('Loaded external stylesheet', url);
109
- return resolve(url);
110
- };
111
-
112
- // Inject it into the document's <head> tag
113
- document.head.appendChild(script);
114
-
115
- }
116
-
117
- return promise;
118
- }
119
-
120
-
121
- ///////////////////////////////////////////////////////////////////////////////
122
-
123
- service.exists = function(value) {
124
- var isUndefinedOrNull;
125
-
126
- ////////////////////////
127
-
128
- if (Array.isArray(value)) {
129
- return true;
130
- }
131
-
132
- ////////////////////////
133
-
134
- if (value === 0) {
135
- return true;
136
- }
137
-
138
- ////////////////////////
139
-
140
- switch (typeof value) {
141
- case 'undefined':
142
- case 'null':
143
- isUndefinedOrNull = true;
144
- break;
145
- default:
146
- var string = String(value).toLowerCase();
147
- switch (string) {
148
- case '':
149
- case 'undefined':
150
- case 'null':
151
- isUndefinedOrNull = true;
152
- break;
153
- }
154
- break;
155
- }
156
-
157
- return !!!isUndefinedOrNull;
158
- }
159
-
160
- //////////////////////////////////
161
-
162
- service.parseDate = function(input) {
163
-
164
- if (!input) {
165
- return;
166
- }
167
-
168
- if (_isDate(input)) {
169
- return input;
170
- }
171
-
172
- //Attempt to create a date
173
- var d = new Date(input);
174
- var isValid = d instanceof Date && !isNaN(d);
175
-
176
- if (isValid) {
177
- return d;
178
- }
179
-
180
- return;
181
- }
182
-
183
- service.parseURL = function(string) {
184
-
185
- if (!string) {
186
- return false;
187
- }
188
-
189
- const relative = _startsWith(string, '/');
190
- if (relative) {
191
- return string;
192
- }
193
-
194
- if (_startsWith(string, '://')) {
195
- return string;
196
- }
197
-
198
- if (_startsWith(string, 'mailto:')) {
199
- return string;
200
- }
201
-
202
- if (_startsWith(string, 'tel:')) {
203
- return string;
204
- }
205
-
206
- if (_startsWith(string, 'sms:')) {
207
- return string;
208
- }
209
-
210
- //////////////////////////////////
211
- //If someone entered an email by accident
212
- var email = service.parseEmail(string);
213
- //Convert it to a mailto link
214
- if (email && email === string) {
215
- return `mailto:${email}`
216
- }
217
-
218
- //////////////////////////////////
219
-
220
- const withHttp = string => !/^https?:\/\//i.test(string) ? `http://${string}` : string;
221
- string = withHttp(string);
222
- //TODO: test this more.
223
- string = string.replace(/\s/g, '');
224
-
225
-
226
-
227
-
228
-
229
-
230
- var valid = RegExp('(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-@]*)?(\\#[-a-z\\d_@]*)?$', 'i').test(string);
231
-
232
- if (!valid) {
233
- return false;
234
- }
235
-
236
-
237
-
238
- ///////////////////////////
239
-
240
- return withHttp(string)
241
- }
242
-
243
-
244
- ///////////////////////////////////////////////
245
-
246
- service.parseNumber = function(input, decimalPoints) {
247
- if (!input) {
248
- return 0;
249
- }
250
-
251
- input = Number(input);
252
- if (isNaN(input)) {
253
- return 0;
254
- }
255
-
256
- if (decimalPoints) {
257
- var str = input.toFixed(decimalPoints);
258
- input = service.parseNumber(str);
259
- }
260
-
261
- return input;
262
- }
263
-
264
-
265
- service.isValidEmailAddress = function(email) {
266
-
267
- var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
268
-
269
- if (!email) return false;
270
-
271
- var emailParts = email.split('@');
272
-
273
- if (emailParts.length !== 2) return false
274
-
275
- var account = emailParts[0];
276
- var address = emailParts[1];
277
-
278
- if (account.length > 64) return false
279
-
280
- else if (address.length > 255) return false
281
-
282
- var domainParts = address.split('.');
283
- if (domainParts.some(function(part) {
284
- return part.length > 63;
285
- })) return false;
286
-
287
-
288
- if (!tester.test(email)) return false;
289
-
290
- return true;
291
- }
292
-
293
-
294
- service.parseEmail = function(input) {
295
-
296
- if (!input) {
297
- return false;
298
- }
299
-
300
- var lowercase = String(input).toLowerCase();
301
- var valid = service.isValidEmailAddress(lowercase);
302
-
303
- if (!valid) {
304
- return false;
305
- } else {
306
- return lowercase;
307
- }
308
- }
309
-
310
- //////////////////////////////////
311
-
312
- service.parseInt = function(input) {
313
- if (!input) {
314
- return 0;
315
- }
316
-
317
- input = parseInt(input);
318
- if (isNaN(input)) {
319
- return 0;
320
- }
321
-
322
- return input;
323
- }
324
-
325
-
326
-
327
- service.cleanValue = function(data, type, options) {
328
-
329
- if (!options) {
330
- options = {};
331
- }
332
-
333
- ////////////////////////
334
-
335
- var noInputValue = service.exists(data);
336
- if (options.strict && noInputValue && type != 'boolean') {
337
- return data;
338
- }
339
-
340
- ////////////////////////
341
-
342
- switch (type) {
343
- case 'reference':
344
- return service.id(data, true);
345
- break;
346
- case 'boolean':
347
- return service.parseBoolean(data);
348
- break;
349
- case 'url':
350
- return service.parseURL(data);
351
- break;
352
- case 'key':
353
- return service.machineName(data);
354
- break;
355
- case 'email':
356
- return service.parseEmail(data);
357
- break;
358
- case 'date':
359
- var parsed = service.parseDate(data, options);
360
-
361
- if (parsed === undefined) {
362
- return;
363
- } else {
364
- return parsed;
365
- }
366
- break;
367
- case 'number':
368
- case 'decimal':
369
- case 'float':
370
- var val = service.parseNumber(data);
371
- if (String(val) == String(Number(data))) {
372
- return val;
373
- }
374
- return;
375
- break;
376
- case 'integer':
377
- var val = service.parseInt(data);
378
- if (String(val) == String(parseInt(data))) {
379
- return val;
380
- }
381
- return;
382
- break;
383
- case 'group':
384
- return data;
385
- break;
386
- case 'object':
387
- if (_isObject(data) && !Array.isArray(data)) {
388
- return data
389
- }
390
-
391
- return;
392
- break;
393
- case 'string':
394
- if (service.exists(data)) {
395
- var stringed = String(data);
396
- if (stringed == '[object Object]') {
397
- return;
398
- }
399
-
400
- return stringed
401
- } else {
402
- return;
403
- }
404
-
405
- // if(!data) {
406
- // return '';
407
- // }
408
-
409
- // if(Array.isArray(data)) {
410
- // return JSON.stringify(data);
411
- // }
412
-
413
- // if(Object.isObject(data)) {
414
- // return JSON.stringify(data);
415
- // }
416
-
417
- // return String(data);
418
-
419
- // break;
420
- default:
421
- return String(data)
422
- break;
423
- }
424
- }
425
-
426
-
427
-
428
- service.isValidValue = function(value, dataType, strict) {
429
-
430
- var isValue = service.exists(value);
431
- var valueIsNumber = (typeof value == 'number')
432
-
433
- ////////////////////////
434
-
435
- var isValidEntry = false;
436
-
437
- if (!isValue) {
438
- return false;
439
- }
440
-
441
- ////////////////////////
442
-
443
- switch (dataType) {
444
-
445
- case 'url':
446
- if (strict) {
447
- isValidEntry = _startsWith(value, '/') || _startsWith(value, '://') || _startsWith(value, 'http://') || _startsWith(value, 'https://');
448
- } else {
449
- isValidEntry = String(value) === service.parseURL(value);
450
- }
451
- break;
452
- case 'key':
453
- isValidEntry = String(value) === service.machineName(value);
454
- break;
455
- case 'date':
456
-
457
- //If we are being strict
458
- if (strict) {
459
- //And the input is not a javascript date object
460
- if (typeof value != 'object' || !_isDate(value)) {
461
- return false;
462
- }
463
- }
464
-
465
- ///////////////////////////////
466
- var parsed = service.parseDate(value);
467
- return parsed !== undefined;
468
- break;
469
- case 'email':
470
-
471
- if (strict) {
472
- isValidEntry = value === service.parseEmail(value);
473
- } else {
474
- isValidEntry = String(value).toLowerCase() === service.parseEmail(value);
475
- }
476
-
477
- break;
478
- case 'number':
479
- case 'decimal':
480
- case 'float':
481
- if (strict) {
482
- isValidEntry = valueIsNumber && (Number(value) === service.parseNumber(value));
483
- } else {
484
- isValidEntry = Number(value) === service.parseNumber(value);
485
- }
486
- break;
487
- case 'integer':
488
- if (strict) {
489
- isValidEntry = valueIsNumber && (Number(value) === service.parseInt(value));
490
- } else {
491
- isValidEntry = Number(value) === service.parseInt(value);
492
- }
493
- break;
494
- case 'boolean':
495
-
496
- var parsed = service.parseBoolean(value);
497
-
498
- //Only accept true booleans
499
- if (strict) {
500
- if (value === true || value === false) {
501
- isValidEntry = value === parsed;
502
- }
503
- } else {
504
- isValidEntry = parsed === true || parsed === false;
505
- }
506
- break;
507
- case 'reference':
508
- if (strict) {
509
- isValidEntry = String(value) === service.id(value);
510
- } else {
511
- isValidEntry = !!service.id(value);
512
- }
513
- break;
514
- case 'string':
515
- var checkString = String(value);
516
- if (strict) {
517
- if (typeof value != 'string') {
518
- return false;
519
- }
520
- }
521
-
522
- if (checkString == '[object Object]') {
523
- return false;
524
- }
525
-
526
- isValidEntry = true;
527
- break;
528
- // case 'group':
529
- // isValidEntry = _isObject(value);
530
- // break;
531
- case 'object':
532
-
533
-
534
- isValidEntry = _isObject(value) && !Array.isArray(value);
535
- break;
536
- case 'array':
537
- isValidEntry = Array.isArray(value);
538
- break;
539
- }
540
-
541
- ////////////////////////
542
-
543
- return isValidEntry
544
- }
545
-
546
- service.parseBoolean = function(value) {
547
- switch (String(value).toLowerCase()) {
548
- case 'true':
549
- case 'y':
550
- case 'yes':
551
- case '1':
552
- case 't':
553
- value = true;
554
- break;
555
- case 'false':
556
- case 'n':
557
- case 'no':
558
- case '0':
559
- case 'f':
560
- case 'undefined':
561
- case 'null':
562
- case '':
563
- case '-1':
564
- value = false;
565
- break;
566
- }
567
-
568
- return !!value;
569
- }
570
-
571
-
572
-
573
-
574
- ///////////////////////////////////////////////////////////////////////////////
575
-
576
- service.clone = function(input) {
577
- return JSON.parse(JSON.stringify(input));
578
- }
579
-
580
- ///////////////////////////////////////////////////////////////////////////////
581
-
582
- service.mapFields = function(fields, options) {
583
-
584
- if (!options) {
585
- options = {};
586
- }
587
-
588
- //////////////////////////////
589
-
590
- var output = [];
591
- var trail = [];
592
- var titles = [];
593
- var currentDepth = 1;
594
- var depthLimit = options.depth;
595
- var delimiter = options.arrayDelimeter || '[]';
596
-
597
-
598
- //Loop through each field
599
- fields.forEach(mapField);
600
-
601
- //////////////////////////////
602
-
603
- //Recursively map the fields
604
- function mapField(field, i) {
605
- var fieldKey = field.key;
606
- var isGroup = field.type == 'group';
607
- var singleValue = (field.minimum === field.maximum) && field.minimum === 1;
608
- var asObject = field.asObject; // || (isGroup && singleValue);
609
- var isLayout = isGroup && !asObject;
610
-
611
- //////////////////////////////////
612
-
613
- // Whether to clone the field or use the existing reference
614
- var mapped = options.original ? field : service.clone(field);
615
-
616
- mapped.trail = trail.slice();
617
- mapped.trail.push(fieldKey)
618
-
619
- mapped.path = mapped.trail.join('.');
620
- mapped.titles = titles.slice();
621
- mapped.titles.push(field.title || '')
622
-
623
-
624
- const isNotLayoutOrIsAllowed = (!isLayout || options.includeLayout);
625
-
626
- //If its an actual element or we've asked to include
627
- //layout only elements
628
- if (isNotLayoutOrIsAllowed) {
629
- //Add it to the mix
630
- output.push(mapped);
631
- }
632
-
633
- //////////////////////////////////
634
-
635
- //Now see if there are child fields and should we go further
636
- var limitHit = depthLimit && (currentDepth >= depthLimit);
637
-
638
- //If there are child fields for this field
639
- if (field.fields && field.fields.length) {
640
- //If it's just a group with no extra key
641
- if (isLayout) {
642
- //Loop through fields as if they are at the same depth
643
- field.fields.forEach(mapField)
644
- } else {
645
-
646
- //We don't need to traverse any further
647
- //because we hit the limit
648
- if (limitHit) {
649
- return;
650
- }
651
-
652
- //Move down a level and add to the object
653
- //Include the key in the path trail
654
- currentDepth++;
655
-
656
- let injectKey = fieldKey;
657
- if (options.includeArrayDelimeter) {
658
- if (!singleValue) {
659
- injectKey = `${fieldKey}${delimiter}`
660
- }
661
- }
662
- trail.push(injectKey)
663
- titles.push(field.title);
664
-
665
- //Loop through each field
666
- field.fields.forEach(mapField)
667
-
668
- //Move back up a level before we go to the next field
669
- currentDepth--;
670
- trail.pop();
671
- titles.pop();
672
- }
673
-
674
- }
675
-
676
- }
677
-
678
- return output;
679
- }
680
-
681
- ///////////////////////////////////////////////////////////////////////////////
682
-
683
- /**
684
- * A helpful function that can take a keyed object literal and map it to url query string parameters
685
- * @alias utils.mapParameters
686
- * @param {Object} parameters The object you want to transalte
687
- * @return {String} The query string
688
- * @example
689
- * //Returns &this=that&hello=world
690
- * sdk.utils.mapParameters({"this":"that", "hello":"world"})
691
- */
692
- service.mapParameters = function(parameters) {
693
-
694
- parameters = parameters || {}
695
-
696
- var array = [];
697
-
698
- Object.entries(parameters)
699
- .forEach(function([key, value]) {
700
-
701
- if (value === undefined || value === null || value == false) {
702
- return;
703
- }
704
-
705
-
706
-
707
- if (Array.isArray(value)) {
708
- value.forEach(function(v) {
709
- array.push(`${key}=${encodeURIComponent(v)}`);
710
- })
711
- } else {
712
- array.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(value)));
713
- }
714
-
715
- })
716
-
717
- return array.join('&');
718
-
719
- }
720
-
721
- ///////////////////////////////////////////////////////////////////////////////
722
-
723
- /**
724
- * A function that will take an integer and a currency string and return a formatted numeric amount rounded to 2 decimal places
725
- * @alias utils.formatCurrency
726
- * @param {Integer} value The amount in cents
727
- * @param {String} currency The currency to format
728
- * @return {String} The formatted value
729
- * @example
730
- *
731
- * //Returns £10.00
732
- * sdk.utils.formatCurrency(1000, 'gbp');
733
- *
734
- * //Returns $10.00
735
- * sdk.utils.formatCurrency(1000, 'usd');
736
- *
737
- */
738
- service.formatCurrency = function(value, currency, decimalPoints) {
739
-
740
- if (!value || isNaN(value)) {
741
- value = 0;
742
- }
743
-
744
- decimalPoints = decimalPoints || 2;
745
-
746
- var currencyPrefix = service.currencySymbol(currency);
747
- return `${currencyPrefix}${parseFloat(Number(value) / 100).toFixed(decimalPoints)}`;
748
-
749
- }
750
-
751
-
752
-
753
- /**
754
- * A function that will take an id and return the type key
755
- * @alias utils.getTypeFromID
756
- * @param {String} id The id of an object
757
- * @return {String} The key
758
- * @example
759
- *
760
- * // Returns 'user'
761
- * sdk.utils.getTypeFromID('52b523f775beea960013f6cd');
762
- *
763
- * // Returns 'role'
764
- * sdk.utils.getTypeFromID('62b59cb572fb4772e7b5fa93');
765
- *
766
- */
767
- service.getTypeFromID = function(id) {
768
-
769
- id = service.id(id);
770
-
771
- if (!id) {
772
- return;
773
- }
774
-
775
- const lookup = {
776
- "21": "organisation",
777
- "23": "comment",
778
- "24": "persona",
779
- "25": "audio",
780
- "26": "campaign",
781
- "28": "smartlist",
782
- "29": "cache",
783
- "40": "application",
784
- "41": "action",
785
- "42": "billinginvoice",
786
- "43": "componentsnapshot",
787
- "44": "diff",
788
- "45": "email",
789
- "46": "submission",
790
- "49": "import",
791
- "53": "socket",
792
- "54": "timetrigger",
793
- "61": "article",
794
- "63": "component",
795
- "65": "event",
796
- "66": "file",
797
- "67": "tag",
798
- "69": "image",
799
- "70": "profile",
800
- "72": "role",
801
- "73": "scope",
802
- "74": "transaction",
803
- "75": "user",
804
- "76": "video",
805
- "77": "workflowcard",
806
- "78": "variable",
807
- "3c": "patoken",
808
- "7b": "uatoken",
809
- "7d": "urtoken",
810
- "2d": "systemtask",
811
- "3d": "export",
812
- "5f": "systemflag",
813
- "2b": "batch",
814
- "3a": "log",
815
- "2e": "stat",
816
- "2f": "unsubscribe",
817
- "6b": "intent",
818
- "7c": "upload",
819
- "2c": "systemtrigger",
820
- "6e": "interface",
821
- "4e": "interfacesnapshot",
822
- "4f": "notification",
823
- "2a": "definition",
824
- "7e": "definitionsnapshot",
825
- "5e": "integration",
826
- "4c": "listener",
827
- "6d": "topic",
828
- "7a": "code",
829
- "4d": "paymentmethod",
830
- "6c": "sslcertificate"
831
- }
832
-
833
- var hexKey = id.slice(8, 10);
834
- return lookup[hexKey];
835
- }
836
-
837
-
838
- /**
839
- * A function that will take a currency string and return the symbol
840
- * @alias utils.currencySymbol
841
- * @param {String} currency The currency
842
- * @return {String} The symbol
843
- * @example
844
- *
845
- * //Returns £
846
- * sdk.utils.currencySymbol('gbp');
847
- *
848
- * //Returns $
849
- * sdk.utils.currencySymbol('usd');
850
- *
851
- */
852
- service.currencySymbol = function(currency) {
853
- //Ensure lowercase currency
854
- currency = String(currency).toLowerCase();
855
-
856
- switch (String(currency).toLowerCase()) {
857
- case 'gbp':
858
- return '£';
859
- break;
860
- case 'eur':
861
- return '€';
862
- break;
863
- default:
864
- return '$';
865
- break;
866
- }
867
- }
868
-
869
-
870
-
871
- service.getAvailableCurrencies = function(DefaultCountryID) {
872
-
873
-
874
- var array = [];
875
-
876
- array.push({
877
- name: `USD (${service.currencySymbol("usd")})`,
878
- value: "usd",
879
- countryCode: { 'US': true },
880
- });
881
-
882
- array.push({
883
- name: `GBP (${service.currencySymbol("gbp")})`,
884
- value: "gbp",
885
- countryCode: { 'GB': true, 'UK': true },
886
- });
887
-
888
- array.push({
889
- name: `CAD (${service.currencySymbol("cad")})`,
890
- value: "cad",
891
- countryCode: { 'CA': true },
892
- });
893
-
894
- array.push({
895
- name: `AUD (${service.currencySymbol("aud")})`,
896
- value: "aud",
897
- countryCode: { 'AU': true },
898
- });
899
-
900
-
901
- array.push({
902
- name: `NZD (${service.currencySymbol("nzd")})`,
903
- value: "nzd",
904
- countryCode: { 'NZ': true },
905
- });
906
-
907
- array.push({
908
- name: `SGD (${service.currencySymbol("sgd")})`,
909
- value: "sgd",
910
- countryCode: { 'SG': true },
911
- });
912
-
913
-
914
- if (DefaultCountryID) {
915
-
916
- var findMatch = array.findIndex(function(currency) {
917
- return currency.countryCode[DefaultCountryID];
918
- })
919
-
920
- const moveArrayItem = (array, fromIndex, toIndex) => {
921
- const arr = [...array];
922
- arr.splice(toIndex, 0, ...arr.splice(fromIndex, 1));
923
- return arr;
924
- }
925
-
926
- if (findMatch != -1) {
927
- array = moveArrayItem(array, findMatch, 0)
928
- }
929
- }
930
-
931
- return array;
932
- }
933
-
934
- ///////////////////////////////////////////////////////////////////////////////
935
-
936
- /**
937
- * Creates a fast keyed hash object from an array of items
938
- * @alias utils.hash
939
- * @param {Array} array The array of items to convert into a hash
940
- * @param {String} key The key or path to the property on each item to use as the hashed key
941
- * @return {Object} A key/value paired object
942
- * @example
943
- * //Returns { jimbo:{id:'jimbo', title:'Jim Jones'}, {id:'roger', title:'Roger Fellow'} }
944
- * sdk.utils.hash([{id:'jimbo', title:'Jim Jones'}, {id:'roger', title:'Roger Fellow'}], 'id');
945
- *
946
- */
947
- service.hash = function(items, key) {
948
- items = !Array.isArray(items) ? [] : items;
949
- return items.reduce(function(memo, item) {
950
- const k = _get(item, key);
951
- memo[k] = item;
952
- return memo;
953
- }, {});
954
- }
955
-
956
-
957
-
958
-
959
- //////////////////////////////////////////////////
960
-
961
- /**
962
- * Returns a subset of values in an array that match a provided rule
963
- * @alias utils.extractFromArray
964
- * @param {Array} array The array you want to extract values from
965
- * @param {String} key The path to the child property you want to extract
966
- * @param {Boolean} sum Whether to sum the extracted values together in total
967
- * @param {Boolean} flatten Whether to flatten nested child arrays
968
- * @param {Boolean} unique Whether to only return unique values
969
- * @param {Boolean} exclude Whether to exclude null or undefined values
970
- * @param {Object} options Pass through extra options for how to extract the values
971
- * @return {Array} An array of all values retrieved from the array, unless provided arguments require otherwise
972
- * @example
973
- * //Returns [12, 45] as all the values
974
- * sdk.utils.extractFromArray([{name:'Wendy', age:12}, {name:'Roger', age:45}], 'age');
975
- *
976
- * //Returns 32
977
- * sdk.utils.extractFromArray([{name:'Wendy', age:12}, {name:'Roger', age:20}], 'age', {sum:true});
978
- *
979
- */
980
- service.extractFromArray = function(array, key, sum, flatten, unique, exclude, options) {
981
-
982
- options = options || {}
983
-
984
- if (sum) {
985
- options.sum = sum;
986
- }
987
-
988
- if (flatten) {
989
- options.flatten = true;
990
- }
991
-
992
- if (unique) {
993
- options.unique = true;
994
- }
995
-
996
- if (exclude) {
997
- options.excludeNull = true;
998
- }
999
-
1000
- /////////////////
1001
-
1002
- //Filter the array options by a certain value and operator
1003
- var extractedValues = array.reduce(function(set, entry) {
1004
- //Get the value from the object
1005
- var retrievedValue = _get(entry, key);
1006
-
1007
- var isNull = (!retrievedValue && (retrievedValue !== false && retrievedValue !== 0));
1008
- if (options.excludeNull && isNull) {
1009
- return set;
1010
- }
1011
-
1012
- set.push(retrievedValue);
1013
- return set;
1014
- }, [])
1015
-
1016
- if (options.flatten) {
1017
- extractedValues = _.flatten(extractedValues);
1018
- }
1019
-
1020
- if (options.unique) {
1021
- extractedValues = _.uniq(extractedValues);
1022
- }
1023
-
1024
- if (options.sum) {
1025
- extractedValues = extractedValues.reduce(function(a, b) {
1026
- return a + b;
1027
- }, 0);
1028
- }
1029
-
1030
- return extractedValues;
1031
- }
1032
-
1033
-
1034
- //////////////////////////////////////////////////////
1035
-
1036
- /**
1037
- * A function that can return a selection of values that were found in an array that match a specific rule,
1038
- * This is often used to evaluate expressions within form fields
1039
- * @alias utils.matchInArray
1040
- * @param {Array} array The array to check
1041
- * @param {String} key The javascript dot notation path to extract
1042
- * @param {String} value The value to compare against
1043
- * @param {String} comparator The logical operator to use to compare the extracted value with the provided value ('>', '<', '>=', '<=', 'in', '==') Defaults to '==' (Is equal to)
1044
- * @return {Array} Returns an array of matching values
1045
- * @example
1046
- * //Returns [{name:'Michael', age:45}] as that is only item in the array that matches the criteria
1047
- * sdk.utils.matchInArray([{name:'Wendy', age:12}, {name:'Michael', age:45}], 'age', 45, '>=');
1048
- *
1049
- */
1050
- service.matchInArray = function(array, key, v, comparator) {
1051
-
1052
- //Filter the array options by a certain v and comparator
1053
- var matches = array.filter(function(entry) {
1054
- //Get the v from the object
1055
- var extracted = _get(entry, key);
1056
- var found;
1057
-
1058
- switch (comparator) {
1059
- case 'in':
1060
- found = extracted.includes(v);
1061
- break;
1062
- case '>=':
1063
- found = (extracted >= v);
1064
- break;
1065
- case '<=':
1066
- found = (extracted <= v);
1067
- break;
1068
- case '<':
1069
- found = (extracted < v);
1070
- break;
1071
- case '>':
1072
- found = (extracted > v);
1073
- break;
1074
- case '==':
1075
- default:
1076
- if (v === undefined) {
1077
- found = extracted;
1078
- } else {
1079
- found = (extracted == v);
1080
- }
1081
- break;
1082
- }
1083
-
1084
- return found;
1085
- })
1086
-
1087
- return matches;
1088
- }
1089
-
1090
- ///////////////////////////////////////////////////////////////////////////////
1091
-
1092
- /**
1093
- * A helpful class that can take an array of values and return them as a comma seperated
1094
- * string, If the values are objects, then a property to use as the string representation can be specified
1095
- * @alias utils.comma
1096
- * @param {Array} array The array of values to translate
1097
- * @param {String} path An optional property key to use for each value
1098
- * @return {String} The resulting comma seperated string
1099
- * @example
1100
- * //Returns 'cat, dog, bird'
1101
- * sdk.utils.comma(['cat', 'dog', 'bird']);
1102
- *
1103
- * //Returns 'cat, dog, bird'
1104
- * sdk.utils.comma([{title:'cat'}, {title:'dog'}, {title:'bird'}], 'title');
1105
- */
1106
- service.comma = function(array, path, limit) {
1107
-
1108
- if (limit) {
1109
- array = array.slice(0, limit);
1110
- }
1111
-
1112
- return _.chain(array)
1113
- .compact()
1114
- .map(function(item) {
1115
- if (path && path.length) {
1116
- return _get(item, path);
1117
- }
1118
-
1119
- return item;
1120
- })
1121
- .value()
1122
- .join(', ');
1123
- }
1124
-
1125
- ///////////////////////////////////////////////////////////////////////////////
1126
-
1127
- //Helper function to get an id of an object
1128
-
1129
- /**
1130
- * Returns a specified _id for an object
1131
- * @alias utils.id
1132
- * @param {Object} input An object that is or has an _id property
1133
- * @param {Boolean} asObjectID Whether to convert to a Mongo ObjectId
1134
- * @return {String} Will return either a string or a Mongo ObjectId
1135
- *
1136
- * @example
1137
- *
1138
- * //Returns '5cb3d8b3a2219970e6f86927'
1139
- * sdk.utils.id('5cb3d8b3a2219970e6f86927')
1140
- *
1141
- * //Returns true
1142
- * typeof service.id({_id:'5cb3d8b3a2219970e6f86927', title, ...}) == 'string';
1143
-
1144
- * //Returns true
1145
- * typeof service.id({_id:'5cb3d8b3a2219970e6f86927'}, true) == 'object';
1146
- */
1147
- service.id = function(source) {
1148
-
1149
- if (!source) {
1150
- return;
1151
- }
1152
-
1153
- /////////////////////////////////
1154
-
1155
- var output;
1156
-
1157
- if (source._id) {
1158
- output = String(source._id);
1159
- } else {
1160
- output = String(source);
1161
- }
1162
-
1163
-
1164
- var isValid = service.isValidID(output);
1165
- if (!isValid) {
1166
- return;
1167
- }
1168
-
1169
- return output;
1170
- }
1171
-
1172
- ///////////////////////////////////////////////////////////////////////////////
1173
-
1174
- /**
1175
- * Cleans and maps an array of objects to an array of IDs
1176
- * @alias utils.ids
1177
- * @param {Array} array An array of objects or object ids
1178
- * @param {Boolean} asObjectID Whether or not to map the ids as Mongo ObjectIds
1179
- * @return {Array} An array of Ids
1180
- *
1181
- * @example
1182
- * //Returns ['5cb3d8b3a2219970e6f86927', '5cb3d8b3a2219970e6f86927', '5cb3d8b3a2219970e6f86927']
1183
- * sdk.utils.ids([{_id:'5cb3d8b3a2219970e6f86927'}, {_id:'5cb3d8b3a2219970e6f86927'}, null, '5cb3d8b3a2219970e6f86927'])
1184
- */
1185
-
1186
- service.ids = function(array) {
1187
-
1188
- if (!array) {
1189
- return [];
1190
- }
1191
-
1192
- /////////////////////////////////
1193
-
1194
- var ids = Object.keys(array.reduce(function(set, entry) {
1195
-
1196
- if (!entry) {
1197
- return set;
1198
- }
1199
-
1200
- var cleaned = service.id(entry)
1201
-
1202
- if (cleaned) {
1203
- set[cleaned] = 1;
1204
- }
1205
-
1206
- return set;
1207
- }, {}))
1208
-
1209
- ///////////////////////////////
1210
-
1211
- return ids;
1212
- }
1213
-
1214
-
1215
- ///////////////////////////////////////////////////////////////////////////////
1216
-
1217
- service.isValidID = function(input) {
1218
- var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")
1219
- return checkForHexRegExp.test(String(input));
1220
-
1221
- }
1222
-
1223
- ///////////////////////////////////////////////////////////////////////////////
1224
-
1225
- /**
1226
- * Helper function for retrieving a human readable error message from server error response objects
1227
- * @alias utils.errorMessage
1228
- * @param {Object} error The error object to translate
1229
- * @return {String} The resulting human readable error message
1230
- */
1231
- service.errorMessage = function(err) {
1232
-
1233
- if (!err) {
1234
- return;
1235
- }
1236
-
1237
-
1238
- if (Array.isArray(err)) {
1239
- err = err[0];
1240
- }
1241
-
1242
- ////////////////////////////////////
1243
-
1244
-
1245
- var candidates = [
1246
- 'response.data.message',
1247
- 'response.data',
1248
- 'message',
1249
- ]
1250
-
1251
- var message;
1252
-
1253
- candidates.forEach(function(path) {
1254
- if (message) {
1255
- return;
1256
- }
1257
-
1258
- var m = _get(err, path);
1259
- if (m) {
1260
- message = m;
1261
- }
1262
- })
1263
-
1264
- if (Array.isArray(message)) {
1265
- message = message[0];
1266
- }
1267
-
1268
- ////////////////////////////////////
1269
-
1270
- message = message || JSON.stringify(err);
1271
-
1272
- ////////////////////////////////////
1273
-
1274
- return message;
1275
- }
1276
-
1277
- ////////////////////////////////////
1278
-
1279
- /**
1280
- * Generates a globally unique ID, helpful for adding unique keys for iterable loops
1281
- * @alias utils.guid
1282
- * @return {String} The new globally unique identifier
1283
- * @example
1284
- * //Returns 4323a78br-z16h-289j-zwl1-938lda334asd
1285
- * sdk.utils.guid()
1286
- */
1287
- service.guid = function() {
1288
- var u = (new Date()).getTime().toString(16) + Math.random().toString(16).substring(2) + "0".repeat(16);
1289
- return u.substr(0, 8) + '-' + u.substr(8, 4) + '-4000-8' + u.substr(12, 3) + '-' + u.substr(15, 12);
1290
- }
1291
-
1292
-
1293
-
1294
-
1295
- ////////////////////////////////////
1296
- ////////////////////////////////////
1297
- ////////////////////////////////////
1298
-
1299
- /**
1300
- * Helper function for cleaning strings to use as database ids
1301
- * @alias utils.machineName
1302
- * @param {String} string The string to clean eg. (Awesome Event!)
1303
- * @return {String} A cleaned and formatted string eg. (awesomeEvent)
1304
- */
1305
- service.machineName = function(string) {
1306
-
1307
- if (!string || !string.length) {
1308
- return;
1309
- }
1310
-
1311
- var regexp = /[^a-zA-Z0-9-_]+/g;
1312
- var cleaned = String(string).replace(regexp, ' ').trim();
1313
- return _camelCase(cleaned);
1314
- }
1315
-
1316
- /////////////////////////////////////////////
1317
- /////////////////////////////////////////////
1318
- /////////////////////////////////////////////
1319
-
1320
-
1321
- export default service;
1322
-
1323
-
1324
- /////////////////////////////////////////////
1325
-
1326
- //Export the event dispatcher
1327
- export function EventDispatcher() {
1328
-
1329
- var listeners = {};
1330
-
1331
- /////////////////////////////////////////////
1332
-
1333
- var dispatcher = {}
1334
-
1335
- /////////////////////////////////////////////
1336
-
1337
- //Remove all listeners
1338
- dispatcher.removeAllListeners = function() {
1339
- listeners = {};
1340
- }
1341
-
1342
- /////////////////////////////////////////////
1343
-
1344
- dispatcher.dispatch = function(event, details) {
1345
-
1346
- if (listeners[event]) {
1347
- //For each listener
1348
- listeners[event].forEach(function(callback) {
1349
- return callback(details);
1350
- });
1351
- }
1352
- }
1353
-
1354
- /////////////////////////////////////////////
1355
-
1356
- dispatcher.addEventListener = function(event, callback) {
1357
-
1358
- if (!listeners[event]) {
1359
- listeners[event] = [];
1360
- }
1361
-
1362
- const type = typeof callback;
1363
- if (type !== 'function') {
1364
- throw new Error(`addEventListener() requires a function but ${type} was added`);
1365
- } else {
1366
- if (listeners[event].indexOf(callback) == -1) {
1367
- //Add to the listeners
1368
- listeners[event].push(callback)
1369
- } else {
1370
- //A
1371
- //lready listening
1372
- }
1373
- }
1374
- }
1375
-
1376
- /////////////////////////////////////////////
1377
-
1378
- dispatcher.removeEventListener = function(event, callback) {
1379
-
1380
- if (!listeners[event]) {
1381
- listeners[event] = [];
1382
- }
1383
-
1384
- //Get the index of the listener
1385
- var index = listeners[event].indexOf(callback);
1386
-
1387
- if (index != -1) {
1388
- //Remove from the listeners
1389
- listeners[event].splice(index, 1);
1390
- }
1391
- }
1392
-
1393
-
1394
- /////////////////////////////////////////////
1395
-
1396
- //Wrap the event listener functionality
1397
- dispatcher.bootstrap = function(service) {
1398
- if (!service) {
1399
- // console.log('No service to bootstrap to')
1400
- return;
1401
- }
1402
-
1403
- service.dispatch = dispatcher.dispatch;
1404
- service.addEventListener = dispatcher.addEventListener;
1405
- service.removeEventListener = dispatcher.removeEventListener;
1406
- service.removeAllListeners = dispatcher.removeAllListeners;
1407
- }
1408
-
1409
- /////////////////////////////////////////////
1410
-
1411
- return dispatcher;
1412
- }