moost 0.5.1 → 0.5.3

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.
package/dist/index.cjs CHANGED
@@ -7,6 +7,26 @@ var logger = require('@prostojs/logger');
7
7
  var hookable = require('hookable');
8
8
  var wooks = require('wooks');
9
9
 
10
+ let defaultLogger;
11
+ function setDefaultLogger(logger) {
12
+ defaultLogger = logger;
13
+ }
14
+ function getDefaultLogger(topic) {
15
+ if (!defaultLogger) {
16
+ defaultLogger = new logger.ProstoLogger({
17
+ level: 4,
18
+ transports: [
19
+ logger.createConsoleTransort({
20
+ format: logger.coloredConsole,
21
+ }),
22
+ ],
23
+ });
24
+ }
25
+ return topic && defaultLogger instanceof logger.ProstoLogger
26
+ ? defaultLogger.createTopic(topic)
27
+ : defaultLogger;
28
+ }
29
+
10
30
  async function runPipes(pipes, initialValue, metas, level) {
11
31
  let v = initialValue;
12
32
  for (const pipe of pipes) {
@@ -35,6 +55,17 @@ function getMoostMate() {
35
55
  }
36
56
 
37
57
  const sharedMoostInfact = getNewMoostInfact();
58
+ let loggingOptions = {
59
+ newInstance: 'SINGLETON',
60
+ warn: true,
61
+ error: true,
62
+ };
63
+ function setInfactLoggingOptions(options) {
64
+ loggingOptions = {
65
+ ...loggingOptions,
66
+ ...options,
67
+ };
68
+ }
38
69
  function getMoostInfact() {
39
70
  return sharedMoostInfact;
40
71
  }
@@ -80,6 +111,82 @@ function getNewMoostInfact() {
80
111
  }
81
112
  },
82
113
  storeProvideRegByInstance: true,
114
+ on: (event, targetClass, message, args) => {
115
+ switch (event) {
116
+ case 'new-instance': {
117
+ const isForEvent = getMoostMate().read(targetClass)?.injectable !== 'SINGLETON';
118
+ const isSingleton = !isForEvent;
119
+ if (loggingOptions.newInstance === false ||
120
+ (loggingOptions.newInstance === 'FOR_EVENT' && !isForEvent) ||
121
+ (loggingOptions.newInstance === 'SINGLETON' && isSingleton)) {
122
+ return;
123
+ }
124
+ break;
125
+ }
126
+ case 'warn': {
127
+ if (!loggingOptions.warn) {
128
+ return;
129
+ }
130
+ break;
131
+ }
132
+ case 'error': {
133
+ if (!loggingOptions.error) {
134
+ return;
135
+ }
136
+ break;
137
+ }
138
+ }
139
+ let logger;
140
+ try {
141
+ logger = eventCore.useEventLogger('infact');
142
+ }
143
+ catch (error) {
144
+ logger = getDefaultLogger('infact');
145
+ }
146
+ const instance = `${''}${targetClass.name}${''}`;
147
+ switch (event) {
148
+ case 'new-instance': {
149
+ const params = args
150
+ ?.map(a => {
151
+ switch (typeof a) {
152
+ case 'number':
153
+ case 'boolean': {
154
+ return `${''}${a}${'' + ''}`;
155
+ }
156
+ case 'string': {
157
+ return `${''}"${a.slice(0, 1)}..."${'' + ''}`;
158
+ }
159
+ case 'object': {
160
+ if (Array.isArray(a)) {
161
+ return `[${a.length}]`;
162
+ }
163
+ if (mate$1.getConstructor(a)) {
164
+ return mate$1.getConstructor(a).name;
165
+ }
166
+ return '{}';
167
+ }
168
+ default: {
169
+ return '*';
170
+ }
171
+ }
172
+ })
173
+ .map(a => `${'' + ''}${a}${'' + ''}`)
174
+ .join(', ') || '';
175
+ logger.info(`new ${instance}${'' + ''}(${params})`);
176
+ break;
177
+ }
178
+ case 'warn': {
179
+ const hier = `${'' + ''}⋱ ${args?.map(String).join(' → ') || ''}`;
180
+ logger.warn(`${instance} - ${message} ${hier}`);
181
+ break;
182
+ }
183
+ case 'error': {
184
+ const hier = `${'' + ''}⋱ ${args?.map(String).join(' → ') || ''}`;
185
+ logger.error(`Failed to instantiate ${instance}. ${message} ${hier}`);
186
+ break;
187
+ }
188
+ }
189
+ },
83
190
  });
84
191
  }
85
192
 
@@ -253,29 +360,16 @@ function getParentProps(constructor) {
253
360
  return [];
254
361
  }
255
362
 
