-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathhelpers.ts
More file actions
135 lines (117 loc) · 4.61 KB
/
helpers.ts
File metadata and controls
135 lines (117 loc) · 4.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import { checkSync } from 'recheck';
import authHandler from './auth-handler';
import { HttpClient, cliux, configHandler } from '.';
export const isAuthenticated = () => authHandler.isAuthenticated();
export const doesBranchExist = async (stack, branchName) => {
return stack
.branch(branchName)
.fetch()
.catch((error) => {
return error;
});
};
export const isManagementTokenValid = async (stackAPIKey, managementToken) => {
const httpClient = new HttpClient({ headers: { api_key: stackAPIKey, authorization: managementToken } });
try {
const response = (await httpClient.get(`${configHandler.get('region').cma}/v3/environments?limit=1`))?.data;
if (response?.environments) {
return { valid: true };
} else if (response?.error_code) {
return { valid: false, message: response.error_message };
} else {
throw typeof response === 'string' ? response : '';
}
} catch (error) {
return { valid: 'failedToCheck', message: `Failed to check the validity of the Management token. ${error}` };
}
};
export const createDeveloperHubUrl = (developerHubBaseUrl: string): string => {
developerHubBaseUrl = developerHubBaseUrl?.replace('api', 'developerhub-api');
developerHubBaseUrl = developerHubBaseUrl.startsWith('dev11')
? developerHubBaseUrl.replace('dev11', 'dev')
: developerHubBaseUrl;
developerHubBaseUrl = developerHubBaseUrl.endsWith('io')
? developerHubBaseUrl.replace('io', 'com')
: developerHubBaseUrl;
return developerHubBaseUrl.startsWith('http') ? developerHubBaseUrl : `https://${developerHubBaseUrl}`;
};
export const validatePath = (input: string) => {
const pattern = /[*$%#<>{}!&?]/g;
if (pattern.test(input)) {
cliux.print(`\nPlease add a directory path without any of the special characters: (*,&,{,},[,],$,%,<,>,?,!)`, {
color: 'yellow',
});
return false;
}
return true;
};
// To escape special characters in a string
export const escapeRegExp = (str: string) => str?.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// To remove the relative path
export const sanitizePath = (str: string) => str?.replace(/^(\.\.(\/|\\|$))+/, '');
// To validate the UIDs of assets
export const validateUids = (uid) => /^[a-zA-Z0-9]+$/.test(uid);
// Validate File name
export const validateFileName = (fileName) => /^[a-zA-Z0-9-_\.]+$/.test(fileName);
// Validate Regex for ReDDos
export const validateRegex = (str: unknown) => {
const stringValue = typeof str === 'string' ? str : str.toString();
return checkSync(stringValue, '');
};
export const formatError = function (error: any) {
let parsedError: any;
// Parse the error
try {
if (typeof error === 'string') {
parsedError = JSON.parse(error);
} else if (typeof error?.message === 'string') {
parsedError = JSON.parse(error.message);
} else {
parsedError = error;
}
} catch (e) {
parsedError = error;
}
// Check if parsedError is an empty object
if (parsedError && typeof parsedError === 'object' && Object.keys(parsedError).length === 0) {
return `An unknown error occurred. ${error}`;
}
// Check for specific SSL error
if (parsedError?.code === 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY') {
return 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY occurred during SSL certificate verification! Please check your certificate configuration.';
}
// Handle self signed certificate error
if (parsedError?.code === 'SELF_SIGNED_CERT_IN_CHAIN') {
return 'Self-signed certificate in the certificate chain! Please ensure your certificate configuration is correct and the necessary CA certificates are trusted.';
}
// Determine the error message
let message =
parsedError.errorMessage || parsedError.error_message || parsedError?.code || parsedError.message || parsedError;
if (typeof message === 'object') {
message = JSON.stringify(message);
}
// If message is in JSON format, parse it to extract the actual message string
try {
const parsedMessage = JSON.parse(message);
if (typeof parsedMessage === 'object') {
message = parsedMessage?.message || message;
}
} catch (e) {
// message is not in JSON format, no need to parse
}
// Append detailed error information if available
if (parsedError.errors && Object.keys(parsedError.errors).length > 0) {
const entityNames: { [key: string]: string } = {
authorization: 'Authentication',
api_key: 'Stack API key',
uid: 'Content Type',
access_token: 'Delivery Token',
};
message +=
' ' +
Object.entries(parsedError.errors)
.map(([key, value]) => `${entityNames[key] || key} ${value}`)
.join(' ');
}
return message;
};