@kwiz/common 1.0.1

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 (310) hide show
  1. package/LICENSE +21 -0
  2. package/dist/_dependencies.d.ts +1 -0
  3. package/dist/_dependencies.js +8 -0
  4. package/dist/_dependencies.js.map +1 -0
  5. package/dist/helpers/Guid.d.ts +119 -0
  6. package/dist/helpers/Guid.js +183 -0
  7. package/dist/helpers/Guid.js.map +1 -0
  8. package/dist/helpers/_dependencies.d.ts +2 -0
  9. package/dist/helpers/_dependencies.js +21 -0
  10. package/dist/helpers/_dependencies.js.map +1 -0
  11. package/dist/helpers/base64.d.ts +8 -0
  12. package/dist/helpers/base64.js +178 -0
  13. package/dist/helpers/base64.js.map +1 -0
  14. package/dist/helpers/browser.d.ts +144 -0
  15. package/dist/helpers/browser.js +1200 -0
  16. package/dist/helpers/browser.js.map +1 -0
  17. package/dist/helpers/browserinfo.d.ts +23 -0
  18. package/dist/helpers/browserinfo.js +215 -0
  19. package/dist/helpers/browserinfo.js.map +1 -0
  20. package/dist/helpers/collections.base.d.ts +128 -0
  21. package/dist/helpers/collections.base.js +430 -0
  22. package/dist/helpers/collections.base.js.map +1 -0
  23. package/dist/helpers/collections.d.ts +18 -0
  24. package/dist/helpers/collections.js +99 -0
  25. package/dist/helpers/collections.js.map +1 -0
  26. package/dist/helpers/color.d.ts +11 -0
  27. package/dist/helpers/color.js +57 -0
  28. package/dist/helpers/color.js.map +1 -0
  29. package/dist/helpers/cookies.d.ts +6 -0
  30. package/dist/helpers/cookies.js +56 -0
  31. package/dist/helpers/cookies.js.map +1 -0
  32. package/dist/helpers/date.d.ts +43 -0
  33. package/dist/helpers/date.js +158 -0
  34. package/dist/helpers/date.js.map +1 -0
  35. package/dist/helpers/debug.d.ts +33 -0
  36. package/dist/helpers/debug.js +177 -0
  37. package/dist/helpers/debug.js.map +1 -0
  38. package/dist/helpers/emails.d.ts +2 -0
  39. package/dist/helpers/emails.js +10 -0
  40. package/dist/helpers/emails.js.map +1 -0
  41. package/dist/helpers/eval.d.ts +1 -0
  42. package/dist/helpers/eval.js +10 -0
  43. package/dist/helpers/eval.js.map +1 -0
  44. package/dist/helpers/file.d.ts +11 -0
  45. package/dist/helpers/file.js +55 -0
  46. package/dist/helpers/file.js.map +1 -0
  47. package/dist/helpers/flatted.d.ts +20 -0
  48. package/dist/helpers/flatted.js +135 -0
  49. package/dist/helpers/flatted.js.map +1 -0
  50. package/dist/helpers/functions.d.ts +4 -0
  51. package/dist/helpers/functions.js +17 -0
  52. package/dist/helpers/functions.js.map +1 -0
  53. package/dist/helpers/graph/calendar.types.d.ts +3 -0
  54. package/dist/helpers/graph/calendar.types.js +15 -0
  55. package/dist/helpers/graph/calendar.types.js.map +1 -0
  56. package/dist/helpers/http.d.ts +25 -0
  57. package/dist/helpers/http.js +70 -0
  58. package/dist/helpers/http.js.map +1 -0
  59. package/dist/helpers/images.d.ts +16 -0
  60. package/dist/helpers/images.js +21 -0
  61. package/dist/helpers/images.js.map +1 -0
  62. package/dist/helpers/index.d.ts +29 -0
  63. package/dist/helpers/index.js +46 -0
  64. package/dist/helpers/index.js.map +1 -0
  65. package/dist/helpers/json.d.ts +3 -0
  66. package/dist/helpers/json.js +44 -0
  67. package/dist/helpers/json.js.map +1 -0
  68. package/dist/helpers/md5.d.ts +5 -0
  69. package/dist/helpers/md5.js +172 -0
  70. package/dist/helpers/md5.js.map +1 -0
  71. package/dist/helpers/objects.d.ts +49 -0
  72. package/dist/helpers/objects.js +271 -0
  73. package/dist/helpers/objects.js.map +1 -0
  74. package/dist/helpers/promises.d.ts +14 -0
  75. package/dist/helpers/promises.js +112 -0
  76. package/dist/helpers/promises.js.map +1 -0
  77. package/dist/helpers/random.d.ts +2 -0
  78. package/dist/helpers/random.js +32 -0
  79. package/dist/helpers/random.js.map +1 -0
  80. package/dist/helpers/scheduler/scheduler.d.ts +39 -0
  81. package/dist/helpers/scheduler/scheduler.js +109 -0
  82. package/dist/helpers/scheduler/scheduler.js.map +1 -0
  83. package/dist/helpers/sharepoint.d.ts +112 -0
  84. package/dist/helpers/sharepoint.js +629 -0
  85. package/dist/helpers/sharepoint.js.map +1 -0
  86. package/dist/helpers/strings.d.ts +56 -0
  87. package/dist/helpers/strings.js +282 -0
  88. package/dist/helpers/strings.js.map +1 -0
  89. package/dist/helpers/typecheckers.d.ts +56 -0
  90. package/dist/helpers/typecheckers.js +274 -0
  91. package/dist/helpers/typecheckers.js.map +1 -0
  92. package/dist/helpers/url.d.ts +46 -0
  93. package/dist/helpers/url.js +199 -0
  94. package/dist/helpers/url.js.map +1 -0
  95. package/dist/helpers/urlhelper.d.ts +16 -0
  96. package/dist/helpers/urlhelper.js +96 -0
  97. package/dist/helpers/urlhelper.js.map +1 -0
  98. package/dist/index.d.ts +15 -0
  99. package/dist/index.js +37 -0
  100. package/dist/index.js.map +1 -0
  101. package/dist/types/common.types.d.ts +19 -0
  102. package/dist/types/common.types.js +4 -0
  103. package/dist/types/common.types.js.map +1 -0
  104. package/dist/types/flatted.types.d.ts +49 -0
  105. package/dist/types/flatted.types.js +3 -0
  106. package/dist/types/flatted.types.js.map +1 -0
  107. package/dist/types/globals.types.d.ts +6 -0
  108. package/dist/types/globals.types.js +3 -0
  109. package/dist/types/globals.types.js.map +1 -0
  110. package/dist/types/graph/calendar.types.d.ts +79 -0
  111. package/dist/types/graph/calendar.types.js +3 -0
  112. package/dist/types/graph/calendar.types.js.map +1 -0
  113. package/dist/types/graph/index.d.ts +1 -0
  114. package/dist/types/graph/index.js +18 -0
  115. package/dist/types/graph/index.js.map +1 -0
  116. package/dist/types/index.d.ts +11 -0
  117. package/dist/types/index.js +28 -0
  118. package/dist/types/index.js.map +1 -0
  119. package/dist/types/knownscript.types.d.ts +22 -0
  120. package/dist/types/knownscript.types.js +3 -0
  121. package/dist/types/knownscript.types.js.map +1 -0
  122. package/dist/types/libs/datajs.types.d.ts +29 -0
  123. package/dist/types/libs/datajs.types.js +3 -0
  124. package/dist/types/libs/datajs.types.js.map +1 -0
  125. package/dist/types/libs/ics.types.d.ts +29 -0
  126. package/dist/types/libs/ics.types.js +3 -0
  127. package/dist/types/libs/ics.types.js.map +1 -0
  128. package/dist/types/libs/index.d.ts +3 -0
  129. package/dist/types/libs/index.js +20 -0
  130. package/dist/types/libs/index.js.map +1 -0
  131. package/dist/types/libs/msal.types.d.ts +33 -0
  132. package/dist/types/libs/msal.types.js +63 -0
  133. package/dist/types/libs/msal.types.js.map +1 -0
  134. package/dist/types/locales.d.ts +122 -0
  135. package/dist/types/locales.js +1 -0
  136. package/dist/types/locales.js.map +1 -0
  137. package/dist/types/localstoragecache.types.d.ts +8 -0
  138. package/dist/types/localstoragecache.types.js +3 -0
  139. package/dist/types/localstoragecache.types.js.map +1 -0
  140. package/dist/types/moment.d.ts +6 -0
  141. package/dist/types/moment.js +1 -0
  142. package/dist/types/moment.js.map +1 -0
  143. package/dist/types/regex.types.d.ts +14 -0
  144. package/dist/types/regex.types.js +3 -0
  145. package/dist/types/regex.types.js.map +1 -0
  146. package/dist/types/rest.types.d.ts +81 -0
  147. package/dist/types/rest.types.js +24 -0
  148. package/dist/types/rest.types.js.map +1 -0
  149. package/dist/types/sharepoint.types.d.ts +1432 -0
  150. package/dist/types/sharepoint.types.js +629 -0
  151. package/dist/types/sharepoint.types.js.map +1 -0
  152. package/dist/types/sharepoint.utils.types.d.ts +246 -0
  153. package/dist/types/sharepoint.utils.types.js +26 -0
  154. package/dist/types/sharepoint.utils.types.js.map +1 -0
  155. package/dist/utils/_dependencies.d.ts +3 -0
  156. package/dist/utils/_dependencies.js +24 -0
  157. package/dist/utils/_dependencies.js.map +1 -0
  158. package/dist/utils/base64.d.ts +2 -0
  159. package/dist/utils/base64.js +41 -0
  160. package/dist/utils/base64.js.map +1 -0
  161. package/dist/utils/consolelogger.d.ts +73 -0
  162. package/dist/utils/consolelogger.js +281 -0
  163. package/dist/utils/consolelogger.js.map +1 -0
  164. package/dist/utils/date.d.ts +10 -0
  165. package/dist/utils/date.js +30 -0
  166. package/dist/utils/date.js.map +1 -0
  167. package/dist/utils/emails.d.ts +2 -0
  168. package/dist/utils/emails.js +24 -0
  169. package/dist/utils/emails.js.map +1 -0
  170. package/dist/utils/index.d.ts +13 -0
  171. package/dist/utils/index.js +31 -0
  172. package/dist/utils/index.js.map +1 -0
  173. package/dist/utils/knownscript.d.ts +99 -0
  174. package/dist/utils/knownscript.js +261 -0
  175. package/dist/utils/knownscript.js.map +1 -0
  176. package/dist/utils/localstoragecache.d.ts +19 -0
  177. package/dist/utils/localstoragecache.js +372 -0
  178. package/dist/utils/localstoragecache.js.map +1 -0
  179. package/dist/utils/rest.d.ts +17 -0
  180. package/dist/utils/rest.js +402 -0
  181. package/dist/utils/rest.js.map +1 -0
  182. package/dist/utils/script.d.ts +33 -0
  183. package/dist/utils/script.js +169 -0
  184. package/dist/utils/script.js.map +1 -0
  185. package/dist/utils/sharepoint.rest/common.d.ts +32 -0
  186. package/dist/utils/sharepoint.rest/common.js +146 -0
  187. package/dist/utils/sharepoint.rest/common.js.map +1 -0
  188. package/dist/utils/sharepoint.rest/date.d.ts +2 -0
  189. package/dist/utils/sharepoint.rest/date.js +57 -0
  190. package/dist/utils/sharepoint.rest/date.js.map +1 -0
  191. package/dist/utils/sharepoint.rest/file.folder.d.ts +58 -0
  192. package/dist/utils/sharepoint.rest/file.folder.js +305 -0
  193. package/dist/utils/sharepoint.rest/file.folder.js.map +1 -0
  194. package/dist/utils/sharepoint.rest/index.d.ts +11 -0
  195. package/dist/utils/sharepoint.rest/index.js +28 -0
  196. package/dist/utils/sharepoint.rest/index.js.map +1 -0
  197. package/dist/utils/sharepoint.rest/item.d.ts +81 -0
  198. package/dist/utils/sharepoint.rest/item.js +444 -0
  199. package/dist/utils/sharepoint.rest/item.js.map +1 -0
  200. package/dist/utils/sharepoint.rest/list.d.ts +228 -0
  201. package/dist/utils/sharepoint.rest/list.js +868 -0
  202. package/dist/utils/sharepoint.rest/list.js.map +1 -0
  203. package/dist/utils/sharepoint.rest/listutils/GetListItemsByCaml.d.ts +19 -0
  204. package/dist/utils/sharepoint.rest/listutils/GetListItemsByCaml.js +629 -0
  205. package/dist/utils/sharepoint.rest/listutils/GetListItemsByCaml.js.map +1 -0
  206. package/dist/utils/sharepoint.rest/listutils/GetListItemsById.d.ts +14 -0
  207. package/dist/utils/sharepoint.rest/listutils/GetListItemsById.js +222 -0
  208. package/dist/utils/sharepoint.rest/listutils/GetListItemsById.js.map +1 -0
  209. package/dist/utils/sharepoint.rest/listutils/common.d.ts +3 -0
  210. package/dist/utils/sharepoint.rest/listutils/common.js +198 -0
  211. package/dist/utils/sharepoint.rest/listutils/common.js.map +1 -0
  212. package/dist/utils/sharepoint.rest/user-search.d.ts +76 -0
  213. package/dist/utils/sharepoint.rest/user-search.js +239 -0
  214. package/dist/utils/sharepoint.rest/user-search.js.map +1 -0
  215. package/dist/utils/sharepoint.rest/user.d.ts +71 -0
  216. package/dist/utils/sharepoint.rest/user.js +404 -0
  217. package/dist/utils/sharepoint.rest/user.js.map +1 -0
  218. package/dist/utils/sharepoint.rest/web.d.ts +107 -0
  219. package/dist/utils/sharepoint.rest/web.js +929 -0
  220. package/dist/utils/sharepoint.rest/web.js.map +1 -0
  221. package/dist/utils/sod.d.ts +29 -0
  222. package/dist/utils/sod.js +177 -0
  223. package/dist/utils/sod.js.map +1 -0
  224. package/package.json +60 -0
  225. package/readme.md +13 -0
  226. package/src/_dependencies.ts +2 -0
  227. package/src/helpers/Guid.ts +182 -0
  228. package/src/helpers/_dependencies.ts +3 -0
  229. package/src/helpers/base64.ts +174 -0
  230. package/src/helpers/browser.test.js +9 -0
  231. package/src/helpers/browser.ts +1299 -0
  232. package/src/helpers/browserinfo.ts +293 -0
  233. package/src/helpers/collections.base.test.js +26 -0
  234. package/src/helpers/collections.base.ts +439 -0
  235. package/src/helpers/collections.ts +108 -0
  236. package/src/helpers/color.ts +55 -0
  237. package/src/helpers/cookies.ts +55 -0
  238. package/src/helpers/date.test.js +97 -0
  239. package/src/helpers/date.ts +163 -0
  240. package/src/helpers/debug.ts +187 -0
  241. package/src/helpers/emails.ts +7 -0
  242. package/src/helpers/eval.ts +5 -0
  243. package/src/helpers/file.test.js +51 -0
  244. package/src/helpers/file.ts +59 -0
  245. package/src/helpers/flatted.ts +150 -0
  246. package/src/helpers/functions.ts +17 -0
  247. package/src/helpers/graph/calendar.types.ts +11 -0
  248. package/src/helpers/http.ts +70 -0
  249. package/src/helpers/images.ts +23 -0
  250. package/src/helpers/index.ts +29 -0
  251. package/src/helpers/json.ts +39 -0
  252. package/src/helpers/md5.ts +190 -0
  253. package/src/helpers/objects.test.js +27 -0
  254. package/src/helpers/objects.ts +256 -0
  255. package/src/helpers/promises.test.js +18 -0
  256. package/src/helpers/promises.ts +102 -0
  257. package/src/helpers/random.ts +27 -0
  258. package/src/helpers/scheduler/scheduler.test.js +104 -0
  259. package/src/helpers/scheduler/scheduler.ts +132 -0
  260. package/src/helpers/sharepoint.ts +681 -0
  261. package/src/helpers/strings.test.js +43 -0
  262. package/src/helpers/strings.ts +288 -0
  263. package/src/helpers/typecheckers.test.js +35 -0
  264. package/src/helpers/typecheckers.ts +263 -0
  265. package/src/helpers/url.test.js +18 -0
  266. package/src/helpers/url.ts +202 -0
  267. package/src/helpers/urlhelper.ts +104 -0
  268. package/src/index.ts +24 -0
  269. package/src/types/common.types.ts +16 -0
  270. package/src/types/flatted.types.ts +60 -0
  271. package/src/types/globals.types.ts +7 -0
  272. package/src/types/graph/calendar.types.ts +81 -0
  273. package/src/types/graph/index.ts +1 -0
  274. package/src/types/index.ts +12 -0
  275. package/src/types/knownscript.types.ts +19 -0
  276. package/src/types/libs/datajs.types.ts +29 -0
  277. package/src/types/libs/ics.types.ts +31 -0
  278. package/src/types/libs/index.ts +4 -0
  279. package/src/types/libs/msal.types.ts +79 -0
  280. package/src/types/locales.ts +125 -0
  281. package/src/types/localstoragecache.types.ts +9 -0
  282. package/src/types/moment.ts +7 -0
  283. package/src/types/regex.types.ts +17 -0
  284. package/src/types/rest.types.ts +94 -0
  285. package/src/types/sharepoint.types.ts +1413 -0
  286. package/src/types/sharepoint.utils.types.ts +246 -0
  287. package/src/utils/_dependencies.ts +4 -0
  288. package/src/utils/base64.ts +27 -0
  289. package/src/utils/consolelogger.ts +315 -0
  290. package/src/utils/date.ts +36 -0
  291. package/src/utils/emails.ts +25 -0
  292. package/src/utils/index.ts +13 -0
  293. package/src/utils/knownscript.ts +280 -0
  294. package/src/utils/localstoragecache.ts +419 -0
  295. package/src/utils/rest.ts +465 -0
  296. package/src/utils/script.ts +168 -0
  297. package/src/utils/sharepoint.rest/common.ts +149 -0
  298. package/src/utils/sharepoint.rest/date.ts +61 -0
  299. package/src/utils/sharepoint.rest/file.folder.ts +368 -0
  300. package/src/utils/sharepoint.rest/index.ts +11 -0
  301. package/src/utils/sharepoint.rest/item.ts +456 -0
  302. package/src/utils/sharepoint.rest/list.ts +1144 -0
  303. package/src/utils/sharepoint.rest/listutils/GetListItemsByCaml.ts +750 -0
  304. package/src/utils/sharepoint.rest/listutils/GetListItemsById.ts +265 -0
  305. package/src/utils/sharepoint.rest/listutils/common.ts +202 -0
  306. package/src/utils/sharepoint.rest/user-search.ts +254 -0
  307. package/src/utils/sharepoint.rest/user.ts +447 -0
  308. package/src/utils/sharepoint.rest/web.ts +1031 -0
  309. package/src/utils/sod.ts +193 -0
  310. package/tsconfig.json +21 -0
