yini-parser 1.0.0-alpha.1

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 (46) hide show
  1. package/CHANGELOG.md +0 -0
  2. package/LICENSE +201 -0
  3. package/README.md +120 -0
  4. package/dist/src/YINI.js +122 -0
  5. package/dist/src/config/env.js +15 -0
  6. package/dist/src/core/ErrorDataHandler.js +207 -0
  7. package/dist/src/core/YINIVisitor.js +856 -0
  8. package/dist/src/core/objectBuilder.js +166 -0
  9. package/dist/src/core/types.js +36 -0
  10. package/dist/src/grammar/YiniLexer.js +370 -0
  11. package/dist/src/grammar/YiniParser.js +2106 -0
  12. package/dist/src/grammar/YiniParserVisitor.js +14 -0
  13. package/dist/src/index.js +189 -0
  14. package/dist/src/parseEntry.js +155 -0
  15. package/dist/src/parsers/extractHeaderParts.js +103 -0
  16. package/dist/src/parsers/extractSignificantYiniLine.js +68 -0
  17. package/dist/src/parsers/parseBoolean.js +12 -0
  18. package/dist/src/parsers/parseNull.js +11 -0
  19. package/dist/src/parsers/parseNumber.js +49 -0
  20. package/dist/src/parsers/parseSectionHeader.js +111 -0
  21. package/dist/src/parsers/parseString.js +40 -0
  22. package/dist/src/utils/pathAndFileName.js +15 -0
  23. package/dist/src/utils/string.js +97 -0
  24. package/dist/src/utils/system.js +23 -0
  25. package/dist/src/yiniHelpers.js +141 -0
  26. package/dist/tests/integration/1-core-parsing/parse-bigger-section-nesting-as-object.test.js +83 -0
  27. package/dist/tests/integration/1-core-parsing/parse-section-nesting-w-classic-markers.test.js +170 -0
  28. package/dist/tests/integration/1-core-parsing/parse-section-nesting-w-nsh-markers.test.js +27 -0
  29. package/dist/tests/integration/1-core-parsing/read some values from level 1 and 2.test.js +77 -0
  30. package/dist/tests/integration/1-core-parsing/throw on bad section heads.test.js +162 -0
  31. package/dist/tests/integration/10-special-validation-modes/validation-modes.test.js +38 -0
  32. package/dist/tests/integration/2-file-structure-and-error/able to parse mixed case filenames.test.js +72 -0
  33. package/dist/tests/integration/2-file-structure-and-error/throw error on bad file extensions.test.js +36 -0
  34. package/dist/tests/integration/2-file-structure-and-error/throw error parsing bad content.test.js +80 -0
  35. package/dist/tests/smoke/A-general-smoke.test.js +259 -0
  36. package/dist/tests/smoke/B-parse-inline-smoke.test.js +270 -0
  37. package/dist/tests/smoke/C-traverse-file-smoke.test.js +141 -0
  38. package/dist/tests/smoke/D-parse-file-smoke.test.js +134 -0
  39. package/dist/tests/unit/parsers/extractHeaderParts.unit.test.js +490 -0
  40. package/dist/tests/unit/parsers/parseSectionHeader-classic.unit.test.js +421 -0
  41. package/dist/tests/unit/parsers/parseSectionHeader-nsh.unit.test.js +436 -0
  42. package/dist/tests/unit/parsers/parseSectionHeader-throw-on-invalid.unit.test.js +168 -0
  43. package/dist/tests/unit/utils/utils-pathAndFileName.unit.test.js +80 -0
  44. package/dist/tests/unit/utils/utils-string.unit.test.js +185 -0
  45. package/dist/tests/unit/yiniHelpers.unit.test.js +306 -0
  46. package/package.json +94 -0
