@superoffice/webapi 11.7.727 → 11.9.1204

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 (163) hide show
  1. package/LICENSE.md +15 -15
  2. package/README.md +184 -184
  3. package/__tests__/Appointment63-notz.json +1925 -1925
  4. package/__tests__/Appointment63-utctz.json +1925 -1925
  5. package/__tests__/Appointment63.json +1925 -1925
  6. package/__tests__/AppointmentTzTest.ts +115 -115
  7. package/__tests__/AxiosNockTest.ts +28 -28
  8. package/__tests__/ContactDefault.json +699 -699
  9. package/__tests__/ContactEntity.json +272 -272
  10. package/__tests__/ContactRestTest.ts +144 -144
  11. package/__tests__/ContactTest.ts +395 -395
  12. package/__tests__/ConvertersTest.ts +97 -97
  13. package/__tests__/DocumentTest.ts +101 -101
  14. package/__tests__/Person210-notz.json +1932 -1932
  15. package/__tests__/Person210-utctz.json +1932 -1932
  16. package/__tests__/Person210.json +1932 -1932
  17. package/__tests__/PersonImageData.nock +22 -22
  18. package/__tests__/PersonTest.ts +41 -41
  19. package/__tests__/PersonTzTest.ts +113 -113
  20. package/__tests__/RecurrenceInfo.json +55 -55
  21. package/__tests__/ResponseCallbackTest.ts +23 -23
  22. package/__tests__/TableRights.json +441 -441
  23. package/__tests__/WebapiTest.ts +264 -264
  24. package/__tests__/Webhook.json +16 -16
  25. package/__tests__/WebhookTest.ts +209 -209
  26. package/dist/cjs/AIAgent.d.ts +62 -0
  27. package/dist/cjs/AIAgent.d.ts.map +1 -1
  28. package/dist/cjs/AIAgent.js +149 -0
  29. package/dist/cjs/AIAgent.js.map +1 -1
  30. package/dist/cjs/Carriers.d.ts +640 -14
  31. package/dist/cjs/Carriers.d.ts.map +1 -1
  32. package/dist/cjs/Converters.d.ts +24 -0
  33. package/dist/cjs/Converters.d.ts.map +1 -1
  34. package/dist/cjs/Converters.js +388 -17
  35. package/dist/cjs/Converters.js.map +1 -1
  36. package/dist/cjs/DiagnosticsAgent.d.ts +38 -0
  37. package/dist/cjs/DiagnosticsAgent.d.ts.map +1 -1
  38. package/dist/cjs/DiagnosticsAgent.js +91 -0
  39. package/dist/cjs/DiagnosticsAgent.js.map +1 -1
  40. package/dist/cjs/Enums.d.ts +77 -1
  41. package/dist/cjs/Enums.d.ts.map +1 -1
  42. package/dist/cjs/Enums.js +83 -4
  43. package/dist/cjs/Enums.js.map +1 -1
  44. package/dist/cjs/ListAgent.d.ts +71 -6
  45. package/dist/cjs/ListAgent.d.ts.map +1 -1
  46. package/dist/cjs/ListAgent.js +157 -0
  47. package/dist/cjs/ListAgent.js.map +1 -1
  48. package/dist/cjs/MarketingAgent.d.ts +68 -0
  49. package/dist/cjs/MarketingAgent.d.ts.map +1 -1
  50. package/dist/cjs/MarketingAgent.js +157 -0
  51. package/dist/cjs/MarketingAgent.js.map +1 -1
  52. package/dist/cjs/TicketAgent.d.ts +23 -0
  53. package/dist/cjs/TicketAgent.d.ts.map +1 -1
  54. package/dist/cjs/TicketAgent.js +65 -0
  55. package/dist/cjs/TicketAgent.js.map +1 -1
  56. package/dist/esm/AIAgent.d.ts +62 -0
  57. package/dist/esm/AIAgent.d.ts.map +1 -1
  58. package/dist/esm/AIAgent.js +150 -1
  59. package/dist/esm/AIAgent.js.map +1 -1
  60. package/dist/esm/Carriers.d.ts +640 -14
  61. package/dist/esm/Carriers.d.ts.map +1 -1
  62. package/dist/esm/Converters.d.ts +24 -0
  63. package/dist/esm/Converters.d.ts.map +1 -1
  64. package/dist/esm/Converters.js +346 -0
  65. package/dist/esm/Converters.js.map +1 -1
  66. package/dist/esm/DiagnosticsAgent.d.ts +38 -0
  67. package/dist/esm/DiagnosticsAgent.d.ts.map +1 -1
  68. package/dist/esm/DiagnosticsAgent.js +91 -0
  69. package/dist/esm/DiagnosticsAgent.js.map +1 -1
  70. package/dist/esm/Enums.d.ts +77 -1
  71. package/dist/esm/Enums.d.ts.map +1 -1
  72. package/dist/esm/Enums.js +79 -0
  73. package/dist/esm/Enums.js.map +1 -1
  74. package/dist/esm/ListAgent.d.ts +71 -6
  75. package/dist/esm/ListAgent.d.ts.map +1 -1
  76. package/dist/esm/ListAgent.js +157 -0
  77. package/dist/esm/ListAgent.js.map +1 -1
  78. package/dist/esm/MarketingAgent.d.ts +68 -0
  79. package/dist/esm/MarketingAgent.d.ts.map +1 -1
  80. package/dist/esm/MarketingAgent.js +157 -0
  81. package/dist/esm/MarketingAgent.js.map +1 -1
  82. package/dist/esm/TicketAgent.d.ts +23 -0
  83. package/dist/esm/TicketAgent.d.ts.map +1 -1
  84. package/dist/esm/TicketAgent.js +65 -0
  85. package/dist/esm/TicketAgent.js.map +1 -1
  86. package/examples-js/hello.js +12 -12
  87. package/examples-ts/hello.ts +8 -8
  88. package/package.json +93 -93
  89. package/scripts/postbuild.js +22 -22
  90. package/scripts/setVersion.js +44 -44
  91. package/src/AIAgent.ts +2239 -1992
  92. package/src/AppointmentAgent.ts +6263 -6263
  93. package/src/AppointmentRestApi.ts +225 -225
  94. package/src/ArchiveAgent.ts +1950 -1950
  95. package/src/AssociateAgent.ts +422 -422
  96. package/src/AxiosCacheHandler.ts +74 -74
  97. package/src/BLOBAgent.ts +2100 -2100
  98. package/src/Base64.ts +285 -285
  99. package/src/BatchAgent.ts +910 -910
  100. package/src/BulkUpdateAgent.ts +504 -504
  101. package/src/CRMScriptAgent.ts +1390 -1390
  102. package/src/Carriers.ts +53121 -52274
  103. package/src/ChatAgent.ts +1422 -1422
  104. package/src/ConfigurationAgent.ts +2228 -2228
  105. package/src/ContactAgent.ts +1756 -1756
  106. package/src/ContactRestApi.ts +237 -237
  107. package/src/Converters.ts +23496 -23090
  108. package/src/CustomerServiceAgent.ts +1799 -1799
  109. package/src/DashAgent.ts +1674 -1674
  110. package/src/DatabaseAgent.ts +120 -120
  111. package/src/DatabaseTableAgent.ts +534 -534
  112. package/src/Day_js.ts +41 -41
  113. package/src/DiagnosticsAgent.ts +1384 -1240
  114. package/src/DocumentAgent.ts +5079 -5079
  115. package/src/DocumentMigrationAgent.ts +524 -524
  116. package/src/DocumentRestApi.ts +259 -259
  117. package/src/EMailAgent.ts +5328 -5328
  118. package/src/Enums.ts +6998 -6916
  119. package/src/ErpSyncAgent.ts +2658 -2658
  120. package/src/FavouriteAgent.ts +720 -720
  121. package/src/FindAgent.ts +2330 -2330
  122. package/src/ForeignSystemAgent.ts +1710 -1710
  123. package/src/FreeTextAgent.ts +372 -372
  124. package/src/ImportAgent.ts +304 -304
  125. package/src/LicenseAgent.ts +1230 -1230
  126. package/src/ListAgent.ts +11451 -11237
  127. package/src/MDOAgent.ts +748 -748
  128. package/src/MarketingAgent.ts +1146 -890
  129. package/src/MessagingAgent.ts +384 -384
  130. package/src/NavigatorAgent.ts +140 -140
  131. package/src/NumberAllocationAgent.ts +296 -296
  132. package/src/PersonAgent.ts +3287 -3287
  133. package/src/PersonRestApi.ts +241 -241
  134. package/src/PhoneListAgent.ts +458 -458
  135. package/src/PocketAgent.ts +780 -780
  136. package/src/PreferenceAgent.ts +1900 -1900
  137. package/src/PreviewsAgent.ts +116 -116
  138. package/src/ProjectAgent.ts +2391 -2391
  139. package/src/ProjectRestApi.ts +239 -239
  140. package/src/QuoteAgent.ts +5159 -5159
  141. package/src/RelationAgent.ts +220 -220
  142. package/src/ReportAgent.ts +154 -154
  143. package/src/ResourceAgent.ts +358 -358
  144. package/src/SaintAgent.ts +601 -601
  145. package/src/SaleAgent.ts +2034 -2034
  146. package/src/SaleRestApi.ts +233 -233
  147. package/src/SelectionAgent.ts +3195 -3195
  148. package/src/SentryAgent.ts +462 -462
  149. package/src/SoApiConstants.ts +8 -8
  150. package/src/TargetsAgent.ts +1104 -1104
  151. package/src/TicketAgent.ts +3708 -3638
  152. package/src/TimeZoneAgent.ts +528 -528
  153. package/src/TooltipsAgent.ts +116 -116
  154. package/src/UserAgent.ts +4856 -4856
  155. package/src/UserDefinedFieldInfoAgent.ts +1764 -1764
  156. package/src/ViewStateAgent.ts +858 -858
  157. package/src/WebApi.ts +872 -872
  158. package/src/WebApiBase.ts +565 -565
  159. package/src/WebhookAgent.ts +388 -388
  160. package/src/WorkflowAgent.ts +1338 -1338
  161. package/tsconfig.esm.json +8 -8
  162. package/tsconfig.jest.json +8 -8
  163. package/tsconfig.json +34 -34
