@celljs/core 3.9.0 → 4.1.0

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 (219) hide show
  1. package/README.md +0 -6
  2. package/cell.remote.yml +8 -0
  3. package/cell.yml +0 -3
  4. package/esm/common/application/application-entry.js +21 -3
  5. package/esm/common/application/application-entry.js.map +1 -1
  6. package/esm/common/application/application-host.d.ts +38 -0
  7. package/esm/common/application/application-host.js +17 -0
  8. package/esm/common/application/application-host.js.map +1 -0
  9. package/esm/common/application/application-protocol.js +1 -1
  10. package/esm/common/application/application-protocol.js.map +1 -1
  11. package/esm/common/application/index.d.ts +1 -0
  12. package/esm/common/application/index.js +1 -0
  13. package/esm/common/application/index.js.map +1 -1
  14. package/esm/common/config/config-provider.js +2 -1
  15. package/esm/common/config/config-provider.js.map +1 -1
  16. package/esm/common/config/env-config-util.d.ts +48 -0
  17. package/esm/common/config/env-config-util.js +185 -0
  18. package/esm/common/config/env-config-util.js.map +1 -0
  19. package/esm/common/config/index.d.ts +1 -0
  20. package/esm/common/config/index.js +1 -0
  21. package/esm/common/config/index.js.map +1 -1
  22. package/esm/common/container/auto-bind.js +26 -12
  23. package/esm/common/container/auto-bind.js.map +1 -1
  24. package/esm/common/el/expression-compiler.d.ts +4 -15
  25. package/esm/common/el/expression-compiler.js +6 -163
  26. package/esm/common/el/expression-compiler.js.map +1 -1
  27. package/esm/common/el/expression-handler.d.ts +7 -2
  28. package/esm/common/el/expression-handler.js +14 -53
  29. package/esm/common/el/expression-handler.js.map +1 -1
  30. package/esm/common/el/expression-util.d.ts +68 -0
  31. package/esm/common/el/expression-util.js +347 -0
  32. package/esm/common/el/expression-util.js.map +1 -0
  33. package/esm/common/el/index.d.ts +1 -0
  34. package/esm/common/el/index.js +1 -0
  35. package/esm/common/el/index.js.map +1 -1
  36. package/esm/common/logger/abstract-logger.d.ts +4 -2
  37. package/esm/common/logger/abstract-logger.js +11 -6
  38. package/esm/common/logger/abstract-logger.js.map +1 -1
  39. package/esm/common/logger/logger-protocol.d.ts +4 -0
  40. package/esm/common/logger/logger-protocol.js +2 -0
  41. package/esm/common/logger/logger-protocol.js.map +1 -1
  42. package/esm/common/logger/logger.js +7 -7
  43. package/esm/common/logger/logger.js.map +1 -1
  44. package/esm/common/test/mock-logger.d.ts +1 -0
  45. package/esm/common/test/mock-logger.js +3 -0
  46. package/esm/common/test/mock-logger.js.map +1 -1
  47. package/esm/common/utils/emitter.d.ts +1 -10
  48. package/esm/common/utils/emitter.js +0 -56
  49. package/esm/common/utils/emitter.js.map +1 -1
  50. package/esm/common/utils/mime-type-util.js +1 -1
  51. package/esm/common/utils/mime-type-util.js.map +1 -1
  52. package/esm/common/utils/mime-type.js +1 -1
  53. package/esm/common/utils/mime-type.js.map +1 -1
  54. package/esm/node/context/context.d.ts +11 -2
  55. package/esm/node/context/context.js +36 -12
  56. package/esm/node/context/context.js.map +1 -1
  57. package/esm/node/index.d.ts +0 -1
  58. package/esm/node/index.js +0 -1
  59. package/esm/node/index.js.map +1 -1
  60. package/lib/common/aop/aop.spec.d.ts +2 -0
  61. package/lib/common/aop/aop.spec.d.ts.map +1 -0
  62. package/lib/common/aop/aop.spec.js +170 -0
  63. package/lib/common/aop/aop.spec.js.map +1 -0
  64. package/lib/common/application/application-entry.d.ts.map +1 -1
  65. package/lib/common/application/application-entry.js +21 -3
  66. package/lib/common/application/application-entry.js.map +1 -1
  67. package/lib/common/application/application-host.d.ts +39 -0
  68. package/lib/common/application/application-host.d.ts.map +1 -0
  69. package/lib/common/application/application-host.js +20 -0
  70. package/lib/common/application/application-host.js.map +1 -0
  71. package/lib/common/application/application-protocol.js +1 -1
  72. package/lib/common/application/application-protocol.js.map +1 -1
  73. package/lib/common/application/index.d.ts +1 -0
  74. package/lib/common/application/index.d.ts.map +1 -1
  75. package/lib/common/application/index.js +1 -0
  76. package/lib/common/application/index.js.map +1 -1
  77. package/lib/common/application/lifecycle.spec.d.ts +2 -0
  78. package/lib/common/application/lifecycle.spec.d.ts.map +1 -0
  79. package/lib/common/application/lifecycle.spec.js +155 -0
  80. package/lib/common/application/lifecycle.spec.js.map +1 -0
  81. package/lib/common/config/config-provider.js +2 -1
  82. package/lib/common/config/config-provider.js.map +1 -1
  83. package/lib/common/config/env-config-util.d.ts +49 -0
  84. package/lib/common/config/env-config-util.d.ts.map +1 -0
  85. package/lib/common/config/env-config-util.js +188 -0
  86. package/lib/common/config/env-config-util.js.map +1 -0
  87. package/lib/common/config/env-config-util.spec.d.ts +2 -0
  88. package/lib/common/config/env-config-util.spec.d.ts.map +1 -0
  89. package/lib/common/config/env-config-util.spec.js +314 -0
  90. package/lib/common/config/env-config-util.spec.js.map +1 -0
  91. package/lib/common/config/index.d.ts +1 -0
  92. package/lib/common/config/index.d.ts.map +1 -1
  93. package/lib/common/config/index.js +1 -0
  94. package/lib/common/config/index.js.map +1 -1
  95. package/lib/common/container/assembly.spec.d.ts +2 -0
  96. package/lib/common/container/assembly.spec.d.ts.map +1 -0
  97. package/lib/common/container/assembly.spec.js +464 -0
  98. package/lib/common/container/assembly.spec.js.map +1 -0
  99. package/lib/common/container/auto-bind.js +26 -12
  100. package/lib/common/container/auto-bind.js.map +1 -1
  101. package/lib/common/el/expression-compiler.d.ts +4 -15
  102. package/lib/common/el/expression-compiler.d.ts.map +1 -1
  103. package/lib/common/el/expression-compiler.js +6 -163
  104. package/lib/common/el/expression-compiler.js.map +1 -1
  105. package/lib/common/el/expression-handler.d.ts +7 -2
  106. package/lib/common/el/expression-handler.d.ts.map +1 -1
  107. package/lib/common/el/expression-handler.js +14 -56
  108. package/lib/common/el/expression-handler.js.map +1 -1
  109. package/lib/common/el/expression-handler.spec.d.ts +2 -0
  110. package/lib/common/el/expression-handler.spec.d.ts.map +1 -0
  111. package/lib/common/el/expression-handler.spec.js +99 -0
  112. package/lib/common/el/expression-handler.spec.js.map +1 -0
  113. package/lib/common/el/expression-util.d.ts +69 -0
  114. package/lib/common/el/expression-util.d.ts.map +1 -0
  115. package/lib/common/el/expression-util.js +352 -0
  116. package/lib/common/el/expression-util.js.map +1 -0
  117. package/lib/common/el/expression-util.spec.d.ts +2 -0
  118. package/lib/common/el/expression-util.spec.d.ts.map +1 -0
  119. package/lib/common/el/expression-util.spec.js +45 -0
  120. package/lib/common/el/expression-util.spec.js.map +1 -0
  121. package/lib/common/el/index.d.ts +1 -0
  122. package/lib/common/el/index.d.ts.map +1 -1
  123. package/lib/common/el/index.js +1 -0
  124. package/lib/common/el/index.js.map +1 -1
  125. package/lib/common/el/value-and-el.spec.d.ts +2 -0
  126. package/lib/common/el/value-and-el.spec.d.ts.map +1 -0
  127. package/lib/common/el/value-and-el.spec.js +216 -0
  128. package/lib/common/el/value-and-el.spec.js.map +1 -0
  129. package/lib/common/logger/abstract-logger.d.ts +4 -2
  130. package/lib/common/logger/abstract-logger.d.ts.map +1 -1
  131. package/lib/common/logger/abstract-logger.js +10 -5
  132. package/lib/common/logger/abstract-logger.js.map +1 -1
  133. package/lib/common/logger/logger-protocol.d.ts +4 -0
  134. package/lib/common/logger/logger-protocol.d.ts.map +1 -1
  135. package/lib/common/logger/logger-protocol.js +3 -1
  136. package/lib/common/logger/logger-protocol.js.map +1 -1
  137. package/lib/common/logger/logger.js +7 -7
  138. package/lib/common/logger/logger.js.map +1 -1
  139. package/lib/common/logger/logger.spec.d.ts +2 -0
  140. package/lib/common/logger/logger.spec.d.ts.map +1 -0
  141. package/lib/common/logger/logger.spec.js +57 -0
  142. package/lib/common/logger/logger.spec.js.map +1 -0
  143. package/lib/common/test/mock-logger.d.ts +1 -0
  144. package/lib/common/test/mock-logger.d.ts.map +1 -1
  145. package/lib/common/test/mock-logger.js +3 -0
  146. package/lib/common/test/mock-logger.js.map +1 -1
  147. package/lib/common/utils/emitter.d.ts +1 -10
  148. package/lib/common/utils/emitter.d.ts.map +1 -1
  149. package/lib/common/utils/emitter.js +1 -58
  150. package/lib/common/utils/emitter.js.map +1 -1
  151. package/lib/common/utils/mime-type-util.js +1 -1
  152. package/lib/common/utils/mime-type-util.js.map +1 -1
  153. package/lib/common/utils/mime-type.js +1 -1
  154. package/lib/common/utils/mime-type.js.map +1 -1
  155. package/lib/common/utils/utils-behavior.spec.d.ts +2 -0
  156. package/lib/common/utils/utils-behavior.spec.d.ts.map +1 -0
  157. package/lib/common/utils/utils-behavior.spec.js +232 -0
  158. package/lib/common/utils/utils-behavior.spec.js.map +1 -0
  159. package/lib/node/context/context.d.ts +11 -2
  160. package/lib/node/context/context.d.ts.map +1 -1
  161. package/lib/node/context/context.js +36 -10
  162. package/lib/node/context/context.js.map +1 -1
  163. package/lib/node/context/context.spec.d.ts +2 -0
  164. package/lib/node/context/context.spec.d.ts.map +1 -0
  165. package/lib/node/context/context.spec.js +202 -0
  166. package/lib/node/context/context.spec.js.map +1 -0
  167. package/lib/node/index.d.ts +0 -1
  168. package/lib/node/index.d.ts.map +1 -1
  169. package/lib/node/index.js +0 -1
  170. package/lib/node/index.js.map +1 -1
  171. package/package.json +20 -41
  172. package/src/common/aop/aop.spec.ts +145 -0
  173. package/src/common/application/application-entry.ts +20 -4
  174. package/src/common/application/application-host.ts +46 -0
  175. package/src/common/application/application-protocol.ts +1 -1
  176. package/src/common/application/index.ts +1 -0
  177. package/src/common/application/lifecycle.spec.ts +148 -0
  178. package/src/common/config/config-provider.ts +1 -1
  179. package/src/common/config/env-config-util.spec.ts +341 -0
  180. package/src/common/config/env-config-util.ts +225 -0
  181. package/src/common/config/index.ts +1 -0
  182. package/src/common/container/assembly.spec.ts +293 -0
  183. package/src/common/container/auto-bind.ts +23 -10
  184. package/src/common/el/expression-compiler.ts +6 -166
  185. package/src/common/el/expression-handler.spec.ts +110 -0
  186. package/src/common/el/expression-handler.ts +14 -51
  187. package/src/common/el/expression-util.spec.ts +45 -0
  188. package/src/common/el/expression-util.ts +363 -0
  189. package/src/common/el/index.ts +2 -1
  190. package/src/common/el/value-and-el.spec.ts +186 -0
  191. package/src/common/logger/abstract-logger.ts +12 -6
  192. package/src/common/logger/logger-protocol.ts +5 -0
  193. package/src/common/logger/logger.spec.ts +61 -0
  194. package/src/common/logger/logger.ts +7 -7
  195. package/src/common/test/mock-logger.ts +3 -0
  196. package/src/common/utils/emitter.ts +1 -63
  197. package/src/common/utils/mime-type-util.ts +1 -1
  198. package/src/common/utils/mime-type.ts +1 -1
  199. package/src/common/utils/utils-behavior.spec.ts +259 -0
  200. package/src/node/context/context.spec.ts +219 -0
  201. package/src/node/context/context.ts +35 -10
  202. package/src/node/index.ts +0 -1
  203. package/cell-remote.yml +0 -3
  204. package/esm/node/utils/crc.d.ts +0 -1
  205. package/esm/node/utils/crc.js +0 -7
  206. package/esm/node/utils/crc.js.map +0 -1
  207. package/esm/node/utils/index.d.ts +0 -1
  208. package/esm/node/utils/index.js +0 -2
  209. package/esm/node/utils/index.js.map +0 -1
  210. package/lib/node/utils/crc.d.ts +0 -2
  211. package/lib/node/utils/crc.d.ts.map +0 -1
  212. package/lib/node/utils/crc.js +0 -10
  213. package/lib/node/utils/crc.js.map +0 -1
  214. package/lib/node/utils/index.d.ts +0 -2
  215. package/lib/node/utils/index.d.ts.map +0 -1
  216. package/lib/node/utils/index.js +0 -18
  217. package/lib/node/utils/index.js.map +0 -1
  218. package/src/node/utils/crc.ts +0 -7
  219. package/src/node/utils/index.ts +0 -1
