@nejs/basic-extensions 2.21.5 → 2.22.6

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 (266) hide show
  1. package/README.md +78 -4
  2. package/dist/@nejs/basic-extensions.bundle.2.22.6.js +25 -0
  3. package/dist/@nejs/basic-extensions.bundle.2.22.6.js.map +7 -0
  4. package/dist/cjs/classes/index.cjs +11129 -0
  5. package/dist/cjs/classes/index.cjs.map +7 -0
  6. package/dist/cjs/index.cjs +15191 -0
  7. package/dist/cjs/index.cjs.map +7 -0
  8. package/dist/cjs/utils/index.cjs +3954 -0
  9. package/dist/cjs/utils/index.cjs.map +7 -0
  10. package/dist/esm/basic-extensions.mjs +25 -0
  11. package/dist/esm/basic-extensions.mjs.map +7 -0
  12. package/package.json +16 -22
  13. package/repl.bootstrap.js +4 -7
  14. package/repl.history +26 -26
  15. package/src/classes/enumeration.js +466 -0
  16. package/src/classes/index.js +5 -1
  17. package/src/index.js +3 -1
  18. package/src/regular.expression.extensions.js +0 -35
  19. package/src/utils/toolkit.js +699 -516
  20. package/tests/arrayextensions.test.js +3 -3
  21. package/tests/index.test.js +3 -1
  22. package/tests/newClasses/asyncIterable.test.js +3 -3
  23. package/tests/newClasses/deferred.test.js +3 -3
  24. package/tests/newClasses/descriptor.test.js +3 -3
  25. package/tests/newClasses/iterable.test.js +3 -3
  26. package/tests/newClasses/refmap.test.js +3 -3
  27. package/tests/newClasses/refset.test.js +3 -3
  28. package/tests/objectextensions.test.js +3 -3
  29. package/tests/setextensions.test.js +3 -3
  30. package/tests/stringextensions.test.js +3 -2
  31. package/tests/utils/descriptor.utils.test.js +1 -1
  32. package/tests/utils/toolkit.test.js +429 -163
  33. package/.esdoc.json +0 -9
  34. package/.vscode/settings.json +0 -5
  35. package/bin/build +0 -27
  36. package/bin/clean +0 -14
  37. package/bin/esbuild +0 -91
  38. package/bin/fixup +0 -13
  39. package/bin/repl.basics.js +0 -584
  40. package/bin/repl.signature.js +0 -63
  41. package/bin/version +0 -100
  42. package/dist/@nejs/basic-extensions.bundle.2.21.5.js +0 -25
  43. package/dist/@nejs/basic-extensions.bundle.2.21.5.js.map +0 -7
  44. package/dist/cjs/array.extensions.d.ts +0 -39
  45. package/dist/cjs/array.extensions.js +0 -477
  46. package/dist/cjs/array.extensions.js.map +0 -1
  47. package/dist/cjs/big.int.extension.d.ts +0 -31
  48. package/dist/cjs/big.int.extension.js +0 -273
  49. package/dist/cjs/big.int.extension.js.map +0 -1
  50. package/dist/cjs/classes/asyncIterable.d.ts +0 -126
  51. package/dist/cjs/classes/asyncIterable.js +0 -209
  52. package/dist/cjs/classes/asyncIterable.js.map +0 -1
  53. package/dist/cjs/classes/deferred.d.ts +0 -146
  54. package/dist/cjs/classes/deferred.js +0 -291
  55. package/dist/cjs/classes/deferred.js.map +0 -1
  56. package/dist/cjs/classes/descriptor.d.ts +0 -334
  57. package/dist/cjs/classes/descriptor.js +0 -537
  58. package/dist/cjs/classes/descriptor.js.map +0 -1
  59. package/dist/cjs/classes/enum.d.ts +0 -50
  60. package/dist/cjs/classes/enum.js +0 -405
  61. package/dist/cjs/classes/enum.js.map +0 -1
  62. package/dist/cjs/classes/index.d.ts +0 -15
  63. package/dist/cjs/classes/index.js +0 -63
  64. package/dist/cjs/classes/index.js.map +0 -1
  65. package/dist/cjs/classes/introspector.d.ts +0 -20
  66. package/dist/cjs/classes/introspector.js +0 -130
  67. package/dist/cjs/classes/introspector.js.map +0 -1
  68. package/dist/cjs/classes/iterable.d.ts +0 -169
  69. package/dist/cjs/classes/iterable.js +0 -268
  70. package/dist/cjs/classes/iterable.js.map +0 -1
  71. package/dist/cjs/classes/param.parser.d.ts +0 -221
  72. package/dist/cjs/classes/param.parser.js +0 -242
  73. package/dist/cjs/classes/param.parser.js.map +0 -1
  74. package/dist/cjs/classes/pluggable.proxy.d.ts +0 -153
  75. package/dist/cjs/classes/pluggable.proxy.js +0 -444
  76. package/dist/cjs/classes/pluggable.proxy.js.map +0 -1
  77. package/dist/cjs/classes/property.d.ts +0 -79
  78. package/dist/cjs/classes/property.js +0 -284
  79. package/dist/cjs/classes/property.js.map +0 -1
  80. package/dist/cjs/classes/refmap.d.ts +0 -238
  81. package/dist/cjs/classes/refmap.js +0 -421
  82. package/dist/cjs/classes/refmap.js.map +0 -1
  83. package/dist/cjs/classes/refset.d.ts +0 -186
  84. package/dist/cjs/classes/refset.js +0 -370
  85. package/dist/cjs/classes/refset.js.map +0 -1
  86. package/dist/cjs/classes/symkeys.d.ts +0 -349
  87. package/dist/cjs/classes/symkeys.js +0 -510
  88. package/dist/cjs/classes/symkeys.js.map +0 -1
  89. package/dist/cjs/classes/type.d.ts +0 -56
  90. package/dist/cjs/classes/type.js +0 -405
  91. package/dist/cjs/classes/type.js.map +0 -1
  92. package/dist/cjs/function.extensions.d.ts +0 -12
  93. package/dist/cjs/function.extensions.js +0 -758
  94. package/dist/cjs/function.extensions.js.map +0 -1
  95. package/dist/cjs/global.this.d.ts +0 -2
  96. package/dist/cjs/global.this.js +0 -300
  97. package/dist/cjs/global.this.js.map +0 -1
  98. package/dist/cjs/index.d.ts +0 -31
  99. package/dist/cjs/index.js +0 -228
  100. package/dist/cjs/index.js.map +0 -1
  101. package/dist/cjs/json.extensions.d.ts +0 -2
  102. package/dist/cjs/json.extensions.js +0 -109
  103. package/dist/cjs/json.extensions.js.map +0 -1
  104. package/dist/cjs/map.extensions.d.ts +0 -3
  105. package/dist/cjs/map.extensions.js +0 -143
  106. package/dist/cjs/map.extensions.js.map +0 -1
  107. package/dist/cjs/math.extension.d.ts +0 -14
  108. package/dist/cjs/math.extension.js +0 -71
  109. package/dist/cjs/math.extension.js.map +0 -1
  110. package/dist/cjs/number.extension.d.ts +0 -44
  111. package/dist/cjs/number.extension.js +0 -278
  112. package/dist/cjs/number.extension.js.map +0 -1
  113. package/dist/cjs/object.extensions.d.ts +0 -33
  114. package/dist/cjs/object.extensions.js +0 -1091
  115. package/dist/cjs/object.extensions.js.map +0 -1
  116. package/dist/cjs/package.json +0 -3
  117. package/dist/cjs/proxy.extensions.d.ts +0 -2
  118. package/dist/cjs/proxy.extensions.js +0 -207
  119. package/dist/cjs/proxy.extensions.js.map +0 -1
  120. package/dist/cjs/reflect.extensions.d.ts +0 -14
  121. package/dist/cjs/reflect.extensions.js +0 -316
  122. package/dist/cjs/reflect.extensions.js.map +0 -1
  123. package/dist/cjs/regular.expression.extensions.d.ts +0 -2
  124. package/dist/cjs/regular.expression.extensions.js +0 -423
  125. package/dist/cjs/regular.expression.extensions.js.map +0 -1
  126. package/dist/cjs/set.extensions.d.ts +0 -40
  127. package/dist/cjs/set.extensions.js +0 -355
  128. package/dist/cjs/set.extensions.js.map +0 -1
  129. package/dist/cjs/string.extensions.d.ts +0 -23
  130. package/dist/cjs/string.extensions.js +0 -704
  131. package/dist/cjs/string.extensions.js.map +0 -1
  132. package/dist/cjs/symbol.extensions.d.ts +0 -11
  133. package/dist/cjs/symbol.extensions.js +0 -735
  134. package/dist/cjs/symbol.extensions.js.map +0 -1
  135. package/dist/cjs/utils/copy.object.d.ts +0 -408
  136. package/dist/cjs/utils/copy.object.js +0 -720
  137. package/dist/cjs/utils/copy.object.js.map +0 -1
  138. package/dist/cjs/utils/descriptor.utils.d.ts +0 -298
  139. package/dist/cjs/utils/descriptor.utils.js +0 -889
  140. package/dist/cjs/utils/descriptor.utils.js.map +0 -1
  141. package/dist/cjs/utils/index.d.ts +0 -75
  142. package/dist/cjs/utils/index.js +0 -61
  143. package/dist/cjs/utils/index.js.map +0 -1
  144. package/dist/cjs/utils/stdout.d.ts +0 -742
  145. package/dist/cjs/utils/stdout.js +0 -1042
  146. package/dist/cjs/utils/stdout.js.map +0 -1
  147. package/dist/cjs/utils/toolkit.d.ts +0 -1898
  148. package/dist/cjs/utils/toolkit.js +0 -1378
  149. package/dist/cjs/utils/toolkit.js.map +0 -1
  150. package/dist/cjs/weakref.extensions.d.ts +0 -2
  151. package/dist/cjs/weakref.extensions.js +0 -19
  152. package/dist/cjs/weakref.extensions.js.map +0 -1
  153. package/dist/mjs/array.extensions.d.ts +0 -39
  154. package/dist/mjs/array.extensions.js +0 -474
  155. package/dist/mjs/array.extensions.js.map +0 -1
  156. package/dist/mjs/big.int.extension.d.ts +0 -31
  157. package/dist/mjs/big.int.extension.js +0 -270
  158. package/dist/mjs/big.int.extension.js.map +0 -1
  159. package/dist/mjs/classes/asyncIterable.d.ts +0 -126
  160. package/dist/mjs/classes/asyncIterable.js +0 -204
  161. package/dist/mjs/classes/asyncIterable.js.map +0 -1
  162. package/dist/mjs/classes/deferred.d.ts +0 -146
  163. package/dist/mjs/classes/deferred.js +0 -287
  164. package/dist/mjs/classes/deferred.js.map +0 -1
  165. package/dist/mjs/classes/descriptor.d.ts +0 -334
  166. package/dist/mjs/classes/descriptor.js +0 -533
  167. package/dist/mjs/classes/descriptor.js.map +0 -1
  168. package/dist/mjs/classes/enum.d.ts +0 -50
  169. package/dist/mjs/classes/enum.js +0 -400
  170. package/dist/mjs/classes/enum.js.map +0 -1
  171. package/dist/mjs/classes/index.d.ts +0 -15
  172. package/dist/mjs/classes/index.js +0 -46
  173. package/dist/mjs/classes/index.js.map +0 -1
  174. package/dist/mjs/classes/introspector.d.ts +0 -20
  175. package/dist/mjs/classes/introspector.js +0 -126
  176. package/dist/mjs/classes/introspector.js.map +0 -1
  177. package/dist/mjs/classes/iterable.d.ts +0 -169
  178. package/dist/mjs/classes/iterable.js +0 -263
  179. package/dist/mjs/classes/iterable.js.map +0 -1
  180. package/dist/mjs/classes/param.parser.d.ts +0 -221
  181. package/dist/mjs/classes/param.parser.js +0 -238
  182. package/dist/mjs/classes/param.parser.js.map +0 -1
  183. package/dist/mjs/classes/pluggable.proxy.d.ts +0 -153
  184. package/dist/mjs/classes/pluggable.proxy.js +0 -438
  185. package/dist/mjs/classes/pluggable.proxy.js.map +0 -1
  186. package/dist/mjs/classes/property.d.ts +0 -79
  187. package/dist/mjs/classes/property.js +0 -280
  188. package/dist/mjs/classes/property.js.map +0 -1
  189. package/dist/mjs/classes/refmap.d.ts +0 -238
  190. package/dist/mjs/classes/refmap.js +0 -417
  191. package/dist/mjs/classes/refmap.js.map +0 -1
  192. package/dist/mjs/classes/refset.d.ts +0 -186
  193. package/dist/mjs/classes/refset.js +0 -366
  194. package/dist/mjs/classes/refset.js.map +0 -1
  195. package/dist/mjs/classes/symkeys.d.ts +0 -349
  196. package/dist/mjs/classes/symkeys.js +0 -506
  197. package/dist/mjs/classes/symkeys.js.map +0 -1
  198. package/dist/mjs/classes/type.d.ts +0 -56
  199. package/dist/mjs/classes/type.js +0 -401
  200. package/dist/mjs/classes/type.js.map +0 -1
  201. package/dist/mjs/function.extensions.d.ts +0 -12
  202. package/dist/mjs/function.extensions.js +0 -755
  203. package/dist/mjs/function.extensions.js.map +0 -1
  204. package/dist/mjs/global.this.d.ts +0 -2
  205. package/dist/mjs/global.this.js +0 -264
  206. package/dist/mjs/global.this.js.map +0 -1
  207. package/dist/mjs/index.d.ts +0 -31
  208. package/dist/mjs/index.js +0 -206
  209. package/dist/mjs/index.js.map +0 -1
  210. package/dist/mjs/json.extensions.d.ts +0 -2
  211. package/dist/mjs/json.extensions.js +0 -106
  212. package/dist/mjs/json.extensions.js.map +0 -1
  213. package/dist/mjs/map.extensions.d.ts +0 -3
  214. package/dist/mjs/map.extensions.js +0 -140
  215. package/dist/mjs/map.extensions.js.map +0 -1
  216. package/dist/mjs/math.extension.d.ts +0 -14
  217. package/dist/mjs/math.extension.js +0 -68
  218. package/dist/mjs/math.extension.js.map +0 -1
  219. package/dist/mjs/number.extension.d.ts +0 -44
  220. package/dist/mjs/number.extension.js +0 -275
  221. package/dist/mjs/number.extension.js.map +0 -1
  222. package/dist/mjs/object.extensions.d.ts +0 -33
  223. package/dist/mjs/object.extensions.js +0 -1088
  224. package/dist/mjs/object.extensions.js.map +0 -1
  225. package/dist/mjs/package.json +0 -3
  226. package/dist/mjs/proxy.extensions.d.ts +0 -2
  227. package/dist/mjs/proxy.extensions.js +0 -204
  228. package/dist/mjs/proxy.extensions.js.map +0 -1
  229. package/dist/mjs/reflect.extensions.d.ts +0 -14
  230. package/dist/mjs/reflect.extensions.js +0 -313
  231. package/dist/mjs/reflect.extensions.js.map +0 -1
  232. package/dist/mjs/regular.expression.extensions.d.ts +0 -2
  233. package/dist/mjs/regular.expression.extensions.js +0 -420
  234. package/dist/mjs/regular.expression.extensions.js.map +0 -1
  235. package/dist/mjs/set.extensions.d.ts +0 -40
  236. package/dist/mjs/set.extensions.js +0 -352
  237. package/dist/mjs/set.extensions.js.map +0 -1
  238. package/dist/mjs/string.extensions.d.ts +0 -23
  239. package/dist/mjs/string.extensions.js +0 -701
  240. package/dist/mjs/string.extensions.js.map +0 -1
  241. package/dist/mjs/symbol.extensions.d.ts +0 -11
  242. package/dist/mjs/symbol.extensions.js +0 -732
  243. package/dist/mjs/symbol.extensions.js.map +0 -1
  244. package/dist/mjs/utils/copy.object.d.ts +0 -408
  245. package/dist/mjs/utils/copy.object.js +0 -702
  246. package/dist/mjs/utils/copy.object.js.map +0 -1
  247. package/dist/mjs/utils/descriptor.utils.d.ts +0 -298
  248. package/dist/mjs/utils/descriptor.utils.js +0 -875
  249. package/dist/mjs/utils/descriptor.utils.js.map +0 -1
  250. package/dist/mjs/utils/index.d.ts +0 -75
  251. package/dist/mjs/utils/index.js +0 -45
  252. package/dist/mjs/utils/index.js.map +0 -1
  253. package/dist/mjs/utils/stdout.d.ts +0 -742
  254. package/dist/mjs/utils/stdout.js +0 -1037
  255. package/dist/mjs/utils/stdout.js.map +0 -1
  256. package/dist/mjs/utils/toolkit.d.ts +0 -1898
  257. package/dist/mjs/utils/toolkit.js +0 -1373
  258. package/dist/mjs/utils/toolkit.js.map +0 -1
  259. package/dist/mjs/weakref.extensions.d.ts +0 -2
  260. package/dist/mjs/weakref.extensions.js +0 -16
  261. package/dist/mjs/weakref.extensions.js.map +0 -1
  262. package/jsdoc-config.json +0 -31
  263. package/tsconfig.base.json +0 -28
  264. package/tsconfig.cjs.json +0 -8
  265. package/tsconfig.esm.json +0 -8
  266. package/vitest.config.js +0 -7