@@ -0,0 +1,465 @@
1
+ import { AllRestCacheOptionsKeys, IDictionary, IJsonSyncResult, IRequestBody, IRequestObjects, IRestCacheOptions, IRestError, IRestOptions, IRestRequestOptions, assign, getGlobal, hasOwnProperty, isNullOrEmptyString, isNullOrUndefined, isNumber, isObject, isPrimitiveValue, isString, jsonClone, jsonParse, jsonTypes } from "./_dependencies";
2
+ import { ConsoleLogger } from "./consolelogger";
3
+ import { getCacheItem, setCacheItem } from "./localstoragecache";
4
+ import { getFormDigest } from "./sharepoint.rest/web";
5
+
6
+ var logger = ConsoleLogger.get("kwizcom.rest.module");
7
+ const supressDebugMessages = true;
8
+
9
+ /** cache for 1 day */
10
+ export const noLocalCache: IRestOptions = { allowCache: false };
11
+ /** cache for 1 days */
12
+ export const longLocalCache: IRestOptions = { allowCache: true, localStorageExpiration: { days: 1 } };
13
+ /** cache for 2 days */
14
+ export const extraLongLocalCache: IRestOptions = { allowCache: true, localStorageExpiration: { days: 2 } };
15
+ /** cache for 7 days */
16
+ export const weeekLongLocalCache: IRestOptions = { allowCache: true, localStorageExpiration: { days: 7 } };
17
+ /** cache for 30 days */
18
+ export const monthLongLocalCache: IRestOptions = { allowCache: true, localStorageExpiration: { days: 30 } };
19
+ /** cache for 5 minutes */
20
+ export const shortLocalCache: IRestOptions = { allowCache: true, localStorageExpiration: { minutes: 5 } };
21
+ /** cache for 15 minutes */
22
+ export const mediumLocalCache: IRestOptions = { allowCache: true, localStorageExpiration: { minutes: 15 } };
23
+
24
+ interface IPendingRequest<T> {
25
+ objects: IRequestObjects;
26
+ /**the main promise */
27
+ promise: Promise<T>;
28
+ /**additional listeners
29
+ * must add a separate promise, so that I can make a full(not shallow) copy of the result.
30
+ * this way if the first caller changes the object, the second caller gets it unchanged.
31
+ */
32
+ listeners: {
33
+ resolve: (result: T) => void;
34
+ reject: (reason: any) => void;
35
+ }[];
36
+ }
37
+
38
+ //if allowCache is true, results will be stored/returned from here
39
+ var _cachedResults = getGlobal<{ [key: string]: IJsonSyncResult<any>; }>("utils_restmodule_cachedResults");
40
+ //cannot use from top window, example: DVP, if you open view item popup and close it too fast, there might be a pending request that never resolves since the handler code was unloaded from the window.
41
+ var _pendingRequests = getGlobal<IDictionary<IPendingRequest<any>>>("utils_restmodule_pendingRequests", undefined, true);
42
+
43
+ function getDefaultOptions(): IRestOptions {
44
+ return {
45
+ includeDigestInPost: true,
46
+ headers: {
47
+ }
48
+ };
49
+ }
50
+
51
+ function fillHeaders(xhr: XMLHttpRequest, headers: { [key: string]: string; }) {
52
+ for (let header in headers)
53
+ if (hasOwnProperty(headers, header)) {
54
+ let val = headers[header];
55
+ if (!isNullOrEmptyString(val))
56
+ xhr.setRequestHeader(header, val);
57
+ }
58
+ }
59
+
60
+ function getXhr(url: string, body?: IRequestBody, options?: IRestOptions, async = true): IRequestObjects {
61
+ var optionsWithDefaults = assign<IRestOptions>({}, getDefaultOptions(), options);
62
+ let myCacheOptions: IRestCacheOptions & { cacheKey?: string; } = {};
63
+ Object.keys(AllRestCacheOptionsKeys).forEach(key => {
64
+ if (hasOwnProperty(optionsWithDefaults, key)) {
65
+ myCacheOptions[key] = optionsWithDefaults[key];
66
+ delete optionsWithDefaults[key];
67
+ }
68
+ });
69
+ let myOptions: IRestRequestOptions = { ...optionsWithDefaults };
70
+
71
+ var xhr: XMLHttpRequest = new XMLHttpRequest();
72
+
73
+ let jsonType = myOptions.jsonMetadata || jsonTypes.verbose;
74
+
75
+ if (myOptions.cors) {
76
+ xhr.withCredentials = true;
77
+ }
78
+
79
+ if (isNullOrUndefined(myOptions.headers)) myOptions.headers = {};//issue 660 in case the sender sent headers as null
80
+ if (isNullOrUndefined(myOptions.headers["Accept"])) {
81
+ myOptions.headers["Accept"] = jsonType;
82
+ }
83
+
84
+ let method = myOptions.method;
85
+ if (isNullOrEmptyString(method)) {
86
+ method = isNullOrUndefined(body) ? "GET" : "POST";
87
+ }
88
+
89
+ myOptions.method = method;
90
+ xhr.open(method, url, async !== false);
91
+ if (method === "GET") {
92
+ if (myOptions.includeDigestInGet === true) {//by default don't add it, unless explicitly asked in options
93
+ xhr.setRequestHeader("X-RequestDigest", getFormDigest(myOptions.spWebUrl));
94
+ }
95
+ }
96
+ else if (method === "POST") {
97
+ if (isNullOrUndefined(myOptions.headers["content-type"])) {
98
+ myOptions.headers["content-type"] = jsonType;
99
+ }
100
+
101
+ if (myOptions.includeDigestInPost !== false) {//if explicitly set to false - don't include it
102
+ xhr.setRequestHeader("X-RequestDigest", getFormDigest(myOptions.spWebUrl));
103
+ }
104
+ }
105
+
106
+ if (!isNullOrEmptyString(myOptions.xHttpMethod)) {
107
+ myOptions.headers["X-HTTP-Method"] = myOptions.xHttpMethod;
108
+
109
+ if (myOptions.xHttpMethod === "MERGE" || myOptions.xHttpMethod === "DELETE" || myOptions.xHttpMethod === "PUT") {
110
+ myOptions.headers["If-Match"] = "*";// update regadless of other user changes
111
+ }
112
+ }
113
+
114
+ fillHeaders(xhr, myOptions.headers);
115
+
116
+ if (!isNullOrEmptyString(myOptions.responseType) && myOptions.responseType !== "text") {
117
+ if (myCacheOptions.allowCache === true &&
118
+ (myOptions.responseType === "blob" || myOptions.responseType === "arraybuffer" || myOptions.responseType === "document")) {
119
+ logger.warn("When allowCache is true, Blob, ArrayBuffer and Document response types will only be stored in runtime memory and not committed to local storage.");
120
+ }
121
+ xhr.responseType = myOptions.responseType;
122
+ }
123
+
124
+ //we do not support cache if there is a request body
125
+ //postCacheKey - allow cache on post request for stuff like get item by CamlQuery
126
+ if (isNullOrUndefined(body) || !isNullOrEmptyString(myOptions.postCacheKey)) {
127
+ myCacheOptions.cacheKey = (url + '|' + JSON.stringify(myOptions)).trim().toLowerCase();
128
+ }
129
+
130
+ return {
131
+ xhr: xhr,
132
+ options: myOptions,
133
+ cacheOptions: myCacheOptions
134
+ };
135
+ }
136
+
137
+ function getCachedResult<T>(objects: IRequestObjects): IJsonSyncResult<T> {
138
+ var cacheKey = objects.cacheOptions.cacheKey;
139
+ if (objects.cacheOptions.allowCache === true && objects.cacheOptions.forceCacheUpdate !== true) {
140
+ if (isNullOrEmptyString(cacheKey)) {
141
+ logger.warn('cache is not supported for this type of request.');
142
+ return null;
143
+ }
144
+
145
+ if (isNullOrUndefined(_cachedResults[cacheKey])) {
146
+ //try to load from local storage
147
+ let result = getCacheItem<IJsonSyncResult<T>>('jsr_' + cacheKey);
148
+
149
+ if (!isNullOrUndefined(result) && (result.success === true || result.status === 404)) {
150
+ if (!result.cachedTime) {
151
+ let now = new Date();
152
+ now.setDate(-1);
153
+ result.cachedTime = now.getTime();
154
+ }
155
+
156
+ _cachedResults[cacheKey] = result;
157
+ }
158
+ }
159
+
160
+ if (!isNullOrUndefined(_cachedResults[cacheKey])) {
161
+ let result = _cachedResults[cacheKey];
162
+
163
+ var maxAge = isNumber(objects.cacheOptions.maxAge) && objects.cacheOptions.maxAge > 0 ? objects.cacheOptions.maxAge : null;
164
+
165
+ if (maxAge && result.cachedTime) {
166
+ let now = new Date().getTime();
167
+ var cachedTime = result.cachedTime;
168
+ var validUntil = cachedTime + (maxAge * 1000);
169
+
170
+ if (now > validUntil) {
171
+ logger.debug("getCachedResult - entry has out lived max age");
172
+ return null;
173
+ }
174
+ }
175
+
176
+ return {
177
+ ..._cachedResults[cacheKey],
178
+ result: _canSafelyStringify(_cachedResults[cacheKey].result) ?
179
+ jsonClone(_cachedResults[cacheKey].result) :
180
+ _cachedResults[cacheKey].result
181
+ };
182
+ }
183
+ }
184
+ return null;
185
+ }
186
+
187
+ function setCachedResult<T>(cacheOptions: IRestCacheOptions & { cacheKey?: string; }, response: IJsonSyncResult<T>) {
188
+ if (isNullOrEmptyString(cacheOptions.cacheKey)) {
189
+ return;
190
+ }
191
+ response.cachedTime = new Date().getTime();
192
+ let isResultSerializable = _canSafelyStringify(response.result);
193
+
194
+ _cachedResults[cacheOptions.cacheKey] = {
195
+ ...response,
196
+ result: isResultSerializable ? jsonClone(response.result) : response.result
197
+ };
198
+
199
+ if (!isResultSerializable) {
200
+ logger.warn("When allowCache is true, Blob, ArrayBuffer and Document response types will only be stored in runtime memory and not committed to local storage.");
201
+ }
202
+
203
+ if (isResultSerializable && !isNullOrUndefined(cacheOptions.localStorageExpiration) && response && response.success === true) {
204
+ setCacheItem('jsr_' + cacheOptions.cacheKey, response, cacheOptions.localStorageExpiration as any);
205
+ }
206
+ }
207
+
208
+ function getPendingRequest<T = any>(objects: IRequestObjects): IPendingRequest<T> {
209
+ var cacheKey = objects.cacheOptions.cacheKey;
210
+ if (isNullOrEmptyString(cacheKey)) {
211
+ logger.warn('cache is not supported for this type of request.');
212
+ } else if (!isNullOrUndefined(_pendingRequests[cacheKey])) {
213
+ //returned from cache
214
+ return _pendingRequests[cacheKey];
215
+ }
216
+ return null;
217
+ }
218
+
219
+ function getParsedResponse<T>(objects: IRequestObjects) {
220
+ let parsedResponse: T = null;
221
+ if (!isNullOrEmptyString(objects.options.responseType) && objects.options.responseType !== "text") {
222
+ parsedResponse = objects.xhr.response;
223
+ } else {
224
+ //maybe its not JSON?
225
+ parsedResponse = jsonParse(objects.xhr.responseText);
226
+ if (isNullOrUndefined(parsedResponse)) {
227
+ parsedResponse = objects.xhr.responseText as any;
228
+ }
229
+ }
230
+
231
+ return parsedResponse;
232
+ }
233
+
234
+ function setPendingRequest<T = any>(cacheKey: string, objects: IRequestObjects, promise: Promise<T>): IPendingRequest<T> {
235
+ if (isNullOrEmptyString(cacheKey)) {
236
+ return null;
237
+ }
238
+
239
+ _pendingRequests[cacheKey] = { objects: objects, promise: promise, listeners: [] };
240
+ return _pendingRequests[cacheKey];
241
+ }
242
+
243
+ function removePendingRequest(cacheKey: string) {
244
+ if (isNullOrEmptyString(cacheKey)) {
245
+ return;
246
+ }
247
+
248
+ try {
249
+ _pendingRequests[cacheKey] = null;
250
+ delete _pendingRequests[cacheKey];
251
+ } catch (ex) {
252
+ }
253
+ }
254
+
255
+ function _getRestErrorMessage(xhr: XMLHttpRequest) {
256
+ try {
257
+ //issue 245, external datasource might return error.code as a number with a plain text message.
258
+ if (!isNullOrUndefined(xhr) && !isNullOrEmptyString(xhr.responseText)) {
259
+ let error = jsonParse<{ code: string | number; message: string; }>(xhr.responseText);
260
+ if (!isNullOrUndefined(error) && !isNullOrEmptyString(error.code)) {
261
+ if (isString(error.code) && error.code.indexOf("SPQueryThrottledException") !== -1) {
262
+ return !isNullOrEmptyString(error.message) ? `${error.message} (SPQueryThrottledException)` : `an error occured (SPQueryThrottledException)`;
263
+ }
264
+ if (!isNullOrEmptyString(error.message)) return error.message;
265
+ }
266
+ }
267
+ } catch (e) { }
268
+ return `an error occured`;
269
+ }
270
+
271
+ function _canSafelyStringify(result: any) {
272
+ //this would return false positives on some response strings
273
+ //return isObject(result) && !(result instanceof ArrayBuffer || result instanceof Blob || result instanceof Document);
274
+
275
+ if (isPrimitiveValue(result)) return true;
276
+ else if (isObject(result)) {
277
+ return !(result instanceof ArrayBuffer) && !(result instanceof Blob) && !(result instanceof Document);
278
+ }
279
+ else return false;//shouldn't get here... since result should either be primitive value or an object
280
+ }
281
+
282
+ export function GetJsonSync<T>(url: string, body?: IRequestBody, options?: IRestOptions): IJsonSyncResult<T> {
283
+ let xhr: XMLHttpRequest = null;
284
+ let syncResult: IJsonSyncResult<T> = null;
285
+ let objects = getXhr(url, body, options, false);
286
+ try {
287
+ var cachedResult = getCachedResult<T>(objects);
288
+ if (!isNullOrUndefined(cachedResult)) {
289
+ return cachedResult;
290
+ }
291
+
292
+ xhr = objects.xhr;
293
+
294
+ if (objects.options.method === "GET") {
295
+ objects.xhr.send();
296
+ }
297
+ else {
298
+ objects.xhr.send(body);
299
+ }
300
+
301
+ if (objects.options.returnXhrObject === true) {
302
+ return {
303
+ status: xhr.status,
304
+ success: xhr.status >= 200 && xhr.status < 400,
305
+ result: xhr as any as T
306
+ } as any;
307
+ }
308
+
309
+ // status < 300 leaves out 304 responses which are successful responses so we should use < 400
310
+ if (objects.xhr.status >= 200 && objects.xhr.status < 400) {
311
+ let result: T = getParsedResponse<T>(objects);
312
+
313
+ syncResult = {
314
+ status: xhr.status,
315
+ success: true,
316
+ result: result
317
+ };
318
+
319
+ setCachedResult(objects.cacheOptions, syncResult);
320
+ } else {
321
+ throw new Error("Error code: " + objects.xhr.status);
322
+ }
323
+ } catch (e) {
324
+ //make sure errors get here and not returned without catch...
325
+ let responseText = xhr.responseText;
326
+ let errorData: any;
327
+ if (!isNullOrEmptyString(responseText)) {
328
+ errorData = jsonParse(responseText);
329
+ if (isNullOrUndefined(errorData)) {
330
+ errorData = responseText;
331
+ }
332
+ }
333
+
334
+ let errorMessage = _getRestErrorMessage(xhr);
335
+
336
+ syncResult = {
337
+ status: xhr && xhr.status || -1,
338
+ success: false,
339
+ errorData: errorData,
340
+ errorMessage: errorMessage
341
+ };
342
+ setCachedResult(objects.cacheOptions, syncResult);
343
+ }
344
+ return syncResult;
345
+ }
346
+
347
+ export function GetJson<T>(url: string, body?: IRequestBody, options?: IRestOptions): Promise<T> {
348
+ try {
349
+ let objects = getXhr(url, body, options);
350
+
351
+ var cachedResult = getCachedResult<T>(objects);
352
+ if (!isNullOrUndefined(cachedResult)) {
353
+ if (!supressDebugMessages) {
354
+ logger.debug(`GetJson - request fulfilled by cached results: ${url}`);
355
+ }
356
+ if (cachedResult.success) {
357
+ return Promise.resolve(cachedResult.result);
358
+ }
359
+ else {
360
+ return Promise.reject({
361
+ message: isNullOrEmptyString(cachedResult.errorMessage) ? "an error occured in cached results" : cachedResult.errorMessage,
362
+ errorData: cachedResult.errorData
363
+ } as IRestError);
364
+ }
365
+ }
366
+
367
+ var pendingRequest = getPendingRequest(objects);
368
+ var xhrPromise: Promise<T> = null;
369
+
370
+ if (isNullOrUndefined(pendingRequest)) {
371
+ if (!supressDebugMessages) {
372
+ logger.debug(`GetJson - request fulfilled by new request: ${url}`);
373
+ }
374
+ xhrPromise = new Promise((resolve, reject) => {
375
+ let promiseResolved = false;
376
+
377
+ objects.xhr.addEventListener("readystatechange", () => {
378
+ if (objects.xhr.readyState === XMLHttpRequest.DONE) {
379
+ try {
380
+ if (!supressDebugMessages) {
381
+ logger.debug(`readystate changed: ${url}`);
382
+ }
383
+ if (objects.options.returnXhrObject === true) {
384
+ promiseResolved = true;
385
+ resolve(objects.xhr as any as T);
386
+ }
387
+
388
+ let parsedResponse: T = getParsedResponse<T>(objects);
389
+
390
+ // status < 300 leaves out 304 responses which are successful responses so we should use < 400
391
+ if (objects.xhr.status >= 200 && objects.xhr.status < 400) {
392
+ setCachedResult(objects.cacheOptions, { status: objects.xhr.status, success: true, result: parsedResponse });
393
+ promiseResolved = true;
394
+ resolve(parsedResponse);
395
+ if (pendingRequest) {
396
+ pendingRequest.listeners.forEach(l => {
397
+ let listenerParsedResponse: T = getParsedResponse<T>(objects);
398
+ l.resolve(listenerParsedResponse);
399
+ });
400
+ }
401
+ } else {
402
+ let errorMessage = _getRestErrorMessage(objects.xhr);
403
+ setCachedResult(objects.cacheOptions, { status: objects.xhr.status, success: false, errorData: parsedResponse, errorMessage: errorMessage });
404
+ promiseResolved = true;
405
+ reject({ message: errorMessage, errorData: parsedResponse, xhr: objects.xhr } as IRestError);
406
+ if (pendingRequest) {
407
+ pendingRequest.listeners.forEach(l => l.reject({ message: errorMessage, errorData: parsedResponse, xhr: objects.xhr } as IRestError));
408
+ }
409
+ }
410
+ } catch (e) {
411
+ if (!supressDebugMessages) {
412
+ logger.error(`readystate error: ${e}: ${url}`);
413
+ }
414
+ }
415
+ if (!promiseResolved) {
416
+ if (!supressDebugMessages) {
417
+ logger.debug(`promise NOT resolved. resoving myself...: ${url}`);
418
+ }
419
+
420
+ promiseResolved = true;
421
+ reject({ message: "an unknown error occured", xhr: objects.xhr } as IRestError);
422
+ }
423
+ else if (!supressDebugMessages) {
424
+ logger.debug(`promise resolved. removing pending request object: ${url}`);
425
+ }
426
+
427
+ removePendingRequest(objects.cacheOptions.cacheKey);
428
+ }
429
+ });
430
+ });
431
+
432
+ if (objects.xhr.readyState === XMLHttpRequest.OPENED) {
433
+ //only set this if our request is on the way
434
+ pendingRequest = setPendingRequest(objects.cacheOptions.cacheKey, objects, xhrPromise);
435
+
436
+ if (!supressDebugMessages) {
437
+ logger.debug(`${url}: sending request, setPendingRequest`);
438
+ }
439
+
440
+ if (objects.options.method === "GET") {
441
+ objects.xhr.send();
442
+ } else {
443
+ objects.xhr.send(body);
444
+ }
445
+ }
446
+ else logger.error('xhr not opened');
447
+ } else if (pendingRequest) {
448
+ if (!supressDebugMessages) {
449
+ logger.debug(`GetJson - request fulfilled by pending requests: ${url}`);
450
+ }
451
+ //must add a separate promise, so that I can make a full(not shallow) copy of the result.
452
+ //this way if the first caller changes the object, the second caller gets it unchanged.
453
+ xhrPromise = new Promise<T>((resolve, reject) => {
454
+ pendingRequest.listeners.push({
455
+ resolve: (result: T) => resolve(result),
456
+ reject: (reason) => reject(reason)
457
+ });
458
+ });
459
+ }
460
+
461
+ return xhrPromise;
462
+ } catch (e) {
463
+ return Promise.reject({ message: "an error occured" });
464
+ }
465
+ }
@@ -0,0 +1,168 @@
1
+ import { IKnownScript, isDebug, isNotEmptyArray, isNullOrEmptyString, isNullOrUndefined, ksGlobal, noop } from "./_dependencies";
2
+ import Sod from "./sod";
3
+
4
+ export interface IScriptUtils {
5
+ /** @deprecated - use wrapFunction instead from helpers/functions */
6
+ wrapFunction3?: (originalFunction: () => void, instance: any, doBefore: () => void, doAfter: () => void) => void;
7
+ loadKnownScript: (script: IKnownScript) => void;
8
+ loadKnownScript_Sync: (script: IKnownScript) => void;
9
+ ensureScript: (scriptUrl: string, global: ksGlobal, callback: () => void, sodName: string) => void;
10
+ ensureScripts: (scripts: { scriptUrl: string; global: ksGlobal; sodName: string; }[], callback: () => void) => void;
11
+ }
12
+
13
+ export default class script implements IScriptUtils {
14
+ private static instance: script = null;
15
+ public isRtl = false;
16
+ public static get Instance() {
17
+ if (script.instance === null) {
18
+ //share single instance between all imports
19
+ if (typeof (window as any).kSingleScripts !== 'undefined')
20
+ script.instance = (window as any).kSingleScripts;//a global instance already exists, use it
21
+ else {
22
+ script.instance = new script();
23
+ (window as any).kSingleScripts = script.instance;//place this instance in the global namespace for others to reuse
24
+ }
25
+ }
26
+ return script.instance;
27
+ }
28
+
29
+ public async loadKnownScript(knownScript: IKnownScript) {
30
+ var promisesDependencies: Promise<any>[] = [];
31
+ (knownScript.dependencies || []).forEach(dep => {
32
+ promisesDependencies.push(this.loadKnownScript(dep));
33
+ });
34
+
35
+ if (promisesDependencies.length > 0)
36
+ await Promise.all(promisesDependencies);
37
+
38
+ return new Promise((resolve, reject) => {
39
+ this.ensureKnownScriptInternal(knownScript, () => {
40
+ resolve(Sod.getGlobal(knownScript.global));
41
+ });
42
+ });
43
+ }
44
+ public loadKnownScript_Sync(knownScript: IKnownScript) {
45
+ try {
46
+ if (isNotEmptyArray(knownScript.dependencies)) {
47
+ (knownScript.dependencies || []).forEach(dep => {
48
+ this.loadKnownScript_Sync(dep)
49
+ });
50
+ }
51
+ } catch {
52
+ }
53
+
54
+ this.ensureKnownScriptInternal(knownScript, noop, true);
55
+ return Sod.getGlobal(knownScript.global);
56
+ }
57
+
58
+ private ensureKnownScriptInternal(knownScript: IKnownScript, callback: () => void, sync = false) {
59
+ let url = isDebug() && !knownScript.forceMin ? knownScript.url.replace('.min.js', '.js') : knownScript.url;
60
+ if (url[0] === '/') url = "https://apps.kwizcom.com" + url;
61
+
62
+ if (sync === true)
63
+ this.ensureScriptSync(url, knownScript.global, callback, knownScript.sodName);
64
+ else
65
+ this.ensureScript(url, knownScript.global, callback, knownScript.sodName);
66
+
67
+ let cssFiles = this.isRtl === true && !isNullOrUndefined(knownScript.rtlCss) ? knownScript.rtlCss : knownScript.css;
68
+ if (!isNullOrUndefined(cssFiles))
69
+ cssFiles.forEach(css => {
70
+ if (!isNullOrEmptyString(css)) {
71
+ let cssurl = isDebug() && !knownScript.forceMin ? css.replace('.min.css', '.css') : css;
72
+ if (cssurl[0] === '/') cssurl = "https://apps.kwizcom.com" + cssurl;
73
+
74
+ let knownStyles = document.getElementsByClassName("kwizcom_known_css");
75
+ let found = false;
76
+ for (let si = 0; si < knownStyles.length; si++) {
77
+ let elm: HTMLLinkElement = knownStyles[si] as HTMLLinkElement;
78
+ if (elm.href && elm.href.toLowerCase() === cssurl.toLowerCase()) {
79
+ found = true;
80
+ break;
81
+ }
82
+ }
83
+ if (!found) {
84
+ let link = document.createElement("link");
85
+ link.rel = "stylesheet";
86
+ link.className = "kwizcom_known_css";
87
+ link.type = "text/css";
88
+ link.href = cssurl;
89
+ document.head.appendChild(link);
90
+ }
91
+ }
92
+ });
93
+ }
94
+
95
+ public loadCss(cssUrl: string) {
96
+ let knownStyles = document.getElementsByClassName("kwizcom_known_css");
97
+ let found = false;
98
+ for (let si = 0; si < knownStyles.length; si++) {
99
+ let elm: HTMLLinkElement = knownStyles[si] as HTMLLinkElement;
100
+ if (elm.href && elm.href.toLowerCase() === cssUrl.toLowerCase()) {
101
+ found = true;
102
+ break;
103
+ }
104
+ }
105
+ if (!found) {
106
+ let link = document.createElement("link");
107
+ link.rel = "stylesheet";
108
+ link.className = "kwizcom_known_css";
109
+ link.type = "text/css";
110
+ link.href = cssUrl;
111
+ document.head.appendChild(link);
112
+ }
113
+ }
114
+
115
+ public ensureScriptSync(scriptUrl: string, global: ksGlobal, callback?: () => void, sodName?: string) {
116
+ //in IE there is no promise, we cannot use any async functions
117
+ return Sod.ensureScriptNoPromise(scriptUrl, global, callback, sodName, true);
118
+ }
119
+ public async ensureScript(scriptUrl: string, global: ksGlobal, callback?: () => void, sodName?: string) {
120
+ return Sod.ensureScript(scriptUrl, global, callback, sodName, false);
121
+ }
122
+ /** ensure a collection of scripts and call the callback when they are all done */
123
+ public async ensureScripts(scripts: { scriptUrl: string; global: ksGlobal; sodName: string; }[], callback: () => void) {
124
+ let promises: Promise<void>[] = [];
125
+ let length = scripts.length;
126
+ let finished = 0;
127
+ let onFinished = typeof (callback) !== "function" ? null : () => {
128
+ finished++;
129
+ if (finished === length)//all finished
130
+ callback();
131
+ };
132
+ scripts.forEach(scr => {
133
+ promises.push(Sod.ensureScript(scr.scriptUrl, scr.global, onFinished, scr.sodName));
134
+ });
135
+
136
+ return Promise.all(promises);
137
+ }
138
+
139
+ private _WrapFunctionArr: any[] = [];
140
+
141
+ /** @deprecated - use wrapFunction instead from helpers/functions */
142
+ public wrapFunction3(originalFunction: () => void, instance: any, doBefore: () => void, doAfter: () => void) {
143
+ try {
144
+ if (instance !== null) {
145
+ originalFunction.bind(instance);
146
+ }
147
+ var idx = this._WrapFunctionArr.length;
148
+ this._WrapFunctionArr[idx] = originalFunction;
149
+
150
+ originalFunction = function (...args: any[]) {
151
+ if (typeof (doBefore) === "function") {
152
+ doBefore.apply(instance, args);
153
+ }
154
+ var returnValue = this._WrapFunctionArr[idx].apply(instance, args);
155
+ if (typeof (doAfter) === "function") {
156
+ doAfter.apply(instance, args);
157
+ }
158
+
159
+ return returnValue;
160
+ };
161
+ if (instance !== null) {
162
+ originalFunction.bind(instance);
163
+ }
164
+ } catch (e) {
165
+ if (isDebug()) console.log('unhandled error in wrapFunction3');
166
+ }
167
+ }
168
+ }