@@ -0,0 +1,363 @@
1
+ import { Jexl } from 'jexl';
2
+ import { ExpressionCompiler, ExpressionCompilerOptions, ExpressionContext } from './expression-protocol';
3
+
4
+ interface MiddleExpression {
5
+ expression: any;
6
+ nextText?: string;
7
+ }
8
+
9
+ /**
10
+ * Splits a text into literal sections and compiled `${...}` expressions (jexl). It has no dependency
11
+ * injection, so the build (@celljs/vite) and the runtime share it through `@celljs/core/el`.
12
+ */
13
+ export class ExpressionSectionCompiler implements ExpressionCompiler {
14
+
15
+ protected static jexlEngine?: any;
16
+
17
+ /** @param jexl the engine; the runtime passes the one of its JexlEngineProvider, which has the transforms */
18
+ constructor(protected readonly jexl: () => any = () => (ExpressionSectionCompiler.jexlEngine ??= new Jexl())) { }
19
+
20
+ private ESCAPE_CHAR = '\\';
21
+ private SPECIAL_CHAR = '$';
22
+ private BRACKET_BEGIN = '{';
23
+ private BRACKET_END = '}';
24
+
25
+ protected getSpecialChar(opitons: Required<ExpressionCompilerOptions>): string {
26
+ if (opitons.ignoreSpecialChar) {
27
+ return '';
28
+ }
29
+ return opitons.specialChar;
30
+ }
31
+
32
+ protected equalsSpecialChar(opitons: Required<ExpressionCompilerOptions>, char: string): boolean {
33
+ if (opitons.ignoreSpecialChar) {
34
+ return false;
35
+ }
36
+ return char === opitons.specialChar;
37
+ }
38
+
39
+ compileSections(text: string, options: ExpressionCompilerOptions): any[] {
40
+ const merged = {
41
+ ...{ escapeChar: this.ESCAPE_CHAR, specialChar: this.SPECIAL_CHAR, bracketBegin: this.BRACKET_BEGIN, bracketEnd: this.BRACKET_END, ...options }
42
+ } as Required<ExpressionCompilerOptions>;
43
+ if (!text || text.indexOf(`${this.getSpecialChar(merged)}${merged.bracketBegin}`) < 0) {
44
+ return [];
45
+ }
46
+
47
+ const sections: any[] = [];
48
+ let middleText: string | undefined = text;
49
+ while (middleText) {
50
+ const me: MiddleExpression | undefined = this.middleCompile(middleText, merged);
51
+ if (!me) {
52
+ sections.push(middleText);
53
+ middleText = undefined;
54
+ } else {
55
+ sections.push(me.expression);
56
+ middleText = me.nextText;
57
+ }
58
+ }
59
+
60
+ return sections;
61
+ }
62
+
63
+ protected middleCompile(text: string, options: Required<ExpressionCompilerOptions>): MiddleExpression | undefined {
64
+ let me: MiddleExpression | undefined;
65
+ const prefix = `${this.getSpecialChar(options)}${options.bracketBegin}`;
66
+ const prefix2 = `${prefix}${options.bracketBegin}`;
67
+ if (text.startsWith(prefix2)) {
68
+ me = this.nextMiddleExpression(text.substring(prefix2.length), 2, options);
69
+ } else if (text.startsWith(prefix)) {
70
+ me = this.nextMiddleExpression(text.substring(prefix.length), undefined, options);
71
+ } else {
72
+ me = this.nextString(text, options);
73
+ }
74
+ return me;
75
+ }
76
+
77
+ protected nextMiddleExpression(text: string, bracketBeginCharNum = 1, options: Required<ExpressionCompilerOptions>): MiddleExpression | undefined {
78
+ let stringed = false;
79
+ let escaped = false;
80
+ let bracketBeginCharFound = 0;
81
+
82
+ const section: string[] = [];
83
+ for (let i = 0; i < text.length; i++) {
84
+ const c = text[i];
85
+ if (!escaped) {
86
+ if ('\'' === c || '"' === c) {
87
+ stringed = !stringed;
88
+ section.push(c);
89
+ continue;
90
+ } else
91
+ if (c === options.escapeChar) {
92
+ escaped = true;
93
+ continue;
94
+ }
95
+ }
96
+
97
+ if (stringed) {
98
+ section.push(c);
99
+ escaped = false;
100
+ } else if (escaped) {
101
+ if (this.equalsSpecialChar(options, c) || options.bracketBegin === c || options.bracketEnd === c) {
102
+ section.push(c);
103
+ } else {
104
+ section.push(options.escapeChar);
105
+ section.push(c);
106
+ }
107
+ escaped = false;
108
+ } else if (options.bracketBegin === c) {
109
+ bracketBeginCharFound++;
110
+ section.push(c);
111
+ } else if (options.bracketEnd === c) {
112
+ if (bracketBeginCharFound === 0 && bracketBeginCharNum === 1) {
113
+ const jexlEngine = this.jexl();
114
+ const expression = jexlEngine.createExpression(section.join(''));
115
+ let nextText;
116
+ if (i !== text.length - 1) {
117
+ nextText = text.substring(i + 1);
118
+ }
119
+ return { expression, nextText };
120
+ } else if (bracketBeginCharFound > 0) {
121
+ bracketBeginCharFound--;
122
+ section.push(c);
123
+ } else {
124
+ bracketBeginCharNum--;
125
+ }
126
+ } else {
127
+ section.push(c);
128
+ }
129
+ }
130
+ }
131
+
132
+ protected nextString(text: string, options: Required<ExpressionCompilerOptions>): MiddleExpression {
133
+ let escaped = false;
134
+ let specialCharFound = false;
135
+
136
+ const section: string[] = [];
137
+ for (let i = 0; i < text.length; i++) {
138
+ const c = text[i];
139
+ if (!escaped) {
140
+ if ('\'' === c || '"' === c) {
141
+ section.push(c);
142
+ continue;
143
+ } else
144
+ if (c === options.escapeChar) {
145
+ escaped = true;
146
+ continue;
147
+ }
148
+ }
149
+
150
+ if (escaped) {
151
+ if (this.equalsSpecialChar(options, c) || options.bracketBegin === c || options.bracketEnd === c) {
152
+ section.push(c);
153
+ } else {
154
+ section.push(options.escapeChar);
155
+ section.push(c);
156
+ }
157
+ escaped = false;
158
+ } else
159
+ if (specialCharFound || options.ignoreSpecialChar) {
160
+ if (options.bracketBegin === c) {
161
+ const expression = section.join('');
162
+ const nextText = options.ignoreSpecialChar ? text.substring(i) : text.substring(i - 1);
163
+ return { expression, nextText };
164
+ } else {
165
+ if (!options.ignoreSpecialChar) {
166
+ specialCharFound = false;
167
+ section.push(options.specialChar);
168
+ }
169
+ section.push(c);
170
+ }
171
+ } else {
172
+ if (this.equalsSpecialChar(options, c)) {
173
+ specialCharFound = true;
174
+ } else {
175
+ section.push(c);
176
+ }
177
+ }
178
+ }
179
+
180
+ return { expression: section.join('') };
181
+ }
182
+
183
+ }
184
+
185
+ /** An expression of the configuration that cannot be evaluated; `path` is its key, e.g. `cell.db.url`. */
186
+ export class ExpressionError extends Error {
187
+
188
+ override readonly name = 'ExpressionError';
189
+
190
+ constructor(readonly path: string, readonly template: string, message: string, override readonly cause?: unknown) {
191
+ super(message);
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Evaluation of `${...}` expressions, shared by the runtime (ExpressionHandler) and the build
197
+ * (@celljs/vite) through `@celljs/core/el`. The result of an expression is never evaluated again: a value
198
+ * that comes from the environment (`${env.X}`), from a template variable or from another expression is
199
+ * text, whatever it contains. References between configuration keys still resolve: a key that refers to
200
+ * another one evaluates that key's own template (see {@link ExpressionUtil.evaluateConfiguration}).
201
+ */
202
+ export namespace ExpressionUtil {
203
+
204
+ export interface Options {
205
+ /** Defaults to an {@link ExpressionSectionCompiler} on a plain jexl engine (no transforms). */
206
+ compiler?: ExpressionCompiler;
207
+ compilerOptions?: ExpressionCompilerOptions;
208
+ }
209
+
210
+ let defaultCompiler: ExpressionCompiler | undefined;
211
+
212
+ function compilerOf(options: Options): ExpressionCompiler {
213
+ return options.compiler ?? (defaultCompiler ??= new ExpressionSectionCompiler());
214
+ }
215
+
216
+ /**
217
+ * Evaluates the expressions of `text`: a text with a single expression keeps the type of its value,
218
+ * mixed text is joined into a string. `context` may be a function, then it is only called when the text
219
+ * has an expression.
220
+ */
221
+ export function evaluateText(text: string, context: ExpressionContext | (() => ExpressionContext), options: Options = {}): any {
222
+ const sections = compilerOf(options).compileSections(text, options.compilerOptions);
223
+ if (!sections.some(section => typeof section !== 'string')) {
224
+ return text;
225
+ }
226
+ const c = typeof context === 'function' ? context() : context;
227
+ if (sections.length === 1) {
228
+ return sections[0].evalSync(c);
229
+ }
230
+ return sections.map(section => (typeof section === 'string' ? section : section.evalSync(c))).join('');
231
+ }
232
+
233
+ /**
234
+ * Replaces the templates (strings) of `node` by `evaluate`'s values, in place, depth first. Objects
235
+ * marked `_ignoreEl` are left alone, circular references are not followed, and values are not walked
236
+ * into: what an expression returns is not a template.
237
+ */
238
+ export function walk(node: any, evaluate: (text: string, owner: any, key: string) => any,
239
+ enter?: (child: object, owner: object, key: string) => void): void {
240
+ doWalk(node, [], evaluate, enter);
241
+ }
242
+
243
+ function doWalk(node: any, ancestors: object[], evaluate: (text: string, owner: any, key: string) => any,
244
+ enter?: (child: object, owner: object, key: string) => void): void {
245
+ if (typeof node !== 'object' || node === null || node._ignoreEl === true || ancestors.includes(node)) {
246
+ return;
247
+ }
248
+ ancestors.push(node);
249
+ for (const key of Object.keys(node)) {
250
+ const child = node[key];
251
+ if (typeof child === 'string') {
252
+ const value = evaluate(child, node, key);
253
+ if (value !== child) {
254
+ node[key] = value;
255
+ }
256
+ } else {
257
+ if (enter && typeof child === 'object' && child !== null) {
258
+ enter(child, node, key);
259
+ }
260
+ doWalk(child, ancestors, evaluate, enter);
261
+ }
262
+ }
263
+ ancestors.pop();
264
+ }
265
+
266
+ /**
267
+ * Evaluates the configuration `root` in place. An expression sees the configuration through a view in
268
+ * which every template that it reaches is evaluated first (once, cached), so keys refer to each other in
269
+ * any order; a value an expression returns is never evaluated again. Objects marked `_ignoreEl` (such
270
+ * as `env`) are read as they are. Failures, including a circular reference, are {@link ExpressionError}s
271
+ * naming the key.
272
+ */
273
+ export function evaluateConfiguration(root: ExpressionContext, options: Options = {}): void {
274
+ const values = new Map<object, Map<string, unknown>>();
275
+ const resolving: string[] = [];
276
+ const paths = new WeakMap<object, string>([[root, '']]);
277
+ const views = new WeakMap<object, object>();
278
+ const targets = new WeakMap<object, object>();
279
+
280
+ const pathOf = (owner: object, key: string) => {
281
+ const base = paths.get(owner);
282
+ return base ? `${base}.${key}` : key;
283
+ };
284
+ const unwrap = (value: any): any => {
285
+ if (typeof value !== 'object' || value === null) {
286
+ return value;
287
+ }
288
+ const target = targets.get(value);
289
+ if (target) {
290
+ return target;
291
+ }
292
+ // Arrays and objects an expression builds may hold views of the configuration.
293
+ if (Array.isArray(value)) {
294
+ return value.map(unwrap);
295
+ }
296
+ if (Object.getPrototypeOf(value) === Object.prototype) {
297
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, unwrap(v)]));
298
+ }
299
+ return value;
300
+ };
301
+ const valueOf = (owner: any, key: string): unknown => {
302
+ const cached = values.get(owner);
303
+ if (cached?.has(key)) {
304
+ return cached.get(key);
305
+ }
306
+ const template = owner[key];
307
+ const path = pathOf(owner, key);
308
+ if (resolving.includes(path)) {
309
+ throw new ExpressionError(path, template, `Circular reference in the configuration: ${[...resolving, path].join(' -> ')}`);
310
+ }
311
+ resolving.push(path);
312
+ let value: unknown;
313
+ try {
314
+ value = unwrap(evaluateText(template, () => view(root), options));
315
+ } catch (error) {
316
+ if (error instanceof ExpressionError) {
317
+ throw error;
318
+ }
319
+ throw new ExpressionError(path, template, `Cannot evaluate ${path}: ${template} (${(error as Error)?.message ?? error})`, error);
320
+ } finally {
321
+ resolving.pop();
322
+ }
323
+ if (!values.has(owner)) {
324
+ values.set(owner, new Map());
325
+ }
326
+ values.get(owner)!.set(key, value);
327
+ return value;
328
+ };
329
+ const view = (target: any): any => {
330
+ if (typeof target !== 'object' || target === null || target._ignoreEl === true) {
331
+ return target;
332
+ }
333
+ let proxy = views.get(target);
334
+ if (!proxy) {
335
+ const created: object = new Proxy(target, {
336
+ get: (t, key, receiver) => {
337
+ const value = Reflect.get(t, key, receiver);
338
+ if (typeof key !== 'string' || !Object.prototype.hasOwnProperty.call(t, key)) {
339
+ return value;
340
+ }
341
+ if (typeof value === 'string') {
342
+ return valueOf(t, key);
343
+ }
344
+ if (typeof value === 'object' && value !== null && !paths.has(value)) {
345
+ paths.set(value, pathOf(t, key));
346
+ }
347
+ return view(value);
348
+ }
349
+ });
350
+ views.set(target, created);
351
+ targets.set(created, target);
352
+ proxy = created;
353
+ }
354
+ return proxy;
355
+ };
356
+
357
+ walk(root, (text, owner, key) => valueOf(owner, key), (child, owner, key) => {
358
+ if (!paths.has(child)) {
359
+ paths.set(child, pathOf(owner, key));
360
+ }
361
+ });
362
+ }
363
+ }
@@ -2,5 +2,6 @@ export * from './expression-protocol';
2
2
  export * from './expression-compiler';
