@kwiz/common 1.0.129 → 1.0.133

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 (111) hide show
  1. package/LICENSE +21 -21
  2. package/lib/cjs/config.js +2 -0
  3. package/lib/cjs/config.js.map +1 -1
  4. package/lib/cjs/types/libs/msal.types.js +26 -26
  5. package/lib/cjs/utils/sharepoint.rest/user.js +11 -11
  6. package/lib/esm/config.js +2 -0
  7. package/lib/esm/config.js.map +1 -1
  8. package/lib/esm/types/libs/msal.types.js +26 -26
  9. package/lib/esm/utils/sharepoint.rest/user.js +11 -11
  10. package/lib/types/config.d.ts +2 -0
  11. package/package.json +81 -81
  12. package/readme.md +17 -17
  13. package/.github/workflows/npm-publish.yml +0 -24
  14. package/.madgerc +0 -3
  15. package/fix-folder-imports.js +0 -27
  16. package/src/_dependencies.ts +0 -13
  17. package/src/config.ts +0 -17
  18. package/src/exports-index.ts +0 -4
  19. package/src/helpers/Guid.ts +0 -182
  20. package/src/helpers/base64.ts +0 -174
  21. package/src/helpers/browser.test.js +0 -13
  22. package/src/helpers/browser.ts +0 -1505
  23. package/src/helpers/browserinfo.ts +0 -293
  24. package/src/helpers/collections.base.test.js +0 -26
  25. package/src/helpers/collections.base.ts +0 -438
  26. package/src/helpers/collections.ts +0 -108
  27. package/src/helpers/color.ts +0 -55
  28. package/src/helpers/cookies.ts +0 -60
  29. package/src/helpers/date.test.js +0 -120
  30. package/src/helpers/date.ts +0 -189
  31. package/src/helpers/debug.ts +0 -187
  32. package/src/helpers/diagrams.ts +0 -44
  33. package/src/helpers/emails.ts +0 -7
  34. package/src/helpers/eval.ts +0 -5
  35. package/src/helpers/exports-index.ts +0 -30
  36. package/src/helpers/file.test.js +0 -51
  37. package/src/helpers/file.ts +0 -64
  38. package/src/helpers/flatted.ts +0 -150
  39. package/src/helpers/functions.ts +0 -17
  40. package/src/helpers/graph/calendar.types.ts +0 -11
  41. package/src/helpers/graph/exports-index.ts +0 -1
  42. package/src/helpers/http.ts +0 -70
  43. package/src/helpers/images.ts +0 -23
  44. package/src/helpers/json.ts +0 -45
  45. package/src/helpers/md5.ts +0 -190
  46. package/src/helpers/objects.test.js +0 -34
  47. package/src/helpers/objects.ts +0 -275
  48. package/src/helpers/promises.test.js +0 -38
  49. package/src/helpers/promises.ts +0 -166
  50. package/src/helpers/random.ts +0 -27
  51. package/src/helpers/scheduler/exports-index.ts +0 -1
  52. package/src/helpers/scheduler/scheduler.test.js +0 -104
  53. package/src/helpers/scheduler/scheduler.ts +0 -132
  54. package/src/helpers/sharepoint.ts +0 -797
  55. package/src/helpers/strings.test.js +0 -123
  56. package/src/helpers/strings.ts +0 -338
  57. package/src/helpers/typecheckers.test.js +0 -35
  58. package/src/helpers/typecheckers.ts +0 -267
  59. package/src/helpers/url.test.js +0 -44
  60. package/src/helpers/url.ts +0 -208
  61. package/src/helpers/urlhelper.ts +0 -112
  62. package/src/index.ts +0 -6
  63. package/src/types/auth.ts +0 -63
  64. package/src/types/common.types.ts +0 -16
  65. package/src/types/exports-index.ts +0 -15
  66. package/src/types/flatted.types.ts +0 -60
  67. package/src/types/globals.types.ts +0 -7
  68. package/src/types/graph/calendar.types.ts +0 -81
  69. package/src/types/graph/exports-index.ts +0 -1
  70. package/src/types/knownscript.types.ts +0 -19
  71. package/src/types/libs/datajs.types.ts +0 -29
  72. package/src/types/libs/exports-index.ts +0 -3
  73. package/src/types/libs/ics.types.ts +0 -31
  74. package/src/types/libs/msal.types.ts +0 -58
  75. package/src/types/locales.ts +0 -126
  76. package/src/types/localstoragecache.types.ts +0 -9
  77. package/src/types/location.types.ts +0 -28
  78. package/src/types/moment.ts +0 -12
  79. package/src/types/regex.types.ts +0 -17
  80. package/src/types/rest.types.ts +0 -96
  81. package/src/types/sharepoint.types.ts +0 -1467
  82. package/src/types/sharepoint.utils.types.ts +0 -307
  83. package/src/utils/auth/common.ts +0 -119
  84. package/src/utils/auth/discovery.test.js +0 -13
  85. package/src/utils/auth/discovery.ts +0 -132
  86. package/src/utils/auth/exports-index.ts +0 -2
  87. package/src/utils/base64.ts +0 -28
  88. package/src/utils/consolelogger.ts +0 -334
  89. package/src/utils/date.ts +0 -173
  90. package/src/utils/emails.ts +0 -25
  91. package/src/utils/exports-index.ts +0 -11
  92. package/src/utils/knownscript.ts +0 -287
  93. package/src/utils/localstoragecache.ts +0 -447
  94. package/src/utils/rest.ts +0 -502
  95. package/src/utils/script.ts +0 -171
  96. package/src/utils/sharepoint.rest/common.ts +0 -160
  97. package/src/utils/sharepoint.rest/date.ts +0 -63
  98. package/src/utils/sharepoint.rest/exports-index.ts +0 -11
  99. package/src/utils/sharepoint.rest/file.folder.ts +0 -685
  100. package/src/utils/sharepoint.rest/item.ts +0 -547
  101. package/src/utils/sharepoint.rest/list.ts +0 -1572
  102. package/src/utils/sharepoint.rest/listutils/GetListItemsByCaml.ts +0 -775
  103. package/src/utils/sharepoint.rest/listutils/GetListItemsById.ts +0 -275
  104. package/src/utils/sharepoint.rest/listutils/common.ts +0 -207
  105. package/src/utils/sharepoint.rest/listutils/exports-index.ts +0 -3
  106. package/src/utils/sharepoint.rest/location.ts +0 -142
  107. package/src/utils/sharepoint.rest/navigation-links.ts +0 -87
  108. package/src/utils/sharepoint.rest/user-search.ts +0 -253
  109. package/src/utils/sharepoint.rest/user.ts +0 -559
  110. package/src/utils/sharepoint.rest/web.ts +0 -1385
  111. package/src/utils/sod.ts +0 -195