@@ -1,1042 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StdoutGlobalPatches = exports.StringConsoleExtension = exports.SC = exports.StringConsole = void 0;
4
- exports.captureStdout = captureStdout;
5
- const extension_1 = require("@nejs/extension");
6
- /**
7
- * Captures the output written to `process.stdout` during the execution of
8
- * a callback function. This function temporarily overrides the standard
9
- * output stream to capture any data written to it, allowing for inspection
10
- * or testing of console output.
11
- *
12
- * @param {Function|*} callback - The function to execute, during which
13
- * `process.stdout` is captured. If not a function, it will be treated
14
- * as the first argument to a console log.
15
- * @param {Array} [args=[]] - Arguments to pass to the callback function.
16
- * @param {Object} [thisArg=console] - The value of `this` provided for
17
- * the call to `callback`.
18
- * @returns {string} The captured output from `process.stdout`.
19
- *
20
- * @example
21
- * const output = captureStdout(() => {
22
- * console.log('Hello, World!')
23
- * })
24
- * console.log(output) // Outputs: 'Hello, World!'
25
- *
26
- * @description
27
- * This function is useful for testing or capturing console output without
28
- * displaying it in the terminal. It works by temporarily replacing
29
- * `process.stdout.write` with a custom function that appends output to a
30
- * string. After the callback is executed, the original `process.stdout.write`
31
- * is restored.
32
- */
33
- function captureStdout(callback, args = [], thisArg = console) {
34
- let captured = '';
35
- const originalWrite = process.stdout.write;
36
- if (typeof callback !== 'function') {
37
- let newArgs = [callback];
38
- if (thisArg) {
39
- newArgs.push(thisArg);
40
- }
41
- newArgs = newArgs.concat(args);
42
- callback = function () {
43
- console.log(...newArgs);
44
- };
45
- thisArg = console;
46
- args = [];
47
- }
48
- process.stdout.write = (chunk, encoding, callback) => {
49
- captured += chunk;
50
- };
51
- try {
52
- callback.apply(thisArg, args);
53
- }
54
- finally {
55
- process.stdout.write = originalWrite;
56
- }
57
- return captured.substring(0, captured.length - 1);
58
- }
59
- /**
60
- * A class that simulates a console for capturing and manipulating console
61
- * output as strings. This class provides methods to log messages, format
62
- * them with colors, and store them in a buffer for later inspection or
63
- * manipulation.
64
- *
65
- * @example
66
- * const stringConsole = new StringConsole()
67
- * stringConsole.log('Hello, World!')
68
- * stringConsole.buffer // ['Hello, World!']
69
- *
70
- * @description
71
- * The StringConsole class is designed to capture console output without
72
- * displaying it in the terminal. It stores the output in a buffer, allowing
73
- * for easy retrieval and manipulation. This is particularly useful for
74
- * testing or when console output needs to be processed programmatically.
75
- */
76
- class StringConsole {
77
- /**
78
- * @type {Array}
79
- * @description
80
- * The buffer array is used to store captured console output. It is
81
- * initialized as an empty array and can be populated with strings
82
- * representing console messages. This buffer serves as a temporary
83
- * storage for output that can be manipulated or inspected later.
84
- *
85
- * @example
86
- * const console = new StringConsole()
87
- * console.buffer.push('Hello, World!')
88
- * console.buffer // ['Hello, World!']
89
- */
90
- buffer = [];
91
- /**
92
- * The last index of the buffer when capture began. This number should be
93
- * set to `NaN` when not in use.
94
- *
95
- * @type {number|NaN}
96
- */
97
- capturedAt = NaN;
98
- /**
99
- * If this is `true`, all "logged" output will be captured in an ever
100
- * growing buffer.
101
- *
102
- * @type {boolean}
103
- * @see {@link StringConsole.buffer}
104
- */
105
- captureOutput = true;
106
- /**
107
- * @typedef {
108
- * Int8Array|Int16Array|Int32Array|Float32Array|Float64Array
109
- * } TypedArray
110
- */
111
- /**
112
- * @typedef {(
113
- * chunk: string|Buffer|TypedArray|DataView,
114
- * encoding: string|null,
115
- * callback: ()=>{}
116
- * )=>boolean} StringConsoleRecorder
117
- * @property {boolean} [Symbol.for('StringConsole.recorder')]
118
- */
119
- /**
120
- * The recorder function is what is subsituted for the `process.stdout.write`
121
- * function whenever we need to temporarily capture the output of data bound
122
- * for the bidirectional read-write stream, `stdout`.
123
- *
124
- * @type {StringConsoleRecorder}
125
- * @param {string|Buffer|TypedArray|DataView|any} chunk Optional data to
126
- * write. For streams not operating in object mode, chunk must be a
127
- * {@link String}, {@link Buffer}, {@link Int8Array}, {@link Int16Array},
128
- * {@link Int32Array}, {@link Float32Array}, {@link Float64Array} or
129
- * {@link DataView}. For object mode streams, chunk may be any JavaScript
130
- * value other than `null`.
131
- * @param {string|null} encoding the encoding, if chunk is a string.
132
- * Default: `'utf8'`
133
- * @param {Function} callback callback for when this chunk of data is
134
- * flushed.
135
- *
136
- * @returns {boolean} false if the stream wishes for the calling code to
137
- * wait for the 'drain' event to be emitted before continuing to write
138
- * additional data; otherwise true.
139
- */
140
- recorder = Object.defineProperty(function recorder(chunk, encoding, callback) { this.buffer.push(chunk); }, Symbol.for(`StringConsole.recorder`), { value: true, configurable: true });
141
- /**
142
- * Initializes a new instance of the StringConsole class.
143
- *
144
- * @param {string|string[]} [initialContents] - The initial contents to
145
- * populate the buffer. If an array is provided, it will be used directly
146
- * as the buffer. If a single string is provided, it will be converted
147
- * to a string and added to the buffer.
148
- *
149
- * @example
150
- * const console1 = new StringConsole('Hello')
151
- * console1.buffer // ['Hello']
152
- *
153
- * const console2 = new StringConsole(['Hello', 'World'])
154
- * console2.buffer // ['Hello', 'World']
155
- */
156
- constructor(captureOutput = true, initialContents = undefined) {
157
- this.recorder = this.recorder.bind(this);
158
- if (Array.isArray(initialContents))
159
- this.buffer = initialContents;
160
- else if (initialContents)
161
- this.buffer.push(String(initialContents));
162
- }
163
- /**
164
- * Clears the buffer by removing all elements.
165
- *
166
- * This method utilizes the `splice` function to remove all elements
167
- * from the buffer array, effectively resetting it to an empty state.
168
- * This is useful when you want to discard all previously captured
169
- * console output and start fresh.
170
- *
171
- * @returns {StringConsole} `this` to allow for calling `clear()`
172
- * before immediately invoking a console method.
173
- *
174
- * @example
175
- * const console = new StringConsole(['Hello', 'World'])
176
- * console.clear()
177
- * console.buffer // []
178
- */
179
- clear() {
180
- this.buffer.splice(0, this.buffer.length);
181
- return this;
182
- }
183
- /**
184
- * Checks if the console output is currently being captured.
185
- *
186
- * This method determines if the `process.stdout.write` function has been
187
- * overridden to capture console output by checking for the presence of
188
- * a specific symbol.
189
- *
190
- * @returns {boolean} True if capturing is active, false otherwise.
191
- *
192
- * @example
193
- * const stringConsole = new StringConsole()
194
- * stringConsole.startCapture()
195
- * console.log(stringConsole.isCapturing()) // Stores 'true' in the buffer
196
- */
197
- isCapturing() {
198
- return Reflect.has(process.stdout.write, Symbol.for('StringConsole.recorder'));
199
- }
200
- /**
201
- * Starts capturing console output.
202
- *
203
- * This method overrides the `process.stdout.write` function with a custom
204
- * recorder function to capture all console output.
205
- *
206
- * @returns {number} the last index of the buffer in its current state or
207
- * 0 if it is empty
208
- *
209
- * @example
210
- * const stringConsole = new StringConsole()
211
- * stringConsole.startCapture()
212
- * console.log('This will be stored in stringConsole.buffer')
213
- */
214
- startCapture() {
215
- if (this.captureOutput === false)
216
- this.buffer = [];
217
- process.stdout.write = this.recorder;
218
- process.stderr.write = this.recorder;
219
- this.capturedAt = this.buffer.length ? this.buffer.length : 0;
220
- return this.capturedAt;
221
- }
222
- /**
223
- * An object containing two properties covering the captured content
224
- * while `process.stdout.write` was swapped. It should contain the
225
- * range of line indicies as well as the content as an array of strings
226
- *
227
- * @typedef {object} StringConsoleCapturedOutput
228
- * @property {number[]} range an array of two numbers, a starting index
229
- * and an ending index. This value will be [NaN,NaN] if this instance
230
- * has indicated that storing captured output is disabled.
231
- * @property {string[]} lines an array of strings of captured output
232
- * that occurred in between calls to {@link ~startCapture} and then
233
- * ending call to {@link ~stopCapture}
234
- */
235
- /**
236
- * Stops capturing console output.
237
- *
238
- * This method restores the original `process.stdout.write` function,
239
- * ceasing the capture of console output.
240
- *
241
- * @returns {StringConsoleCapturedOutput} the range of indices capturing
242
- * the lines of the buffer that have been added since capturing was
243
- * started.
244
- *
245
- * @example
246
- * const stringConsole = new StringConsole()
247
- * stringConsole.startCapture()
248
- * console.log('This will be stored in stringConsole.buffer')
249
- * stringConsole.stopCapture()
250
- * console.log('This will not be captured')
251
- */
252
- stopCapture() {
253
- const range = [this.capturedAt || 0, this.buffer.length - 1];
254
- const lines = this.buffer.slice(range[0], range[1] + 1);
255
- if (this.captureOutput === false)
256
- this.buffer = [];
257
- process.stdout.write = StringConsole[Symbol.for('process.stdout.write')];
258
- process.stderr.write = StringConsole[Symbol.for('process.stderr.write')];
259
- this.capturedAt = NaN;
260
- return { range, lines };
261
- }
262
- /**
263
- * Joins the StringConsole output as a single string. By default, each entry
264
- * captured so far is joined on a new line. Pass a different joiner such as
265
- * an empty string or a whitespace character, as examples, to change the
266
- * output string.
267
- *
268
- * @param {string} joinOn the string to join the output buffer on, defaults
269
- * to a new line character
270
- * @returns a single string of contatenated entries so far to this buffer.
271
- */
272
- toString(joinOn = '') {
273
- return this.buffer.join(joinOn);
274
- }
275
- /**
276
- * Captures formatted debug messages as though they'd been printed. The
277
- * resulting output that would have been printed is stored in the buffer
278
- * as well as being returned.
279
- *
280
- * This method formats the provided arguments with color coding specific
281
- * to the 'debug' level as though `console.debug` were used. The output
282
- * is captured and stored in the buffer for later inspection, but not
283
- * actually printed to the standard output.
284
- *
285
- * @param {any[]} args - The arguments to be log captured. These can be
286
- * of any type and will be formatted with color coding without being logged.
287
- *
288
- * @returns {string} The captured console output as a string.
289
- *
290
- * @example
291
- * const stringConsole = new StringConsole()
292
- * stringConsole.debug('[debug]', 'message')
293
- * stringConsole.buffer // Contains the captured messages so far as an array
294
- */
295
- debug(...args) {
296
- args = this.constructor.colorArgs('debug', args);
297
- this.startCapture();
298
- console.debug(...args);
299
- return this.stopCapture().lines.join('\n');
300
- }
301
- /**
302
- * Captures formatted error messages as though they'd been printed. The
303
- * resulting output that would have been printed is stored in the buffer
304
- * as well as being returned.
305
- *
306
- * This method formats the provided arguments with color coding specific
307
- * to the 'error' level as though `console.error` were used. The output
308
- * is captured and stored in the buffer for later inspection, but not
309
- * actually printed to the standard output.
310
- *
311
- * @param {any[]} args - The arguments to be log captured. These can be
312
- * of any type and will be formatted with color coding without being logged.
313
- *
314
- * @returns {string} The captured console output as a string.
315
- *
316
- * @example
317
- * const stringConsole = new StringConsole()
318
- * stringConsole.error('[error]', 'message')
319
- * stringConsole.buffer // Contains the captured messages so far as an array
320
- */
321
- error(...args) {
322
- args = this.constructor.colorArgs('error', args);
323
- this.startCapture();
324
- console.error(...args);
325
- return this.stopCapture().lines.join('\n');
326
- }
327
- /**
328
- * Groups console output under a specified group name and captures the
329
- * output. No content will actually be logged to the console, just
330
- * the output that normally would be is formatted in a string and returned
331
- * instead.
332
- *
333
- * This method allows you to format multiple messages under a single
334
- * group name. It captures the output of each invocation and stores it in
335
- * a buffer. The captured output is returned as a single string.
336
- *
337
- * @param {string} groupName - The name of the group under which the
338
- * messages will be logged.
339
- * @param {...Array} invocations - An array of invocations where each
340
- * invocation is an array. The first element is the log level (e.g.,
341
- * 'log', 'info'), and the remaining elements are the arguments to be
342
- * logged.
343
- *
344
- * @returns {string} The captured console output as a string.
345
- *
346
- * @example
347
- * const console = new StringConsole()
348
- * const output = console.group('MyGroup',
349
- * ['log', 'Hello'],
350
- * ['warn', 'Warning!']
351
- * )
352
- *
353
- * console.buffer // Contains the captured group output
354
- */
355
- group(groupName, ...invocations) {
356
- const commands = ['log', 'info', 'warn', 'error', 'debug', 'trace'];
357
- const buffer = [];
358
- invocations = invocations.filter(i => commands.includes(i?.[0]));
359
- if (groupName)
360
- groupName = this.constructor.style(groupName, ['underline', 'bold']);
361
- else
362
- groupName = this.constructor.style('grouped', ['underline', 'bold']);
363
- this.startCapture();
364
- console.group(groupName);
365
- for (const invocation of invocations) {
366
- if (!Array.isArray(invocation) || invocation.length < 2)
367
- continue;
368
- const [level, ...args] = invocation;
369
- console[level](...this.constructor.colorArgs(level, args));
370
- }
371
- console.groupEnd(groupName);
372
- return this.stopCapture().lines.join('');
373
- }
374
- /**
375
- * Captures formatted info messages as though they'd been printed. The
376
- * resulting output that would have been printed is stored in the buffer
377
- * as well as being returned.
378
- *
379
- * This method formats the provided arguments with color coding specific
380
- * to the 'info' level as though `console.info` were used. The output
381
- * is captured and stored in the buffer for later inspection, but not
382
- * actually printed to the standard output.
383
- *
384
- * @param {any[]} args - The arguments to be log captured. These can be
385
- * of any type and will be formatted with color coding without being logged.
386
- *
387
- * @returns {string} The captured console output as a string.
388
- *
389
- * @example
390
- * const stringConsole = new StringConsole()
391
- * stringConsole.info('[info]', 'message')
392
- * stringConsole.buffer // Contains the captured messages so far as an array
393
- */
394
- info(...args) {
395
- args = this.constructor.colorArgs('info', args);
396
- this.startCapture();
397
- console.info(...args);
398
- return this.stopCapture().lines.join('\n');
399
- }
400
- /**
401
- * Captures formatted log messages as though they'd been printed. The
402
- * resulting output that would have been printed is stored in the buffer
403
- * as well as being returned.
404
- *
405
- * This method formats the provided arguments with color coding specific
406
- * to the 'log' level as though `console.log` were used. The output
407
- * is captured and stored in the buffer for later inspection, but not
408
- * actually printed to the standard output.
409
- *
410
- * @param {any[]} args - The arguments to be log captured. These can be
411
- * of any type and will be formatted with color coding without being logged.
412
- *
413
- * @returns {string} The captured console output as a string.
414
- *
415
- * @example
416
- * const stringConsole = new StringConsole()
417
- * stringConsole.log('[log]', 'message')
418
- * stringConsole.buffer // Contains the captured messages so far as an array
419
- */
420
- log(...args) {
421
- args = this.constructor.colorArgs('log', args);
422
- this.startCapture();
423
- console.log(...args);
424
- return this.stopCapture().lines.join('\n');
425
- }
426
- /**
427
- * Captures formatted trace messages as though they'd been printed. The
428
- * resulting output that would have been printed is stored in the buffer
429
- * as well as being returned.
430
- *
431
- * This method formats the provided arguments with color coding specific
432
- * to the 'trace' level as though `console.trace` were used. The output
433
- * is captured and stored in the buffer for later inspection, but not
434
- * actually printed to the standard output.
435
- *
436
- * @param {any[]} args - The arguments to be log captured. These can be
437
- * of any type and will be formatted with color coding without being logged.
438
- *
439
- * @returns {string} The captured console output as a string.
440
- *
441
- * @example
442
- * const stringConsole = new StringConsole()
443
- * stringConsole.trace('[trace]', 'message')
444
- * stringConsole.buffer // Contains the captured messages so far as an array
445
- */
446
- trace(...args) {
447
- args = this.constructor.colorArgs('trace', args);
448
- this.startCapture();
449
- console.trace(...args);
450
- return this.stopCapture().lines.join('\n');
451
- }
452
- /**
453
- * Captures formatted warn messages as though they'd been printed. The
454
- * resulting output that would have been printed is stored in the buffer
455
- * as well as being returned.
456
- *
457
- * This method formats the provided arguments with color coding specific
458
- * to the 'warn' level as though `console.warn` were used. The output
459
- * is captured and stored in the buffer for later inspection, but not
460
- * actually printed to the standard output.
461
- *
462
- * @param {any[]} args - The arguments to be log captured. These can be
463
- * of any type and will be formatted with color coding without being logged.
464
- *
465
- * @returns {string} The captured console output as a string.
466
- *
467
- * @example
468
- * const stringConsole = new StringConsole()
469
- * stringConsole.warn('[warn]', 'message')
470
- * stringConsole.buffer // Contains the captured messages so far as an array
471
- */
472
- warn(...args) {
473
- args = this.constructor.colorArgs('warn', args);
474
- this.startCapture();
475
- console.warn(...args);
476
- return this.stopCapture().lines.join('\n');
477
- }
478
- /**
479
- * Captures a single line of text that would be logged to the console if
480
- * the console function of the same name were to be invoked. The string
481
- * is formatted according to the log colors, or any pre-existing colors as
482
- * those are untouched. After formatting, the string is returned.
483
- *
484
- * @param {...*} args the arguments to be logged. These can be of any
485
- * type and will be passed to the underlying console's method of the same
486
- * name.
487
- *
488
- * @returns {string}
489
- *
490
- * @example
491
- * const string = StringConsole.debug('[debug]: %o', someVariable)
492
- */
493
- static debug(...args) {
494
- return this.#console.clear().debug(...args);
495
- }
496
- /**
497
- * Captures a single line of text that would be logged to the console if
498
- * the console function of the same name were to be invoked. The string
499
- * is formatted according to the log colors, or any pre-existing colors as
500
- * those are untouched. After formatting, the string is returned.
501
- *
502
- * @param {...*} args the arguments to be logged. These can be of any
503
- * type and will be passed to the underlying console's method of the same
504
- * name.
505
- *
506
- * @returns {string}
507
- *
508
- * @example
509
- * const string = StringConsole.error('[error]: %o', someVariable)
510
- */
511
- static error(...args) {
512
- return this.#console.clear().error(...args);
513
- }
514
- /**
515
- * Groups console output under a specified group name and captures the
516
- * output. No content will actually be logged to the console, just
517
- * the output that normally would be is formatted in a string and returned
518
- * instead.
519
- *
520
- * This method allows you to format multiple messages under a single
521
- * group name. It captures the output of each invocation and stores it in
522
- * a buffer. The captured output is returned as a single string.
523
- *
524
- * @param {string} groupName - The name of the group under which the
525
- * messages will be logged.
526
- * @param {...Array} invocations - An array of invocations where each
527
- * invocation is an array. The first element is the log level (e.g.,
528
- * 'log', 'info'), and the remaining elements are the arguments to be
529
- * logged.
530
- *
531
- * @returns {string} The captured console output as a string.
532
- *
533
- * @example
534
- * const console = new StringConsole()
535
- * const output = console.group('MyGroup',
536
- * ['log', 'Hello'],
537
- * ['warn', 'Warning!']
538
- * )
539
- *
540
- * console.buffer // Contains the captured group output
541
- */
542
- static group(groupName, ...invocations) {
543
- return this.#console.clear().group(groupName, ...invocations);
544
- }
545
- /**
546
- * Captures a single line of text that would be logged to the console if
547
- * the console function of the same name were to be invoked. The string
548
- * is formatted according to the log colors, or any pre-existing colors as
549
- * those are untouched. After formatting, the string is returned.
550
- *
551
- * @param {...*} args the arguments to be logged. These can be of any
552
- * type and will be passed to the underlying console's method of the same
553
- * name.
554
- *
555
- * @returns {string}
556
- *
557
- * @example
558
- * const string = StringConsole.info('[info]: %o', someVariable)
559
- */
560
- static info(...args) {
561
- return this.#console.clear().info(...args);
562
- }
563
- /**
564
- * Captures a single line of text that would be logged to the console if
565
- * the console function of the same name were to be invoked. The string
566
- * is formatted according to the log colors, or any pre-existing colors as
567
- * those are untouched. After formatting, the string is returned.
568
- *
569
- * @param {...*} args the arguments to be logged. These can be of any
570
- * type and will be passed to the underlying console's method of the same
571
- * name.
572
- *
573
- * @returns {string}
574
- *
575
- * @example
576
- * const string = StringConsole.log('[log]: %o', someVariable)
577
- */
578
- static log(...args) {
579
- return this.#console.clear().log(...args);
580
- }
581
- /**
582
- * Captures a single line of text that would be logged to the console if
583
- * the console function of the same name were to be invoked. The string
584
- * is formatted according to the log colors, or any pre-existing colors as
585
- * those are untouched. After formatting, the string is returned.
586
- *
587
- * @param {...*} args the arguments to be logged. These can be of any
588
- * type and will be passed to the underlying console's method of the same
589
- * name.
590
- *
591
- * @returns {string}
592
- *
593
- * @example
594
- * const string = StringConsole.trace('[trace]: %o', someVariable)
595
- */
596
- static trace(...args) {
597
- return this.#console.clear().trace(...args);
598
- }
599
- /**
600
- * Captures a single line of text that would be logged to the console if
601
- * the console function of the same name were to be invoked. The string
602
- * is formatted according to the log colors, or any pre-existing colors as
603
- * those are untouched. After formatting, the string is returned.
604
- *
605
- * @param {...*} args the arguments to be logged. These can be of any
606
- * type and will be passed to the underlying console's method of the same
607
- * name.
608
- *
609
- * @returns {string}
610
- *
611
- * @example
612
- * const string = StringConsole.warn('[warn]: %o', someVariable)
613
- */
614
- static warn(...args) {
615
- return this.#console.clear().warn(...args);
616
- }
617
- /**
618
- * Internal instance of {@link StringConsole} used for static logging
619
- * methods.
620
- *
621
- * @type {StringConsole}
622
- */
623
- static #console = new StringConsole(false);
624
- /**
625
- * A static map defining color codes for console output. Each color is
626
- * associated with an array containing two numbers, which represent
627
- * the ANSI escape codes for styling text in the terminal.
628
- *
629
- * The first number in the array is the suffix code for the standard
630
- * color, while the second number suffix code to undo the color. These
631
- * codes are useless without the pen prefix code.
632
- *
633
- * @type {Map<string, number[]>}
634
- * @see {@link StringConsole.pens}
635
- *
636
- * @example
637
- * // Accessing the color codes for 'red'
638
- * const redCodes = StringConsole.colors.get('red')
639
- * const fgCodes = StringConsole.pens.get('foreground')
640
- * const prefix = `\x1b[${fgCodes[0]}${redCodes[0]}m`
641
- * const suffix = `\x1b[${fgCodes[1]}${redCodes[1]}m`
642
- * // Outputs: "Text" in red but "!!" in the default color
643
- * console.log(`${prefix}Text!!${suffix}`)
644
- *
645
- * @description
646
- * This map is used to apply color coding to console messages, enhancing
647
- * readability and providing visual cues for different log levels.
648
- */
649
- static colors = new Map([
650
- ['black', [0, 9]],
651
- ['red', [1, 9]],
652
- ['green', [2, 9]],
653
- ['yellow', [3, 9]],
654
- ['blue', [4, 9]],
655
- ['magenta', [5, 9]],
656
- ['cyan', [6, 9]],
657
- ['white', [7, 9]]
658
- ]);
659
- /**
660
- * A static map defining the color schemes for different logging levels.
661
- * Each log level is associated with an array of color styles that are
662
- * applied to the console output for that level.
663
- *
664
- * The available log levels and their corresponding color styles are:
665
- * - 'log': White
666
- * - 'info': Cyan
667
- * - 'warn': Yellow
668
- * - 'error': Red
669
- * - 'trace': Magenta
670
- * - 'debug': Bold Yellow
671
- *
672
- * @type {Map<string, string[]>}
673
- *
674
- * @example
675
- * const logColor = StringConsole.levels.get('log') // ['white']
676
- * const errorColor = StringConsole.levels.get('error') // ['red']
677
- */
678
- static levels = Object.defineProperties(new Map([
679
- ['log', ['white']],
680
- ['info', ['cyan']],
681
- ['warn', ['yellow']],
682
- ['error', ['red']],
683
- ['trace', ['magenta']],
684
- ['debug', ['bold', 'yellow']]
685
- ]), {
686
- color: {
687
- value: function color(key) {
688
- for (const value of this.get(key)) {
689
- if (StringConsole.colors.has(value)) {
690
- return StringConsole.colors.get(value);
691
- }
692
- }
693
- return StringConsole.colors.get('white');
694
- },
695
- configurable: true,
696
- },
697
- styles: {
698
- value: function styles(key) {
699
- const styles = [];
700
- for (const value of this.get(key)) {
701
- if (StringConsole.styles.has(value)) {
702
- styles.push(StringConsole.styles.get(value));
703
- }
704
- }
705
- return styles;
706
- },
707
- configurable: true,
708
- },
709
- });
710
- /**
711
- * A static map defining the ANSI escape codes for different pen styles
712
- * used in console output. Each pen style is associated with an array
713
- * containing two numbers: the first for setting the style and the second
714
- * for resetting it.
715
- *
716
- * The available pen styles and their corresponding ANSI codes are:
717
- * - 'foreground': [3, 3] - Standard foreground color
718
- * - 'background': [4, 4] - Standard background color
719
- * - 'bright.foreground': [9, 3] - Bright foreground color
720
- * - 'bright.background': [10, 4] - Bright background color
721
- *
722
- * These are prefixes for both enabling and disabling. Normally a red color
723
- * is represented using SGR (Select Graphic Rendition) codes like \x1b[31m
724
- * for the foreground and \x1b[39m to return to normal color. So the 3
725
- * determines a foreground prefix for starting and stopping (the 3's in 31
726
- * and 39). Background prefixes are usually 4. These change for bright
727
- * colors which use 9 and 3, and 10 and 4, respectively.
728
- *
729
- * @type {Map<string, number[]>}
730
- *
731
- * @example
732
- * // [3, 3]
733
- * const foregroundPen = StringConsole.pens.get('foreground')
734
- *
735
- * // [10, 4]
736
- * const brightBackgroundPen = StringConsole.pens.get('bright.background')
737
- */
738
- static pens = new Map([
739
- ['foreground', [3, 3]],
740
- ['background', [4, 4]],
741
- ['bright.foreground', [9, 3]],
742
- ['bright.background', [10, 4]]
743
- ]);
744
- /**
745
- * A static map defining ANSI escape codes for various text styles used
746
- * in console output. Each style is associated with an array containing
747
- * two escape codes: one for enabling the style and one for disabling it.
748
- *
749
- * The available styles and their corresponding ANSI codes are:
750
- * - 'reset': Resets all styles to default.
751
- * - 'blink': Enables blinking text.
752
- * - 'bold': Makes text bold.
753
- * - 'conceal': Conceals text.
754
- * - 'dim': Dims the text.
755
- * - 'italics': Italicizes the text.
756
- * - 'negative': Inverts the foreground and background colors.
757
- * - 'strike': Strikes through the text.
758
- * - 'underline': Underlines the text.
759
- *
760
- * @type {Map<string, string[]>}
761
- *
762
- * @example
763
- * const boldStyle = StringConsole.styles.get('bold')
764
- * // ['\x1b[1m', '\x1b[22m']
765
- */
766
- static styles = new Map([
767
- ['reset', ['\x1b[0m']],
768
- ['blink', ['\x1b[5m', '\x1b[25m']],
769
- ['bold', ['\x1b[1m', '\x1b[22m']],
770
- ['conceal', ['\x1b[8m', '\x1b[28m']],
771
- ['dim', ['\x1b[2m', '\x1b[22m']],
772
- ['italics', ['\x1b[3m', '\x1b[23m']],
773
- ['negative', ['\x1b[7m', '\x1b[27m']],
774
- ['strike', ['\x1b[9m', '\x1b[29m']],
775
- ['underline', ['\x1b[4m', '\x1b[24m']]
776
- ]);
777
- /**
778
- * Applies ANSI color codes to a given string based on specified options.
779
- * This method checks if the string already contains color codes or if
780
- * the input is not a string, in which case it returns the original input.
781
- * Otherwise, it formats the string with the specified color and pen
782
- * options.
783
- *
784
- * @param {string} string - The string to be colorized.
785
- * @param {Object} [options] - Configuration options for colorization.
786
- * @param {string} [options.level] - The log level determining
787
- * which colors to apply.
788
- * @param {number[]} [options.rgb8] a single color code where 0 - 7, for
789
- * the 'standard' colors specified by the SGR sequences 30 to 37; 8-15 are
790
- * high intensity or bright colors,
791
- * @param {number[]} [options.rgb24] An array of three values, ordered, red,
792
- * green and then blue. The values should range from 0 to 255.
793
- * @param {string|string[]} [options.styles] defaulting to an empty array, if
794
- * supplied with a single known style {@link ~styles}, or an array of them.
795
- * @param {string} [options.pen='foreground'] - The pen type for color
796
- * application, either 'foreground' or 'background'.
797
- * @param {Array} [options.buffer=[]] - An array to prepend to the
798
- * formatted string.
799
- * @param {Array} [options.before=[]] - An array of strings to prepend
800
- * before the main string.
801
- * @param {Array} [options.after=[]] - An array of strings to append
802
- * after the main string. 16 - 231, for the colors in the 6 × 6 × 6 cube
803
- * defined by 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5); 232-255:
804
- * grayscale from dark to light in 24 steps.
805
- *
806
- * @returns {string} The colorized string with ANSI codes applied.
807
- *
808
- * @example
809
- * const coloredString = StringConsole.color('Hello', {
810
- * level: 'info',
811
- * pen: 'bright.foreground'
812
- * })
813
- * console.log(coloredString)
814
- */
815
- static color(string, options = {
816
- level: undefined,
817
- color: undefined,
818
- pen: 'foreground',
819
- rgb8: undefined,
820
- rgb24: [186, 186, 186],
821
- styles: [],
822
- buffer: [],
823
- before: [],
824
- after: [],
825
- }) {
826
- const { colors: Colors, styles: Styles, pens: Pens, levels: Levels } = this;
827
- let useColors = undefined;
828
- let useRGB = false;
829
- let styles = [];
830
- const pens = this.pens.get(options?.pen ?? 'foreground');
831
- const [p0, p1] = pens;
832
- if (options?.styles) {
833
- if (Array.isArray(options.styles))
834
- styles = options.styles
835
- .filter(s => Styles.has(s))
836
- .map(s => Styles.get(s));
837
- else if (typeof options.styles === 'string' && Styles.has(options.styles))
838
- styles = Styles.get(options.styles);
839
- }
840
- if (options?.level && Levels.has(options.level)) {
841
- useColors = Levels.color(options.level);
842
- const addlStyles = Levels.styles(options.level);
843
- if (addlStyles.length)
844
- styles = styles.concat(addlStyles);
845
- }
846
- else if (options?.color && Colors.has(options.color))
847
- useColors = Colors.get(options.color);
848
- else if (options?.rgb24 && Array.isArray(options.rgb24)) {
849
- useColors = [`\x1b[${p0}8;2;${options.rgb24.join(';')};m`, `\x1b[${p1}9m`];
850
- useRGB = true;
851
- }
852
- else if (options?.rgb8 && typeof options.rgb8 === 'number') {
853
- useColors = [`\x1b[${p0}8;5;${options.rgb8}m`, `\x1b[${p1}9m`];
854
- useRGB = true;
855
- }
856
- else
857
- useColors = [9, 9];
858
- const [c0, c1] = (useRGB
859
- ? useColors
860
- : useColors?.map((c, i) => `\x1b[${pens[i]}${c}m`) ?? [`\x1b[39;49m`]);
861
- if (this.hasColor(string))
862
- return string;
863
- if (typeof string !== 'string')
864
- return string;
865
- if (string instanceof String)
866
- (string = String(string));
867
- if (!useColors)
868
- return string;
869
- if (options?.buffer && !Array.isArray(options.buffer))
870
- options.buffer = [String(options.buffer)];
871
- if (options?.before && !Array.isArray(options.before))
872
- options.before = [String(options.before)];
873
- if (options?.after && !Array.isArray(options.after))
874
- options.after = [String(options.after)];
875
- const buffer = [].concat(options?.buffer ?? []);
876
- const before = [].concat(options?.before ?? []);
877
- const after = [].concat(options?.after ?? []);
878
- if (c0)
879
- before.push(c0);
880
- if (c1)
881
- after.push(c1);
882
- for (const style of styles) {
883
- if (style?.[0])
884
- before.push(style[0]);
885
- if (style?.[1])
886
- after.push(style[1]);
887
- }
888
- return [...buffer, before.join(''), string, after.join('')].join('');
889
- }
890
- /**
891
- * Applies color formatting to each argument based on the specified log level.
892
- *
893
- * This method processes an array of arguments, applying color formatting
894
- * to each one according to the provided log level. The color formatting
895
- * is determined by the `color` method, which uses the log level to
896
- * select the appropriate color scheme.
897
- *
898
- * @param {string} level - The log level that determines the color scheme
899
- * to be applied. Common levels include 'log', 'info', 'warn', 'error',
900
- * etc.
901
- * @param {Array} args - An array of arguments to be formatted. Each
902
- * argument will be processed individually to apply the color formatting.
903
- *
904
- * @returns {Array} A new array containing the formatted arguments with
905
- * color applied.
906
- *
907
- * @example
908
- * const formattedArgs = StringConsole.colorArgs(
909
- * 'info',
910
- * ['Message 1', 'Message 2']
911
- * )
912
- * // formattedArgs will contain the messages with 'info' level
913
- * // color formatting
914
- */
915
- static colorArgs(level, args) {
916
- const newArgs = [];
917
- if (args === null || args === undefined || !Array.isArray(args))
918
- return args;
919
- for (const arg of args) {
920
- newArgs.push(this.color(arg, { level }));
921
- }
922
- return newArgs;
923
- }
924
- /**
925
- * Determines if a given string contains ANSI color codes.
926
- *
927
- * This method checks for the presence of ANSI escape codes in the
928
- * provided string, which are used for color formatting in terminal
929
- * outputs. The presence of these codes indicates that the string
930
- * has color formatting applied.
931
- *
932
- * @param {string} string - The string to be checked for ANSI color codes.
933
- *
934
- * @returns {boolean} Returns true if the string contains ANSI color codes,
935
- * otherwise false.
936
- *
937
- * @example
938
- * const hasColor = StringConsole.hasColor('\x1b[31mRed Text\x1b[0m')
939
- * // hasColor will be true
940
- *
941
- * const noColor = StringConsole.hasColor('Plain Text')
942
- * // noColor will be false
943
- */
944
- static hasColor(string) {
945
- return string.includes('\x1b[');
946
- }
947
- /**
948
- * Applies a series of styles to a given string using ANSI escape codes.
949
- *
950
- * This method takes a string and an array of style names or style arrays,
951
- * and applies the corresponding ANSI escape codes to the string. The
952
- * styles are defined in the `styles` map, which associates style names
953
- * with their respective ANSI codes.
954
- *
955
- * @param {string} string - The string to which styles will be applied.
956
- * @param {string|string[]} styles - A style name or an array of style
957
- * names/arrays to be applied. Each style can be a string that matches
958
- * a key in the `styles` map or an array containing ANSI codes.
959
- *
960
- * @returns {string} The styled string with ANSI escape codes applied.
961
- *
962
- * @example
963
- * const styledText = StringConsole.style('Hello', ['bold', 'underline'])
964
- * // styledText will have 'Hello' with bold and underline styles
965
- */
966
- static style(string, styles) {
967
- const before = [];
968
- const after = [];
969
- const buffer = [];
970
- if (typeof styles === 'string' && this.styles.has(styles)) {
971
- styles = [styles];
972
- }
973
- for (const style of styles) {
974
- let group = [];
975
- if (this.styles.has(style))
976
- group = this.styles.get(style);
977
- else if (Array.isArray(style) && style.length >= 1)
978
- group = style;
979
- if (group?.[0])
980
- before.push(group?.[0]);
981
- if (group?.[1])
982
- after.push(group?.[1]);
983
- }
984
- return [before.join(''), string, after.join('')].join('');
985
- }
986
- /* Since this class captures the swaps the process.stdout.write function,
987
- * in to and out of place repeatedly, we want to avoid any possible issues
988
- * where this conflict could be problematic. To this end, we capture the
989
- * global process.stdout.write function as a copy when this class is defined
990
- * but before it is used.
991
- *
992
- * If no other code modifies the `writer` property, this is created as a
993
- * non-enumerable alias to the [Symbol.for('process.stdout.write')] symbol
994
- * the actual function is stored in.
995
- */
996
- static {
997
- Object.defineProperties(StringConsole, {
998
- [Symbol.for('process.stdout.write')]: {
999
- value: Object.defineProperties(process.stdout.write, {
1000
- [Symbol.for('original')]: { value: true, configurable: true },
1001
- isOriginal: { get() { return true; }, configurable: true },
1002
- }),
1003
- configurable: true,
1004
- },
1005
- [Symbol.for('process.stderr.write')]: {
1006
- value: Object.defineProperties(process.stderr.write, {
1007
- [Symbol.for('original')]: { value: true, configurable: true },
1008
- isOriginal: { get() { return true; }, configurable: true },
1009
- }),
1010
- configurable: true,
1011
- },
1012
- });
1013
- if (!Reflect.has(StringConsole, 'writer')) {
1014
- Object.defineProperties(StringConsole, {
1015
- writer: {
1016
- value: StringConsole[Symbol.for('process.stdout.write')],
1017
- configurable: true,
1018
- },
1019
- errorWriter: {
1020
- value: StringConsole[Symbol.for('process.stderr.write')],
1021
- configurable: true,
1022
- },
1023
- });
1024
- }
1025
- }
1026
- }
1027
- exports.StringConsole = StringConsole;
1028
- exports.SC = StringConsole;
1029
- exports.StringConsoleExtension = new extension_1.Extension(StringConsole);
1030
- exports.StdoutGlobalPatches = new extension_1.Patch(globalThis, {
1031
- [extension_1.Patch.kMutablyHidden]: {
1032
- captureStdout,
1033
- }
1034
- });
1035
- exports.default = {
1036
- SC: StringConsole,
1037
- StringConsole,
1038
- StringConsoleExtension: exports.StringConsoleExtension,
1039
- StdoutGlobalPatches: exports.StdoutGlobalPatches,
1040
- captureStdout,
1041
- };
1042
- //# sourceMappingURL=stdout.js.map