@oino-ts/types 0.0.11

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.
@@ -0,0 +1,265 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OINOStr = void 0;
4
+ const _1 = require(".");
5
+ /**
6
+ * Static class string utilities.
7
+ *
8
+ */
9
+ class OINOStr {
10
+ /**
11
+ * Split string by the top level of the given type of brackets.
12
+ * E.g. splitByBrackets("a(bc(d))ef(gh)kl", true, true, '(', ')') would return ["a", "bc(d)", "ef", "gh", "kl"]
13
+ *
14
+ * @param str string to split
15
+ * @param includePartsBetweenBlocks whether to include strings between top level brackets
16
+ * @param includeTrailingUnescapedBlock whether to include final block that is missing necessary end brackets
17
+ * @param startBracket starting bracket, e.g. '('
18
+ * @param endBracket ending bracket, e.g. ')'
19
+ *
20
+ */
21
+ static splitByBrackets(str, includePartsBetweenBlocks, includeTrailingUnescapedBlock, startBracket, endBracket) {
22
+ let result = [];
23
+ let parenthesis_count = 0;
24
+ let start = 0;
25
+ let end = 0;
26
+ while (end < str.length) {
27
+ if (str[end] == startBracket) {
28
+ if (parenthesis_count == 0) {
29
+ if ((end > start) && includePartsBetweenBlocks) { // there is some first level string to add to result
30
+ result.push(str.substring(start, end));
31
+ }
32
+ start = end + 1;
33
+ }
34
+ parenthesis_count++;
35
+ }
36
+ else if (str[end] == endBracket) {
37
+ parenthesis_count--;
38
+ if (parenthesis_count == 0) {
39
+ if (end >= start) {
40
+ result.push(str.substring(start, end));
41
+ }
42
+ start = end + 1;
43
+ }
44
+ }
45
+ end++;
46
+ }
47
+ if ((end > start) && ((includePartsBetweenBlocks && (parenthesis_count == 0)) || (includeTrailingUnescapedBlock && (parenthesis_count > 0)))) { // if there is stuff after last block or unfinished block (and those are supported)
48
+ result.push(str.substring(start, end)); // i == str.length
49
+ }
50
+ return result;
51
+ }
52
+ /**
53
+ * Split string by delimeter excluding delimeters inside given brackets.
54
+ * E.g. splitExcludingBrackets("a,(bc,d),ef,(g,h),k", ',', '(', ')') would return ["a", "bc,d", "ef", "g,h", "k"]
55
+ *
56
+ * @param str string to split
57
+ * @param delimeter string to use as delimeter
58
+ * @param startBracket starting bracket, e.g. '('
59
+ * @param endBracket ending bracket, e.g. ')'
60
+ */
61
+ static splitExcludingBrackets(str, delimeter, startBracket, endBracket) {
62
+ let result = [];
63
+ let bracket_level = 0;
64
+ let start = 0;
65
+ let end = 0;
66
+ while (end < str.length) {
67
+ if (str[end] == startBracket) {
68
+ bracket_level++;
69
+ }
70
+ else if (str[end] == endBracket) {
71
+ bracket_level--;
72
+ }
73
+ else if ((str[end] == delimeter) && (bracket_level == 0)) { // only delimeters at top level will break
74
+ result.push(str.substring(start, end));
75
+ start = end + 1;
76
+ }
77
+ end++;
78
+ }
79
+ if (end > start) {
80
+ result.push(str.substring(start, end)); // i == str.length
81
+ }
82
+ return result;
83
+ }
84
+ /**
85
+ * Encode OINO serialized strings as valid JSON.
86
+ *
87
+ * @param str string to encode
88
+ * @param valueType wether it is a value type
89
+ */
90
+ static encodeJSON(str, valueType = false) {
91
+ if (str === undefined) { // no undefined literal in JSON
92
+ return "null";
93
+ }
94
+ else if (str === null) {
95
+ return "null";
96
+ }
97
+ else {
98
+ if (valueType) {
99
+ return str;
100
+ }
101
+ else {
102
+ return JSON.stringify(str);
103
+ }
104
+ }
105
+ }
106
+ /**
107
+ * Decode JSON string as OINO serialization.
108
+ *
109
+ * @param str string to decode
110
+ */
111
+ static decodeJSON(str) {
112
+ return str; // JSON parsing using JS methods, no need to decode anything
113
+ }
114
+ /**
115
+ * Encode OINO serialized strings as valid CSV.
116
+ *
117
+ * @param str string to encode
118
+ */
119
+ static encodeCSV(str) {
120
+ if (str === undefined) {
121
+ return "";
122
+ }
123
+ else if (str === null) {
124
+ return "null";
125
+ }
126
+ else {
127
+ return "\"" + str.replaceAll("\"", "\"\"") + "\"";
128
+ }
129
+ }
130
+ /**
131
+ * Decode CSV string as OINO serialization.
132
+ *
133
+ * @param str string to decode
134
+ */
135
+ static decodeCSV(str) {
136
+ return str.replaceAll("\"\"", "\"");
137
+ }
138
+ /**
139
+ * Encode OINO serialized strings as valid Formdata.
140
+ *
141
+ * @param str string to encode
142
+ */
143
+ static encodeFormdata(str) {
144
+ if (str === undefined) {
145
+ return "";
146
+ }
147
+ else if (str === null) {
148
+ return "";
149
+ }
150
+ else {
151
+ return str;
152
+ }
153
+ }
154
+ /**
155
+ * Decode Formdata string as OINO serialization.
156
+ *
157
+ * @param str string to decode
158
+ */
159
+ static decodeFormdata(str) {
160
+ return str;
161
+ }
162
+ /**
163
+ * Encode OINO serialized strings as valid Urlencode.
164
+ *
165
+ * @param str string to encode
166
+ */
167
+ static encodeUrlencode(str) {
168
+ if (str === undefined) {
169
+ return "";
170
+ }
171
+ else if (str === null) {
172
+ return "null";
173
+ }
174
+ else {
175
+ return encodeURIComponent(str);
176
+ }
177
+ }
178
+ /**
179
+ * Decode Urlencode string as OINO serialization.
180
+ *
181
+ * @param str string to decode
182
+ */
183
+ static decodeUrlencode(str) {
184
+ return decodeURIComponent(str);
185
+ }
186
+ /**
187
+ * Encode OINO serialized strings as valid HTML content.
188
+ *
189
+ * @param str string to encode
190
+ */
191
+ static encodeHtml(str) {
192
+ if (str === undefined) {
193
+ return "";
194
+ }
195
+ else if (str === null) {
196
+ return "";
197
+ }
198
+ else {
199
+ return str.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;');
200
+ }
201
+ }
202
+ /**
203
+ * Decode HTML string as OINO serialization.
204
+ *
205
+ * @param str string to encode
206
+ */
207
+ static decodeHtml(str) {
208
+ return str.replaceAll('&amp;', '&').replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '"').replaceAll('&#039;', "'");
209
+ }
210
+ /**
211
+ * Decode content type formatted string as OINO serialization.
212
+ *
213
+ * @param str string to decode
214
+ * @param contentType content type for serialization
215
+ *
216
+ */
217
+ static decode(str, contentType) {
218
+ if (contentType == _1.OINOContentType.csv) {
219
+ return this.decodeCSV(str);
220
+ }
221
+ else if (contentType == _1.OINOContentType.json) {
222
+ return this.decodeJSON(str);
223
+ }
224
+ else if (contentType == _1.OINOContentType.formdata) {
225
+ return this.decodeFormdata(str);
226
+ }
227
+ else if (contentType == _1.OINOContentType.urlencode) {
228
+ return this.decodeUrlencode(str);
229
+ }
230
+ else if (contentType == _1.OINOContentType.html) {
231
+ return str;
232
+ }
233
+ else {
234
+ return str;
235
+ }
236
+ }
237
+ /**
238
+ * Encode OINO serialized string to the content type formatting.
239
+ *
240
+ * @param str string to encode
241
+ * @param contentType content type for serialization
242
+ *
243
+ */
244
+ static encode(str, contentType) {
245
+ if (contentType == _1.OINOContentType.csv) {
246
+ return this.encodeCSV(str);
247
+ }
248
+ else if (contentType == _1.OINOContentType.json) {
249
+ return this.encodeJSON(str);
250
+ }
251
+ else if (contentType == _1.OINOContentType.formdata) {
252
+ return this.encodeFormdata(str);
253
+ }
254
+ else if (contentType == _1.OINOContentType.urlencode) {
255
+ return this.encodeUrlencode(str);
256
+ }
257
+ else if (contentType == _1.OINOContentType.html) {
258
+ return this.encodeHtml(str);
259
+ }
260
+ else {
261
+ return str || "";
262
+ }
263
+ }
264
+ }
265
+ exports.OINOStr = OINOStr;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OINOContentType = exports.OINO_DEBUG_PREFIX = exports.OINO_INFO_PREFIX = exports.OINO_WARNING_PREFIX = exports.OINO_ERROR_PREFIX = exports.OINOStr = exports.OINOResult = exports.OINOConsoleLog = exports.OINOLogLevel = exports.OINOLog = exports.OINOBenchmark = void 0;
4
+ var OINOBenchmark_js_1 = require("./OINOBenchmark.js");
5
+ Object.defineProperty(exports, "OINOBenchmark", { enumerable: true, get: function () { return OINOBenchmark_js_1.OINOBenchmark; } });
6
+ var OINOLog_js_1 = require("./OINOLog.js");
7
+ Object.defineProperty(exports, "OINOLog", { enumerable: true, get: function () { return OINOLog_js_1.OINOLog; } });
8
+ Object.defineProperty(exports, "OINOLogLevel", { enumerable: true, get: function () { return OINOLog_js_1.OINOLogLevel; } });
9
+ Object.defineProperty(exports, "OINOConsoleLog", { enumerable: true, get: function () { return OINOLog_js_1.OINOConsoleLog; } });
10
+ var OINOResult_js_1 = require("./OINOResult.js");
11
+ Object.defineProperty(exports, "OINOResult", { enumerable: true, get: function () { return OINOResult_js_1.OINOResult; } });
12
+ var OINOStr_js_1 = require("./OINOStr.js");
13
+ Object.defineProperty(exports, "OINOStr", { enumerable: true, get: function () { return OINOStr_js_1.OINOStr; } });
14
+ /** OINO error message prefix */
15
+ exports.OINO_ERROR_PREFIX = "OINO ERROR";
16
+ /** OINO warning message prefix */
17
+ exports.OINO_WARNING_PREFIX = "OINO WARNING";
18
+ /** OINO info message prefix */
19
+ exports.OINO_INFO_PREFIX = "OINO INFO";
20
+ /** OINO debug message prefix */
21
+ exports.OINO_DEBUG_PREFIX = "OINO DEBUG";
22
+ /** Supported content format mime-types */
23
+ var OINOContentType;
24
+ (function (OINOContentType) {
25
+ /** JSON encoded data */
26
+ OINOContentType["json"] = "application/json";
27
+ /** CSV encoded data */
28
+ OINOContentType["csv"] = "text/csv";
29
+ /** Multipart encoded form data */
30
+ OINOContentType["formdata"] = "multipart/form-data";
31
+ /** URL encoded form data */
32
+ OINOContentType["urlencode"] = "application/x-www-form-urlencoded";
33
+ /** HTML encoded data (output only) */
34
+ OINOContentType["html"] = "text/html";
35
+ })(OINOContentType || (exports.OINOContentType = OINOContentType = {}));
@@ -0,0 +1,62 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+ /**
7
+ * Static class for benchmarking functions.
8
+ *
9
+ */
10
+ export class OINOBenchmark {
11
+ static _benchmarkCount = {};
12
+ static _benchmarkData = {};
13
+ static _benchmarkEnabled = {};
14
+ static _benchmarkStart = {};
15
+ /**
16
+ * Reset benchmark data (but not what is enabled).
17
+ *
18
+ */
19
+ static reset() {
20
+ this._benchmarkData = {};
21
+ this._benchmarkCount = {};
22
+ }
23
+ /**
24
+ * Set benchmark names that are enabled.
25
+ *
26
+ * @param names array of those benchmarks that are enabled
27
+ */
28
+ static setEnabled(names) {
29
+ this._benchmarkEnabled = {};
30
+ names.forEach(name => {
31
+ this._benchmarkEnabled[name] = true;
32
+ });
33
+ }
34
+ /**
35
+ * Start benchmark timing.
36
+ *
37
+ * @param name of the benchmark
38
+ */
39
+ static start(name) {
40
+ if (this._benchmarkEnabled[name]) {
41
+ if (this._benchmarkCount[name] == undefined) {
42
+ this._benchmarkCount[name] = 0;
43
+ this._benchmarkData[name] = 0;
44
+ }
45
+ this._benchmarkStart[name] = performance.now();
46
+ }
47
+ }
48
+ /**
49
+ * Complete benchmark timing
50
+ *
51
+ * @param name of the benchmark
52
+ */
53
+ static end(name) {
54
+ let result = 0;
55
+ if (this._benchmarkEnabled[name]) {
56
+ this._benchmarkCount[name] += 1;
57
+ this._benchmarkData[name] += performance.now() - this._benchmarkStart[name];
58
+ result = this._benchmarkData[name] / this._benchmarkCount[name];
59
+ }
60
+ return result;
61
+ }
62
+ }
@@ -0,0 +1,135 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+ /** Logging levels */
7
+ export var OINOLogLevel;
8
+ (function (OINOLogLevel) {
9
+ /** Debug messages */
10
+ OINOLogLevel[OINOLogLevel["debug"] = 0] = "debug";
11
+ /** Informational messages */
12
+ OINOLogLevel[OINOLogLevel["info"] = 1] = "info";
13
+ /** Warning messages */
14
+ OINOLogLevel[OINOLogLevel["warn"] = 2] = "warn";
15
+ /** Error messages */
16
+ OINOLogLevel[OINOLogLevel["error"] = 3] = "error";
17
+ })(OINOLogLevel || (OINOLogLevel = {}));
18
+ /**
19
+ * Abstract base class for logging implementations supporting
20
+ * - error, warning, info and debug channels
21
+ * - setting level of logs outputted
22
+ *
23
+ */
24
+ export class OINOLog {
25
+ static _instance;
26
+ _logLevel = OINOLogLevel.warn;
27
+ /**
28
+ * Abstract logging method to implement the actual logging operation.
29
+ *
30
+ * @param logLevel level of the log events
31
+ *
32
+ */
33
+ constructor(logLevel = OINOLogLevel.warn) {
34
+ // console.log("OINOLog.constructor: logLevel=" + logLevel)
35
+ this._logLevel = logLevel;
36
+ }
37
+ /**
38
+ * Abstract logging method to implement the actual logging operation.
39
+ *
40
+ * @param level level of the log event
41
+ * @param levelStr level string of the log event
42
+ * @param message message of the log event
43
+ * @param data structured data associated with the log event
44
+ *
45
+ */
46
+ static _log(level, levelStr, message, data) {
47
+ // console.log("_log: level=" + level + ", levelStr=" + levelStr + ", message=" + message + ", data=" + data)
48
+ if ((OINOLog._instance) && (OINOLog._instance._logLevel <= level)) {
49
+ OINOLog._instance?._writeLog(levelStr, message, data);
50
+ }
51
+ }
52
+ /**
53
+ * Set active logger and log level.
54
+ *
55
+ * @param logger logger instance
56
+ *
57
+ */
58
+ static setLogger(logger) {
59
+ // console.log("setLogger: " + log)
60
+ if (logger) {
61
+ OINOLog._instance = logger;
62
+ }
63
+ }
64
+ /**
65
+ * Set log level.
66
+ *
67
+ * @param logLevel log level to use
68
+ *
69
+ */
70
+ static setLogLevel(logLevel) {
71
+ if (OINOLog._instance) {
72
+ OINOLog._instance._logLevel = logLevel;
73
+ }
74
+ }
75
+ /**
76
+ * Log error event.
77
+ *
78
+ * @param message message of the log event
79
+ * @param data structured data associated with the log event
80
+ *
81
+ */
82
+ static error(message, data) {
83
+ OINOLog._log(OINOLogLevel.error, "ERROR", message, data);
84
+ }
85
+ /**
86
+ * Log warning event.
87
+ *
88
+ * @param message message of the log event
89
+ * @param data structured data associated with the log event
90
+ *
91
+ */
92
+ static warning(message, data) {
93
+ OINOLog._log(OINOLogLevel.warn, "WARN", message, data);
94
+ }
95
+ /**
96
+ * Log info event.
97
+ *
98
+ * @param message message of the log event
99
+ * @param data structured data associated with the log event
100
+ *
101
+ */
102
+ static info(message, data) {
103
+ OINOLog._log(OINOLogLevel.info, "INFO", message, data);
104
+ }
105
+ /**
106
+ * Log debug event.
107
+ *
108
+ * @param message message of the log event
109
+ * @param data structured data associated with the log event
110
+ *
111
+ */
112
+ static debug(message, data) {
113
+ OINOLog._log(OINOLogLevel.debug, "DEBUG", message, data);
114
+ }
115
+ }
116
+ /**
117
+ * Logging implementation based on console.log.
118
+ *
119
+ */
120
+ export class OINOConsoleLog extends OINOLog {
121
+ /**
122
+ * Constructor of `OINOConsoleLog`
123
+ * @param logLevel logging level
124
+ */
125
+ constructor(logLevel = OINOLogLevel.warn) {
126
+ super(logLevel);
127
+ }
128
+ _writeLog(level, message, data) {
129
+ let log = "OINOLog " + level + ": " + message;
130
+ if (data) {
131
+ log += " " + JSON.stringify(data);
132
+ }
133
+ console.log(log);
134
+ }
135
+ }
@@ -0,0 +1,132 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+ import { OINO_DEBUG_PREFIX, OINO_ERROR_PREFIX, OINO_INFO_PREFIX, OINO_WARNING_PREFIX } from ".";
7
+ /**
8
+ * OINO API request result object with returned data and/or http status code/message and
9
+ * error / warning messages.
10
+ *
11
+ */
12
+ export class OINOResult {
13
+ /** Wheter request was successfully executed */
14
+ success;
15
+ /** HTTP status code */
16
+ statusCode;
17
+ /** HTTP status message */
18
+ statusMessage;
19
+ /** Error / warning messages */
20
+ messages;
21
+ /**
22
+ * Constructor of OINOResult.
23
+ *
24
+ */
25
+ constructor() {
26
+ this.success = true;
27
+ this.statusCode = 200;
28
+ this.statusMessage = "OK";
29
+ this.messages = [];
30
+ }
31
+ /**
32
+ * Set HTTP OK status (does not reset messages).
33
+ *
34
+ */
35
+ setOk() {
36
+ this.success = true;
37
+ this.statusCode = 200;
38
+ this.statusMessage = "OK";
39
+ }
40
+ /**
41
+ * Set HTTP error status using given code and message.
42
+ *
43
+ * @param statusCode HTTP status code
44
+ * @param statusMessage HTTP status message
45
+ * @param operation operation where error occured
46
+ *
47
+ */
48
+ setError(statusCode, statusMessage, operation) {
49
+ this.success = false;
50
+ this.statusCode = statusCode;
51
+ if (this.statusMessage != "OK") {
52
+ this.messages.push(this.statusMessage); // latest error becomes status, but if there was something non-trivial, add it to the messages
53
+ }
54
+ if (statusMessage.startsWith(OINO_ERROR_PREFIX)) {
55
+ this.statusMessage = statusMessage;
56
+ }
57
+ else {
58
+ this.statusMessage = OINO_ERROR_PREFIX + " (" + operation + "): " + statusMessage;
59
+ }
60
+ }
61
+ /**
62
+ * Add warning message.
63
+ *
64
+ * @param message HTTP status message
65
+ * @param operation operation where warning occured
66
+ *
67
+ */
68
+ addWarning(message, operation) {
69
+ message = message.trim();
70
+ if (message) {
71
+ this.messages.push(OINO_WARNING_PREFIX + " (" + operation + "): " + message);
72
+ }
73
+ }
74
+ /**
75
+ * Add info message.
76
+ *
77
+ * @param message HTTP status message
78
+ * @param operation operation where info occured
79
+ *
80
+ */
81
+ addInfo(message, operation) {
82
+ message = message.trim();
83
+ if (message) {
84
+ this.messages.push(OINO_INFO_PREFIX + " (" + operation + "): " + message);
85
+ }
86
+ }
87
+ /**
88
+ * Add debug message.
89
+ *
90
+ * @param message HTTP status message
91
+ * @param operation operation where debug occured
92
+ *
93
+ */
94
+ addDebug(message, operation) {
95
+ message = message.trim();
96
+ if (message) {
97
+ this.messages.push(OINO_DEBUG_PREFIX + " (" + operation + "): " + message);
98
+ }
99
+ }
100
+ /**
101
+ * Copy given messages to HTTP headers.
102
+ *
103
+ * @param headers HTTP headers
104
+ * @param copyErrors wether error messages should be copied (default true)
105
+ * @param copyWarnings wether warning messages should be copied (default false)
106
+ * @param copyInfos wether info messages should be copied (default false)
107
+ * @param copyDebug wether debug messages should be copied (default false)
108
+ *
109
+ */
110
+ copyMessagesToHeaders(headers, copyErrors = true, copyWarnings = false, copyInfos = false, copyDebug = false) {
111
+ let j = 1;
112
+ for (let i = 0; i < this.messages.length; i++) {
113
+ const message = this.messages[i].replaceAll("\r", " ").replaceAll("\n", " ");
114
+ if (copyErrors && message.startsWith(OINO_ERROR_PREFIX)) {
115
+ headers.append('X-OINO-MESSAGE-' + j, message);
116
+ j++;
117
+ }
118
+ if (copyWarnings && message.startsWith(OINO_WARNING_PREFIX)) {
119
+ headers.append('X-OINO-MESSAGE-' + j, message);
120
+ j++;
121
+ }
122
+ if (copyInfos && message.startsWith(OINO_INFO_PREFIX)) {
123
+ headers.append('X-OINO-MESSAGE-' + j, message);
124
+ j++;
125
+ }
126
+ if (copyDebug && message.startsWith(OINO_DEBUG_PREFIX)) {
127
+ headers.append('X-OINO-MESSAGE-' + j, message);
128
+ j++;
129
+ }
130
+ }
131
+ }
132
+ }