3
3
  export * from './expression-context-provider';
4
4
  export * from './expression-handler';
5
+ export * from './expression-util';
5
6
  export * from './jexl-engine-provider';
6
- export * from './core-context-initializer';
7
+ export * from './core-context-initializer';
@@ -0,0 +1,186 @@
1
+ import { describe, it, afterAll } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { ApplicationFactory } from '../application/application-factory';
4
+ import { Component, Value } from '../annotation';
5
+ import { ContainerUtil } from '../container/container-util';
6
+ import { ConfigUtil } from '../config/config-util';
7
+ import { ExpressionHandler } from './expression-protocol';
8
+
9
+ /**
10
+ * @Value、ConfigUtil 与 EL(${...},jexl)的约定(阶段 1.E 行为测试)。
11
+ * 配置就是 ApplicationFactory.create() 的第一个参数(CLI 生成的入口会把合并后的 cell.yml 传进来)。
12
+ */
13
+ const boot = (props: Record<string, any>) => ApplicationFactory.create(props);
14
+ const el = () => ContainerUtil.get<ExpressionHandler>(ExpressionHandler);
15
+
16
+ describe('core @Value 与配置', () => {
17
+
18
+ it('@Value(key) 读配置;@Value() 不带参数时以属性名为 key', async () => {
19
+ @Component()
20
+ class Settings {
21
+ @Value('cell.name')
22
+ readonly name: string;
23
+ @Value()
24
+ readonly port: number;
25
+ }
26
+ await boot({ cell: { name: 'demo' }, port: 8080 });
27
+ const s = ContainerUtil.get(Settings);
28
+ expect(s.name).to.equal('demo');
29
+ expect(s.port).to.equal(8080);
30
+ });
31
+
32
+ it('值里的 ${...} 会求值,可以引用其他配置,多层引用也会继续求值', async () => {
33
+ @Component()
34
+ class Urls {
35
+ @Value('cell.url')
36
+ readonly url: string;
37
+ @Value('cell.chain')
38
+ readonly chain: string;
39
+ }
40
+ await boot({ cell: { host: 'example.com', url: 'https://${cell.host}:443/api', chain: '${cell.url}', } });
41
+ const u = ContainerUtil.get(Urls);
42
+ expect(u.url).to.equal('https://example.com:443/api');
43
+ expect(u.chain).to.equal('https://example.com:443/api');
44
+ });
45
+
46
+ it('取对象时,对象里的字符串也会求值;取不到的 key 为 undefined', async () => {
47
+ @Component()
48
+ class Db {
49
+ @Value('cell.db')
50
+ readonly db: { host: string, port: number, hosts: string[] };
51
+ @Value('cell.missing.deep')
52
+ readonly missing?: unknown;
53
+ }
54
+ await boot({ cell: { region: 'eu', db: { host: 'db.${cell.region}.local', port: 5432, hosts: ['a.${cell.region}', 'b'] } } });
55
+ const d = ContainerUtil.get(Db);
56
+ expect(d.db).to.deep.equal({ host: 'db.eu.local', port: 5432, hosts: ['a.eu', 'b'] });
57
+ expect(d.missing).to.equal(undefined);
58
+ });
59
+
60
+ it('构造器参数也能用 @Value', async () => {
61
+ @Component()
62
+ class WithCtor {
63
+ constructor(@Value('cell.size') readonly size: number) { }
64
+ }
65
+ await boot({ cell: { size: 3 } });
66
+ expect(ContainerUtil.get(WithCtor).size).to.equal(3);
67
+ });
68
+
69
+ it('detached 的 @Value:不在容器里的对象每次读取都取当前容器的配置', async () => {
70
+ class Plain {
71
+ @Value({ el: 'cell.mode', detached: true })
72
+ readonly mode: string;
73
+ }
74
+ const p = new Plain();
75
+ await boot({ cell: { mode: 'a' } });
76
+ expect(p.mode).to.equal('a');
77
+ await boot({ cell: { mode: 'b' } });
78
+ expect(p.mode).to.equal('b');
79
+ });
80
+
81
+ it('ConfigUtil.get:取值、默认值', async () => {
82
+ await boot({ cell: { a: 1, ref: '${cell.a}' } });
83
+ expect(ConfigUtil.get('cell.a')).to.equal(1);
84
+ expect(ConfigUtil.get('cell.ref')).to.equal(1);
85
+ expect(ConfigUtil.get('cell.none', 'dflt')).to.equal('dflt');
86
+ });
87
+
88
+ it('现状:create() 过程中第一次求值就会就地改写传入的配置对象,getRaw() 拿到的也是求值后的结果', async () => {
89
+ // expression-handler.ts getContext():第一次拿到上下文时 this.handle(c, c),把整份配置原地求值;
90
+ // 创建 Application 时注入的组件(如 Logger)读配置,这一步在 create() 返回前就发生了
91
+ const props = { cell: { a: 1, ref: '${cell.a}' as unknown, nested: ['${cell.a}'] as unknown[] } };
92
+ await boot(props);
93
+ expect(ConfigUtil.getRaw()).to.equal(props);
94
+ expect(props.cell.ref).to.equal(1);
95
+ expect(props.cell.nested[0]).to.equal(1);
96
+ });
97
+
98
+ it('false、0、空串都是有效的值:@Value 拿得到,ConfigUtil.get 只在值为 undefined 时用默认值(F3)', async () => {
99
+ @Component()
100
+ class Flags {
101
+ @Value('cell.enabled')
102
+ readonly enabled: boolean;
103
+ @Value('cell.retries')
104
+ readonly retries: number;
105
+ @Value('cell.prefix')
106
+ readonly prefix: string;
107
+ }
108
+ await boot({ cell: { enabled: false, retries: 0, prefix: '' } });
109
+ const f = ContainerUtil.get(Flags);
110
+ expect(f.enabled).to.equal(false);
111
+ expect(f.retries).to.equal(0);
112
+ expect(f.prefix).to.equal('');
113
+ expect(ConfigUtil.get('cell.retries', 3)).to.equal(0);
114
+ expect(ConfigUtil.get('cell.enabled', true)).to.equal(false);
115
+ expect(ConfigUtil.get('cell.missing', 3)).to.equal(3);
116
+ });
117
+ });
118
+
119
+ describe('core EL(ExpressionHandler)', () => {
120
+ const ENV_KEY = 'CELL_T13_EL_PROBE';
121
+ afterAll(() => {
122
+ delete process.env[ENV_KEY];
123
+ });
124
+
125
+ it('没有 ${ 的文本原样返回;只有一个表达式时保留类型,混排时拼成字符串', async () => {
126
+ await boot({ cell: { n: 2 } });
127
+ expect(el().handle('plain text')).to.equal('plain text');
128
+ expect(el().handle('${cell.n + 1}')).to.equal(3);
129
+ expect(el().handle('${cell.n > 1}')).to.equal(true);
130
+ expect(el().handle('n=${cell.n}, n2=${cell.n * cell.n}')).to.equal('n=2, n2=4');
131
+ });
132
+
133
+ it('jexl 的运算、三元、字符串里的 } 都能正确切分', async () => {
134
+ await boot({ cell: { port: 3000, name: 'x' } });
135
+ expect(el().handle('${cell.port > 1000 ? "high" : "low"}')).to.equal('high');
136
+ expect(el().handle('${"a}b" + cell.name}')).to.equal('a}bx');
137
+ expect(el().handle('[${cell.name}]')).to.equal('[x]');
138
+ });
139
+
140
+ it('现状:反斜杠转义只阻止求值,反斜杠本身留在结果里', async () => {
141
+ await boot({ cell: { name: 'x' } });
142
+ expect(el().handle('cost \\${cell.name}')).to.equal('cost \\${cell.name}');
143
+ });
144
+
145
+ it.todo('期望:\\${...} 得到字面量 ${...}(去掉转义符),否则配置里无法写出 ${', () => { });
146
+
147
+ it('内置 transform:replace、regexp、eval', async () => {
148
+ await boot({ cell: { name: 'svc', tpl: '${cell.name}-v1' } });
149
+ expect(el().handle('${"a-b-c"|replace("-", "_")}')).to.equal('a_b_c');
150
+ const re = el().handle('${"^ab+$"|regexp("i")}');
151
+ expect(re).to.be.instanceOf(RegExp);
152
+ expect(re.test('ABBB')).to.equal(true);
153
+ expect(el().handle('${"${cell.name}"|eval}')).to.equal('svc');
154
+ });
155
+
156
+ it('可以传入自己的上下文;未定义的变量为 undefined', async () => {
157
+ await boot({});
158
+ expect(el().handle('${a.b * 2}', { a: { b: 21 } })).to.equal(42);
159
+ expect(el().handle('${nothing.here}', {})).to.equal(undefined);
160
+ });
161
+
162
+ it('处理对象时就地求值;带 _ignoreEl 的子对象不求值', async () => {
163
+ await boot({ cell: { v: 'ok' } });
164
+ const obj = { a: '${cell.v}', nested: { b: ['${cell.v}!'] }, raw: { _ignoreEl: true, c: '${cell.v}' } };
165
+ const out = el().handle(obj);
166
+ expect(out).to.equal(obj);
167
+ expect(obj.a).to.equal('ok');
168
+ expect(obj.nested.b[0]).to.equal('ok!');
169
+ expect(obj.raw.c).to.equal('${cell.v}');
170
+ });
171
+
172
+ it('env 是进程环境变量(遍历整份配置时 env 子树带 _ignoreEl,不会被就地求值)', async () => {
173
+ process.env[ENV_KEY] = 'plain-value';
174
+ await boot({ cell: {} });
175
+ expect(el().handle(`\${env.${ENV_KEY}}`)).to.equal('plain-value');
176
+ expect(ConfigUtil.getRaw().env?.[ENV_KEY]).to.equal('plain-value');
177
+ });
178
+
179
+ it('来自 env 的字符串不再求值,经配置间接引用时也一样(F6)', async () => {
180
+ process.env[ENV_KEY] = '${cell.other}';
181
+ await boot({ cell: { other: 'from-config', viaEnv: `\${env.${ENV_KEY}}`, viaKey: '${cell.viaEnv}' } });
182
+ expect(el().handle(`\${env.${ENV_KEY}}`)).to.equal('${cell.other}');
183
+ expect(el().handle('${cell.viaEnv}')).to.equal('${cell.other}');
184
+ expect(el().handle('${cell.viaKey}')).to.equal('${cell.other}');
185
+ });
186
+ });
@@ -1,5 +1,5 @@
1
1
  import { Autowired, Optional, Value } from '../annotation';
