ofsc-utility 1.0.40 → 1.0.41

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.
@@ -1 +1,13 @@
1
- export declare function getOAuthToken(clientId: string, clientSecret: string, instanceUrl: string): Promise<any>;
1
+ interface OAuthTokenOptions {
2
+ /** Max retry attempts for transient (5xx) failures. Default: 2 */
3
+ maxRetries?: number;
4
+ /** Base delay in ms between retries (exponential backoff). Default: 1000 */
5
+ retryDelayMs?: number;
6
+ /** Request timeout in ms. Default: 10000 */
7
+ timeoutMs?: number;
8
+ }
9
+ /**
10
+ * Fetches an OAuth access token from OFSC.
11
+ */
12
+ export declare function getOAuthToken(clientId: string, clientSecret: string, instanceUrl: string, options?: OAuthTokenOptions): Promise<string>;
13
+ export {};
@@ -1,30 +1,63 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getOAuthToken = getOAuthToken;
4
- async function getOAuthToken(clientId, clientSecret, instanceUrl) {
4
+ /**
5
+ * Fetches an OAuth access token from OFSC.
6
+ */
7
+ async function getOAuthToken(clientId, clientSecret, instanceUrl, options = {}) {
8
+ const { maxRetries = 3, retryDelayMs = 1000, timeoutMs = 10000 } = options;
5
9
  const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/oauthTokenService/v2/token`;
6
10
  const credentials = btoa(`${clientId}@${instanceUrl}:${clientSecret}`);
7
11
  const headers = {
8
12
  'Content-Type': 'application/x-www-form-urlencoded',
9
- 'Authorization': `Basic ${credentials}`
13
+ 'Authorization': `Basic ${credentials}`,
10
14
  };
11
- const body = new URLSearchParams({
12
- 'grant_type': 'client_credentials'
13
- });
14
- try {
15
- const response = await fetch(url, {
16
- method: 'POST',
17
- headers: headers,
18
- body: body
19
- });
20
- if (!response.ok) {
21
- throw new Error(`HTTP error! status: ${response.status}`);
15
+ const body = new URLSearchParams({ grant_type: 'client_credentials' });
16
+ let lastError;
17
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
18
+ //AbortController is a built-in browser/Node API for cancelling async operations
19
+ // controller.signal & controller.abort() are used to cancel the fetch request if it takes too long
20
+ const controller = new AbortController();
21
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
22
+ try {
23
+ const response = await fetch(url, {
24
+ method: 'POST',
25
+ headers,
26
+ body,
27
+ signal: controller.signal,
28
+ });
29
+ clearTimeout(timeout);
30
+ if (response.ok) {
31
+ const data = (await response.json());
32
+ if (!data.access_token) {
33
+ throw new Error('OAuth response did not contain an access_token');
34
+ }
35
+ return data.access_token;
36
+ }
37
+ // Retry only on server-side / transient errors
38
+ if (response.status >= 500 && response.status < 600 && attempt < maxRetries) {
39
+ lastError = new Error(`OAuth token request failed with status ${response.status}`);
40
+ await delay(retryDelayMs * 2 ** attempt);
41
+ continue;
42
+ }
43
+ // Non-retriable (4xx) or out of retries — fail fast
44
+ const bodyText = await response.text().catch(() => '');
45
+ throw new Error(`OAuth token request failed: ${response.status} ${response.statusText}${bodyText ? ` - ${bodyText}` : ''}`);
46
+ }
47
+ catch (error) {
48
+ clearTimeout(timeout);
49
+ lastError = error;
50
+ const isAbort = error instanceof Error && error.name === 'AbortError';
51
+ const isNetworkError = error instanceof TypeError;
52
+ if ((isAbort || isNetworkError) && attempt < maxRetries) {
53
+ await delay(retryDelayMs * 2 ** attempt);
54
+ continue;
55
+ }
56
+ throw new Error(`Failed to fetch OAuth token after ${attempt + 1} attempt(s): ${error instanceof Error ? error.message : String(error)}`);
22
57
  }
23
- const data = await response.json();
24
- return data.access_token;
25
- }
26
- catch (error) {
27
- console.error('Error fetching OAuth token:', error);
28
- throw error;
29
58
  }
59
+ throw lastError instanceof Error ? lastError : new Error('Failed to fetch OAuth token');
60
+ }
61
+ function delay(ms) {
62
+ return new Promise((resolve) => setTimeout(resolve, ms));
30
63
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofsc-utility",
3
- "version": "1.0.40",
3
+ "version": "1.0.41",
4
4
  "description": "TypeScript helpers for Oracle Field Service Cloud (OFSC): events, resources, inventories, metadata and CSV/Excel utilities.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",