@dnv-plant/typescriptpws 1.0.0-alpha.0 → 1.0.0-alpha.1785261

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.
package/src/utilities.ts CHANGED
@@ -1,218 +1,218 @@
1
- /***********************************************************************
2
- * This file has been auto-generated by a code generation tool.
3
- * Version: 1.0.0
4
- * Date/time: 30 Jan 2025 11:43:04
5
- * Template: templates/typescriptpws/utilities.razor.
6
- ***********************************************************************/
7
-
8
- import jwt from "jsonwebtoken";
9
- import axios, { AxiosResponse } from "axios";
10
-
11
- import { REST_API_URI, PWS_CLIENT_ID, REST_API_VERSION } from "./constants";
12
-
13
- // Get headers for requests
14
- function getHeaders(accessToken: string) {
15
- return {
16
- "Content-Type": "application/json",
17
- Authorization: `Bearer ${accessToken}`,
18
- };
19
- }
20
-
21
- // Post JSON to URL and time the call
22
- export async function postRequest(url: string, data: string): Promise<AxiosResponse> {
23
- try {
24
- const accessToken = getAccessToken();
25
-
26
- if (!accessToken) {
27
- throw new Error("Access token not found");
28
- }
29
-
30
- const [, expiryDate, hasExpired] = getAccessTokenInfo(accessToken);
31
-
32
- if (!hasExpired) {
33
- const response = await axios.post(url, data, { headers: getHeaders(accessToken) });
34
- return response;
35
- } else {
36
- console.log(`Your access token has expired: ${expiryDate}`);
37
- throw new Error("Expired access token");
38
- }
39
- } catch (error: unknown) {
40
- if (axios.isAxiosError(error)) {
41
- console.error("Error during HTTP request:", error.response?.data || error.message);
42
- throw error;
43
- } else {
44
- console.error("Unexpected error:", error);
45
- throw new Error("Unexpected error occurred");
46
- }
47
- }
48
- }
49
-
50
- // Put JSON to URL and time the call
51
- export async function putRequest(url: string, data: string) {
52
- try {
53
- const accessToken = getAccessToken();
54
-
55
- if (!accessToken) {
56
- throw new Error("Access token not found");
57
- }
58
-
59
- const [, expiryDate, hasExpired] = getAccessTokenInfo(accessToken);
60
-
61
- if (!hasExpired) {
62
- const response = await axios.put(url, data, { headers: getHeaders(accessToken) });
63
- return response;
64
- } else {
65
- console.log(`Your access token has expired: ${expiryDate}`);
66
- throw new Error("Expired access token");
67
- }
68
- } catch (error: unknown) {
69
- if (axios.isAxiosError(error)) {
70
- console.error("Error during HTTP request:", error.response?.data || error.message);
71
- throw error;
72
- } else {
73
- console.error("Unexpected error:", error);
74
- throw new Error("Unexpected error occurred");
75
- }
76
- }
77
- }
78
-
79
- // Get data from URL
80
- export async function getRequest(url: string) {
81
- try {
82
- const accessToken = getAccessToken();
83
-
84
- if (!accessToken) {
85
- throw new Error("Access token not found");
86
- }
87
-
88
- const [, expiryDate, hasExpired] = getAccessTokenInfo(accessToken);
89
-
90
- if (!hasExpired) {
91
- const response = await axios.get(url, { headers: getHeaders(accessToken) });
92
- return response;
93
- } else {
94
- console.log(`Your access token has expired: ${expiryDate}`);
95
- throw new Error("Expired access token");
96
- }
97
- } catch (error: unknown) {
98
- if (axios.isAxiosError(error)) {
99
- console.error("Error during HTTP request:", error.response?.data || error.message);
100
- throw error;
101
- } else {
102
- console.error("Unexpected error:", error);
103
- throw new Error("Unexpected error occurred");
104
- }
105
- }
106
- }
107
-
108
- // Get access token from environment variables
109
- function getAccessToken() {
110
- const debug = process.env.PYPWS_DEBUG;
111
-
112
- let accessToken = process.env.PWS_ACCESS_TOKEN || process.env.PYPWS_ACCESS_TOKEN;
113
-
114
- if (!accessToken) {
115
- console.log(
116
- "Access token not found. Please define an environment variable called PWS_ACCESS_TOKEN and set its value to your access token (downloaded from the Plant Web Services web site)."
117
- );
118
- return null;
119
- }
120
-
121
- // Migrate PYPWS_ACCESS_TOKEN if needed
122
- if (process.env.PYPWS_ACCESS_TOKEN && !process.env.PWS_ACCESS_TOKEN) {
123
- console.log("Migrating PYPWS_ACCESS_TOKEN to PWS_ACCESS_TOKEN.");
124
-
125
- process.env.PWS_ACCESS_TOKEN = process.env.PYPWS_ACCESS_TOKEN;
126
- process.env.PYPWS_ACCESS_TOKEN = undefined;
127
- }
128
-
129
- // Debugging output
130
- if (debug) {
131
- console.log("Found access token in environment variable.");
132
- const tokenInfo = getAccessTokenInfo(accessToken);
133
- if (tokenInfo) {
134
- const [platform, expiryDate, hasExpired] = tokenInfo;
135
- console.log(`Platform: ${platform}. Expiry date: ${expiryDate}. Expired: ${hasExpired}`);
136
- }
137
- }
138
-
139
- return accessToken;
140
- }
141
-
142
- // Get platform, expiry date and token expiration status
143
- function getAccessTokenInfo(accessToken: string): [string, string, boolean] {
144
- const decoded = jwt.decode(accessToken);
145
-
146
- // Ensure the token is valid and contains the expected properties
147
- if (!decoded || typeof decoded !== "object" || !("exp" in decoded)) {
148
- throw new Error("Invalid or malformed token");
149
- }
150
-
151
- const exp = decoded.exp as number;
152
- const aud = decoded.aud as string | undefined;
153
-
154
- if (typeof exp !== "number") {
155
- throw new Error("Token does not have a valid expiration time");
156
- }
157
-
158
- const platform = aud || "unknown";
159
- const expiryDate = new Date(exp * 1000).toISOString();
160
- const hasExpired = Date.now() >= exp * 1000;
161
-
162
- return [platform, expiryDate, hasExpired];
163
- }
164
-
165
- // Get API root URL
166
- function getApiRoot() {
167
- const accessToken = getAccessToken();
168
- const devMode = process.env.DEV_MODE || false;
169
-
170
- if (accessToken) {
171
- const [platform] = getAccessTokenInfo(accessToken);
172
-
173
- // Determine API root based on devMode
174
- const apiTarget = devMode ? "/api/" : `${platform}/api/`;
175
-
176
- if (process.env.PYPWS_DEBUG) {
177
- console.log(`Dev Mode: ${devMode}, API Target: ${apiTarget}`);
178
- }
179
-
180
- return apiTarget;
181
- }
182
-
183
- if (process.env.PYPWS_DEBUG) {
184
- console.warn("Access token not found. Falling back to REST_API_URI.");
185
- }
186
-
187
- return REST_API_URI;
188
- }
189
-
190
- // Get API version
191
- function getApiVersion() {
192
- return process.env.PYPWS_API_VERSION || REST_API_VERSION;
193
- }
194
-
195
- // Get analytics API target URL
196
- export function getAnalyticsApiTarget() {
197
- return `${getApiRoot()}analytics/v${getApiVersion()}/`;
198
- }
199
-
200
- // Get materials API target URL
201
- export function getMaterialsApiTarget() {
202
- return `${getApiRoot()}materials-storage/v${getApiVersion()}/`;
203
- }
204
-
205
- // Get client alias ID
206
- export function getClientAliasId() {
207
- return process.env.PYPWS_CLIENT_ALIAS_ID || PWS_CLIENT_ID;
208
- }
209
-
210
- // Convert snake_case to camelCase
211
- export function convertSnakeCaseToCamelCase(snakeStr: string) {
212
- return snakeStr.replace(/_./g, (s) => s.charAt(1).toUpperCase());
213
- }
214
-
215
- // Convert camelCase to snake_case
216
- export function convertCamelCaseToSnakeCase(camelStr: string) {
217
- return camelStr.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
1
+ /***********************************************************************
2
+ * This file has been auto-generated by a code generation tool.
3
+ * Version: 1.0.0
4
+ * Date/time: 30 Jan 2025 11:43:04
5
+ * Template: templates/typescriptpws/utilities.razor.
6
+ ***********************************************************************/
7
+
8
+ import jwt from "jsonwebtoken";
9
+ import axios, { AxiosResponse } from "axios";
10
+
11
+ import { REST_API_URI, PWS_CLIENT_ID, REST_API_VERSION } from "./constants";
12
+
13
+ // Get headers for requests
14
+ function getHeaders(accessToken: string) {
15
+ return {
16
+ "Content-Type": "application/json",
17
+ Authorization: `Bearer ${accessToken}`,
18
+ };
19
+ }
20
+
21
+ // Post JSON to URL and time the call
22
+ export async function postRequest(url: string, data: string): Promise<AxiosResponse> {
23
+ try {
24
+ const accessToken = getAccessToken();
25
+
26
+ if (!accessToken) {
27
+ throw new Error("Access token not found");
28
+ }
29
+
30
+ const [, expiryDate, hasExpired] = getAccessTokenInfo(accessToken);
31
+
32
+ if (!hasExpired) {
33
+ const response = await axios.post(url, data, { headers: getHeaders(accessToken) });
34
+ return response;
35
+ } else {
36
+ console.log(`Your access token has expired: ${expiryDate}`);
37
+ throw new Error("Expired access token");
38
+ }
39
+ } catch (error: unknown) {
40
+ if (axios.isAxiosError(error)) {
41
+ console.error("Error during HTTP request:", error.response?.data || error.message);
42
+ throw error;
43
+ } else {
44
+ console.error("Unexpected error:", error);
45
+ throw new Error("Unexpected error occurred");
46
+ }
47
+ }
48
+ }
49
+
50
+ // Put JSON to URL and time the call
51
+ export async function putRequest(url: string, data: string) {
52
+ try {
53
+ const accessToken = getAccessToken();
54
+
55
+ if (!accessToken) {
56
+ throw new Error("Access token not found");
57
+ }
58
+
59
+ const [, expiryDate, hasExpired] = getAccessTokenInfo(accessToken);
60
+
61
+ if (!hasExpired) {
62
+ const response = await axios.put(url, data, { headers: getHeaders(accessToken) });
63
+ return response;
64
+ } else {
65
+ console.log(`Your access token has expired: ${expiryDate}`);
66
+ throw new Error("Expired access token");
67
+ }
68
+ } catch (error: unknown) {
69
+ if (axios.isAxiosError(error)) {
70
+ console.error("Error during HTTP request:", error.response?.data || error.message);
71
+ throw error;
72
+ } else {
73
+ console.error("Unexpected error:", error);
74
+ throw new Error("Unexpected error occurred");
75
+ }
76
+ }
77
+ }
78
+
79
+ // Get data from URL
80
+ export async function getRequest(url: string) {
81
+ try {
82
+ const accessToken = getAccessToken();
83
+
84
+ if (!accessToken) {
85
+ throw new Error("Access token not found");
86
+ }
87
+
88
+ const [, expiryDate, hasExpired] = getAccessTokenInfo(accessToken);
89
+
90
+ if (!hasExpired) {
91
+ const response = await axios.get(url, { headers: getHeaders(accessToken) });
92
+ return response;
93
+ } else {
94
+ console.log(`Your access token has expired: ${expiryDate}`);
95
+ throw new Error("Expired access token");
96
+ }
97
+ } catch (error: unknown) {
98
+ if (axios.isAxiosError(error)) {
99
+ console.error("Error during HTTP request:", error.response?.data || error.message);
100
+ throw error;
101
+ } else {
102
+ console.error("Unexpected error:", error);
103
+ throw new Error("Unexpected error occurred");
104
+ }
105
+ }
106
+ }
107
+
108
+ // Get access token from environment variables
109
+ function getAccessToken() {
110
+ const debug = process.env.PYPWS_DEBUG;
111
+
112
+ let accessToken = process.env.PWS_ACCESS_TOKEN || process.env.PYPWS_ACCESS_TOKEN;
113
+
114
+ if (!accessToken) {
115
+ console.log(
116
+ "Access token not found. Please define an environment variable called PWS_ACCESS_TOKEN and set its value to your access token (downloaded from the Plant Web Services web site)."
117
+ );
118
+ return null;
119
+ }
120
+
121
+ // Migrate PYPWS_ACCESS_TOKEN if needed
122
+ if (process.env.PYPWS_ACCESS_TOKEN && !process.env.PWS_ACCESS_TOKEN) {
123
+ console.log("Migrating PYPWS_ACCESS_TOKEN to PWS_ACCESS_TOKEN.");
124
+
125
+ process.env.PWS_ACCESS_TOKEN = process.env.PYPWS_ACCESS_TOKEN;
126
+ process.env.PYPWS_ACCESS_TOKEN = undefined;
127
+ }
128
+
129
+ // Debugging output
130
+ if (debug) {
131
+ console.log("Found access token in environment variable.");
132
+ const tokenInfo = getAccessTokenInfo(accessToken);
133
+ if (tokenInfo) {
134
+ const [platform, expiryDate, hasExpired] = tokenInfo;
135
+ console.log(`Platform: ${platform}. Expiry date: ${expiryDate}. Expired: ${hasExpired}`);
136
+ }
137
+ }
138
+
139
+ return accessToken;
140
+ }
141
+
142
+ // Get platform, expiry date and token expiration status
143
+ function getAccessTokenInfo(accessToken: string): [string, string, boolean] {
144
+ const decoded = jwt.decode(accessToken);
145
+
146
+ // Ensure the token is valid and contains the expected properties
147
+ if (!decoded || typeof decoded !== "object" || !("exp" in decoded)) {
148
+ throw new Error("Invalid or malformed token");
149
+ }
150
+
151
+ const exp = decoded.exp as number;
152
+ const aud = decoded.aud as string | undefined;
153
+
154
+ if (typeof exp !== "number") {
155
+ throw new Error("Token does not have a valid expiration time");
156
+ }
157
+
158
+ const platform = aud || "unknown";
159
+ const expiryDate = new Date(exp * 1000).toISOString();
160
+ const hasExpired = Date.now() >= exp * 1000;
161
+
162
+ return [platform, expiryDate, hasExpired];
163
+ }
164
+
165
+ // Get API root URL
166
+ function getApiRoot() {
167
+ const accessToken = getAccessToken();
168
+ const devMode = process.env.DEV_MODE || false;
169
+
170
+ if (accessToken) {
171
+ const [platform] = getAccessTokenInfo(accessToken);
172
+
173
+ // Determine API root based on devMode
174
+ const apiTarget = devMode ? "/api/" : `${platform}/api/`;
175
+
176
+ if (process.env.PYPWS_DEBUG) {
177
+ console.log(`Dev Mode: ${devMode}, API Target: ${apiTarget}`);
178
+ }
179
+
180
+ return apiTarget;
181
+ }
182
+
183
+ if (process.env.PYPWS_DEBUG) {
184
+ console.warn("Access token not found. Falling back to REST_API_URI.");
185
+ }
186
+
187
+ return REST_API_URI;
188
+ }
189
+
190
+ // Get API version
191
+ function getApiVersion() {
192
+ return process.env.PYPWS_API_VERSION || REST_API_VERSION;
193
+ }
194
+
195
+ // Get analytics API target URL
196
+ export function getAnalyticsApiTarget() {
197
+ return `${getApiRoot()}analytics/v${getApiVersion()}/`;
198
+ }
199
+
200
+ // Get materials API target URL
201
+ export function getMaterialsApiTarget() {
202
+ return `${getApiRoot()}materials-storage/v${getApiVersion()}/`;
203
+ }
204
+
205
+ // Get client alias ID
206
+ export function getClientAliasId() {
207
+ return process.env.PYPWS_CLIENT_ALIAS_ID || PWS_CLIENT_ID;
208
+ }
209
+
210
+ // Convert snake_case to camelCase
211
+ export function convertSnakeCaseToCamelCase(snakeStr: string) {
212
+ return snakeStr.replace(/_./g, (s) => s.charAt(1).toUpperCase());
213
+ }
214
+
215
+ // Convert camelCase to snake_case
216
+ export function convertCamelCaseToSnakeCase(camelStr: string) {
217
+ return camelStr.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
218
218
  }