2
- import { Logger, LOGGER_LEVEL, LogLevel, onLogEmitter, TraceIdProvider } from './logger-protocol';
2
+ import { Logger, LOGGER_LEVEL, LOG_LEVELS, LogLevel, onLogEmitter, TraceIdProvider } from './logger-protocol';
3
3
 
4
4
  export abstract class AbstractLogger implements Logger {
5
5
  protected instance: Logger;
@@ -24,18 +24,24 @@ export abstract class AbstractLogger implements Logger {
24
24
  return context ? `[${context}] ` : '';
25
25
  }
26
26
 
27
- protected resolvePrefix(): string {
27
+ isEnabled(level: LogLevel): boolean {
28
+ const configured = LOG_LEVELS.indexOf(this.level);
29
+ return LOG_LEVELS.indexOf(level) >= (configured < 0 ? LOG_LEVELS.indexOf('info') : configured);
30
+ }
31
+
32
+ /** `level` is the level of the message, not the configured one. */
33
+ protected resolvePrefix(level: LogLevel): string {
28
34
  const time = new Date().toISOString();
29
- return `${time} [${this.level}]`;
35
+ return `${time} [${level}]`;
30
36
  }
31
37
 
32
- protected log(message: any, context?: string, logFn: (...args: any[]) => void = console.info): void {
38
+ protected log(message: any, context?: string, logFn: (...args: any[]) => void = console.info, level: LogLevel = 'info'): void {
33
39
  const traceId = this.traceIdProvider?.provide();
34
40
  const traceStr = traceId ? ` [trace: ${traceId}]` : '';
35
41
  const contextStr = this.resolveContextString(context);
36
- logFn(`${this.resolvePrefix()}${traceStr}${contextStr}${message}`);
42
+ logFn(`${this.resolvePrefix(level)}${traceStr}${contextStr}${message}`);
37
43
  onLogEmitter.fire({
38
- level: this.level,
44
+ level,
39
45
  traceId,
40
46
  rootContext: this.context,
41
47
  context,
@@ -7,6 +7,9 @@ export const TraceIdProvider = Symbol('TraceIdProvider');
7
7
  export const LoggerService = Symbol('LoggerService');
8
8
 
9
9
  export type LogLevel = 'verbose' | 'debug' | 'info' | 'warn' | 'error';
10
+
11
+ /** Levels from the most to the least verbose: a logger at a level writes that level and the ones after it. */
12
+ export const LOG_LEVELS: readonly LogLevel[] = ['verbose', 'debug', 'info', 'warn', 'error'];
10
13
  export interface LogMessage {
11
14
  level: LogLevel;
12
15
  traceId?: string;
@@ -25,6 +28,8 @@ export interface Logger {
25
28
  error(message: any, context?: string): void;
26
29
  warn(message: any, context?: string): void;
27
30
  debug(message: any, context?: string): void;
31
+ /** Whether messages of `level` are written; check it before building an expensive message. */
32
+ isEnabled(level: LogLevel): boolean;
28
33
  time(label: string): void;
29
34
  timeEnd(label: string, context?: string): number | undefined;
30
35
 
@@ -0,0 +1,61 @@
1
+ import { afterEach, describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { LoggerImpl } from './logger';
4
+ import { LogLevel, LogMessage, onLogEmitter } from './logger-protocol';
5
+
6
+ const consoleFns = ['info', 'warn', 'error', 'debug'] as const;
7
+ const originals = Object.fromEntries(consoleFns.map(name => [name, console[name]]));
8
+
9
+ function capture(level: LogLevel) {
10
+ const lines: { fn: string; text: string }[] = [];
11
+ for (const name of consoleFns) {
12
+ console[name] = (text: string) => lines.push({ fn: name, text });
13
+ }
14
+ const logger = new LoggerImpl();
15
+ Object.assign(logger, { level });
16
+ return { logger, lines };
17
+ }
18
+
19
+ afterEach(() => Object.assign(console, originals));
20
+
21
+ describe('LoggerImpl', () => {
22
+ it('labels each line with the level of the message, not the configured one', () => {
23
+ const { logger, lines } = capture('debug');
24
+ logger.debug('d');
25
+ logger.info('i');
26
+ logger.warn('w');
27
+ logger.error('e');
28
+ expect(lines.map(l => [l.fn, /\[(\w+)\]/.exec(l.text)?.[1], l.text.slice(-1)])).to.deep.equal([
29
+ ['debug', 'debug', 'd'],
30
+ ['info', 'info', 'i'],
31
+ ['warn', 'warn', 'w'],
32
+ ['error', 'error', 'e'],
33
+ ]);
34
+ });
35
+
36
+ it('writes the configured level and the ones after it', () => {
37
+ const { logger, lines } = capture('warn');
38
+ logger.debug('d');
39
+ logger.info('i');
40
+ logger.warn('w');
41
+ logger.error('e');
42
+ expect(lines.map(l => l.fn)).to.deep.equal(['warn', 'error']);
43
+ expect([logger.isEnabled('verbose'), logger.isEnabled('debug'), logger.isEnabled('info'), logger.isEnabled('warn'), logger.isEnabled('error')])
44
+ .to.deep.equal([false, false, false, true, true]);
45
+ });
46
+
47
+ it('treats an unknown configured level as info', () => {
48
+ const { logger } = capture('loud' as LogLevel);
49
+ expect(logger.isEnabled('debug')).to.equal(false);
50
+ expect(logger.isEnabled('info')).to.equal(true);
51
+ });
52
+
53
+ it('reports the level of the message to onLog', () => {
54
+ const { logger } = capture('info');
55
+ const seen: LogMessage[] = [];
56
+ const listener = onLogEmitter.event(m => seen.push(m));
57
+ logger.warn('w');
58
+ listener.dispose();
59
+ expect(seen.map(m => [m.level, m.message])).to.deep.equal([['warn', 'w']]);
60
+ });
61
+ });