256
- function getDefaultLogger(topic) {
257
- return new logger.ProstoLogger({
258
- level: 4,
259
- transports: [
260
- logger.createConsoleTransort({
261
- format: logger.coloredConsole,
262
- }),
263
- ],
264
- }, topic);
265
- }
266
-
267
363
  async function getCallableFn(targetInstance, fn, pipes, logger) {
268
364
  const mate = getMoostMate();
269
365
  const meta = mate.read(fn);
270
366
  if (meta?.injectable) {
271
367
  const infact = getMoostInfact();
272
- infact.silent(true);
273
368
  const instance = (await infact.getForInstance(targetInstance, fn, {
274
369
  customData: {
275
370
  pipes: [...(pipes || []), ...(meta.pipes || [])].sort((a, b) => a.priority - b.priority),
276
371
  },
277
372
  }));
278
- infact.silent(false);
279
373
  return ((...args) => instance.handler(...args));
280
374
  }
281
375
  if (typeof fn === 'function') {
@@ -462,7 +556,7 @@ async function bindControllerMethods(options) {
462
556
  getIterceptorHandler,
463
557
  resolveArgs,
464
558
  logHandler: (eventName) => {
465
- options.logger.info(`${eventName} ${'' + '' + ''}→ ${classConstructor.name}.${''}${method}${''}()`);
559
+ options.moostInstance.logMappedHandler(eventName, classConstructor, method);
466
560
  },
467
561
  register(h, path, args) {
468
562
  const data = wm.get(h);
@@ -555,44 +649,6 @@ function Intercept(handler, priority, name) {
555
649
  }, true);
556
650
  }
557
651
 
558
- exports.TPipePriority = void 0;
559
- (function (TPipePriority) {
560
- TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
561
- TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
562
- TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
563
- TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
564
- TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
565
- TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
566
- TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
567
- TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
568
- TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
569
- })(exports.TPipePriority || (exports.TPipePriority = {}));
570
-
571
- function Pipe(handler, priority) {
572
- if (typeof priority !== 'number') {
573
- priority = typeof handler.priority === 'number' ? handler.priority : exports.TPipePriority.TRANSFORM;
574
- }
575
- return getMoostMate().decorate('pipes', { handler, priority }, true);
576
- }
577
-
578
- function Provide(type, fn) {
579
- return getMoostMate().decorate(meta => {
580
- meta.provide = meta.provide || {};
581
- Object.assign(meta.provide, infact$1.createProvideRegistry([type, fn]));
582
- return meta;
583
- });
584
- }
585
- function Replace(type, newType) {
586
- return getMoostMate().decorate(meta => {
587
- meta.replace = meta.replace || {};
588
- Object.assign(meta.replace, infact$1.createReplaceRegistry([type, newType]));
589
- return meta;
590
- });
591
- }
592
- function Inject(type) {
593
- return getMoostMate().decorate('inject', type);
594
- }
595
-
596
652
  function Resolve(resolver, label) {
597
653
  return (target, key, index) => {
598
654
  const i = typeof index === 'number' ? index : undefined;
@@ -618,9 +674,6 @@ function Const(value, label) {
618
674
  function ConstFactory(factory, label) {
619
675
  return Resolve(async () => factory(), label);
620
676
  }
621
- function InjectEventLogger(topic) {
622
- return Resolve(() => eventCore.useEventLogger(topic));
623
- }
624
677
  function fillLabel(target, key, index, name) {
625
678
  if (name) {
626
679
  const meta = getMoostMate().read(target, key);
@@ -635,6 +688,59 @@ function fillLabel(target, key, index, name) {
635
688
  }
636
689
  }
637
690
 
691
+ function InjectEventLogger(topic) {
692
+ return Resolve(() => eventCore.useEventLogger(topic));
693
+ }
694
+ function InjectMoostLogger(topic) {
695
+ return Resolve(async () => {
696
+ const { instantiate, getControllerMeta } = useControllerContext();
697
+ const moostApp = await instantiate(Moost);
698
+ const meta = getControllerMeta();
699
+ return moostApp.getLogger(meta?.loggerTopic || topic || meta?.id);
700
+ });
701
+ }
702
+ function LoggerTopic(topic) {
703
+ return getMoostMate().decorate('loggerTopic', topic);
704
+ }
705
+
706
+ exports.TPipePriority = void 0;
707
+ (function (TPipePriority) {
708
+ TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
709
+ TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
710
+ TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
711
+ TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
712
+ TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
713
+ TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
714
+ TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
715
+ TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
716
+ TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
717
+ })(exports.TPipePriority || (exports.TPipePriority = {}));
718
+
719
+ function Pipe(handler, priority) {
720
+ if (typeof priority !== 'number') {
721
+ priority = typeof handler.priority === 'number' ? handler.priority : exports.TPipePriority.TRANSFORM;
722
+ }
723
+ return getMoostMate().decorate('pipes', { handler, priority }, true);
724
+ }
725
+
726
+ function Provide(type, fn) {
727
+ return getMoostMate().decorate(meta => {
728
+ meta.provide = meta.provide || {};
729
+ Object.assign(meta.provide, infact$1.createProvideRegistry([type, fn]));
730
+ return meta;
731
+ });
732
+ }
733
+ function Replace(type, newType) {
734
+ return getMoostMate().decorate(meta => {
735
+ meta.replace = meta.replace || {};
736
+ Object.assign(meta.replace, infact$1.createReplaceRegistry([type, newType]));
737
+ return meta;
738
+ });
739
+ }
740
+ function Inject(type) {
741
+ return getMoostMate().decorate('inject', type);
742
+ }
743
+
638
744
  function defineInterceptorFn(fn, priority = exports.TInterceptorPriority.INTERCEPTOR) {
639
745
  fn.priority = priority;
640
746
  return fn;
@@ -671,7 +777,7 @@ class Moost extends hookable.Hookable {
671
777
  this.replace = {};
672
778
  this.unregisteredControllers = [];
673
779
  this.logger = options?.logger || getDefaultLogger(`${'' + ''}moost`);
674
- getMoostInfact().setLogger(this.getLogger('infact'));
780
+ setDefaultLogger(this.logger);
675
781
  const mate = getMoostMate();
676
782
  Object.assign(mate, { logger: this.getLogger('mate') });
677
783
  }
@@ -682,7 +788,7 @@ class Moost extends hookable.Hookable {
682
788
  this.callHook('event-end', source);
683
789
  }
684
790
  getLogger(topic) {
685
- if (this.logger instanceof logger.ProstoLogger) {
791
+ if (topic && this.logger instanceof logger.ProstoLogger) {
686
792
  return this.logger.createTopic(topic);
687
793
  }
688
794
  return this.logger;
@@ -712,8 +818,6 @@ class Moost extends hookable.Hookable {
712
818
  }
713
819
  }
714
820
  async bindControllers() {
715
- const infact = getMoostInfact();
716
- infact.setLogger(this.logger);
717
821
  const meta = getMoostMate();
718
822
  const thisMeta = meta.read(this);
719
823
  const provide = { ...thisMeta?.provide, ...this.provide };
@@ -753,14 +857,9 @@ class Moost extends hookable.Hookable {
753
857
  }
754
858
  const getInstance = instance
755
859
  ? () => Promise.resolve(instance)
756
- : async () => {
757
- infact.silent(true);
758
- const instance = (await infact.get(controller, {
759
- ...infactOpts,
760
- }));
761
- infact.silent(false);
762
- return instance;
763
- };
860
+ : async () => (await infact.get(controller, {
861
+ ...infactOpts,
862
+ }));
764
863
  const classConstructor = mate$1.isConstructor(controller)
765
864
  ? controller
766
865
  : mate$1.getConstructor(controller);
@@ -775,6 +874,7 @@ class Moost extends hookable.Hookable {
775
874
  provide: classMeta?.provide,
776
875
  replace: classMeta?.replace,
777
876
  logger: this.logger,
877
+ moostInstance: this,
778
878
  }));
779
879
  if (classMeta && classMeta.importController) {
780
880
  const prefix = typeof replaceOwnPrefix === 'string' ? replaceOwnPrefix : classMeta.controller?.prefix;
@@ -858,6 +958,11 @@ class Moost extends hookable.Hookable {
858
958
  this.unregisteredControllers.push(...controllers);
859
959
  return this;
860
960
  }
961
+ logMappedHandler(eventName, classConstructor, method, stroke, prefix) {
962
+ const c = stroke ? __DYE_CROSSED__ : '';
963
+ const coff = stroke ? __DYE_CROSSED_OFF__ : '';
964
+ this.logger.info(`${prefix || ''}${c}${eventName} ${'' + '' + '' + c}→ ${classConstructor.name}.${'' + c}${method}${''}()${coff}`);
965
+ }
861
966
  }
862
967
 
863
968
  Object.defineProperty(exports, "getConstructor", {
@@ -900,6 +1005,14 @@ Object.defineProperty(exports, "createReplaceRegistry", {
900
1005
  enumerable: true,
901
1006
  get: function () { return infact$1.createReplaceRegistry; }
902
1007
  });
1008
+ Object.defineProperty(exports, "ProstoLogger", {
1009
+ enumerable: true,
1010
+ get: function () { return logger.ProstoLogger; }
1011
+ });
1012
+ Object.defineProperty(exports, "clearGlobalWooks", {
1013
+ enumerable: true,
1014
+ get: function () { return wooks.clearGlobalWooks; }
1015
+ });
903
1016
  Object.defineProperty(exports, "getGlobalWooks", {
904
1017
  enumerable: true,
905
1018
  get: function () { return wooks.getGlobalWooks; }
@@ -914,10 +1027,12 @@ exports.ImportController = ImportController;
914
1027
  exports.Inherit = Inherit;
915
1028
  exports.Inject = Inject;
916
1029
  exports.InjectEventLogger = InjectEventLogger;
1030
+ exports.InjectMoostLogger = InjectMoostLogger;
917
1031
  exports.Injectable = Injectable;
918
1032
  exports.Intercept = Intercept;
919
1033
  exports.InterceptorHandler = InterceptorHandler;
920
1034
  exports.Label = Label;
1035
+ exports.LoggerTopic = LoggerTopic;
921
1036
  exports.Moost = Moost;
922
1037
  exports.Optional = Optional;
923
1038
  exports.Param = Param;
@@ -939,4 +1054,5 @@ exports.getNewMoostInfact = getNewMoostInfact;
939
1054
  exports.registerEventScope = registerEventScope;
940
1055
  exports.resolvePipe = resolvePipe;
941
1056
  exports.setControllerContext = setControllerContext;
1057
+ exports.setInfactLoggingOptions = setInfactLoggingOptions;
942
1058
  exports.useControllerContext = useControllerContext;
package/dist/index.d.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  import { useEventLogger } from '@wooksjs/event-core';
2
2
  export { ContextInjector, EventLogger, THook, getContextInjector, replaceContextInjector, useAsyncEventContext, useEventLogger } from '@wooksjs/event-core';
3
+ import { TConsoleBase } from '@prostojs/logger';
4
+ export { ProstoLogger, TConsoleBase } from '@prostojs/logger';
3
5
  import { TProvideRegistry, Infact, TReplaceRegistry, TProvideFn } from '@prostojs/infact';
4
6
  export { TProvideRegistry, createProvideRegistry, createReplaceRegistry } from '@prostojs/infact';
5
- import { TConsoleBase } from '@prostojs/logger';
6
7
  import { Hookable } from 'hookable';
7
8
  import * as _prostojs_mate from '@prostojs/mate';
8
9
  import { TMateParamMeta, Mate } from '@prostojs/mate';
9
10
  export { getConstructor, isConstructor } from '@prostojs/mate';
10
- export { getGlobalWooks } from 'wooks';
11
+ export { clearGlobalWooks, getGlobalWooks } from 'wooks';
11
12
 
12
13
  type TAny = any;
13
14
  type TAnyFn = (...a: TAny[]) => unknown;
@@ -136,6 +137,12 @@ declare function Intercept(handler: TCallableClassFunction<TInterceptorFn>, prio
136
137
 
137
138
  type TDecoratorLevel = 'CLASS' | 'METHOD' | 'PROP' | 'PARAM';
138
139
 
140
+ interface TInfactLoggingOptions {
141
+ newInstance?: true | false | 'FOR_EVENT' | 'SINGLETON';
142
+ warn?: true | false;
143
+ error?: true | false;
144
+ }
145
+ declare function setInfactLoggingOptions(options: TInfactLoggingOptions): void;
139
146
  declare function getMoostInfact(): Infact<TMoostMetadata<TEmpty>, TMoostMetadata<TEmpty>, TMoostParamsMetadata, TCustom>;
140
147
  interface TCustom {
141
148
  pipes?: TPipeData[];
@@ -192,6 +199,7 @@ interface TMoostMetadata<H extends TObject = TEmpty> extends TCommonMetaFields,
192
199
  returnType?: TFunction;
193
200
  provide?: TProvideRegistry;
194
201
  replace?: TReplaceRegistry;
202
+ loggerTopic?: string;
195
203
  params: Array<TMateParamMeta & TMoostParamsMetadata>;
196
204
  }
197
205
  interface TMoostParamsMetadata extends TCommonMetaFields, TCommonMoostMeta {
@@ -242,6 +250,25 @@ interface TCommonMoostMeta {
242
250
  */
243
251
  declare function Injectable(scope?: true | TInjectableScope): ClassDecorator;
244
252
 
253
+ /**
254
+ * Resolves event logger from event context
255
+ * @param topic
256
+ * @returns Resolver to '@wooksjs/event-core' (EventLogger)
257
+ */
258
+ declare function InjectEventLogger(topic?: string): ParameterDecorator & PropertyDecorator;
259
+ /**
260
+ * Resolves app-level logger
261
+ * @param topic - logger topic (can be overrided by @LoggerTopic)
262
+ * @returns
263
+ */
264
+ declare function InjectMoostLogger(topic?: string): ParameterDecorator & PropertyDecorator;
265
+ /**
266
+ * Sets logger topic (used in @InjectMoostLogger)
267
+ * @param topic - logger topic (banner)
268
+ * @returns
269
+ */
270
+ declare function LoggerTopic(topic: string): MethodDecorator & ClassDecorator & ParameterDecorator & PropertyDecorator;
271
+
245
272
  /**
246
273
  * ## Pipe
247
274
  * ### @Decorator
@@ -314,12 +341,6 @@ declare function Const<T>(value: T, label?: string): ParameterDecorator & Proper
314
341
  * @paramType unknown
315
342
  */
316
343
  declare function ConstFactory<T>(factory: () => T | Promise<T>, label?: string): ParameterDecorator & PropertyDecorator;
317
- /**
318
- * Resolves event logger from event context
319
- * @param topic
320
- * @returns Resolver to '@wooksjs/event-core' (EventLogger)
321
- */
322
- declare function InjectEventLogger(topic?: string): ParameterDecorator & PropertyDecorator;
323
344
 
324
345
  declare class InterceptorHandler {
325
346
  protected handlers: Array<{
@@ -486,7 +507,7 @@ declare class Moost extends Hookable {
486
507
  * @param topic
487
508
  * @returns
488
509
  */
489
- getLogger(topic: string): TConsoleBase;
510
+ getLogger(topic?: string): TConsoleBase;
490
511
  adapter<T extends TMoostAdapter<TAny>>(a: T): T;
491
512
  getControllersOverview(): TControllerOverview[];
492
513
  /**
@@ -524,6 +545,7 @@ declare class Moost extends Hookable {
524
545
  * @returns
525
546
  */
526
547
  registerControllers(...controllers: Array<TObject | TFunction | [string, TObject | TFunction]>): this;
548
+ logMappedHandler(eventName: string, classConstructor: Function, method: string, stroke?: boolean, prefix?: string): void;
527
549
  }
528
550
  interface TMoostAdapterOptions<H, T> {
529
551
  prefix: string;
@@ -637,4 +659,4 @@ type TInterceptorClass = TClassFunction<TInterceptorFn>;
637
659
  */
638
660
  declare function definePipeFn<T extends TObject = TEmpty>(fn: TPipeFn<T>, priority?: TPipePriority): TPipeFn<T>;
639
661
 
640
- export { Circular, Const, ConstFactory, Controller, Description, Id, ImportController, Inherit, Inject, InjectEventLogger, Injectable, Intercept, InterceptorHandler, Label, Moost, Optional, Param, Params, Pipe, Provide, Replace, Required, Resolve, type TCallableClassFunction, type TClassConstructor, type TClassFunction, type TContextInjectorHook, type TControllerOverview, type TInjectableScope, type TInterceptorAfter, type TInterceptorBefore, type TInterceptorClass, type TInterceptorData, type TInterceptorFn, type TInterceptorOnError, TInterceptorPriority, type TMoostAdapter, type TMoostAdapterOptions, type TMoostEventHandlerHookOptions, type TMoostEventHandlerOptions, type TMoostHandler, type TMoostMetadata, type TMoostOptions, type TMoostParamsMetadata, type TPipeData, type TPipeFn, type TPipeMetas, TPipePriority, Value, defineInterceptorFn, defineMoostEventHandler, definePipeFn, getInstanceOwnMethods, getInstanceOwnProps, getMoostInfact, getMoostMate, getNewMoostInfact, registerEventScope, resolvePipe, setControllerContext, useControllerContext };
662
+ export { Circular, Const, ConstFactory, Controller, Description, Id, ImportController, Inherit, Inject, InjectEventLogger, InjectMoostLogger, Injectable, Intercept, InterceptorHandler, Label, LoggerTopic, Moost, Optional, Param, Params, Pipe, Provide, Replace, Required, Resolve, type TCallableClassFunction, type TClassConstructor, type TClassFunction, type TContextInjectorHook, type TControllerOverview, type TInjectableScope, type TInterceptorAfter, type TInterceptorBefore, type TInterceptorClass, type TInterceptorData, type TInterceptorFn, type TInterceptorOnError, TInterceptorPriority, type TMoostAdapter, type TMoostAdapterOptions, type TMoostEventHandlerHookOptions, type TMoostEventHandlerOptions, type TMoostHandler, type TMoostMetadata, type TMoostOptions, type TMoostParamsMetadata, type TPipeData, type TPipeFn, type TPipeMetas, TPipePriority, Value, defineInterceptorFn, defineMoostEventHandler, definePipeFn, getInstanceOwnMethods, getInstanceOwnProps, getMoostInfact, getMoostMate, getNewMoostInfact, registerEventScope, resolvePipe, setControllerContext, setInfactLoggingOptions, useControllerContext };
package/dist/index.mjs CHANGED
@@ -1,12 +1,33 @@
1
1
  import { Mate, getConstructor, isConstructor } from '@prostojs/mate';
2
2
  export { getConstructor, isConstructor } from '@prostojs/mate';
3
- import { useEventId, useAsyncEventContext, getContextInjector, useEventLogger, useRouteParams, createAsyncEventContext } from '@wooksjs/event-core';
3
+ import { useEventId, useEventLogger, useAsyncEventContext, getContextInjector, useRouteParams, createAsyncEventContext } from '@wooksjs/event-core';
4
4
  export { ContextInjector, EventLogger, getContextInjector, replaceContextInjector, useAsyncEventContext, useEventLogger } from '@wooksjs/event-core';
5
5
  import { Infact, createProvideRegistry, createReplaceRegistry } from '@prostojs/infact';
6
6
  export { createProvideRegistry, createReplaceRegistry } from '@prostojs/infact';
7
7
  import { ProstoLogger, createConsoleTransort, coloredConsole } from '@prostojs/logger';
8
+ export { ProstoLogger } from '@prostojs/logger';
8
9
  import { Hookable } from 'hookable';
9
- export { getGlobalWooks } from 'wooks';
10
+ export { clearGlobalWooks, getGlobalWooks } from 'wooks';
11
+
12
+ let defaultLogger;
13
+ function setDefaultLogger(logger) {
14
+ defaultLogger = logger;
15
+ }
16
+ function getDefaultLogger(topic) {
17
+ if (!defaultLogger) {
18
+ defaultLogger = new ProstoLogger({
19
+ level: 4,
20
+ transports: [
21
+ createConsoleTransort({
22
+ format: coloredConsole,
23
+ }),
24
+ ],
25
+ });
26
+ }
27
+ return topic && defaultLogger instanceof ProstoLogger
28
+ ? defaultLogger.createTopic(topic)
29
+ : defaultLogger;
30
+ }
10
31
 
11
32
  async function runPipes(pipes, initialValue, metas, level) {
12
33
  let v = initialValue;
@@ -36,6 +57,17 @@ function getMoostMate() {
36
57
  }
37
58
 
38
59
  const sharedMoostInfact = getNewMoostInfact();
60
+ let loggingOptions = {
61
+ newInstance: 'SINGLETON',
62
+ warn: true,
63
+ error: true,
64
+ };
65
+ function setInfactLoggingOptions(options) {
66
+ loggingOptions = {
67
+ ...loggingOptions,
68
+ ...options,
69
+ };
70
+ }
39
71
  function getMoostInfact() {
40
72
  return sharedMoostInfact;
41
73
  }
@@ -81,6 +113,82 @@ function getNewMoostInfact() {
81
113
  }
82
114
  },
83
115
  storeProvideRegByInstance: true,
116
+ on: (event, targetClass, message, args) => {
117
+ switch (event) {
118
+ case 'new-instance': {
119
+ const isForEvent = getMoostMate().read(targetClass)?.injectable !== 'SINGLETON';
120
+ const isSingleton = !isForEvent;
121
+ if (loggingOptions.newInstance === false ||
122
+ (loggingOptions.newInstance === 'FOR_EVENT' && !isForEvent) ||
123
+ (loggingOptions.newInstance === 'SINGLETON' && isSingleton)) {
124
+ return;
125
+ }
126
+ break;
127
+ }
128
+ case 'warn': {
129
+ if (!loggingOptions.warn) {
130
+ return;
131
+ }
132
+ break;
133
+ }
134
+ case 'error': {
135
+ if (!loggingOptions.error) {
136
+ return;
137
+ }
138
+ break;
139
+ }
140
+ }
141
+ let logger;
142
+ try {
143
+ logger = useEventLogger('infact');
144
+ }
145
+ catch (error) {
146
+ logger = getDefaultLogger('infact');
147
+ }
148
+ const instance = `${''}${targetClass.name}${''}`;
149
+ switch (event) {
150
+ case 'new-instance': {
151
+ const params = args
152
+ ?.map(a => {
153
+ switch (typeof a) {
154
+ case 'number':
155
+ case 'boolean': {
156
+ return `${''}${a}${'' + ''}`;
157
+ }
158
+ case 'string': {
159
+ return `${''}"${a.slice(0, 1)}..."${'' + ''}`;
160
+ }
161
+ case 'object': {
162
+ if (Array.isArray(a)) {
163
+ return `[${a.length}]`;
164
+ }
165
+ if (getConstructor(a)) {
166
+ return getConstructor(a).name;
167
+ }
168
+ return '{}';
169
+ }
170
+ default: {
171
+ return '*';
172
+ }
173
+ }
174
+ })
175
+ .map(a => `${'' + ''}${a}${'' + ''}`)
176
+ .join(', ') || '';
177
+ logger.info(`new ${instance}${'' + ''}(${params})`);
178
+ break;
179
+ }
180
+ case 'warn': {
181
+ const hier = `${'' + ''}⋱ ${args?.map(String).join(' → ') || ''}`;
182
+ logger.warn(`${instance} - ${message} ${hier}`);
183
+ break;
184
+ }
185
+ case 'error': {
186
+ const hier = `${'' + ''}⋱ ${args?.map(String).join(' → ') || ''}`;
187
+ logger.error(`Failed to instantiate ${instance}. ${message} ${hier}`);
188
+ break;
189
+ }
190
+ }
191
+ },
84
192
  });
85
193
  }
86
194
 
@@ -254,29 +362,16 @@ function getParentProps(constructor) {
254
362
  return [];
255
363
  }
256
364
 
257
- function getDefaultLogger(topic) {
258
- return new ProstoLogger({
259
- level: 4,
260
- transports: [
261
- createConsoleTransort({
262
- format: coloredConsole,
263
- }),
264
- ],
265
- }, topic);
266
- }
267
-
268
365
  async function getCallableFn(targetInstance, fn, pipes, logger) {
269
366
  const mate = getMoostMate();
270
367
  const meta = mate.read(fn);
271
368
  if (meta?.injectable) {
272
369
  const infact = getMoostInfact();
273
- infact.silent(true);
274
370
  const instance = (await infact.getForInstance(targetInstance, fn, {
275
371
  customData: {
276
372
  pipes: [...(pipes || []), ...(meta.pipes || [])].sort((a, b) => a.priority - b.priority),
277
373
  },
278
374
  }));
279
- infact.silent(false);
280
375
  return ((...args) => instance.handler(...args));
281
376
  }
282
377
  if (typeof fn === 'function') {
@@ -463,7 +558,7 @@ async function bindControllerMethods(options) {
463
558
  getIterceptorHandler,
464
559
  resolveArgs,
465
560
  logHandler: (eventName) => {
466
- options.logger.info(`${eventName} ${'' + '' + ''}→ ${classConstructor.name}.${''}${method}${''}()`);
561
+ options.moostInstance.logMappedHandler(eventName, classConstructor, method);
467
562
  },
468
563
  register(h, path, args) {
469
564
  const data = wm.get(h);
@@ -556,44 +651,6 @@ function Intercept(handler, priority, name) {
556
651
  }, true);
557
652
  }
558
653
 
559
- var TPipePriority;
560
- (function (TPipePriority) {
561
- TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
562
- TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
563
- TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
564
- TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
565
- TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
566
- TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
567
- TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
568
- TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
569
- TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
570
- })(TPipePriority || (TPipePriority = {}));
571
-
572
- function Pipe(handler, priority) {
573
- if (typeof priority !== 'number') {
574
- priority = typeof handler.priority === 'number' ? handler.priority : TPipePriority.TRANSFORM;
575
- }
576
- return getMoostMate().decorate('pipes', { handler, priority }, true);
577
- }
578
-
579
- function Provide(type, fn) {
580
- return getMoostMate().decorate(meta => {
581
- meta.provide = meta.provide || {};
582
- Object.assign(meta.provide, createProvideRegistry([type, fn]));
583
- return meta;
584
- });
585
- }
586
- function Replace(type, newType) {
587
- return getMoostMate().decorate(meta => {
588
- meta.replace = meta.replace || {};
589
- Object.assign(meta.replace, createReplaceRegistry([type, newType]));
590
- return meta;
591
- });
592
- }
593
- function Inject(type) {
594
- return getMoostMate().decorate('inject', type);
595
- }
596
-
597
654
  function Resolve(resolver, label) {
598
655
  return (target, key, index) => {
599
656
  const i = typeof index === 'number' ? index : undefined;
@@ -619,9 +676,6 @@ function Const(value, label) {
619
676
  function ConstFactory(factory, label) {
620
677
  return Resolve(async () => factory(), label);
621
678
  }
622
- function InjectEventLogger(topic) {
623
- return Resolve(() => useEventLogger(topic));
624
- }
625
679
  function fillLabel(target, key, index, name) {
626
680
  if (name) {
627
681
  const meta = getMoostMate().read(target, key);
@@ -636,6 +690,59 @@ function fillLabel(target, key, index, name) {
636
690
  }
637
691
  }
638
692
 
693
+ function InjectEventLogger(topic) {
694
+ return Resolve(() => useEventLogger(topic));
695
+ }
696
+ function InjectMoostLogger(topic) {
697
+ return Resolve(async () => {
698
+ const { instantiate, getControllerMeta } = useControllerContext();
699
+ const moostApp = await instantiate(Moost);
700
+ const meta = getControllerMeta();
701
+ return moostApp.getLogger(meta?.loggerTopic || topic || meta?.id);
702
+ });
703
+ }
704
+ function LoggerTopic(topic) {
705
+ return getMoostMate().decorate('loggerTopic', topic);
706
+ }
707
+
708
+ var TPipePriority;
709
+ (function (TPipePriority) {
710
+ TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
711
+ TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
712
+ TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
713
+ TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
714
+ TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
715
+ TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
716
+ TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
717
+ TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
718
+ TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
719
+ })(TPipePriority || (TPipePriority = {}));
720
+
721
+ function Pipe(handler, priority) {
722
+ if (typeof priority !== 'number') {
723
+ priority = typeof handler.priority === 'number' ? handler.priority : TPipePriority.TRANSFORM;
724
+ }
725
+ return getMoostMate().decorate('pipes', { handler, priority }, true);
726
+ }
727
+
728
+ function Provide(type, fn) {
729
+ return getMoostMate().decorate(meta => {
730
+ meta.provide = meta.provide || {};
731
+ Object.assign(meta.provide, createProvideRegistry([type, fn]));
732
+ return meta;
733
+ });
734
+ }
735
+ function Replace(type, newType) {
736
+ return getMoostMate().decorate(meta => {
737
+ meta.replace = meta.replace || {};
738
+ Object.assign(meta.replace, createReplaceRegistry([type, newType]));
739
+ return meta;
740
+ });
741
+ }
742
+ function Inject(type) {
743
+ return getMoostMate().decorate('inject', type);
744
+ }
745
+
639
746
  function defineInterceptorFn(fn, priority = TInterceptorPriority.INTERCEPTOR) {
640
747
  fn.priority = priority;
641
748
  return fn;
@@ -672,7 +779,7 @@ class Moost extends Hookable {
672
779
  this.replace = {};
673
780
  this.unregisteredControllers = [];
674
781
  this.logger = options?.logger || getDefaultLogger(`${'' + ''}moost`);
675
- getMoostInfact().setLogger(this.getLogger('infact'));
782
+ setDefaultLogger(this.logger);
676
783
  const mate = getMoostMate();
677
784
  Object.assign(mate, { logger: this.getLogger('mate') });
678
785
  }
@@ -683,7 +790,7 @@ class Moost extends Hookable {
683
790
  this.callHook('event-end', source);
684
791
  }
685
792
  getLogger(topic) {
686
- if (this.logger instanceof ProstoLogger) {
793
+ if (topic && this.logger instanceof ProstoLogger) {
687
794
  return this.logger.createTopic(topic);
688
795
  }
689
796
  return this.logger;
@@ -713,8 +820,6 @@ class Moost extends Hookable {
713
820
  }
714
821
  }
715
822
  async bindControllers() {
716
- const infact = getMoostInfact();
717
- infact.setLogger(this.logger);
718
823
  const meta = getMoostMate();
719
824
  const thisMeta = meta.read(this);
720
825
  const provide = { ...thisMeta?.provide, ...this.provide };
@@ -754,14 +859,9 @@ class Moost extends Hookable {
754
859
  }
755
860
  const getInstance = instance
756
861
  ? () => Promise.resolve(instance)
757
- : async () => {
758
- infact.silent(true);
759
- const instance = (await infact.get(controller, {
760
- ...infactOpts,
761
- }));
762
- infact.silent(false);
763
- return instance;
764
- };
862
+ : async () => (await infact.get(controller, {
863
+ ...infactOpts,
864
+ }));
765
865
  const classConstructor = isConstructor(controller)
766
866
  ? controller
767
867
  : getConstructor(controller);
@@ -776,6 +876,7 @@ class Moost extends Hookable {
776
876
  provide: classMeta?.provide,
777
877
  replace: classMeta?.replace,
778
878
  logger: this.logger,
879
+ moostInstance: this,
779
880
  }));
780
881
  if (classMeta && classMeta.importController) {
781
882
  const prefix = typeof replaceOwnPrefix === 'string' ? replaceOwnPrefix : classMeta.controller?.prefix;
@@ -859,6 +960,11 @@ class Moost extends Hookable {
859
960
  this.unregisteredControllers.push(...controllers);
860
961
  return this;
861
962
  }
963
+ logMappedHandler(eventName, classConstructor, method, stroke, prefix) {
964
+ const c = stroke ? __DYE_CROSSED__ : '';
965
+ const coff = stroke ? __DYE_CROSSED_OFF__ : '';
966
+ this.logger.info(`${prefix || ''}${c}${eventName} ${'' + '' + '' + c}→ ${classConstructor.name}.${'' + c}${method}${''}()${coff}`);
967
+ }
862
968
  }
863
969
 
864
- export { Circular, Const, ConstFactory, Controller, Description, Id, ImportController, Inherit, Inject, InjectEventLogger, Injectable, Intercept, InterceptorHandler, Label, Moost, Optional, Param, Params, Pipe, Provide, Replace, Required, Resolve, TInterceptorPriority, TPipePriority, Value, defineInterceptorFn, defineMoostEventHandler, definePipeFn, getInstanceOwnMethods, getInstanceOwnProps, getMoostInfact, getMoostMate, getNewMoostInfact, registerEventScope, resolvePipe, setControllerContext, useControllerContext };
970
+ export { Circular, Const, ConstFactory, Controller, Description, Id, ImportController, Inherit, Inject, InjectEventLogger, InjectMoostLogger, Injectable, Intercept, InterceptorHandler, Label, LoggerTopic, Moost, Optional, Param, Params, Pipe, Provide, Replace, Required, Resolve, TInterceptorPriority, TPipePriority, Value, defineInterceptorFn, defineMoostEventHandler, definePipeFn, getInstanceOwnMethods, getInstanceOwnProps, getMoostInfact, getMoostMate, getNewMoostInfact, registerEventScope, resolvePipe, setControllerContext, setInfactLoggingOptions, useControllerContext };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moost",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "moost",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -31,12 +31,12 @@
31
31
  "prostojs"
32
32
  ],
33
33
  "dependencies": {
34
- "@prostojs/infact": "^0.2.4",
34
+ "@prostojs/infact": "^0.3.0",
35
35
  "@prostojs/mate": "^0.3.3",
36
36
  "@prostojs/logger": "^0.4.3",
37
- "@wooksjs/event-core": "^0.5.18",
37
+ "@wooksjs/event-core": "^0.5.19",
38
38
  "hookable": "^5.5.3",
39
- "wooks": "^0.5.18"
39
+ "wooks": "^0.5.19"
40
40
  },
41
41
  "author": "Artem Maltsev",
42
42
  "license": "MIT",