package/src/WebApiBase.ts CHANGED
@@ -1,565 +1,565 @@
1
- import './Day_js' // ensure day is configured with Duration and UTC
2
-
3
- import axios, {
4
- AxiosInstance,
5
- AxiosRequestConfig,
6
- AxiosResponse,
7
- CancelTokenSource,
8
- InternalAxiosRequestConfig
9
- } from "axios";
10
- import { AxiosCache } from "./AxiosCacheHandler";
11
- import {
12
- HEADER_NAME_ACCEPT_LANGUAGE,
13
- HEADER_NAME_BROWSER_TZ_OFFSET,
14
- HEADER_NAME_CULTURE,
15
- HEADER_NAME_LANGUAGE,
16
- HEADER_NAME_TIMEZONE
17
- } from "./SoApiConstants";
18
-
19
- /** HTTP Request status on options object. Negative values indicate failure or cancellation. */
20
- export enum WebApiStatus {
21
- Unknown = 0,
22
- Pending = 1,
23
- Completed = 10,
24
- Failed = -1,
25
- Cancelled = -4
26
- }
27
-
28
- /** How should Blob objects be returned? */
29
- export enum ReturnBlobType {
30
- /** Return blob as ArrayBuffer */
31
- AsArrayBuffer = 0,
32
- /** Return Base64 string */
33
- AsBase64 = 1,
34
- /** Return blob as string */
35
- AsString = 2
36
- }
37
- /**
38
- * customize a single request: override language, monitor request state, cancel request using cancelToken.
39
- */
40
- export interface WebApiRequestOptions {
41
- /** ISO 2 letter language code ('en', 'sv' etc) or '' to disable language parsing. */
42
- languageCode?: string;
43
- /** ISO 2 letter language code ('en', 'sv' etc) or '' to disable language parsing. */
44
- cultureCode?: string;
45
- /** SuperOffice Timezone ID or name ('UTC', 'AU-WA', 'FR', etc). Blank means the user's current timezone is used; see the SO-TIMEZONE reponse header. */
46
- timezone?: string;
47
- /** Include the timezone info on datetimes in the response? This may trigger conversions. e.g. Datetimes are returned with "Z" or "+2:00" suffix. See the SO-TIMEZONE reponse header. */
48
- timezoneInclude?: boolean;
49
- /** AbortController object - provides a method to abort the request */
50
- abortController?: AbortController;
51
- /** @deprecated cancel token object - provides a cancel(msg) method to abortbort the request */
52
- cancelToken?: CancelTokenSource;
53
- /** Has the HTTP request completed?. Negative values = failure/cancel. Completed OK = 10 */
54
- requestStatus?: WebApiStatus;
55
- /** How should BLOBs be returned: Base64, string or ArrayBuffer. */
56
- returnBlobAs?: ReturnBlobType;
57
- /** Threshold options **/
58
- threshold?: IThreshold;
59
- /** Do something with the response. Use to fetch headers etc. in the response **/
60
- responseCallback?: (response: AxiosResponse) => void;
61
- }
62
-
63
- /**
64
- * Set a threshold on the request. When timeout is reached, callback will be executed. If request finished within timeout a successCallback is called
65
- */
66
- export interface IThreshold {
67
- //Called when timeout is reached
68
- callback?: () => void;
69
- //Called when timeout is not reached
70
- successCallback?: () => void;
71
- //Called when thr request failed
72
- errorCallback?: () => void;
73
- //Threashold time
74
- timeout: number;
75
- //setTimeout handler
76
- timeoutHandler?: any;
77
- }
78
-
79
- /**
80
- * GET requests for the REST API
81
- */
82
- export interface WebApiGetRequestOptions extends WebApiRequestOptions {
83
- /** Return entity only if it has been modified after the date, otherwise return HTTP 304 NotModified */
84
- ifModifiedSince?: Date;
85
-
86
- /** Return entity only if it has not been modified after the date, otherwise return HTTP 412 PreconditionFailed */
87
- ifUnmodifiedSince?: Date;
88
-
89
- /** Should HTTP 304 NotModified response throw error or return NULL? Default = return NULL */
90
- ifNotModifiedThrowError?: boolean;
91
- }
92
-
93
- /**
94
- * PUT and PATCH and DELETE requests for the REST API
95
- */
96
- export interface WebApiPutRequestOptions extends WebApiRequestOptions {
97
- /** Return entity only if it has not been modified after the date, otherwise return HTTP 412 PreconditionFailed */
98
- ifUnmodifiedSince?: Date;
99
- }
100
-
101
- /** RFC6902 patch operations */
102
- export enum WebApiPatchOp {
103
- add = "add",
104
- remove = "remove",
105
- replace = "replace",
106
- test = "test"
107
- }
108
-
109
- /** RFC6902 patch operation description. */
110
- export interface WebApiPatchOperation {
111
- /** "add", "remove", "replace", or "test" */
112
- op: WebApiPatchOp;
113
- /** Path to property to apply op to: "/Department" - case insensitive. */
114
- path: string;
115
- /** Value to replace/add to the property identified by path. Not used by "remove" op. */
116
- value?: any;
117
- }
118
-
119
- /**
120
- * Configure the agent with a default URL, language values, whether to parse resource strings.
121
- * Can be overriden on individual requests using WebApiRequestOptions
122
- */
123
- export interface WebApiOptions {
124
- /** The URL to API endpoint. 'https://crm.example.com/api' */
125
- baseUrl?: string;
126
- /** Additional path to add to the baseUrl. For internal use */
127
- basePath?: string;
128
- /** Should we send a language/culture header? */
129
- resourceParsing?: ResourceParsing;
130
- /** Language ISO code to parse responses to. Sends to server using Accept-Language header. e.g. 'en' or 'sv' */
131
- languageCode?: string;
132
- /** Language ISO code to parse values to. Sends to server using SO-CULTURE header. e.g. 'en' or 'sv'. Defaults to same as languageCode. */
133
- cultureCode?: string;
134
- /** SuperOffice Timezone ID ('UTC', 'AU-WA', 'FR', etc) or '' to disable timezone conversions */
135
- timezone?: string;
136
- /** Include the timezone info on the response? This may trigger conversions into local timezone by the runtime */
137
- timezoneInclude?: boolean;
138
- axios?: AxiosInstance;
139
- /** Default axios configuration. Overridden by languageCode/cultureCode. */
140
- axiosConfig?: AxiosRequestConfig;
141
- resourceManager?: any;
142
- cache?: cacheOptions;
143
- errorHandler?: (error: any) => Promise<any>;
144
- }
145
-
146
- export interface cacheOptions {
147
- refresh?: boolean;
148
- duration?: number;
149
- }
150
-
151
- /** Should WebAPI decode resource and multilang strings? Sets HTTP Language and Culture request headers to blank. */
152
- export enum ResourceParsing {
153
- /** Enables string substitution in responses. Sends the culture/language header. */
154
- Parse = 0,
155
- /** Disables string substitution. Does not send culture/language header. */
156
- DoNotParse = 1
157
- }
158
-
159
- /** Base class for /api/v1/Agents/ clients */
160
- export class WebApiBase {
161
- public static _global_options: WebApiOptions;
162
- protected _options: WebApiOptions;
163
- protected _axios: AxiosInstance;
164
-
165
- constructor(options: WebApiOptions, createAxios: boolean = true) {
166
- const nodejs = typeof process !== "undefined" && process.versions && process.versions.node;
167
- const isBrowser = !nodejs && (typeof window !== "undefined" || typeof self !== "undefined");
168
- if (!isBrowser && !options.baseUrl) throw new Error("WebAPI: BaseURL is not defined.");
169
-
170
- if (!WebApiBase._global_options) WebApiBase._global_options = WebApiBase.CloneOptions(options);
171
-
172
- this.SetBaseUrl(options);
173
-
174
- if (options.resourceManager && options.resourceManager.getCurrentLangCode) {
175
- options.languageCode = options.resourceManager.getCurrentLangCode();
176
- }
177
- if (options.resourceManager && options.resourceManager.getCurrentFormatCode) {
178
- options.cultureCode = options.resourceManager.getCurrentFormatCode();
179
- }
180
- if (!options.axios && createAxios) {
181
- options.axios = axios.create(options.axiosConfig);
182
- // Set UserAgent if not in browser
183
- if (!isBrowser) options.axios.defaults.headers["User-Agent"] = "SO-TS-WebApi/1.0";
184
- options.axios.defaults.headers["Content-Type"] = "application/json";
185
- options.axios.defaults.headers[HEADER_NAME_BROWSER_TZ_OFFSET] =
186
- -new Date().getTimezoneOffset();
187
-
188
- if (options.languageCode)
189
- options.axios.defaults.headers[HEADER_NAME_LANGUAGE] = options.languageCode;
190
- if (options.cultureCode)
191
- options.axios.defaults.headers[HEADER_NAME_CULTURE] = options.cultureCode;
192
- if (options.timezone) options.axios.defaults.headers[HEADER_NAME_TIMEZONE] = options.timezone;
193
- if (options.timezoneInclude) {
194
- options.axios.defaults.headers[HEADER_NAME_TIMEZONE] =
195
- options.axios.defaults.headers[HEADER_NAME_TIMEZONE] ?? "";
196
- if (options.axios.defaults.headers[HEADER_NAME_TIMEZONE])
197
- options.axios.defaults.headers[HEADER_NAME_TIMEZONE] += ",";
198
- options.axios.defaults.headers[HEADER_NAME_TIMEZONE] += "includeTZOffset";
199
- }
200
-
201
- if (options.resourceParsing === ResourceParsing.DoNotParse) {
202
- options.axios.defaults.headers[HEADER_NAME_ACCEPT_LANGUAGE] = "";
203
- options.axios.defaults.headers[HEADER_NAME_LANGUAGE] = "";
204
- options.axios.defaults.headers[HEADER_NAME_CULTURE] = "";
205
- delete options.axios.defaults.headers[HEADER_NAME_LANGUAGE];
206
- delete options.axios.defaults.headers[HEADER_NAME_CULTURE];
207
- }
208
- if (options.cache) {
209
- options.axios.interceptors.request.use(request =>
210
- this.requestHandler(request, options.cache)
211
- );
212
- options.axios.interceptors.response.use(
213
- response => this.responseHandler(response, options.cache),
214
- error => this.errorHandler(error)
215
- );
216
- } else {
217
- options.axios.interceptors.response.use(undefined, options.errorHandler);
218
- }
219
- }
220
- this._options = options;
221
- this._axios = options.axios;
222
- }
223
- private responseHandler(response: AxiosResponse<any>, cache: cacheOptions): AxiosResponse<any> {
224
- if (response.config.url) {
225
- AxiosCache.store(response.config["cachekey"], response.data, cache.duration);
226
- }
227
- return response;
228
- }
229
-
230
- //Handler when cache hits in requestHandler
231
- private errorHandler(error: any) {
232
- if (error && error.headers && error.headers.cached === "true") {
233
- return Promise.resolve(error);
234
- }
235
- if (this._options.errorHandler) {
236
- return this._options.errorHandler(error);
237
- }
238
- return Promise.reject(error);
239
- }
240
-
241
- private requestHandler(request: InternalAxiosRequestConfig, cache?: cacheOptions) {
242
- //if refresh we do nothing
243
- if (cache.refresh) {
244
- return request;
245
- }
246
-
247
- request["cachekey"] =
248
- this.hashValue(request.url + JSON.stringify(request.data)) +
249
- (request.headers.get(HEADER_NAME_LANGUAGE) ? request.headers.get(HEADER_NAME_LANGUAGE) : "");
250
-
251
- const checkIsValidResponse = AxiosCache.isValid(request["cachekey"] || "");
252
- if (checkIsValidResponse.isValid) {
253
- request.headers.set("cached", "true");
254
- request.data = checkIsValidResponse.value || "{}";
255
- // we 'fail' the request and let the error handler take care of the promise
256
- return Promise.reject(request);
257
- }
258
-
259
- return request;
260
- }
261
-
262
- protected SetBaseUrl(options: WebApiOptions): void {
263
- if (options.baseUrl === "") options.baseUrl = "/api/";
264
- if (options.baseUrl.lastIndexOf("/") < options.baseUrl.length - 1) options.baseUrl += "/";
265
- // Move BasePath onto BaseUrl
266
- if (options.basePath) {
267
- if (options.baseUrl.lastIndexOf("api/") < options.baseUrl.length - 4)
268
- options.baseUrl += "api/";
269
- options.baseUrl += options.basePath;
270
- options.basePath = undefined;
271
- }
272
- }
273
- private hashValue(s) {
274
- if (!s) return "";
275
- return (
276
- "_" +
277
- s.split("").reduce(function (a, b) {
278
- a = (a << 5) - a + b.charCodeAt(0);
279
- return a & a;
280
- }, 0)
281
- );
282
- }
283
- protected static CloneOptions(options: WebApiOptions): WebApiOptions {
284
- const clone: WebApiOptions = {
285
- baseUrl: options.baseUrl,
286
- resourceParsing: options.resourceParsing,
287
- languageCode: options.languageCode,
288
- cultureCode: options.cultureCode,
289
- timezone: options.timezone,
290
- timezoneInclude: options.timezoneInclude,
291
- axios: options.axios,
292
- axiosConfig: options.axiosConfig,
293
- resourceManager: options.resourceManager,
294
- cache: options.cache,
295
- errorHandler: options.errorHandler
296
- };
297
- return clone;
298
- }
299
-
300
- public static GetAxiosRequestConfig(
301
- options?: WebApiRequestOptions,
302
- baseOptions?: WebApiOptions
303
- ): AxiosRequestConfig {
304
- let config: AxiosRequestConfig = null;
305
- if (baseOptions) {
306
- if (baseOptions.axiosConfig) config = { ...baseOptions.axiosConfig }; // clone axios config
307
- config = config || {};
308
- if (baseOptions.baseUrl) config.baseURL = baseOptions.baseUrl;
309
- }
310
- config = config || {};
311
- config.params = config.params || {};
312
- config.headers = config.headers || {};
313
- config.headers["Accept"] = "application/json";
314
-
315
- if (options) {
316
- options.requestStatus = WebApiStatus.Pending;
317
- if (typeof options.languageCode == "string") {
318
- config.headers[HEADER_NAME_ACCEPT_LANGUAGE] = options.languageCode;
319
- config.headers[HEADER_NAME_LANGUAGE] = options.languageCode;
320
- }
321
- if (typeof options.cultureCode == "string") {
322
- config.headers[HEADER_NAME_CULTURE] = options.cultureCode;
323
- }
324
- if (typeof options.timezone == "string") {
325
- config.headers[HEADER_NAME_TIMEZONE] = options.timezone;
326
- }
327
- if (options.timezoneInclude) {
328
- config.headers[HEADER_NAME_TIMEZONE] = config.headers[HEADER_NAME_TIMEZONE] ?? "";
329
- if (config.headers[HEADER_NAME_TIMEZONE]) config.headers[HEADER_NAME_TIMEZONE] += ",";
330
- config.headers[HEADER_NAME_TIMEZONE] += "includeTZOffset";
331
- }
332
- // If we have abortController, do not use cancel token
333
- if (options.abortController) {
334
- config.signal = options.abortController.signal;
335
- } else if (options.cancelToken) {
336
- config.cancelToken = options.cancelToken.token;
337
- }
338
- if (options.abortController) {
339
- config.signal = options.abortController.signal;
340
- }
341
- const getOptions = options as WebApiGetRequestOptions;
342
- if (getOptions && getOptions.ifModifiedSince) {
343
- if (typeof getOptions.ifModifiedSince == "object")
344
- config.headers["If-Modified-Since"] = getOptions.ifModifiedSince.toUTCString();
345
- if (typeof getOptions.ifModifiedSince == "string")
346
- config.headers["If-Modified-Since"] = getOptions.ifModifiedSince;
347
- if (!getOptions.ifNotModifiedThrowError)
348
- config.validateStatus = WebApiBase.validateModifiedStatus;
349
- else config.validateStatus = WebApiBase.validate200Status; // 304 throws error
350
- }
351
- if (getOptions && getOptions.ifUnmodifiedSince) {
352
- if (typeof getOptions.ifUnmodifiedSince == "object")
353
- config.headers["If-Unmodified-Since"] = getOptions.ifUnmodifiedSince.toUTCString();
354
- if (typeof getOptions.ifUnmodifiedSince == "string")
355
- config.headers["If-Unmodified-Since"] = getOptions.ifUnmodifiedSince;
356
- }
357
- const putOptions = options as WebApiPutRequestOptions;
358
- if (putOptions && putOptions.ifUnmodifiedSince) {
359
- if (typeof putOptions.ifUnmodifiedSince == "object")
360
- config.headers["If-Unmodified-Since"] = putOptions.ifUnmodifiedSince.toUTCString();
361
- if (typeof putOptions.ifUnmodifiedSince == "string")
362
- config.headers["If-Unmodified-Since"] = putOptions.ifUnmodifiedSince;
363
- }
364
- }
365
- WebApiBase.SetXSRFTokenFromHiddenField();
366
- return config;
367
- }
368
-
369
- public static SetXSRFTokenFromHiddenField() {
370
- // don't do this if we are not in browser context
371
- if (typeof window != "undefined" && document && document.cookie) {
372
- if (document.cookie.indexOf("XSRF-TOKEN") < 0) {
373
- // no XSRF-TOKEN cookie - see if we can add one from the hidden form field
374
- let xsrfToken = undefined;
375
- let msg = undefined;
376
- const xsrfInput = document.getElementById("XSRF_TOKEN") as HTMLInputElement;
377
- if (xsrfInput) {
378
- xsrfToken = xsrfInput.value;
379
- msg = "Setting XSRF cookie from INPUT field";
380
- }
381
- if (!xsrfToken) {
382
- // still no XSRF-TOKEN value
383
- msg = "No XSRF cookie found.";
384
- if (console) console.log(msg);
385
- }
386
- if (xsrfToken) {
387
- // Normalize path:
388
- // "/crm.web/admin/default.aspx" --> "/crm.web/"
389
- // '/crm.web/cs/scripts/ticket.exe' --> '/crm.web/cs/"
390
- let path = window.location.pathname;
391
- let lowpath = path.toLowerCase();
392
- if (lowpath.endsWith("default.aspx")) path = path.substring(0, path.length - 12);
393
- lowpath = path.toLowerCase();
394
- if (lowpath.endsWith("/")) path = path.substring(0, path.length - 1);
395
- lowpath = path.toLowerCase();
396
- if (lowpath.endsWith("/admin")) path = path.substring(0, path.length - 6);
397
- lowpath = path.toLowerCase();
398
- let scriptsPos = lowpath.indexOf("/scripts/");
399
- let exePos = lowpath.indexOf(".fcgi");
400
- if (exePos < 0) exePos = lowpath.indexOf(".exe");
401
- if (scriptsPos > 0 && exePos > 0) {
402
- path = path.substring(0, scriptsPos); // /crm.web/cs/scripts/ticket.exe' --> '/crm.web/cs'
403
- let slashPos = path.lastIndexOf("/");
404
- if (slashPos > 1) path = path.substring(0, slashPos); // '/crm.web/cs' --> ''/crm.web'
405
- }
406
- document.cookie = "XSRF-TOKEN=" + xsrfToken + ";SameSite=Lax;Secure;path=" + path;
407
- if (console) console.log(msg);
408
- document.cookie = "XSRF-FROM-INPUT=" + path + ";SameSite=Lax;Secure;"; // path defaults to document location
409
- }
410
- }
411
- }
412
- }
413
-
414
- // `validateStatus` defines whether to resolve or reject the promise for a given
415
- // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
416
- // or `undefined`), the promise will be resolved; otherwise, the promise will be
417
- // rejected.
418
- // validate 304 Unmodified as ok
419
- private static validateModifiedStatus(status: number): boolean {
420
- const validate: boolean = (status >= 200 && status < 300) || status === 304;
421
- return validate;
422
- }
423
- private static validate200Status(status: number): boolean {
424
- const validate: boolean = status >= 200 && status < 300;
425
- return validate;
426
- }
427
-
428
- public static FigureOutOptions(
429
- baseUrlOrOptions: string | WebApiOptions | undefined,
430
- langOrconfigOrRMOrParse?: string | ResourceParsing | AxiosRequestConfig | any,
431
- langOrResourceOrRM?: string | ResourceParsing | any,
432
- cultureCode?: string
433
- ): WebApiOptions {
434
- let options: WebApiOptions = {};
435
-
436
- if (typeof baseUrlOrOptions == "object") {
437
- // Make a copy so we don't mess up caller's copy of options object
438
- options = baseUrlOrOptions as WebApiOptions;
439
- options = WebApiBase.CloneOptions(options);
440
- } else if (typeof baseUrlOrOptions == "string") {
441
- options = {
442
- baseUrl: baseUrlOrOptions as string
443
- };
444
- }
445
-
446
- if (typeof langOrconfigOrRMOrParse == "string") {
447
- options.languageCode = langOrconfigOrRMOrParse as string;
448
- } else if (typeof langOrconfigOrRMOrParse == "object") {
449
- if (langOrconfigOrRMOrParse.getCurrentLangCode && langOrconfigOrRMOrParse.getCurrentLangCode)
450
- options.resourceManager = langOrconfigOrRMOrParse;
451
- if (
452
- langOrconfigOrRMOrParse.auth ||
453
- langOrconfigOrRMOrParse.baseURL ||
454
- langOrconfigOrRMOrParse.url ||
455
- langOrconfigOrRMOrParse.headers ||
456
- langOrconfigOrRMOrParse.timeout
457
- )
458
- options.axiosConfig = langOrconfigOrRMOrParse as AxiosRequestConfig;
459
- } else if (typeof langOrconfigOrRMOrParse == "number") {
460
- options.resourceParsing = langOrconfigOrRMOrParse as ResourceParsing;
461
- }
462
-
463
- if (typeof langOrResourceOrRM == "string") {
464
- options.languageCode = langOrResourceOrRM as string;
465
- } else if (typeof langOrResourceOrRM == "number") {
466
- options.resourceParsing = langOrResourceOrRM as ResourceParsing;
467
- } else if (typeof langOrResourceOrRM == "object") {
468
- if (langOrResourceOrRM.getCurrentLangCode && langOrResourceOrRM.getCurrentLangCode)
469
- options.resourceManager = langOrResourceOrRM;
470
- if (
471
- langOrResourceOrRM.auth ||
472
- langOrResourceOrRM.baseURL ||
473
- langOrResourceOrRM.url ||
474
- langOrResourceOrRM.headers ||
475
- langOrResourceOrRM.timeout
476
- )
477
- options.axiosConfig = langOrResourceOrRM as AxiosRequestConfig;
478
- }
479
-
480
- if (cultureCode) options.cultureCode = cultureCode;
481
-
482
- // Check for global defaults for missing properties
483
- if (WebApiBase._global_options) {
484
- if (!options.baseUrl) options.baseUrl = WebApiBase._global_options.baseUrl;
485
- if (!options.axios) options.axios = WebApiBase._global_options.axios;
486
- if (!options.axiosConfig) options.axiosConfig = WebApiBase._global_options.axiosConfig;
487
- if (!options.cultureCode) options.cultureCode = WebApiBase._global_options.cultureCode;
488
- if (!options.languageCode) options.languageCode = WebApiBase._global_options.languageCode;
489
- if (!options.timezone) options.timezone = WebApiBase._global_options.timezone;
490
- if (options.timezoneInclude === undefined)
491
- options.timezoneInclude = WebApiBase._global_options.timezoneInclude;
492
- if (!options.resourceManager)
493
- options.resourceManager = WebApiBase._global_options.resourceManager;
494
- if (!options.errorHandler) options.errorHandler = WebApiBase._global_options.errorHandler;
495
- }
496
-
497
- return options;
498
- }
499
-
500
- /** @deprecated Make a new cancel token that can be placed in an WebApiRequestOptions object. */
501
- public MakeCancelToken(): CancelTokenSource {
502
- return axios.CancelToken.source();
503
- }
504
-
505
- /** Make a new AbortController that can be placed in an WebApiRequestOptions object */
506
- public MakeAbortController(): AbortController {
507
- return new AbortController();
508
- }
509
-
510
- /** @deprecated Make a new options object with an cancelToken on it. */
511
- public MakeOptions(): WebApiRequestOptions {
512
- const opts: WebApiRequestOptions = {};
513
- opts.requestStatus = WebApiStatus.Unknown;
514
- opts.cancelToken = this.MakeCancelToken();
515
- return opts;
516
- }
517
-
518
- /** Make a new options object with an abortController on it */
519
- public MakeAbortableOptions(): WebApiRequestOptions {
520
- const opts: WebApiRequestOptions = {};
521
- opts.requestStatus = WebApiStatus.Unknown;
522
- opts.abortController = this.MakeAbortController();
523
- return opts;
524
- }
525
-
526
- public static SetPending(options: WebApiRequestOptions) {
527
- if (options) options.requestStatus = WebApiStatus.Pending;
528
-
529
- if (options && options.threshold) {
530
- options.threshold.timeoutHandler = setTimeout(() => {
531
- //We do not want successCallback to be call if the threshold is reached
532
- if (options.threshold.timeout > 0) options.threshold.successCallback = null;
533
- options.threshold.callback();
534
- }, options.threshold.timeout);
535
- }
536
- if (options?.cancelToken?.token.reason) options.requestStatus = WebApiStatus.Cancelled;
537
- }
538
-
539
- public static SetCompleted(options: WebApiRequestOptions, response: AxiosResponse) {
540
- if (options) {
541
- if (options?.threshold) {
542
- clearTimeout(options.threshold.timeoutHandler);
543
- if (options.threshold.successCallback) options.threshold.successCallback();
544
- }
545
- options.responseCallback?.(response);
546
- if (options.cancelToken?.token?.reason) options.requestStatus = WebApiStatus.Cancelled;
547
- else options.requestStatus = WebApiStatus.Completed;
548
- }
549
- }
550
-
551
- public static HandleError(options: WebApiRequestOptions, config: AxiosRequestConfig, err: any) {
552
- if (options) {
553
- if (options && options.threshold) {
554
- clearTimeout(options.threshold.timeoutHandler);
555
- if (options.threshold.errorCallback) options.threshold.errorCallback();
556
- }
557
-
558
- if ((config?.signal || config?.cancelToken) && axios.isCancel(err)) {
559
- options.requestStatus = WebApiStatus.Cancelled;
560
- } else {
561
- options.requestStatus = WebApiStatus.Failed;
562
- }
563
- }
564
- }
565
- }
1
+ import './Day_js' // ensure day is configured with Duration and UTC
2
+
3
+ import axios, {
4
+ AxiosInstance,
5
+ AxiosRequestConfig,
6
+ AxiosResponse,
7
+ CancelTokenSource,
8
+ InternalAxiosRequestConfig
9
+ } from "axios";
10
+ import { AxiosCache } from "./AxiosCacheHandler";
11
+ import {
12
+ HEADER_NAME_ACCEPT_LANGUAGE,
13
+ HEADER_NAME_BROWSER_TZ_OFFSET,
14
+ HEADER_NAME_CULTURE,
15
+ HEADER_NAME_LANGUAGE,
16
+ HEADER_NAME_TIMEZONE
17
+ } from "./SoApiConstants";
18
+
19
+ /** HTTP Request status on options object. Negative values indicate failure or cancellation. */
20
+ export enum WebApiStatus {
21
+ Unknown = 0,
22
+ Pending = 1,
23
+ Completed = 10,
24
+ Failed = -1,
25
+ Cancelled = -4
26
+ }
27
+
28
+ /** How should Blob objects be returned? */
29
+ export enum ReturnBlobType {
30
+ /** Return blob as ArrayBuffer */
31
+ AsArrayBuffer = 0,
32
+ /** Return Base64 string */
33
+ AsBase64 = 1,
34
+ /** Return blob as string */
35
+ AsString = 2
36
+ }
37
+ /**
38
+ * customize a single request: override language, monitor request state, cancel request using cancelToken.
39
+ */
40
+ export interface WebApiRequestOptions {
41
+ /** ISO 2 letter language code ('en', 'sv' etc) or '' to disable language parsing. */
42
+ languageCode?: string;
43
+ /** ISO 2 letter language code ('en', 'sv' etc) or '' to disable language parsing. */
44
+ cultureCode?: string;
45
+ /** SuperOffice Timezone ID or name ('UTC', 'AU-WA', 'FR', etc). Blank means the user's current timezone is used; see the SO-TIMEZONE reponse header. */
46
+ timezone?: string;
47
+ /** Include the timezone info on datetimes in the response? This may trigger conversions. e.g. Datetimes are returned with "Z" or "+2:00" suffix. See the SO-TIMEZONE reponse header. */
48
+ timezoneInclude?: boolean;
49
+ /** AbortController object - provides a method to abort the request */
50
+ abortController?: AbortController;
51
+ /** @deprecated cancel token object - provides a cancel(msg) method to abortbort the request */
52
+ cancelToken?: CancelTokenSource;
53
+ /** Has the HTTP request completed?. Negative values = failure/cancel. Completed OK = 10 */
54
+ requestStatus?: WebApiStatus;
55
+ /** How should BLOBs be returned: Base64, string or ArrayBuffer. */
56
+ returnBlobAs?: ReturnBlobType;
57
+ /** Threshold options **/
58
+ threshold?: IThreshold;
59
+ /** Do something with the response. Use to fetch headers etc. in the response **/
60
+ responseCallback?: (response: AxiosResponse) => void;
61
+ }
62
+
63
+ /**
64
+ * Set a threshold on the request. When timeout is reached, callback will be executed. If request finished within timeout a successCallback is called
65
+ */
66
+ export interface IThreshold {
67
+ //Called when timeout is reached
68
+ callback?: () => void;
69
+ //Called when timeout is not reached
70
+ successCallback?: () => void;
71
+ //Called when thr request failed
72
+ errorCallback?: () => void;
73
+ //Threashold time
74
+ timeout: number;
75
+ //setTimeout handler
76
+ timeoutHandler?: any;
77
+ }
78
+
79
+ /**
80
+ * GET requests for the REST API
81
+ */
82
+ export interface WebApiGetRequestOptions extends WebApiRequestOptions {
83
+ /** Return entity only if it has been modified after the date, otherwise return HTTP 304 NotModified */
84
+ ifModifiedSince?: Date;
85
+
86
+ /** Return entity only if it has not been modified after the date, otherwise return HTTP 412 PreconditionFailed */
87
+ ifUnmodifiedSince?: Date;
88
+
89
+ /** Should HTTP 304 NotModified response throw error or return NULL? Default = return NULL */
90
+ ifNotModifiedThrowError?: boolean;
91
+ }
92
+
93
+ /**
94
+ * PUT and PATCH and DELETE requests for the REST API
95
+ */
96
+ export interface WebApiPutRequestOptions extends WebApiRequestOptions {
97
+ /** Return entity only if it has not been modified after the date, otherwise return HTTP 412 PreconditionFailed */
98
+ ifUnmodifiedSince?: Date;
99
+ }
100
+
101
+ /** RFC6902 patch operations */
102
+ export enum WebApiPatchOp {
103
+ add = "add",
104
+ remove = "remove",
105
+ replace = "replace",
106
+ test = "test"
107
+ }
108
+
109
+ /** RFC6902 patch operation description. */
110
+ export interface WebApiPatchOperation {
111
+ /** "add", "remove", "replace", or "test" */
112
+ op: WebApiPatchOp;
113
+ /** Path to property to apply op to: "/Department" - case insensitive. */
114
+ path: string;
115
+ /** Value to replace/add to the property identified by path. Not used by "remove" op. */
116
+ value?: any;
117
+ }
118
+
119
+ /**
120
+ * Configure the agent with a default URL, language values, whether to parse resource strings.
121
+ * Can be overriden on individual requests using WebApiRequestOptions
122
+ */
123
+ export interface WebApiOptions {
124
+ /** The URL to API endpoint. 'https://crm.example.com/api' */
125
+ baseUrl?: string;
126
+ /** Additional path to add to the baseUrl. For internal use */
127
+ basePath?: string;
128
+ /** Should we send a language/culture header? */
129
+ resourceParsing?: ResourceParsing;
130
+ /** Language ISO code to parse responses to. Sends to server using Accept-Language header. e.g. 'en' or 'sv' */
131
+ languageCode?: string;
132
+ /** Language ISO code to parse values to. Sends to server using SO-CULTURE header. e.g. 'en' or 'sv'. Defaults to same as languageCode. */
133
+ cultureCode?: string;
134
+ /** SuperOffice Timezone ID ('UTC', 'AU-WA', 'FR', etc) or '' to disable timezone conversions */
135
+ timezone?: string;
136
+ /** Include the timezone info on the response? This may trigger conversions into local timezone by the runtime */
137
+ timezoneInclude?: boolean;
138
+ axios?: AxiosInstance;
139
+ /** Default axios configuration. Overridden by languageCode/cultureCode. */
140
+ axiosConfig?: AxiosRequestConfig;
141
+ resourceManager?: any;
142
+ cache?: cacheOptions;
143
+ errorHandler?: (error: any) => Promise<any>;
144
+ }
145
+
146
+ export interface cacheOptions {
147
+ refresh?: boolean;
148
+ duration?: number;
149
+ }
150
+
151
+ /** Should WebAPI decode resource and multilang strings? Sets HTTP Language and Culture request headers to blank. */
152
+ export enum ResourceParsing {
153
+ /** Enables string substitution in responses. Sends the culture/language header. */
154
+ Parse = 0,
155
+ /** Disables string substitution. Does not send culture/language header. */
156
+ DoNotParse = 1
157
+ }
158
+
159
+ /** Base class for /api/v1/Agents/ clients */
160
+ export class WebApiBase {
161
+ public static _global_options: WebApiOptions;
162
+ protected _options: WebApiOptions;
163
+ protected _axios: AxiosInstance;
164
+
165
+ constructor(options: WebApiOptions, createAxios: boolean = true) {
166
+ const nodejs = typeof process !== "undefined" && process.versions && process.versions.node;
167
+ const isBrowser = !nodejs && (typeof window !== "undefined" || typeof self !== "undefined");
168
+ if (!isBrowser && !options.baseUrl) throw new Error("WebAPI: BaseURL is not defined.");
169
+
170
+ if (!WebApiBase._global_options) WebApiBase._global_options = WebApiBase.CloneOptions(options);
171
+
172
+ this.SetBaseUrl(options);
173
+
174
+ if (options.resourceManager && options.resourceManager.getCurrentLangCode) {
175
+ options.languageCode = options.resourceManager.getCurrentLangCode();
176
+ }
177
+ if (options.resourceManager && options.resourceManager.getCurrentFormatCode) {
178
+ options.cultureCode = options.resourceManager.getCurrentFormatCode();
179
+ }
180
+ if (!options.axios && createAxios) {
181
+ options.axios = axios.create(options.axiosConfig);
182
+ // Set UserAgent if not in browser
183
+ if (!isBrowser) options.axios.defaults.headers["User-Agent"] = "SO-TS-WebApi/1.0";
184
+ options.axios.defaults.headers["Content-Type"] = "application/json";
185
+ options.axios.defaults.headers[HEADER_NAME_BROWSER_TZ_OFFSET] =
186
+ -new Date().getTimezoneOffset();
187
+
188
+ if (options.languageCode)
189
+ options.axios.defaults.headers[HEADER_NAME_LANGUAGE] = options.languageCode;
190
+ if (options.cultureCode)
191
+ options.axios.defaults.headers[HEADER_NAME_CULTURE] = options.cultureCode;
192
+ if (options.timezone) options.axios.defaults.headers[HEADER_NAME_TIMEZONE] = options.timezone;
193
+ if (options.timezoneInclude) {
194
+ options.axios.defaults.headers[HEADER_NAME_TIMEZONE] =
195
+ options.axios.defaults.headers[HEADER_NAME_TIMEZONE] ?? "";
196
+ if (options.axios.defaults.headers[HEADER_NAME_TIMEZONE])
197
+ options.axios.defaults.headers[HEADER_NAME_TIMEZONE] += ",";
198
+ options.axios.defaults.headers[HEADER_NAME_TIMEZONE] += "includeTZOffset";
199
+ }
200
+
201
+ if (options.resourceParsing === ResourceParsing.DoNotParse) {
202
+ options.axios.defaults.headers[HEADER_NAME_ACCEPT_LANGUAGE] = "";
203
+ options.axios.defaults.headers[HEADER_NAME_LANGUAGE] = "";
204
+ options.axios.defaults.headers[HEADER_NAME_CULTURE] = "";
205
+ delete options.axios.defaults.headers[HEADER_NAME_LANGUAGE];
206
+ delete options.axios.defaults.headers[HEADER_NAME_CULTURE];
207
+ }
208
+ if (options.cache) {
209
+ options.axios.interceptors.request.use(request =>
210
+ this.requestHandler(request, options.cache)
211
+ );
212
+ options.axios.interceptors.response.use(
213
+ response => this.responseHandler(response, options.cache),
214
+ error => this.errorHandler(error)
215
+ );
216
+ } else {
217
+ options.axios.interceptors.response.use(undefined, options.errorHandler);
218
+ }
219
+ }
220
+ this._options = options;
221
+ this._axios = options.axios;
222
+ }
223
+ private responseHandler(response: AxiosResponse<any>, cache: cacheOptions): AxiosResponse<any> {
224
+ if (response.config.url) {
225
+ AxiosCache.store(response.config["cachekey"], response.data, cache.duration);
226
+ }
227
+ return response;
228
+ }
229
+
230
+ //Handler when cache hits in requestHandler
231
+ private errorHandler(error: any) {
232
+ if (error && error.headers && error.headers.cached === "true") {
233
+ return Promise.resolve(error);
234
+ }
235
+ if (this._options.errorHandler) {
236
+ return this._options.errorHandler(error);
237
+ }
238
+ return Promise.reject(error);
239
+ }
240
+
241
+ private requestHandler(request: InternalAxiosRequestConfig, cache?: cacheOptions) {
242
+ //if refresh we do nothing
243
+ if (cache.refresh) {
244
+ return request;
245
+ }
246
+
247
+ request["cachekey"] =
248
+ this.hashValue(request.url + JSON.stringify(request.data)) +
249
+ (request.headers.get(HEADER_NAME_LANGUAGE) ? request.headers.get(HEADER_NAME_LANGUAGE) : "");
250
+
251
+ const checkIsValidResponse = AxiosCache.isValid(request["cachekey"] || "");
252
+ if (checkIsValidResponse.isValid) {
253
+ request.headers.set("cached", "true");
254
+ request.data = checkIsValidResponse.value || "{}";
255
+ // we 'fail' the request and let the error handler take care of the promise
256
+ return Promise.reject(request);
257
+ }
258
+
259
+ return request;
260
+ }
261
+
262
+ protected SetBaseUrl(options: WebApiOptions): void {
263
+ if (options.baseUrl === "") options.baseUrl = "/api/";
264
+ if (options.baseUrl.lastIndexOf("/") < options.baseUrl.length - 1) options.baseUrl += "/";
265
+ // Move BasePath onto BaseUrl
266
+ if (options.basePath) {
267
+ if (options.baseUrl.lastIndexOf("api/") < options.baseUrl.length - 4)
268
+ options.baseUrl += "api/";
269
+ options.baseUrl += options.basePath;
270
+ options.basePath = undefined;
271
+ }
272
+ }
273
+ private hashValue(s) {
274
+ if (!s) return "";
275
+ return (
276
+ "_" +
277
+ s.split("").reduce(function (a, b) {
278
+ a = (a << 5) - a + b.charCodeAt(0);
279
+ return a & a;
280
+ }, 0)
281
+ );
282
+ }
283
+ protected static CloneOptions(options: WebApiOptions): WebApiOptions {
284
+ const clone: WebApiOptions = {
285
+ baseUrl: options.baseUrl,
286
+ resourceParsing: options.resourceParsing,
287
+ languageCode: options.languageCode,
288
+ cultureCode: options.cultureCode,
289
+ timezone: options.timezone,
290
+ timezoneInclude: options.timezoneInclude,
291
+ axios: options.axios,
292
+ axiosConfig: options.axiosConfig,
293
+ resourceManager: options.resourceManager,
294
+ cache: options.cache,
295
+ errorHandler: options.errorHandler
296
+ };
297
+ return clone;
298
+ }
299
+
300
+ public static GetAxiosRequestConfig(
301
+ options?: WebApiRequestOptions,
302
+ baseOptions?: WebApiOptions
303
+ ): AxiosRequestConfig {
304
+ let config: AxiosRequestConfig = null;
305
+ if (baseOptions) {
306
+ if (baseOptions.axiosConfig) config = { ...baseOptions.axiosConfig }; // clone axios config
307
+ config = config || {};
308
+ if (baseOptions.baseUrl) config.baseURL = baseOptions.baseUrl;
309
+ }
310
+ config = config || {};
311
+ config.params = config.params || {};
312
+ config.headers = config.headers || {};
313
+ config.headers["Accept"] = "application/json";
314
+
315
+ if (options) {
316
+ options.requestStatus = WebApiStatus.Pending;
317
+ if (typeof options.languageCode == "string") {
318
+ config.headers[HEADER_NAME_ACCEPT_LANGUAGE] = options.languageCode;
319
+ config.headers[HEADER_NAME_LANGUAGE] = options.languageCode;
320
+ }
321
+ if (typeof options.cultureCode == "string") {
322
+ config.headers[HEADER_NAME_CULTURE] = options.cultureCode;
323
+ }
324
+ if (typeof options.timezone == "string") {
325
+ config.headers[HEADER_NAME_TIMEZONE] = options.timezone;
326
+ }
327
+ if (options.timezoneInclude) {
328
+ config.headers[HEADER_NAME_TIMEZONE] = config.headers[HEADER_NAME_TIMEZONE] ?? "";
329
+ if (config.headers[HEADER_NAME_TIMEZONE]) config.headers[HEADER_NAME_TIMEZONE] += ",";
330
+ config.headers[HEADER_NAME_TIMEZONE] += "includeTZOffset";
331
+ }
332
+ // If we have abortController, do not use cancel token
333
+ if (options.abortController) {
334
+ config.signal = options.abortController.signal;
335
+ } else if (options.cancelToken) {
336
+ config.cancelToken = options.cancelToken.token;
337
+ }
338
+ if (options.abortController) {
339
+ config.signal = options.abortController.signal;
340
+ }
341
+ const getOptions = options as WebApiGetRequestOptions;
342
+ if (getOptions && getOptions.ifModifiedSince) {
343
+ if (typeof getOptions.ifModifiedSince == "object")
344
+ config.headers["If-Modified-Since"] = getOptions.ifModifiedSince.toUTCString();
345
+ if (typeof getOptions.ifModifiedSince == "string")
346
+ config.headers["If-Modified-Since"] = getOptions.ifModifiedSince;
347
+ if (!getOptions.ifNotModifiedThrowError)
348
+ config.validateStatus = WebApiBase.validateModifiedStatus;
349
+ else config.validateStatus = WebApiBase.validate200Status; // 304 throws error
350
+ }
351
+ if (getOptions && getOptions.ifUnmodifiedSince) {
352
+ if (typeof getOptions.ifUnmodifiedSince == "object")
353
+ config.headers["If-Unmodified-Since"] = getOptions.ifUnmodifiedSince.toUTCString();
354
+ if (typeof getOptions.ifUnmodifiedSince == "string")
355
+ config.headers["If-Unmodified-Since"] = getOptions.ifUnmodifiedSince;
356
+ }
357
+ const putOptions = options as WebApiPutRequestOptions;
358
+ if (putOptions && putOptions.ifUnmodifiedSince) {
359
+ if (typeof putOptions.ifUnmodifiedSince == "object")
360
+ config.headers["If-Unmodified-Since"] = putOptions.ifUnmodifiedSince.toUTCString();
361
+ if (typeof putOptions.ifUnmodifiedSince == "string")
362
+ config.headers["If-Unmodified-Since"] = putOptions.ifUnmodifiedSince;
363
+ }
364
+ }
365
+ WebApiBase.SetXSRFTokenFromHiddenField();
366
+ return config;
367
+ }
368
+
369
+ public static SetXSRFTokenFromHiddenField() {
370
+ // don't do this if we are not in browser context
371
+ if (typeof window != "undefined" && document && document.cookie) {
372
+ if (document.cookie.indexOf("XSRF-TOKEN") < 0) {
373
+ // no XSRF-TOKEN cookie - see if we can add one from the hidden form field
374
+ let xsrfToken = undefined;
375
+ let msg = undefined;
376
+ const xsrfInput = document.getElementById("XSRF_TOKEN") as HTMLInputElement;
377
+ if (xsrfInput) {
378
+ xsrfToken = xsrfInput.value;
379
+ msg = "Setting XSRF cookie from INPUT field";
380
+ }
381
+ if (!xsrfToken) {
382
+ // still no XSRF-TOKEN value
383
+ msg = "No XSRF cookie found.";
384
+ if (console) console.log(msg);
385
+ }
386
+ if (xsrfToken) {
387
+ // Normalize path:
388
+ // "/crm.web/admin/default.aspx" --> "/crm.web/"
389
+ // '/crm.web/cs/scripts/ticket.exe' --> '/crm.web/cs/"
390
+ let path = window.location.pathname;
391
+ let lowpath = path.toLowerCase();
392
+ if (lowpath.endsWith("default.aspx")) path = path.substring(0, path.length - 12);
393
+ lowpath = path.toLowerCase();
394
+ if (lowpath.endsWith("/")) path = path.substring(0, path.length - 1);
395
+ lowpath = path.toLowerCase();
396
+ if (lowpath.endsWith("/admin")) path = path.substring(0, path.length - 6);
397
+ lowpath = path.toLowerCase();
398
+ let scriptsPos = lowpath.indexOf("/scripts/");
399
+ let exePos = lowpath.indexOf(".fcgi");
400
+ if (exePos < 0) exePos = lowpath.indexOf(".exe");
401
+ if (scriptsPos > 0 && exePos > 0) {
402
+ path = path.substring(0, scriptsPos); // /crm.web/cs/scripts/ticket.exe' --> '/crm.web/cs'
403
+ let slashPos = path.lastIndexOf("/");
404
+ if (slashPos > 1) path = path.substring(0, slashPos); // '/crm.web/cs' --> ''/crm.web'
405
+ }
406
+ document.cookie = "XSRF-TOKEN=" + xsrfToken + ";SameSite=Lax;Secure;path=" + path;
407
+ if (console) console.log(msg);
408
+ document.cookie = "XSRF-FROM-INPUT=" + path + ";SameSite=Lax;Secure;"; // path defaults to document location
409
+ }
410
+ }
411
+ }
412
+ }
413
+
414
+ // `validateStatus` defines whether to resolve or reject the promise for a given
415
+ // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
416
+ // or `undefined`), the promise will be resolved; otherwise, the promise will be
417
+ // rejected.
418
+ // validate 304 Unmodified as ok
419
+ private static validateModifiedStatus(status: number): boolean {
420
+ const validate: boolean = (status >= 200 && status < 300) || status === 304;
421
+ return validate;
422
+ }
423
+ private static validate200Status(status: number): boolean {
424
+ const validate: boolean = status >= 200 && status < 300;
425
+ return validate;
426
+ }
427
+
428
+ public static FigureOutOptions(
429
+ baseUrlOrOptions: string | WebApiOptions | undefined,
430
+ langOrconfigOrRMOrParse?: string | ResourceParsing | AxiosRequestConfig | any,
431
+ langOrResourceOrRM?: string | ResourceParsing | any,
432
+ cultureCode?: string
433
+ ): WebApiOptions {
434
+ let options: WebApiOptions = {};
435
+
436
+ if (typeof baseUrlOrOptions == "object") {
437
+ // Make a copy so we don't mess up caller's copy of options object
438
+ options = baseUrlOrOptions as WebApiOptions;
439
+ options = WebApiBase.CloneOptions(options);
440
+ } else if (typeof baseUrlOrOptions == "string") {
441
+ options = {
442
+ baseUrl: baseUrlOrOptions as string
443
+ };
444
+ }
445
+
446
+ if (typeof langOrconfigOrRMOrParse == "string") {
447
+ options.languageCode = langOrconfigOrRMOrParse as string;
448
+ } else if (typeof langOrconfigOrRMOrParse == "object") {
449
+ if (langOrconfigOrRMOrParse.getCurrentLangCode && langOrconfigOrRMOrParse.getCurrentLangCode)
450
+ options.resourceManager = langOrconfigOrRMOrParse;
451
+ if (
452
+ langOrconfigOrRMOrParse.auth ||
453
+ langOrconfigOrRMOrParse.baseURL ||
454
+ langOrconfigOrRMOrParse.url ||
455
+ langOrconfigOrRMOrParse.headers ||
456
+ langOrconfigOrRMOrParse.timeout
457
+ )
458
+ options.axiosConfig = langOrconfigOrRMOrParse as AxiosRequestConfig;
459
+ } else if (typeof langOrconfigOrRMOrParse == "number") {
460
+ options.resourceParsing = langOrconfigOrRMOrParse as ResourceParsing;
461
+ }
462
+
463
+ if (typeof langOrResourceOrRM == "string") {
464
+ options.languageCode = langOrResourceOrRM as string;
465
+ } else if (typeof langOrResourceOrRM == "number") {
466
+ options.resourceParsing = langOrResourceOrRM as ResourceParsing;
467
+ } else if (typeof langOrResourceOrRM == "object") {
468
+ if (langOrResourceOrRM.getCurrentLangCode && langOrResourceOrRM.getCurrentLangCode)
469
+ options.resourceManager = langOrResourceOrRM;
470
+ if (
471
+ langOrResourceOrRM.auth ||
472
+ langOrResourceOrRM.baseURL ||
473
+ langOrResourceOrRM.url ||
474
+ langOrResourceOrRM.headers ||
475
+ langOrResourceOrRM.timeout
476
+ )
477
+ options.axiosConfig = langOrResourceOrRM as AxiosRequestConfig;
478
+ }
479
+
480
+ if (cultureCode) options.cultureCode = cultureCode;
481
+
482
+ // Check for global defaults for missing properties
483
+ if (WebApiBase._global_options) {
484
+ if (!options.baseUrl) options.baseUrl = WebApiBase._global_options.baseUrl;
485
+ if (!options.axios) options.axios = WebApiBase._global_options.axios;
486
+ if (!options.axiosConfig) options.axiosConfig = WebApiBase._global_options.axiosConfig;
487
+ if (!options.cultureCode) options.cultureCode = WebApiBase._global_options.cultureCode;
488
+ if (!options.languageCode) options.languageCode = WebApiBase._global_options.languageCode;
489
+ if (!options.timezone) options.timezone = WebApiBase._global_options.timezone;
490
+ if (options.timezoneInclude === undefined)
491
+ options.timezoneInclude = WebApiBase._global_options.timezoneInclude;
492
+ if (!options.resourceManager)
493
+ options.resourceManager = WebApiBase._global_options.resourceManager;
494
+ if (!options.errorHandler) options.errorHandler = WebApiBase._global_options.errorHandler;
495
+ }
496
+
497
+ return options;
498
+ }
499
+
500
+ /** @deprecated Make a new cancel token that can be placed in an WebApiRequestOptions object. */
501
+ public MakeCancelToken(): CancelTokenSource {
502
+ return axios.CancelToken.source();
503
+ }
504
+
505
+ /** Make a new AbortController that can be placed in an WebApiRequestOptions object */
506
+ public MakeAbortController(): AbortController {
507
+ return new AbortController();
508
+ }
509
+
510
+ /** @deprecated Make a new options object with an cancelToken on it. */
511
+ public MakeOptions(): WebApiRequestOptions {
512
+ const opts: WebApiRequestOptions = {};
513
+ opts.requestStatus = WebApiStatus.Unknown;
514
+ opts.cancelToken = this.MakeCancelToken();
515
+ return opts;
516
+ }
517
+
518
+ /** Make a new options object with an abortController on it */
519
+ public MakeAbortableOptions(): WebApiRequestOptions {
520
+ const opts: WebApiRequestOptions = {};
521
+ opts.requestStatus = WebApiStatus.Unknown;
522
+ opts.abortController = this.MakeAbortController();
523
+ return opts;
524
+ }
525
+
526
+ public static SetPending(options: WebApiRequestOptions) {
527
+ if (options) options.requestStatus = WebApiStatus.Pending;
528
+
529
+ if (options && options.threshold) {
530
+ options.threshold.timeoutHandler = setTimeout(() => {
531
+ //We do not want successCallback to be call if the threshold is reached
532
+ if (options.threshold.timeout > 0) options.threshold.successCallback = null;
533
+ options.threshold.callback();
534
+ }, options.threshold.timeout);
535
+ }
536
+ if (options?.cancelToken?.token.reason) options.requestStatus = WebApiStatus.Cancelled;
537
+ }
538
+
539
+ public static SetCompleted(options: WebApiRequestOptions, response: AxiosResponse) {
540
+ if (options) {
541
+ if (options?.threshold) {
542
+ clearTimeout(options.threshold.timeoutHandler);
543
+ if (options.threshold.successCallback) options.threshold.successCallback();
544
+ }
545
+ options.responseCallback?.(response);
546
+ if (options.cancelToken?.token?.reason) options.requestStatus = WebApiStatus.Cancelled;
547
+ else options.requestStatus = WebApiStatus.Completed;
548
+ }
549
+ }
550
+
551
+ public static HandleError(options: WebApiRequestOptions, config: AxiosRequestConfig, err: any) {
552
+ if (options) {
553
+ if (options && options.threshold) {
554
+ clearTimeout(options.threshold.timeoutHandler);
555
+ if (options.threshold.errorCallback) options.threshold.errorCallback();
556
+ }
557
+
558
+ if ((config?.signal || config?.cancelToken) && axios.isCancel(err)) {
559
+ options.requestStatus = WebApiStatus.Cancelled;
560
+ } else {
561
+ options.requestStatus = WebApiStatus.Failed;
562
+ }
563
+ }
564
+ }
565
+ }