package/CHANGELOG.md ADDED
File without changes
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Gothenburg, Marko K. S. (Sweden via Finland).
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,120 @@
1
+ >~ YINI ≡
2
+ ---
3
+ # YINI Parser - TypeScript
4
+
5
+ **YINI Parser for TypeScript** — a simple, human-friendly parser and reader for the YINI configuration file format. This library implements the official YINI specification using TypeScript + ANTLR4.
6
+
7
+ YINI is a configuration file format (see [spec] for details):
8
+ https://github.com/YINI-lang/YINI-spec
9
+
10
+ ---
11
+
12
+ ## ✨ Features
13
+ - Simple, strict parsing.
14
+ - Familiar config file style (inspired by INI, YAML, TOML).
15
+ - Easy programmatic usage.
16
+ - Only the `YINI` class is exported; all internal details are private.
17
+
18
+ ### Limitations
19
+ Not all features of the full YINI specification are implemented yet.
20
+
21
+ See [FEATURE-CHECKLIST.md](./FEATURE-CHECKLIST.md) for the current list of implemented YINI features.
22
+
23
+ ---
24
+
25
+ ## 🚀 Installation
26
+
27
+ With **npm**:
28
+ ```sh
29
+ npm install yini-parser
30
+ ```
31
+
32
+ With **yarn**:
33
+ ```sh
34
+ yarn add yini-parser
35
+ ```
36
+
37
+ With **pnpm**:
38
+ ```sh
39
+ pnpm add yini-parser
40
+ ```
41
+
42
+ ---
43
+
44
+ ## Usage
45
+
46
+ > Only import the main class:
47
+ >
48
+ > ```ts
49
+ > import YINI from 'yini-parser';
50
+ > ```
51
+
52
+ ### Example:
53
+ ```ts
54
+ import YINI from 'yini-parser';
55
+
56
+ // Parse from string.
57
+ const config = YINI.parse(`
58
+ ^ Database
59
+ host = localhost
60
+ port = 5432
61
+ `);
62
+
63
+ // Parse from file.
64
+ const configFromFile = YINI.parseFile('./config.yini');
65
+ ```
66
+
67
+ ---
68
+
69
+ ## API
70
+
71
+ Only the `YINI` class is exposed in the public API, with two static methods: `parse` and `parseFile`.
72
+
73
+ ### `YINI.parse(yiniContent: string, strictMode?: boolean, bailSensitivity: 'auto' | 0 | 1 | 2 = "auto", includeMetaData = false): object`
74
+
75
+ Parses YINI code from a string.
76
+
77
+ **Params:**
78
+ - `yiniContent`: The YINI configuration as a string.
79
+ - `strictMode`: (optional, default `false`) Parse in strict mode.
80
+ - `bailSensitivity`: (optional, default `"auto"`) Error tolerance level.
81
+ * If `bailSensitivity` is `"auto"` then bail sensitivity level will be set to 0 if in non-strict mode, if in strict mode then level 1 will be used automatically.
82
+ - `includeMetaData`: If true then additional meta data will be returned along the object.
83
+
84
+ **Bail sensitivity levels:**
85
+ - 0 = 'Ignore-Errors' // Don't bail on errors, persist and try to recover.
86
+ - 1 = 'Abort-on-Errors'
87
+ - 2 = 'Abort-Even-on-Warnings'
88
+
89
+ Returns a JavaScript object representing the parsed configuration (YINI content).
90
+
91
+ ### `YINI.parseFile(yiniContent: string, strictMode?: boolean, bailSensitivity: 'auto' | 0 | 1 | 2 = "auto", includeMetaData = false): object`
92
+
93
+ Parses YINI code from a file.
94
+ - `filePath`: Path to the `.yini` file.
95
+ - Other parameters are the same as `parse(..)`.
96
+
97
+ Returns a JavaScript object representing the parsed YINI configuration file.
98
+
99
+ ---
100
+
101
+ ## Example Output
102
+ --TODO--
103
+
104
+ ---
105
+
106
+ ## 📚 Documentation
107
+ - [Development Setup](./docs/Development%20Setup.md) — How to run, test, and build the project, etc.
108
+ - [Conventions](./docs/Conventions.md) — Project conventions, naming patterns, etc.
109
+
110
+ ---
111
+
112
+ ## License
113
+ This project is licensed under the Apache-2.0 license - see the [LICENSE](<./LICENSE>) file for details.
114
+
115
+ In this project on GitHub, the `libs` directory contains third party software and each is licensed under its own license which is described in its own license file under the respective directory under `libs`.
116
+
117
+ ---
118
+
119
+ > ~ **YINI ≡**
120
+ > [https://yini-lang.org](https://yini-lang.org)
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const fs_1 = __importDefault(require("fs"));
7
+ const env_1 = require("./config/env");
8
+ const parseEntry_1 = require("./parseEntry");
9
+ const pathAndFileName_1 = require("./utils/pathAndFileName");
10
+ const system_1 = require("./utils/system");
11
+ /**
12
+ * This class is the public API, which exposes only parse(..) and
13
+ * parseFile(..), rest of the implementation details are hidden.
14
+ * @note Only parse and parseFile are public.
15
+ */
16
+ class YINI {
17
+ }
18
+ YINI.fullPath = ''; // Used in error reporting.
19
+ /**
20
+ * @param yiniContent YINI code as a string, can be multiple lines.
21
+ * @note The order of properties (members) in each JavaScript object (section) may differ from the order in the input YINI content.
22
+ * @returns The parsed JavaScript object.
23
+ */
24
+ YINI.parse = (yiniContent, strictMode = false, bailSensitivity = 'auto', includeMetaData = false) => {
25
+ (0, system_1.debugPrint)('-> Entered static parse(..) in class YINI\n');
26
+ // Important: First, before anything, trim beginning and trailing whitespaces!
27
+ yiniContent = yiniContent.trim();
28
+ if (!yiniContent) {
29
+ throw new Error('Syntax-Error: Unexpected blank YINI input');
30
+ }
31
+ if (!yiniContent.endsWith('\n')) {
32
+ yiniContent += '\n';
33
+ }
34
+ let level = 0;
35
+ // if (bailSensitivity === 'auto' && !strictMode) level = 0
36
+ // if (bailSensitivity === 'auto' && strictMode) level = 1
37
+ if (bailSensitivity === 'auto') {
38
+ if (!strictMode)
39
+ level = 0;
40
+ if (strictMode)
41
+ level = 1;
42
+ if (process.env.NODE_ENV === 'test')
43
+ level = 1;
44
+ }
45
+ else {
46
+ level = bailSensitivity;
47
+ }
48
+ const options = {
49
+ isStrict: strictMode,
50
+ bailSensitivityLevel: level,
51
+ isIncludeMeta: includeMetaData,
52
+ isWithDiagnostics: (0, env_1.isDev)() || (0, env_1.isDebug)(),
53
+ isWithTiming: (0, env_1.isDebug)(),
54
+ };
55
+ (0, system_1.debugPrint)();
56
+ (0, system_1.debugPrint)('==== Call parse ==========================');
57
+ const result = (0, parseEntry_1.parseMain)(yiniContent, options);
58
+ (0, system_1.debugPrint)('==== End call parse ==========================\n');
59
+ if ((0, env_1.isDev)()) {
60
+ console.log();
61
+ (0, system_1.devPrint)('YINI.parse(..): result:');
62
+ console.log(result);
63
+ (0, system_1.devPrint)('Complete result:');
64
+ (0, system_1.printObject)(result);
65
+ }
66
+ return result;
67
+ };
68
+ /**
69
+ * @param yiniFile Full path to the YINI file.
70
+ * @note The order of properties (members) in each JavaScript object (section) may differ from the order in the input YINI file.
71
+ * @returns The parsed JavaScript object.
72
+ */
73
+ YINI.parseFile = (fullPath, strictMode = false, bailSensitivity = 'auto', includeMetaData = false) => {
74
+ (0, system_1.debugPrint)('Current directory = ' + process.cwd());
75
+ if ((0, pathAndFileName_1.getFileNameExtension)(fullPath).toLowerCase() !== '.yini') {
76
+ console.error('Invalid file extension for YINI file:');
77
+ console.error(`"${fullPath}"`);
78
+ console.log('File does not have a valid ".yini" extension (case-insensitive).');
79
+ throw new Error('Error: Unexpected file extension for YINI file');
80
+ }
81
+ let content = fs_1.default.readFileSync(fullPath, 'utf8');
82
+ let hasNoNewlineAtEOF = false;
83
+ if (!content.endsWith('\n')) {
84
+ content += '\n';
85
+ hasNoNewlineAtEOF = true;
86
+ }
87
+ YINI.fullPath = fullPath;
88
+ let level = 0;
89
+ // if (bailSensitivity === 'auto' && !strictMode) level = 0
90
+ // if (bailSensitivity === 'auto' && strictMode) level = 1
91
+ if (bailSensitivity === 'auto') {
92
+ if (!strictMode)
93
+ level = 0;
94
+ if (strictMode)
95
+ level = 1;
96
+ if (process.env.NODE_ENV === 'test')
97
+ level = 1;
98
+ }
99
+ else {
100
+ level = bailSensitivity;
101
+ }
102
+ const options = {
103
+ isStrict: strictMode,
104
+ bailSensitivityLevel: level,
105
+ isIncludeMeta: includeMetaData,
106
+ isWithDiagnostics: (0, env_1.isDev)() || (0, env_1.isDebug)(),
107
+ isWithTiming: (0, env_1.isDebug)(),
108
+ };
109
+ (0, system_1.debugPrint)();
110
+ (0, system_1.debugPrint)('==== Call parse ==========================');
111
+ const result = (0, parseEntry_1.parseMain)(content, options);
112
+ (0, system_1.debugPrint)('==== End call parse ==========================\n');
113
+ if ((0, env_1.isDev)()) {
114
+ console.log();
115
+ (0, system_1.devPrint)('YINI.parse(..): result:');
116
+ console.log(result);
117
+ (0, system_1.devPrint)('Complete result:');
118
+ (0, system_1.printObject)(result);
119
+ }
120
+ return result;
121
+ };
122
+ exports.default = YINI;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.APP_ENV = exports.NODE_ENV = exports.isTest = exports.isProd = exports.isDev = exports.isDebug = void 0;
4
+ const NODE_ENV = (process.env.NODE_ENV || 'development');
5
+ exports.NODE_ENV = NODE_ENV;
6
+ const APP_ENV = (process.env.APP_ENV || 'local');
7
+ exports.APP_ENV = APP_ENV;
8
+ const isDebug = () => !!process.env.IS_DEBUG;
9
+ exports.isDebug = isDebug;
10
+ const isDev = () => NODE_ENV === 'development';
11
+ exports.isDev = isDev;
12
+ const isProd = () => NODE_ENV === 'production';
13
+ exports.isProd = isProd;
14
+ const isTest = () => NODE_ENV === 'test';
15
+ exports.isTest = isTest;
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ErrorDataHandler = void 0;
4
+ const env_1 = require("../config/env");
5
+ const system_1 = require("../utils/system");
6
+ // All the issue titles are defined here to get a quick overview of all
7
+ // titles, and to easier check that all titles match with relation to
8
+ // the other titles.
9
+ const issueTitle = [
10
+ 'FATAL ERROR!',
11
+ 'Internal error!', // 'Internal-Error'.
12
+ 'Syntax error.', // 'Syntax-Error'.
13
+ 'Syntax warning.',
14
+ 'Notice:',
15
+ 'Info:',
16
+ ];
17
+ /**
18
+ * This class handles all error/notice reporting and processes exit/throwing.
19
+ */
20
+ class ErrorDataHandler {
21
+ /** '1-Abort-on-Errors' is the default.
22
+
23
+ Below is from the YINI spec:
24
+ **Abort Sensitivity Levels** while parsing a YINI document:
25
+ (AKA severity threshold)
26
+ - Level 0 = ignore errors and try parse anyway (may remap falty key/section names)
27
+ - Level 1 = abort on errors only
28
+ - Level 2 = abort even on warnings
29
+ */
30
+ constructor(threshold = '1-Abort-on-Errors') {
31
+ this.numFatalErrors = 0;
32
+ this.numInternalErrors = 0;
33
+ this.numSyntaxErrors = 0;
34
+ this.numSyntaxWarnings = 0;
35
+ this.numNotices = 0;
36
+ this.numInfos = 0;
37
+ this.makeIssuePayload = (type, msgWhat, lineNum, startCol, endCol) => {
38
+ const issue = {
39
+ type,
40
+ msgWhat,
41
+ // msgHintOrFix: string = '', // Hint or wow to fix.
42
+ start: {
43
+ line: lineNum,
44
+ column: startCol,
45
+ },
46
+ end: {
47
+ line: lineNum,
48
+ column: endCol,
49
+ },
50
+ };
51
+ (0, system_1.debugPrint)('issue:');
52
+ (0, env_1.isDebug)() && console.log(issue);
53
+ return issue;
54
+ };
55
+ /**
56
+ * After pushing processing may continue or exit, depending on the error
57
+ * and/or the bail threshold (that can be optionally set my the user).
58
+ *
59
+ * @note This function MIGHT result in a return, throw, or exit depending
60
+ * on the bail policy (set my the user).
61
+ *
62
+ * @param ctx
63
+ * @param type
64
+ * @param msgWhat Name of the specific error or what failed. E.g. "Key already exists in this section scope".
65
+ * @param msgWhy More details and more specific info about the issue/error.
66
+ * @param msgHint Hint or HUMBLE description on how to fix the issue.
67
+ */
68
+ this.pushOrBail = (ctx, type, msgWhat, msgWhy = '', msgHint = '') => {
69
+ var _a, _b, _c, _d, _e, _f;
70
+ (0, system_1.debugPrint)('-> pushOrBail(..)');
71
+ (0, system_1.debugPrint)('ctx.exception?.name =' + ((_a = ctx === null || ctx === void 0 ? void 0 : ctx.exception) === null || _a === void 0 ? void 0 : _a.name));
72
+ (0, system_1.debugPrint)('ctx.exception?.message = ' + ((_b = ctx === null || ctx === void 0 ? void 0 : ctx.exception) === null || _b === void 0 ? void 0 : _b.message));
73
+ (0, system_1.debugPrint)('exception?.offendingToken = ' + ((_c = ctx === null || ctx === void 0 ? void 0 : ctx.exception) === null || _c === void 0 ? void 0 : _c.offendingToken));
74
+ (0, system_1.debugPrint)();
75
+ (0, system_1.debugPrint)('ctx.ruleIndex = ' + (ctx === null || ctx === void 0 ? void 0 : ctx.start.channel));
76
+ (0, system_1.debugPrint)('ctx.ruleIndex = ' + (ctx === null || ctx === void 0 ? void 0 : ctx.ruleIndex));
77
+ (0, system_1.debugPrint)('ctx.ruleContext = ' + (ctx === null || ctx === void 0 ? void 0 : ctx.ruleContext));
78
+ (0, system_1.debugPrint)('ctx.stop?.line = ' + ((_d = ctx === null || ctx === void 0 ? void 0 : ctx.stop) === null || _d === void 0 ? void 0 : _d.line));
79
+ (0, system_1.debugPrint)('ctx.stop?.column = ' + ((_e = ctx === null || ctx === void 0 ? void 0 : ctx.stop) === null || _e === void 0 ? void 0 : _e.column));
80
+ const lineNum = (ctx === null || ctx === void 0 ? void 0 : ctx.start.line) || 0; // Column (1-based).
81
+ const startCol = !ctx ? 0 : ++ctx.start.column; // Column (0-based).
82
+ const endCol = (((_f = ctx === null || ctx === void 0 ? void 0 : ctx.stop) === null || _f === void 0 ? void 0 : _f.column) || 0) + 1; // Column (0-based).
83
+ // Patch message with the offending line number.
84
+ msgWhat += ', at line: ' + lineNum;
85
+ if (process.env.NODE_ENV === 'test') {
86
+ msgWhat += `\nAt line: ${lineNum}, column(s): ${startCol}-${endCol}`;
87
+ }
88
+ (0, system_1.debugPrint)('persistThreshold = ' + this.persistThreshold);
89
+ (0, system_1.debugPrint)('lineNum = ' + lineNum);
90
+ (0, system_1.debugPrint)();
91
+ const issue = this.makeIssuePayload(type, msgWhat, lineNum, startCol, endCol);
92
+ switch (type) {
93
+ case 'Internal-Error':
94
+ this.numInternalErrors++;
95
+ this.emitInternalError(msgWhat, msgWhy, msgHint);
96
+ if (this.persistThreshold === '1-Abort-on-Errors' ||
97
+ this.persistThreshold === '2-Abort-Even-on-Warnings') {
98
+ if (process.env.NODE_ENV === 'test') {
99
+ // In test, throw an error instead of exiting.
100
+ throw new Error(`Internal-Error: ${msgWhat}`);
101
+ }
102
+ else {
103
+ process.exit(2);
104
+ }
105
+ }
106
+ break;
107
+ case 'Syntax-Error':
108
+ this.numSyntaxErrors++;
109
+ this.emitSyntaxError(msgWhat, msgWhy, msgHint);
110
+ if (this.persistThreshold === '1-Abort-on-Errors' ||
111
+ this.persistThreshold === '2-Abort-Even-on-Warnings') {
112
+ if (process.env.NODE_ENV === 'test') {
113
+ // In test, throw an error instead of exiting.
114
+ throw new Error(`Syntax-Error: ${'' + msgWhat}`);
115
+ }
116
+ else {
117
+ process.exit(3);
118
+ }
119
+ }
120
+ break;
121
+ case 'Syntax-Warning':
122
+ this.numSyntaxWarnings++;
123
+ this.emitSyntaxWarning(msgWhat, msgWhy, msgHint);
124
+ if (this.persistThreshold === '2-Abort-Even-on-Warnings') {
125
+ if (process.env.NODE_ENV === 'test') {
126
+ // In test, throw an error instead of exiting.
127
+ throw new Error(`Syntax-Warning: ${msgWhat}`);
128
+ }
129
+ else {
130
+ process.exit(4);
131
+ }
132
+ }
133
+ break;
134
+ case 'Notice':
135
+ this.numNotices++;
136
+ this.emitNotice(msgWhat, msgWhy, msgHint);
137
+ break;
138
+ case 'Info':
139
+ this.numInfos++;
140
+ this.emitInfo(msgWhat, msgWhy, msgHint);
141
+ break;
142
+ default: // Including 'Internal-Error'.
143
+ this.numFatalErrors++;
144
+ this.emitFatalError(msgWhat, msgWhy, msgHint);
145
+ // CANNOT recover fatal errors, will lead to an exit!
146
+ if (process.env.NODE_ENV === 'test') {
147
+ // In test, throw an error instead of exiting.
148
+ throw new Error(`Internal-Error: ${msgWhat}`);
149
+ }
150
+ else {
151
+ process.exit(1);
152
+ // (!) Not sure about the below yet, if it's preferable in this case...
153
+ // Use this instead of process.exit(1), this will
154
+ // lead to that the current thread(s) will exit as well.
155
+ // process.exitCode = 1
156
+ }
157
+ }
158
+ };
159
+ this.emitFatalError = (msgWhat = 'Something went wrong!', msgWhy = '', msgHint = '') => {
160
+ console.error(issueTitle[0]); // Print the issue title.
161
+ msgWhat && console.error(msgWhat);
162
+ msgWhy && console.error(msgWhy);
163
+ msgHint && console.log(msgHint);
164
+ };
165
+ this.emitInternalError = (msgWhat = 'Something went wrong!', msgWhy = '', msgHint = '') => {
166
+ console.error(issueTitle[1]); // Print the issue title.
167
+ msgWhat && console.error(msgWhat);
168
+ msgWhy && console.error(msgWhy);
169
+ msgHint && console.log(msgHint);
170
+ };
171
+ this.emitSyntaxError = (msgWhat, msgWhy = '', msgHint = '') => {
172
+ console.error(issueTitle[2]); // Print the issue title.
173
+ msgWhat && console.error(msgWhat);
174
+ msgWhy && console.error(msgWhy);
175
+ msgHint && console.log(msgHint);
176
+ };
177
+ this.emitSyntaxWarning = (msgWhat, msgWhy = '', msgHint = '') => {
178
+ console.warn(issueTitle[3]); // Print the issue title.
179
+ msgWhat && console.warn(msgWhat);
180
+ msgWhy && console.warn(msgWhy);
181
+ msgHint && console.log(msgHint);
182
+ };
183
+ this.emitNotice = (msgWhat, msgWhy = '', msgHint = '') => {
184
+ console.warn(issueTitle[4]); // Print the issue title.
185
+ msgWhat && console.warn(msgWhat);
186
+ msgWhy && console.warn(msgWhy);
187
+ msgHint && console.log(msgHint);
188
+ };
189
+ this.emitInfo = (msgWhat, msgWhy = '', msgHint = '') => {
190
+ console.info(issueTitle[5]); // Print the issue title.
191
+ msgWhat && console.info(msgWhat);
192
+ msgWhy && console.info(msgWhy);
193
+ msgHint && console.log(msgHint);
194
+ };
195
+ this.persistThreshold = threshold;
196
+ }
197
+ getNumOfErrors() {
198
+ return (this.numFatalErrors + this.numInternalErrors + this.numSyntaxErrors);
199
+ }
200
+ getNumOfWarnings() {
201
+ return this.numSyntaxWarnings;
202
+ }
203
+ getNumOfInfoAndNotices() {
204
+ return this.numNotices + this.numInfos;
205
+ }
206
+ }
207
+ exports.ErrorDataHandler = ErrorDataHandler;