@@ -1,275 +0,0 @@
1
- import { makeUniqueArray } from "./collections.base";
2
- import { jsonParse } from "./json";
3
- import { isDate, isFunction, isNotEmptyArray, isNullOrEmptyString, isNullOrUndefined, isObject, isPrimitiveValue, isString, primitiveTypes } from "./typecheckers";
4
-
5
- /** global window, safe for testing and environments without a browser */
6
- export var $w = typeof window === "undefined" ? {
7
- setTimeout: setTimeout,
8
- clearTimeout: clearTimeout,
9
- location: {
10
- href: "", host: ""
11
- }
12
- } as any as Window : window;
13
-
14
- /** wrapper for hasOwnProperty that satisfies https://eslint.org/docs/latest/rules/no-prototype-builtins */
15
- export function hasOwnProperty(obj: any, prop: string) {
16
- if (!isNullOrUndefined(obj)) {
17
- return Object.prototype.hasOwnProperty.call(obj, prop);
18
- }
19
- return false;
20
- }
21
-
22
- /** empty async function */
23
- /* eslint-disable-next-line @typescript-eslint/no-empty-function */
24
- export var noop = async () => { };
25
- /** empty sync function */
26
- /* eslint-disable-next-line @typescript-eslint/no-empty-function */
27
- export var noops = () => { };
28
-
29
- /** get or create kwizcom object from top window or current window, set allowFromTop if you want to try to get from window.top */
30
- export function getKWizComGlobal(allowFromTop?: boolean) {
31
- if (allowFromTop) {
32
- try {
33
- $w.top["kwizcom"] = $w.top["kwizcom"] || {};
34
- return $w.top["kwizcom"] as IKWizComGlobals;
35
- } catch (ex) { }
36
- }
37
- $w["kwizcom"] = $w["kwizcom"] || {};
38
- return $w["kwizcom"] as IKWizComGlobals;
39
- }
40
- /** get or create kwizcom.globals dictionary from top window or current window. Add or return key:name initialize as defaults or blank object if does not already exist */
41
- export function getGlobal<T>(name: string, defaults?: T, notFromTop?: boolean) {
42
- var kGlobal = getKWizComGlobal(notFromTop !== true);
43
- kGlobal.globals = kGlobal.globals || {};
44
-
45
- if (!kGlobal.globals[name]) {
46
- if (isObject(defaults)) {
47
- // eslint-disable-next-line @typescript-eslint/ban-types
48
- kGlobal.globals[name] = { ...(defaults as object) };
49
- } else {
50
- kGlobal.globals[name] = {};
51
- }
52
- }
53
- return kGlobal.globals[name] as T;
54
- }
55
-
56
- /**
57
- * Automatically bind all functions of instance to instance
58
- * Note: if you use knockout, you should skip ko.isObservable
59
- * @param instance
60
- */
61
- //eslint-disable-next-line @typescript-eslint/ban-types
62
- export function autoBind(instance: any, skip?: (name: string, f: Function) => boolean) {
63
- let funcitonNames = getAllFunctionNames(instance, 1);
64
- funcitonNames.forEach(prop => {
65
- const val = instance[prop];
66
- if (!isFunction(skip) || !skip(prop, val))
67
- instance[prop] = val.bind(instance);
68
- });
69
- }
70
-
71
- /** Implements Object.assign which does not exist in IE
72
- * Copies properties over from overrides into original object
73
- * Merge default and override settings: var merged = assign({},defaults,props)
74
- * Create deep copy of object by var copy = assign({},obj) */
75
- export function assign<T>(original: Partial<T>, ...overrides: Partial<T>[]): T {
76
- if (original === undefined || original === null) {
77
- throw new TypeError('Cannot convert first argument to object');
78
- }
79
-
80
- var to = Object(original);
81
- if (overrides && overrides.length > 0)
82
- overrides.forEach(o => {
83
- if (!isNullOrUndefined(o)) {
84
- var keysArray = Object.keys(Object(o));
85
- for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
86
- var nextKey = keysArray[nextIndex];
87
- var desc = Object.getOwnPropertyDescriptor(o, nextKey);
88
- if (typeof (desc.value) === "undefined" || desc.value === null) {
89
- to[nextKey] = desc.value;
90
- }
91
- else if (typeof (desc.value) === "object") {
92
- //reference type, call assign recursively. fixed problem that object value types from overrides were modified when the returnd object was modified.
93
- if (!Array.isArray(desc.value)) {
94
- to[nextKey] = assign({}, desc.value);
95
- } else {
96
- to[nextKey] = assign([], desc.value);
97
- }
98
- } else {
99
- if (desc !== undefined && desc.enumerable) {
100
- to[nextKey] = desc.value;//this will make a shallow copy, altering the override object o[nextKey];
101
- }
102
- }
103
- }
104
- }
105
- });
106
- return to as T;
107
- }
108
-
109
- export function primitivesEqual(o1: primitiveTypes, o2: primitiveTypes) {
110
- let normalize = (oo: any) => {
111
- if (isNullOrUndefined(oo))
112
- return null;
113
- else if (isDate(oo))
114
- return oo.getTime();
115
- return oo;
116
- };
117
- o1 = normalize(o1);
118
- o2 = normalize(o2);
119
-
120
- return o1 === o2;
121
- }
122
- export function objectsEqual<T extends object>(o1: T, o2: T, ignoreKeys?: string[]) {
123
- let isPrimitive1 = isPrimitiveValue(o1);
124
- let isPrimitive2 = isPrimitiveValue(o2);
125
-
126
- if (isPrimitive1 !== isPrimitive2) return false;//one primitive other not?
127
- if (isPrimitive1)
128
- return primitivesEqual(o1 as unknown as primitiveTypes, o2 as unknown as primitiveTypes);
129
-
130
- if (isFunction(o1) || isFunction(o2)) {
131
- try {
132
- return o1.toString() === o2.toString();
133
- } catch (e) {
134
- return false;
135
- }
136
- }
137
-
138
- ignoreKeys = ignoreKeys || [];
139
- let allKeys = makeUniqueArray(Object.keys(o1).concat(Object.keys(o2))).filter(key => !ignoreKeys.includes(key));
140
- for (let i = 0; i < allKeys.length; i++) {
141
- let key = allKeys[i];
142
- if (!objectsEqual(o1[key], o2[key], ignoreKeys))
143
- return false;
144
- }
145
- return true;
146
- }
147
- export function jsonClone<T>(obj: T): T {
148
- //todo: check if assign utility method is faster
149
- if (isNullOrUndefined(obj)) return null;
150
- let result = obj;
151
- try { result = jsonParse<T>(JSON.stringify(obj)); }
152
- catch (e) {
153
- if (isNotEmptyArray(obj))
154
- result = (obj as any).slice();
155
- else
156
- result = obj;
157
- }
158
-
159
- //clone date objects
160
- try { cloneDatesOnObjectRecursivily(obj, result); } catch (e) { }
161
- return result;
162
- }
163
-
164
- function cloneDatesOnObjectRecursivily(obj1, obj2) {
165
- Object.keys(obj1).forEach(key => {
166
- let v = obj1[key];
167
- if (v === null)
168
- obj2[key] = null;
169
- else if (isDate(v))
170
- obj2[key] = new Date(v.getTime());
171
- else if (isObject(v) && Object.keys(v).length) {
172
- let v2 = obj2[key];
173
- if (isObject(v2))
174
- cloneDatesOnObjectRecursivily(v, v2);
175
- }
176
- });
177
- }
178
-
179
- /** if an object in this path doesnt exist under parent - creates it.*/
180
- export function ensureObjectPath(objectPath: string, defaultValue: any = {}, parent: any = $w) {
181
- if (isNullOrEmptyString(objectPath)) return;
182
- let parts = objectPath.split('.');
183
- for (let i = 0; i < parts.length; i++) {
184
- let partName = parts[i];
185
- if (i === parts.length - 1)//last
186
- {
187
- if (isNullOrUndefined(parent[partName]))
188
- parent[partName] = defaultValue;
189
- }
190
- else {
191
- if (isNullOrUndefined(parent[partName]))
192
- parent[partName] = {};
193
- parent = parent[partName];
194
- }
195
- }
196
- }
197
-
198
- /** If o has propb and not propa - will copy propb into propa and remove propb */
199
- export function keepOne(o: any, propa: string, propb: string) {
200
- /* using the unkown type doesn't work in modern apps project */
201
- if (isObject(o)) {
202
- if (!hasOwnProperty(o, propa) && hasOwnProperty(o, propb)) {
203
- o[propa] = o[propb];
204
- delete o[propb];
205
- }
206
- }
207
- }
208
-
209
- /**return all members and functions of an object, including inherited ones from its base class, excluding the constructor
210
- * send prototypeLevels to limit the number of prototype climbs to get functions from. 0 means unlimited.
211
- */
212
- export function getAllMemberNames(instance: any, prototypeLevels: number): string[] {
213
- let props: string[] = [];
214
- let obj = instance;
215
- let level = 0;
216
- let unlimitedLevels = prototypeLevels < 0;
217
-
218
- do {
219
- props.push(...Object.getOwnPropertyNames(obj));
220
- obj = Object.getPrototypeOf(obj);
221
- level++;
222
- }
223
- while (unlimitedLevels ? !!obj : !!obj && level <= prototypeLevels);
224
-
225
- return makeUniqueArray(props.filter(p => p !== 'constructor' && p !== 'dispose'));
226
- }
227
- /**return all functions of an object, including inherited ones from its base class, excluding the constructor
228
- * send prototypeLevels to limit the number of prototype climbs to get functions from. 0 means unlimited.
229
- */
230
- export function getAllFunctionNames(instance: any, prototypeLevels: number): string[] {
231
- return getAllMemberNames(instance, prototypeLevels).filter(p => isFunction(instance[p]));
232
- }
233
-
234
- /** generic implementation of Object.values */
235
- export function objectValues<T = any>(obj: any): T[] {
236
- return Object.keys(obj).map((key) => {
237
- return obj[key];
238
- }) as T[];
239
- }
240
-
241
- export class DefaultProp<T> {
242
- private _value: T;
243
- private _defaultValue: T | (() => T);
244
- private isValid: (value: T) => boolean;
245
- public set value(newValue: T) { this._value = newValue; }
246
- public get value() {
247
- if (!this.isValid(this._value)) {
248
- this._value = isFunction(this._defaultValue)
249
- ? (this._defaultValue as () => T)()
250
- : this._defaultValue;
251
- }
252
- return this._value;
253
- }
254
- public constructor(defaultValue: T | (() => T), initialValue?: T, isValid?: (value: T) => boolean) {
255
- this._defaultValue = defaultValue;
256
- this._value = initialValue;
257
- this.isValid = isFunction(isValid) ? isValid : v => !isNullOrUndefined(v);
258
- }
259
- }
260
- /** creates a safe property, if the value is null/undefined or empty string - it will return the default value. */
261
- export function GetDefaultProp<T>(defaultValue: T | (() => T), initialValue?: T, isValid?: (value: T) => boolean) {
262
- return new DefaultProp(defaultValue, initialValue, isValid);
263
- }
264
-
265
- /** Get string error message from an error object */
266
- export function GetError(error: any, defaultError: string = "Unknown error"): string {
267
- const err = isNullOrUndefined(error)
268
- ? defaultError
269
- : isString(error)
270
- ? error
271
- : isString((error as Error).message)
272
- ? error.message
273
- : defaultError;
274
- return err.length > 0 ? err : defaultError;
275
- }
@@ -1,38 +0,0 @@
1
- import assert from 'assert/strict';
2
- import test from 'node:test';
3
- import { promiseLock, promiseOnce, sleepAsync } from './promises';
4
-
5
-
6
- test('promiseOnce', async t => {
7
- let promiseOnceTester = promiseOnce("promiseOnceTester", async() => {
8
- return Date.now();
9
- });
10
-
11
- let value = await promiseOnceTester;
12
- await t.test("First call", t => assert.strictEqual(value > 0, true));
13
- //check cache
14
- let value2 = await promiseOnceTester;
15
- await t.test("Second call", t => assert.strictEqual(value === value2, true));
16
- let value3 = await promiseOnceTester;
17
- await t.test("Third call", t => assert.strictEqual(value === value3, true));
18
- });
19
-
20
- test('promisLock', async t => {
21
-
22
- let promiseLockTester = async() => {
23
- return new Date().getTime();
24
- };
25
-
26
- let p1 = promiseLock("promiseLockTest", promiseLockTester);
27
- let p2 = promiseLock("promiseLockTest", promiseLockTester);
28
-
29
- let v1 = await p1;
30
- let v2 = await p2;
31
-
32
- await sleepAsync(1);
33
-
34
- let v3 = await promiseLock("promiseLockTest", promiseLockTester);
35
-
36
- await t.test("During lock", t => assert.strictEqual(v1 === v2, true));
37
- await t.test("After lock", t => assert.strictEqual(v1 === v3, false));
38
- });
@@ -1,166 +0,0 @@
1
- import { IDictionary } from "../types/common.types";
2
- import { getGlobal, hasOwnProperty } from "./objects";
3
- import { isFunction, isNullOrUndefined, isNumber } from "./typecheckers";
4
-
5
- function _getGlobal() {
6
- let _global = getGlobal<{ promises: IDictionary<Promise<any>> }>("helpers_promises",
7
- {
8
- promises: {}
9
- });
10
- return _global;
11
- }
12
-
13
- /**
14
- * Lock all concurrent calls to a resource to one promise for a set duration of time.
15
- * @param {string} key - Unique key to identify the promise.
16
- * @param {() => Promise<T>} promiseFunc - Function that will return the promise to be run only once.
17
- * @param {number} duration - Duration to hold on to the promise result. (default=1)
18
- * @returns {Promise<T>} Returns the single promise that will be fullfilled for all promises with the same key.
19
- * @example
20
- * // returns Promise<string>
21
- * var initTests = await promiseLock<string>("initTests", async () => { ... }, 2);
22
- */
23
- export async function promiseLock<T>(key: string, promiseFunc: () => Promise<T>, duration = 1): Promise<T> {
24
- return promiseOnce(key, promiseFunc).then((result) => {
25
- (globalThis || window).setTimeout(() => {
26
- _deletePromiseByKey(key);
27
- }, isNumber(duration) && duration >= 1 ? duration : 1);
28
- return result;
29
- });
30
- }
31
- /**
32
- * Ensures that a promise runs only once
33
- * @param {string} key - Unique key to identify the promise.
34
- * @param {() => Promise<T>} promiseFunc - Function that will return the promise to be run only once.
35
- * @param {(result: T) => Promise<boolean>} isValidResult - Optional function that returns boolean to indicate if the result returned
36
- * by the promise is valid and should be kepy in memory.
37
- * @returns {Promise<T>} Returns the single promise that will be fullfilled for all promises with the same key.
38
- * @example
39
- * // returns Promise<string>
40
- * var initTests = await promiseOnce<string>("initTests", async () => { ... });
41
- */
42
- export async function promiseOnce<T>(key: string, promiseFunc: () => Promise<T>, isValidResult?: (result: T) => Promise<boolean>): Promise<T> {
43
- let _global = _getGlobal();
44
- let promises = _global.promises;
45
-
46
- if (hasOwnProperty(promises, key) && isFunction(isValidResult)) {
47
- //we have en existing pending promise...
48
- let queuedResult: T = null;
49
- try { queuedResult = await promises[key]; } catch (e) { }
50
- if ((await isValidResult(queuedResult)) !== true) {
51
- _deletePromiseByKey(key);
52
- }
53
- }
54
-
55
- if (!hasOwnProperty(promises, key)) {
56
- promises[key] = promiseFunc();
57
- }
58
-
59
- return promises[key];
60
- }
61
-
62
- /**
63
- * Runs all promises in sequential order.
64
- * @param {(() => Promise<T>)[]} asyncFuncs - Array of functions that return the promises to fullfill.
65
- * @returns {Promise<T[]>} Returns a single promise with a merged array of results that are in the same order as the
66
- * provided promise functions
67
- */
68
- export function promiseAllSequential<T = any>(asyncFuncs: (() => Promise<T>)[]): Promise<T[]> {
69
- if (!Array.isArray(asyncFuncs) || !asyncFuncs.length) {
70
- return Promise.resolve([]);
71
- }
72
- return asyncFuncs.reduce((promiseChain, currentTaskcurrentTask) => (
73
- promiseChain.then((result) => {
74
- let taskResult = currentTaskcurrentTask();
75
- if (isNullOrUndefined(taskResult) || !isFunction(taskResult.then))//culprit - found one that did not return a promise?! make one.
76
- taskResult = Promise.resolve() as any as Promise<T>;
77
-
78
- return taskResult.then(Array.prototype.concat.bind(result));
79
- })
80
- ), Promise.resolve([]));
81
- }
82
-
83
- /**
84
- * Runs N promises in parallel.
85
- * @param {(() => Promise<T>)[]} asyncFuncs - Array of functions that return the promises to fullfill.
86
- * @param {number} [maxParallel] - Max number of promises to run in parallel (default=8).
87
- * @returns {Promise<T[]>} Returns a single promise with a merged array of results that are in the same order as the
88
- * provided promise functions
89
- */
90
- export function promiseNParallel<T>(asyncFuncs: (() => Promise<T>)[], maxParallel: number = 8): Promise<T[]> {
91
- if (!Array.isArray(asyncFuncs) || !asyncFuncs.length) {
92
- return Promise.resolve([]);
93
- }
94
-
95
- let startChain = () => {
96
- let chainData = [];
97
-
98
- if (asyncFuncs.length) {
99
- let next = (data: T) => {
100
- chainData.push(data);
101
- return asyncFuncs.length ? (asyncFuncs.shift())().then(next) : chainData;
102
- };
103
- return (asyncFuncs.shift())().then(next);
104
- } else {
105
- return Promise.resolve(chainData);
106
- }
107
- };
108
-
109
- let chains = [];
110
- for (let k = 0; k < maxParallel; k += 1) {
111
- chains.push(startChain());
112
- }
113
-
114
- return Promise.all(chains).then(d => {
115
- //flatten results
116
- return d.reduce((acc, val) => acc.concat(val), []);
117
- });
118
- }
119
-
120
- /**
121
- * Provides an asnyc sleep function that allows you to delay async/wait calls.
122
- * @param {number} [seconds] - Time to sleep in seconds.
123
- */
124
- export function sleepAsync(seconds?: number): Promise<void> {
125
- return new Promise(resolve => {
126
- (globalThis || window).setTimeout(() => resolve(), seconds > 0 ? seconds * 1000 : 3000);
127
- });
128
- }
129
-
130
- /**
131
- * Provides the ability to retry an async function n times with a optional delay between calls
132
- * @param {(...args) => Promise<T>} fn - Function to retry,
133
- * @param {number} numberOfRetries - Number of times to retry.
134
- * @param {number} [seconds] - Delay between retries in seconds (default=1).
135
- */
136
- export async function retryAsync<T>(fn: (...args) => Promise<T>, numberOfRetries: number, seconds = 1) {
137
- let error: Error = null;
138
-
139
- for (let i = 0; i < numberOfRetries; i++) {
140
- try {
141
- error = null;
142
- await sleepAsync(i === 0 ? 0 : seconds);
143
- return await fn();
144
- } catch (ex) {
145
- error = ex;
146
- }
147
- }
148
-
149
- if (error) {
150
- throw error;
151
- }
152
- throw new Error(`Failed retrying ${numberOfRetries} times`);
153
- }
154
-
155
- function _deletePromiseByKey(key: string) {
156
- let _global = _getGlobal();
157
- let promises = _global.promises;
158
- if (hasOwnProperty(promises, key)) {
159
- try {
160
- delete promises[key];
161
- return true;
162
- } catch {
163
- return false;
164
- }
165
- }
166
- }
@@ -1,27 +0,0 @@
1
- export function getRandomId() {
2
- return Date.now().toString(36) + Math.random().toString(36).substring(2);
3
- }
4
-
5
- export function getUniqueId() {
6
- var _s_hexcode = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
7
- for (var a = "", c = 0; c < 32; c++) {
8
- var b = Math.floor(Math.random() * 16);
9
- switch (c) {
10
- case 8:
11
- a += "-";
12
- break;
13
- case 12:
14
- b = 4;
15
- a += "-";
16
- break;
17
- case 16:
18
- b = b & 3 | 8;
19
- a += "-";
20
- break;
21
- case 20:
22
- a += "-";
23
- }
24
- a += _s_hexcode[b];
25
- }
26
- return a;
27
- }
@@ -1 +0,0 @@
1
- export * from './scheduler';
@@ -1,104 +0,0 @@
1
- import assert from 'assert/strict';
2
- import test from 'node:test';
3
- import { isValidSchedule, getNextUTC } from "./scheduler";
4
- import { ScheduleTypes } from './scheduler';
5
-
6
- var startDate = "2020-01-01T05:00Z";
7
- var invalidOutput = "9999999999";
8
- var schedules = [
9
- { schedule: {}, output: invalidOutput, valid: false },
10
- { schedule: { ScheduleType: "x" }, output: invalidOutput, valid: false },
11
- {
12
- schedule: {
13
- ScheduleType: ScheduleTypes.hourly,
14
- interval: 24
15
- }, output: invalidOutput, valid: false
16
- },
17
- {
18
- name: "move 2 hours",
19
- schedule: {
20
- ScheduleType: ScheduleTypes.hourly,
21
- interval: 2
22
- }, output: "2020010107", valid: true
23
- },
24
- {
25
- schedule: {
26
- ScheduleType: ScheduleTypes.daily,
27
- hours: []
28
- }, output: invalidOutput, valid: false
29
- },
30
- {
31
- schedule: {
32
- ScheduleType: ScheduleTypes.daily,
33
- hours: [5, 2, 9, 26]
34
- }, output: invalidOutput, valid: false
35
- },
36
- {
37
- name: "move to next hour in same day",
38
- schedule: {
39
- ScheduleType: ScheduleTypes.daily,
40
- hours: [5, 2, 9, 22]
41
- }, output: "2020010109", valid: true
42
- },
43
- {
44
- name: "passed last hour, move to next day",
45
- schedule: {
46
- ScheduleType: ScheduleTypes.daily,
47
- hours: [3, 1, 5, 2]
48
- }, output: "2020010201", valid: true
49
- },
50
- {
51
- schedule: {
52
- ScheduleType: ScheduleTypes.weekly,
53
- hours: []
54
- }, output: invalidOutput, valid: false
55
- },
56
- {
57
- schedule: {
58
- ScheduleType: ScheduleTypes.weekly,
59
- hours: [5, 2, 9, 26],
60
- days: [2],
61
- }, output: invalidOutput, valid: false
62
- },
63
- {
64
- schedule: {
65
- ScheduleType: ScheduleTypes.weekly,
66
- hours: [5, 2, 9, 22],
67
- days: [5, 2, 7]
68
- }, output: invalidOutput, valid: false
69
- },
70
- {
71
- name: "day is no ok, move to next day first hour",
72
- schedule: {
73
- ScheduleType: ScheduleTypes.weekly,
74
- hours: [5, 2, 9, 22],
75
- days: [5, 2, 4]
76
- }, output: "2020010202", valid: true
77
- },
78
- {
79
- name: "day is not ok, move to first day in next week",
80
- schedule: {
81
- ScheduleType: ScheduleTypes.weekly,
82
- hours: [5, 2, 9, 22],
83
- days: [2, 0, 1]
84
- }, output: "2020010502", valid: true
85
- },
86
- {
87
- name: "day is ok, move to next hour",
88
- schedule: {
89
- ScheduleType: ScheduleTypes.weekly,
90
- hours: [5, 2, 9, 22],
91
- days: [5, 2, 3, 4]
92
- }, output: "2020010109", valid: true
93
- }
94
- ];
95
-
96
-
97
- test('isValidSchedule', t => {
98
- schedules.forEach(s => assert.strictEqual(isValidSchedule(s.schedule), s.valid));
99
- });
100
-
101
- test('getNextUTC', async t => {
102
- let date = new Date(startDate);
103
- schedules.forEach(s => assert.strictEqual(getNextUTC(date, s.schedule), s.output));
104
- });