@treatwell/moleculer-essentials 2.0.0-beta.3 → 2.0.0-beta.5

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/README.md CHANGED
@@ -16,6 +16,9 @@
16
16
  - [License](#license)
17
17
  <!-- TOC -->
18
18
 
19
+ > [!WARNING]
20
+ > Starting v2.0.0-beta.4, this package is only compatible with moleculer v0.15+
21
+
19
22
  ## Purpose
20
23
 
21
24
  `@treatwell/moleculer-essentials` is a collection of essential utilities and helpers for building
package/dist/index.cjs CHANGED
@@ -30,6 +30,16 @@ function getSchemaFromMoleculer(schema) {
30
30
  }
31
31
  return void 0;
32
32
  }
33
+ function getContextSchemaField(ctx, prop) {
34
+ if (!ctx) {
35
+ return;
36
+ }
37
+ const schema = ctx.action ?? ctx.event;
38
+ if (!schema) {
39
+ return;
40
+ }
41
+ return schema[prop];
42
+ }
33
43
 
34
44
  class RefExtractor {
35
45
  refs = /* @__PURE__ */ new Map();
@@ -730,8 +740,6 @@ class AjvExtractor extends RefExtractor {
730
740
  class AjvValidator extends moleculer.Validators.Base {
731
741
  modes;
732
742
  defaultMode;
733
- // broker is a property of the base class
734
- broker;
735
743
  zodValidator;
736
744
  /**
737
745
  * Cache of compiled validation functions.
@@ -739,7 +747,7 @@ class AjvValidator extends moleculer.Validators.Base {
739
747
  */
740
748
  compiledFns = /* @__PURE__ */ new WeakMap();
741
749
  constructor(opts, defaultMode, zodValidator) {
742
- super();
750
+ super({});
743
751
  this.defaultMode = defaultMode;
744
752
  this.zodValidator = zodValidator;
745
753
  this.modes = /* @__PURE__ */ new Map();
@@ -795,8 +803,10 @@ class AjvValidator extends moleculer.Validators.Base {
795
803
  }
796
804
  const { validator, extractor } = validatorMode;
797
805
  const refSchema = extractor.extract(schema);
798
- const fn = (params, ctx) => {
799
- if (!ctx?.action?.disableTransforms) {
806
+ const fn = (params, opts) => {
807
+ const ctx = opts?.meta.ctx;
808
+ const disableTransforms = getContextSchemaField(ctx, "disableTransforms");
809
+ if (!disableTransforms) {
800
810
  applyBeforeTransforms(schema, params);
801
811
  }
802
812
  const validate = validator.compile(refSchema);
@@ -812,7 +822,7 @@ class AjvValidator extends moleculer.Validators.Base {
812
822
  validate.errors || []
813
823
  );
814
824
  }
815
- if (!ctx?.action?.disableTransforms) {
825
+ if (!disableTransforms) {
816
826
  applyAfterTransforms(schema, params);
817
827
  }
818
828
  return true;
@@ -868,7 +878,7 @@ ${(errors || []).map(
868
878
  }
869
879
  const validate = this.compile(schema, action.validatorMode);
870
880
  return async (ctx) => {
871
- validate(ctx.params != null ? ctx.params : {}, ctx);
881
+ validate(ctx.params != null ? ctx.params : {}, { meta: { ctx } });
872
882
  return handler(ctx);
873
883
  };
874
884
  },
@@ -885,15 +895,21 @@ ${(errors || []).map(
885
895
  }
886
896
  const validate = this.compile(schema, event.validatorMode);
887
897
  return async (ctx) => {
888
- validate(ctx.params != null ? ctx.params : {}, ctx);
898
+ validate(ctx.params != null ? ctx.params : {}, { meta: { ctx } });
889
899
  return handler(ctx);
890
900
  };
891
901
  }
892
902
  };
893
903
  }
904
+ convertSchemaToMoleculer() {
905
+ throw new Error("Not implemented");
906
+ }
894
907
  }
895
908
 
896
909
  class ZodValidator extends moleculer.Validators.Base {
910
+ constructor() {
911
+ super({});
912
+ }
897
913
  compile() {
898
914
  throw new Error("compile should not be used, use validate instead");
899
915
  }
@@ -916,6 +932,7 @@ ${v4.z.prettifyError(res.error)}`,
916
932
  middleware() {
917
933
  return {
918
934
  name: "Validator",
935
+ // @ts-expect-error Moleculer wants action.params to be an object
919
936
  localAction: (handler, action) => {
920
937
  const schema = getSchemaFromMoleculer(action.params);
921
938
  if (!schema) {
@@ -926,6 +943,7 @@ ${v4.z.prettifyError(res.error)}`,
926
943
  return handler(ctx);
927
944
  };
928
945
  },
946
+ // @ts-expect-error Moleculer wants action.params to be an object
929
947
  localEvent: (handler, event) => {
930
948
  const schema = getSchemaFromMoleculer(event.params);
931
949
  if (!schema) {
@@ -938,6 +956,9 @@ ${v4.z.prettifyError(res.error)}`,
938
956
  }
939
957
  };
940
958
  }
959
+ convertSchemaToMoleculer() {
960
+ throw new Error("Not implemented");
961
+ }
941
962
  }
942
963
 
943
964
  class ContextFactory extends moleculer.Context {
@@ -1316,18 +1337,18 @@ function HealthCheckMiddleware(_opts) {
1316
1337
  });
1317
1338
  },
1318
1339
  // After broker started
1319
- started() {
1340
+ async started() {
1320
1341
  const timeout = setTimeout(() => {
1321
1342
  state = "up";
1322
1343
  }, opts.startDebounce);
1323
1344
  timeout.unref();
1324
1345
  },
1325
1346
  // Before broker stopping
1326
- stopping() {
1347
+ async stopping() {
1327
1348
  state = "stopping";
1328
1349
  },
1329
1350
  // After broker stopped
1330
- stopped() {
1351
+ async stopped() {
1331
1352
  state = "down";
1332
1353
  server.close();
1333
1354
  }
@@ -1336,23 +1357,27 @@ function HealthCheckMiddleware(_opts) {
1336
1357
 
1337
1358
  function flattenTags(obj, convertToString = false, path = "") {
1338
1359
  if (!obj) return null;
1339
- return Object.keys(obj).reduce((res, k) => {
1340
- const o = obj[k];
1341
- const pp = (path ? `${path}.` : "") + k;
1342
- if (compat.isObject(o)) {
1343
- if ("toHexString" in o) {
1344
- res[pp] = o.toString();
1345
- } else {
1346
- Object.assign(res, flattenTags(o, convertToString, pp));
1360
+ return Object.keys(obj).reduce(
1361
+ (res, k) => {
1362
+ const o = obj[k];
1363
+ const pp = (path ? `${path}.` : "") + k;
1364
+ if (compat.isObject(o)) {
1365
+ if ("toHexString" in o) {
1366
+ res[pp] = o.toString();
1367
+ } else {
1368
+ Object.assign(res, flattenTags(o, convertToString, pp));
1369
+ }
1370
+ } else if (o !== void 0 && o !== null) {
1371
+ res[pp] = convertToString ? String(o) : o;
1347
1372
  }
1348
- } else if (o !== void 0 && o !== null) {
1349
- res[pp] = convertToString ? String(o) : o;
1350
- }
1351
- return res;
1352
- }, {});
1373
+ return res;
1374
+ },
1375
+ {}
1376
+ );
1353
1377
  }
1354
1378
 
1355
1379
  class NewrelicTraceExporter extends moleculer.TracerExporters.Base {
1380
+ opts = {};
1356
1381
  queue;
1357
1382
  timer = null;
1358
1383
  defaultTags = {};
@@ -1372,11 +1397,11 @@ class NewrelicTraceExporter extends moleculer.TracerExporters.Base {
1372
1397
  */
1373
1398
  init(tracer) {
1374
1399
  super.init(tracer);
1375
- if (this.opts.interval > 0) {
1400
+ if (this.opts.interval && this.opts.interval > 0) {
1376
1401
  this.timer = setInterval(() => this.flush(), this.opts.interval * 1e3);
1377
1402
  this.timer.unref();
1378
1403
  }
1379
- this.defaultTags = typeof this.opts.defaultTags === "function" ? this.opts.defaultTags.call(this, tracer) : this.opts.defaultTags;
1404
+ this.defaultTags = (typeof this.opts.defaultTags === "function" ? this.opts.defaultTags.call(this, tracer) : this.opts.defaultTags) || null;
1380
1405
  if (this.defaultTags) {
1381
1406
  this.defaultTags = flattenTags(this.defaultTags, true);
1382
1407
  }
@@ -1459,7 +1484,6 @@ class NewrelicTraceExporter extends moleculer.TracerExporters.Base {
1459
1484
  "duration.ms": span.duration,
1460
1485
  name: span.name,
1461
1486
  "parent.id": span.parentID,
1462
- // @ts-expect-error fullName isn't declared on span yet
1463
1487
  "service.name": span.service?.fullName || null,
1464
1488
  ...flattenTags(span.tags, true),
1465
1489
  ...flattenTags(this.errorToObject(span.error), true, "error") || {}
@@ -1469,9 +1493,7 @@ class NewrelicTraceExporter extends moleculer.TracerExporters.Base {
1469
1493
  }
1470
1494
 
1471
1495
  class NewrelicMetricsReporter extends moleculer.MetricReporters.Base {
1472
- // Those fields are not declared on the Base class.
1473
- registry;
1474
- logger;
1496
+ opts = {};
1475
1497
  timer = null;
1476
1498
  defaultTags = {};
1477
1499
  constructor(opts) {
@@ -1487,7 +1509,7 @@ class NewrelicMetricsReporter extends moleculer.MetricReporters.Base {
1487
1509
  */
1488
1510
  init(registry) {
1489
1511
  super.init(registry);
1490
- if (this.opts.interval > 0) {
1512
+ if (this.opts.interval && this.opts.interval > 0) {
1491
1513
  this.timer = setInterval(() => this.flush(), this.opts.interval * 1e3);
1492
1514
  this.timer.unref();
1493
1515
  }
@@ -1589,7 +1611,7 @@ class NewrelicMetricsReporter extends moleculer.MetricReporters.Base {
1589
1611
  attributes: labels,
1590
1612
  timestamp,
1591
1613
  value: { count, sum, min: min || 0, max: max || 0 },
1592
- "interval.ms": this.opts.interval * 1e3
1614
+ "interval.ms": (this.opts.interval || 0) * 1e3
1593
1615
  });
1594
1616
  if (buckets) {
1595
1617
  Object.entries(buckets).forEach(([key, val]) => {
package/dist/index.d.cts CHANGED
@@ -1,10 +1,9 @@
1
- import { S as SomeJSONSchema, J as JSONSchemaType, C as CustomActionSchema, A as Alias, a as CustomServiceSchema, D as Document, b as SchemaObject, O as OperationObject, R as ReferenceObject, c as CreateLoggerOptions, M as MoleculerLoggerConfigOptions } from './types-CSx6iC1f.cjs';
2
- export { d as AjvValidator, e as ApiKeySecurityScheme, f as CallbackObject, g as ComponentsObject, h as ContactObject, i as ContextFactory, E as EncodingObject, j as ExampleObject, k as ExternalDocumentationObject, H as HeaderObject, l as HttpSecurityScheme, I as InfoObject, m as InternalCallbackServiceThis, n as InternalObjectServiceThis, L as LicenseObject, o as LinkObject, p as MediaTypeObject, q as OAuth2SecurityScheme, r as OpenIdSecurityScheme, P as ParameterBaseObject, s as ParameterObject, t as PathItemObject, u as PathsObject, v as PropertiesSchema, w as RequestBodyObject, x as RequiredMembers, y as ResponseObject, z as ResponsesObject, B as SecurityRequirementObject, F as SecuritySchemeObject, G as ServerObject, K as ServerVariableObject, T as TagObject, N as Transform, Q as TransformField, U as TransformLevel, V as TransformMap, W as Transformer, X as ValidationSchema, Z as ZodValidator } from './types-CSx6iC1f.cjs';
1
+ import { S as SomeJSONSchema, J as JSONSchemaType, C as CustomActionSchema, A as Alias, a as CustomServiceSchema, D as Document, b as SchemaObject, O as OperationObject, R as ReferenceObject, c as CreateLoggerOptions, M as MoleculerLoggerConfigOptions } from './types-DLBNHgt4.cjs';
2
+ export { d as AjvValidator, e as ApiKeySecurityScheme, f as CallbackObject, g as ComponentsObject, h as ContactObject, i as ContextFactory, E as EncodingObject, j as ExampleObject, k as ExternalDocumentationObject, H as HeaderObject, l as HttpSecurityScheme, I as InfoObject, m as InternalCallbackServiceThis, n as InternalObjectServiceThis, L as LicenseObject, o as LinkObject, p as MediaTypeObject, q as OAuth2SecurityScheme, r as OpenIdSecurityScheme, P as ParameterBaseObject, s as ParameterObject, t as PathItemObject, u as PathsObject, v as PropertiesSchema, w as RequestBodyObject, x as RequiredMembers, y as ResponseObject, z as ResponsesObject, B as SecurityRequirementObject, F as SecuritySchemeObject, G as ServerObject, K as ServerVariableObject, T as TagObject, N as Transform, Q as TransformField, U as TransformLevel, V as TransformMap, W as Transformer, X as ValidationSchema, Z as ZodValidator } from './types-DLBNHgt4.cjs';
3
3
  import { ObjectId } from 'bson';
4
4
  import { z, ZodType } from 'zod/v4';
5
5
  import { Ajv2019 } from 'ajv/dist/2019.js';
6
- import * as Moleculer from 'moleculer';
7
- import { Context, ServiceSchema, ServiceSettingSchema, Service, ServiceBroker, BrokerOptions, Middleware, LoggerConfig, TracerExporters, LoggerInstance, Tracer, Span, MetricReporters, MetricRegistry, MetricReporterOptions } from 'moleculer';
6
+ import { Errors, Context, ServiceSchema, ServiceSettingSchema, Service, ServiceBroker, BrokerOptions, Middleware, LoggerConfig, TracerExporters, Logger as Logger$1, Tracer, Span, MetricReporters, MetricRegistry } from 'moleculer';
8
7
  import { Logger } from 'pino';
9
8
  import 'pino-pretty';
10
9
 
@@ -60,7 +59,7 @@ declare function OpenAPIMixin(options: OpenAPIMixinOptions): Partial<CustomServi
60
59
  description: string;
61
60
  content: {
62
61
  'application/json': {
63
- schema: JSONSchemaType<Omit<Moleculer.Errors.MoleculerServerError, "cause">>;
62
+ schema: JSONSchemaType<Omit<Errors.MoleculerServerError, "cause">>;
64
63
  };
65
64
  };
66
65
  };
@@ -92,7 +91,7 @@ declare function OpenAPIMixin(options: OpenAPIMixinOptions): Partial<CustomServi
92
91
  description: string;
93
92
  content: {
94
93
  'application/json': {
95
- schema: JSONSchemaType<Omit<Moleculer.Errors.ValidationError, "cause">>;
94
+ schema: JSONSchemaType<Omit<Errors.ValidationError, "cause">>;
96
95
  };
97
96
  };
98
97
  };
@@ -271,7 +270,7 @@ declare function createLogger(opts?: CreateLoggerOptions): Logger;
271
270
  declare function createLoggerConfig(opts?: MoleculerLoggerConfigOptions): LoggerConfig;
272
271
 
273
272
  type NewrelicTraceExporterOptions = {
274
- logger?: LoggerInstance;
273
+ logger?: Logger$1;
275
274
  safetyTags?: boolean;
276
275
  /**
277
276
  * Base URL for NewRelic server.
@@ -292,7 +291,7 @@ type NewrelicTraceExporterOptions = {
292
291
  /**
293
292
  * Default span tags.
294
293
  */
295
- defaultTags?: Record<string, unknown> | (() => Record<string, unknown>);
294
+ defaultTags?: Record<string, unknown> | ((tracer?: unknown) => Record<string, unknown>);
296
295
  };
297
296
  /**
298
297
  * >>> Hard copy of the moleculer NewRelic provider. It didn't handle errors correctly
@@ -303,6 +302,7 @@ type NewrelicTraceExporterOptions = {
303
302
  * API v2: https://zipkin.io/zipkin-api/#/
304
303
  */
305
304
  declare class NewrelicTraceExporter extends TracerExporters.Base {
305
+ private readonly opts;
306
306
  private queue;
307
307
  private timer;
308
308
  private defaultTags;
@@ -334,7 +334,7 @@ declare class NewrelicTraceExporter extends TracerExporters.Base {
334
334
  }
335
335
 
336
336
  type DefaultTags = Record<string, unknown> | ((registry: MetricRegistry) => Record<string, unknown>);
337
- type NewrelicMetricsOptions = MetricReporterOptions & {
337
+ type NewrelicMetricsOptions = MetricReporters.Base.MetricReporterOptions & {
338
338
  /**
339
339
  * Base URL for NewRelic server.
340
340
  */
@@ -358,8 +358,7 @@ type NewrelicMetricsOptions = MetricReporterOptions & {
358
358
  * NewRelic API: https://docs.newrelic.com/docs/data-apis/understand-data/metric-data/metric-data-type/
359
359
  */
360
360
  declare class NewrelicMetricsReporter extends MetricReporters.Base {
361
- registry: MetricRegistry;
362
- logger: LoggerInstance;
361
+ private readonly opts;
363
362
  private timer;
364
363
  private defaultTags;
365
364
  constructor(opts: NewrelicMetricsOptions);
package/dist/index.d.mts CHANGED
@@ -1,10 +1,9 @@
1
- import { S as SomeJSONSchema, J as JSONSchemaType, C as CustomActionSchema, A as Alias, a as CustomServiceSchema, D as Document, b as SchemaObject, O as OperationObject, R as ReferenceObject, c as CreateLoggerOptions, M as MoleculerLoggerConfigOptions } from './types-CSx6iC1f.mjs';
2
- export { d as AjvValidator, e as ApiKeySecurityScheme, f as CallbackObject, g as ComponentsObject, h as ContactObject, i as ContextFactory, E as EncodingObject, j as ExampleObject, k as ExternalDocumentationObject, H as HeaderObject, l as HttpSecurityScheme, I as InfoObject, m as InternalCallbackServiceThis, n as InternalObjectServiceThis, L as LicenseObject, o as LinkObject, p as MediaTypeObject, q as OAuth2SecurityScheme, r as OpenIdSecurityScheme, P as ParameterBaseObject, s as ParameterObject, t as PathItemObject, u as PathsObject, v as PropertiesSchema, w as RequestBodyObject, x as RequiredMembers, y as ResponseObject, z as ResponsesObject, B as SecurityRequirementObject, F as SecuritySchemeObject, G as ServerObject, K as ServerVariableObject, T as TagObject, N as Transform, Q as TransformField, U as TransformLevel, V as TransformMap, W as Transformer, X as ValidationSchema, Z as ZodValidator } from './types-CSx6iC1f.mjs';
1
+ import { S as SomeJSONSchema, J as JSONSchemaType, C as CustomActionSchema, A as Alias, a as CustomServiceSchema, D as Document, b as SchemaObject, O as OperationObject, R as ReferenceObject, c as CreateLoggerOptions, M as MoleculerLoggerConfigOptions } from './types-DLBNHgt4.mjs';
2
+ export { d as AjvValidator, e as ApiKeySecurityScheme, f as CallbackObject, g as ComponentsObject, h as ContactObject, i as ContextFactory, E as EncodingObject, j as ExampleObject, k as ExternalDocumentationObject, H as HeaderObject, l as HttpSecurityScheme, I as InfoObject, m as InternalCallbackServiceThis, n as InternalObjectServiceThis, L as LicenseObject, o as LinkObject, p as MediaTypeObject, q as OAuth2SecurityScheme, r as OpenIdSecurityScheme, P as ParameterBaseObject, s as ParameterObject, t as PathItemObject, u as PathsObject, v as PropertiesSchema, w as RequestBodyObject, x as RequiredMembers, y as ResponseObject, z as ResponsesObject, B as SecurityRequirementObject, F as SecuritySchemeObject, G as ServerObject, K as ServerVariableObject, T as TagObject, N as Transform, Q as TransformField, U as TransformLevel, V as TransformMap, W as Transformer, X as ValidationSchema, Z as ZodValidator } from './types-DLBNHgt4.mjs';
3
3
  import { ObjectId } from 'bson';
4
4
  import { z, ZodType } from 'zod/v4';
5
5
  import { Ajv2019 } from 'ajv/dist/2019.js';
6
- import * as Moleculer from 'moleculer';
7
- import { Context, ServiceSchema, ServiceSettingSchema, Service, ServiceBroker, BrokerOptions, Middleware, LoggerConfig, TracerExporters, LoggerInstance, Tracer, Span, MetricReporters, MetricRegistry, MetricReporterOptions } from 'moleculer';
6
+ import { Errors, Context, ServiceSchema, ServiceSettingSchema, Service, ServiceBroker, BrokerOptions, Middleware, LoggerConfig, TracerExporters, Logger as Logger$1, Tracer, Span, MetricReporters, MetricRegistry } from 'moleculer';
8
7
  import { Logger } from 'pino';
9
8
  import 'pino-pretty';
10
9
 
@@ -60,7 +59,7 @@ declare function OpenAPIMixin(options: OpenAPIMixinOptions): Partial<CustomServi
60
59
  description: string;
61
60
  content: {
62
61
  'application/json': {
63
- schema: JSONSchemaType<Omit<Moleculer.Errors.MoleculerServerError, "cause">>;
62
+ schema: JSONSchemaType<Omit<Errors.MoleculerServerError, "cause">>;
64
63
  };
65
64
  };
66
65
  };
@@ -92,7 +91,7 @@ declare function OpenAPIMixin(options: OpenAPIMixinOptions): Partial<CustomServi
92
91
  description: string;
93
92
  content: {
94
93
  'application/json': {
95
- schema: JSONSchemaType<Omit<Moleculer.Errors.ValidationError, "cause">>;
94
+ schema: JSONSchemaType<Omit<Errors.ValidationError, "cause">>;
96
95
  };
97
96
  };
98
97
  };
@@ -271,7 +270,7 @@ declare function createLogger(opts?: CreateLoggerOptions): Logger;
271
270
  declare function createLoggerConfig(opts?: MoleculerLoggerConfigOptions): LoggerConfig;
272
271
 
273
272
  type NewrelicTraceExporterOptions = {
274
- logger?: LoggerInstance;
273
+ logger?: Logger$1;
275
274
  safetyTags?: boolean;
276
275
  /**
277
276
  * Base URL for NewRelic server.
@@ -292,7 +291,7 @@ type NewrelicTraceExporterOptions = {
292
291
  /**
293
292
  * Default span tags.
294
293
  */
295
- defaultTags?: Record<string, unknown> | (() => Record<string, unknown>);
294
+ defaultTags?: Record<string, unknown> | ((tracer?: unknown) => Record<string, unknown>);
296
295
  };
297
296
  /**
298
297
  * >>> Hard copy of the moleculer NewRelic provider. It didn't handle errors correctly
@@ -303,6 +302,7 @@ type NewrelicTraceExporterOptions = {
303
302
  * API v2: https://zipkin.io/zipkin-api/#/
304
303
  */
305
304
  declare class NewrelicTraceExporter extends TracerExporters.Base {
305
+ private readonly opts;
306
306
  private queue;
307
307
  private timer;
308
308
  private defaultTags;
@@ -334,7 +334,7 @@ declare class NewrelicTraceExporter extends TracerExporters.Base {
334
334
  }
335
335
 
336
336
  type DefaultTags = Record<string, unknown> | ((registry: MetricRegistry) => Record<string, unknown>);
337
- type NewrelicMetricsOptions = MetricReporterOptions & {
337
+ type NewrelicMetricsOptions = MetricReporters.Base.MetricReporterOptions & {
338
338
  /**
339
339
  * Base URL for NewRelic server.
340
340
  */
@@ -358,8 +358,7 @@ type NewrelicMetricsOptions = MetricReporterOptions & {
358
358
  * NewRelic API: https://docs.newrelic.com/docs/data-apis/understand-data/metric-data/metric-data-type/
359
359
  */
360
360
  declare class NewrelicMetricsReporter extends MetricReporters.Base {
361
- registry: MetricRegistry;
362
- logger: LoggerInstance;
361
+ private readonly opts;
363
362
  private timer;
364
363
  private defaultTags;
365
364
  constructor(opts: NewrelicMetricsOptions);
package/dist/index.mjs CHANGED
@@ -30,6 +30,16 @@ function getSchemaFromMoleculer(schema) {
30
30
  }
31
31
  return void 0;
32
32
  }
33
+ function getContextSchemaField(ctx, prop) {
34
+ if (!ctx) {
35
+ return;
36
+ }
37
+ const schema = ctx.action ?? ctx.event;
38
+ if (!schema) {
39
+ return;
40
+ }
41
+ return schema[prop];
42
+ }
33
43
 
34
44
  class RefExtractor {
35
45
  refs = /* @__PURE__ */ new Map();
@@ -730,8 +740,6 @@ class AjvExtractor extends RefExtractor {
730
740
  class AjvValidator extends Validators.Base {
731
741
  modes;
732
742
  defaultMode;
733
- // broker is a property of the base class
734
- broker;
735
743
  zodValidator;
736
744
  /**
737
745
  * Cache of compiled validation functions.
@@ -739,7 +747,7 @@ class AjvValidator extends Validators.Base {
739
747
  */
740
748
  compiledFns = /* @__PURE__ */ new WeakMap();
741
749
  constructor(opts, defaultMode, zodValidator) {
742
- super();
750
+ super({});
743
751
  this.defaultMode = defaultMode;
744
752
  this.zodValidator = zodValidator;
745
753
  this.modes = /* @__PURE__ */ new Map();
@@ -795,8 +803,10 @@ class AjvValidator extends Validators.Base {
795
803
  }
796
804
  const { validator, extractor } = validatorMode;
797
805
  const refSchema = extractor.extract(schema);
798
- const fn = (params, ctx) => {
799
- if (!ctx?.action?.disableTransforms) {
806
+ const fn = (params, opts) => {
807
+ const ctx = opts?.meta.ctx;
808
+ const disableTransforms = getContextSchemaField(ctx, "disableTransforms");
809
+ if (!disableTransforms) {
800
810
  applyBeforeTransforms(schema, params);
801
811
  }
802
812
  const validate = validator.compile(refSchema);
@@ -812,7 +822,7 @@ class AjvValidator extends Validators.Base {
812
822
  validate.errors || []
813
823
  );
814
824
  }
815
- if (!ctx?.action?.disableTransforms) {
825
+ if (!disableTransforms) {
816
826
  applyAfterTransforms(schema, params);
817
827
  }
818
828
  return true;
@@ -868,7 +878,7 @@ ${(errors || []).map(
868
878
  }
869
879
  const validate = this.compile(schema, action.validatorMode);
870
880
  return async (ctx) => {
871
- validate(ctx.params != null ? ctx.params : {}, ctx);
881
+ validate(ctx.params != null ? ctx.params : {}, { meta: { ctx } });
872
882
  return handler(ctx);
873
883
  };
874
884
  },
@@ -885,15 +895,21 @@ ${(errors || []).map(
885
895
  }
886
896
  const validate = this.compile(schema, event.validatorMode);
887
897
  return async (ctx) => {
888
- validate(ctx.params != null ? ctx.params : {}, ctx);
898
+ validate(ctx.params != null ? ctx.params : {}, { meta: { ctx } });
889
899
  return handler(ctx);
890
900
  };
891
901
  }
892
902
  };
893
903
  }
904
+ convertSchemaToMoleculer() {
905
+ throw new Error("Not implemented");
906
+ }
894
907
  }
895
908
 
896
909
  class ZodValidator extends Validators.Base {
910
+ constructor() {
911
+ super({});
912
+ }
897
913
  compile() {
898
914
  throw new Error("compile should not be used, use validate instead");
899
915
  }
@@ -916,6 +932,7 @@ ${z.prettifyError(res.error)}`,
916
932
  middleware() {
917
933
  return {
918
934
  name: "Validator",
935
+ // @ts-expect-error Moleculer wants action.params to be an object
919
936
  localAction: (handler, action) => {
920
937
  const schema = getSchemaFromMoleculer(action.params);
921
938
  if (!schema) {
@@ -926,6 +943,7 @@ ${z.prettifyError(res.error)}`,
926
943
  return handler(ctx);
927
944
  };
928
945
  },
946
+ // @ts-expect-error Moleculer wants action.params to be an object
929
947
  localEvent: (handler, event) => {
930
948
  const schema = getSchemaFromMoleculer(event.params);
931
949
  if (!schema) {
@@ -938,6 +956,9 @@ ${z.prettifyError(res.error)}`,
938
956
  }
939
957
  };
940
958
  }
959
+ convertSchemaToMoleculer() {
960
+ throw new Error("Not implemented");
961
+ }
941
962
  }
942
963
 
943
964
  class ContextFactory extends Context {
@@ -1316,18 +1337,18 @@ function HealthCheckMiddleware(_opts) {
1316
1337
  });
1317
1338
  },
1318
1339
  // After broker started
1319
- started() {
1340
+ async started() {
1320
1341
  const timeout = setTimeout(() => {
1321
1342
  state = "up";
1322
1343
  }, opts.startDebounce);
1323
1344
  timeout.unref();
1324
1345
  },
1325
1346
  // Before broker stopping
1326
- stopping() {
1347
+ async stopping() {
1327
1348
  state = "stopping";
1328
1349
  },
1329
1350
  // After broker stopped
1330
- stopped() {
1351
+ async stopped() {
1331
1352
  state = "down";
1332
1353
  server.close();
1333
1354
  }
@@ -1336,23 +1357,27 @@ function HealthCheckMiddleware(_opts) {
1336
1357
 
1337
1358
  function flattenTags(obj, convertToString = false, path = "") {
1338
1359
  if (!obj) return null;
1339
- return Object.keys(obj).reduce((res, k) => {
1340
- const o = obj[k];
1341
- const pp = (path ? `${path}.` : "") + k;
1342
- if (isObject(o)) {
1343
- if ("toHexString" in o) {
1344
- res[pp] = o.toString();
1345
- } else {
1346
- Object.assign(res, flattenTags(o, convertToString, pp));
1360
+ return Object.keys(obj).reduce(
1361
+ (res, k) => {
1362
+ const o = obj[k];
1363
+ const pp = (path ? `${path}.` : "") + k;
1364
+ if (isObject(o)) {
1365
+ if ("toHexString" in o) {
1366
+ res[pp] = o.toString();
1367
+ } else {
1368
+ Object.assign(res, flattenTags(o, convertToString, pp));
1369
+ }
1370
+ } else if (o !== void 0 && o !== null) {
1371
+ res[pp] = convertToString ? String(o) : o;
1347
1372
  }
1348
- } else if (o !== void 0 && o !== null) {
1349
- res[pp] = convertToString ? String(o) : o;
1350
- }
1351
- return res;
1352
- }, {});
1373
+ return res;
1374
+ },
1375
+ {}
1376
+ );
1353
1377
  }
1354
1378
 
1355
1379
  class NewrelicTraceExporter extends TracerExporters.Base {
1380
+ opts = {};
1356
1381
  queue;
1357
1382
  timer = null;
1358
1383
  defaultTags = {};
@@ -1372,11 +1397,11 @@ class NewrelicTraceExporter extends TracerExporters.Base {
1372
1397
  */
1373
1398
  init(tracer) {
1374
1399
  super.init(tracer);
1375
- if (this.opts.interval > 0) {
1400
+ if (this.opts.interval && this.opts.interval > 0) {
1376
1401
  this.timer = setInterval(() => this.flush(), this.opts.interval * 1e3);
1377
1402
  this.timer.unref();
1378
1403
  }
1379
- this.defaultTags = typeof this.opts.defaultTags === "function" ? this.opts.defaultTags.call(this, tracer) : this.opts.defaultTags;
1404
+ this.defaultTags = (typeof this.opts.defaultTags === "function" ? this.opts.defaultTags.call(this, tracer) : this.opts.defaultTags) || null;
1380
1405
  if (this.defaultTags) {
1381
1406
  this.defaultTags = flattenTags(this.defaultTags, true);
1382
1407
  }
@@ -1459,7 +1484,6 @@ class NewrelicTraceExporter extends TracerExporters.Base {
1459
1484
  "duration.ms": span.duration,
1460
1485
  name: span.name,
1461
1486
  "parent.id": span.parentID,
1462
- // @ts-expect-error fullName isn't declared on span yet
1463
1487
  "service.name": span.service?.fullName || null,
1464
1488
  ...flattenTags(span.tags, true),
1465
1489
  ...flattenTags(this.errorToObject(span.error), true, "error") || {}
@@ -1469,9 +1493,7 @@ class NewrelicTraceExporter extends TracerExporters.Base {
1469
1493
  }
1470
1494
 
1471
1495
  class NewrelicMetricsReporter extends MetricReporters.Base {
1472
- // Those fields are not declared on the Base class.
1473
- registry;
1474
- logger;
1496
+ opts = {};
1475
1497
  timer = null;
1476
1498
  defaultTags = {};
1477
1499
  constructor(opts) {
@@ -1487,7 +1509,7 @@ class NewrelicMetricsReporter extends MetricReporters.Base {
1487
1509
  */
1488
1510
  init(registry) {
1489
1511
  super.init(registry);
1490
- if (this.opts.interval > 0) {
1512
+ if (this.opts.interval && this.opts.interval > 0) {
1491
1513
  this.timer = setInterval(() => this.flush(), this.opts.interval * 1e3);
1492
1514
  this.timer.unref();
1493
1515
  }
@@ -1589,7 +1611,7 @@ class NewrelicMetricsReporter extends MetricReporters.Base {
1589
1611
  attributes: labels,
1590
1612
  timestamp,
1591
1613
  value: { count, sum, min: min || 0, max: max || 0 },
1592
- "interval.ms": this.opts.interval * 1e3
1614
+ "interval.ms": (this.opts.interval || 0) * 1e3
1593
1615
  });
1594
1616
  if (buckets) {
1595
1617
  Object.entries(buckets).forEach(([key, val]) => {
@@ -1,7 +1,7 @@
1
1
  import { Document, ObjectId, WithoutId, InferIdType, Filter, OptionalId, WithId, CountDocumentsOptions, DeleteOptions, FindOneAndDeleteOptions, FindOptions, BulkWriteOptions, FindOneAndUpdateOptions, UpdateOptions, FindOneAndReplaceOptions, CollationOptions, CreateCollectionOptions, MongoClient, CollectionOptions, Collection, UpdateFilter, FindCursor, UpdateResult } from 'mongodb';
2
- import { ActionVisibility, BaseValidator, Errors, Context } from 'moleculer';
2
+ import { ActionVisibility, Validators, Errors, Context } from 'moleculer';
3
3
  import { ZodType, ZodObject } from 'zod/v4';
4
- import { X as ValidationSchema, J as JSONSchemaType, C as CustomActionSchema, a as CustomServiceSchema } from '../types-CSx6iC1f.cjs';
4
+ import { X as ValidationSchema, J as JSONSchemaType, C as CustomActionSchema, a as CustomServiceSchema } from '../types-DLBNHgt4.cjs';
5
5
  import { Readable } from 'stream';
6
6
  import 'bson';
7
7
  import 'ajv/dist/2019.js';
@@ -224,7 +224,7 @@ declare class AjvActionSchemaFactory<TSchema extends Document> implements Action
224
224
  declare function addQueryOps<T>(schema: JSONSchemaType<T>, queryOps: QueryOp[]): JSONSchemaType<unknown>;
225
225
 
226
226
  declare function parseStringifiedQuery<TSchema extends Document>(sQuery?: string): Filter<TSchema>;
227
- declare function parseAndValidateQuery<TSchema extends Document>(validator: BaseValidator, schema: ValidationSchema | ZodType | undefined, sQuery: string | undefined): Filter<TSchema>;
227
+ declare function parseAndValidateQuery<TSchema extends Document>(validator: Validators.Base, schema: ValidationSchema | ZodType | undefined, sQuery: string | undefined): Filter<TSchema>;
228
228
 
229
229
  type DatabaseSoftDeleteScope = 'include-deleted' | 'only-deleted' | 'no-deleted';
230
230
  /**
@@ -1,7 +1,7 @@
1
1
  import { Document, ObjectId, WithoutId, InferIdType, Filter, OptionalId, WithId, CountDocumentsOptions, DeleteOptions, FindOneAndDeleteOptions, FindOptions, BulkWriteOptions, FindOneAndUpdateOptions, UpdateOptions, FindOneAndReplaceOptions, CollationOptions, CreateCollectionOptions, MongoClient, CollectionOptions, Collection, UpdateFilter, FindCursor, UpdateResult } from 'mongodb';
2
- import { ActionVisibility, BaseValidator, Errors, Context } from 'moleculer';
2
+ import { ActionVisibility, Validators, Errors, Context } from 'moleculer';
3
3
  import { ZodType, ZodObject } from 'zod/v4';
4
- import { X as ValidationSchema, J as JSONSchemaType, C as CustomActionSchema, a as CustomServiceSchema } from '../types-CSx6iC1f.mjs';
4
+ import { X as ValidationSchema, J as JSONSchemaType, C as CustomActionSchema, a as CustomServiceSchema } from '../types-DLBNHgt4.mjs';
5
5
  import { Readable } from 'stream';
6
6
  import 'bson';
7
7
  import 'ajv/dist/2019.js';
@@ -224,7 +224,7 @@ declare class AjvActionSchemaFactory<TSchema extends Document> implements Action
224
224
  declare function addQueryOps<T>(schema: JSONSchemaType<T>, queryOps: QueryOp[]): JSONSchemaType<unknown>;
225
225
 
226
226
  declare function parseStringifiedQuery<TSchema extends Document>(sQuery?: string): Filter<TSchema>;
227
- declare function parseAndValidateQuery<TSchema extends Document>(validator: BaseValidator, schema: ValidationSchema | ZodType | undefined, sQuery: string | undefined): Filter<TSchema>;
227
+ declare function parseAndValidateQuery<TSchema extends Document>(validator: Validators.Base, schema: ValidationSchema | ZodType | undefined, sQuery: string | undefined): Filter<TSchema>;
228
228
 
229
229
  type DatabaseSoftDeleteScope = 'include-deleted' | 'only-deleted' | 'no-deleted';
230
230
  /**
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.cjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.cjs';
2
2
  import { buildClient, NodeCachingMaterialsManager } from '@aws-crypto/client-node';
3
3
  import 'moleculer';
4
4
  import 'bson';
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.mjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.mjs';
2
2
  import { buildClient, NodeCachingMaterialsManager } from '@aws-crypto/client-node';
3
3
  import 'moleculer';
4
4
  import 'bson';
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.cjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.cjs';
2
2
  import 'moleculer';
3
3
  import 'bson';
4
4
  import 'zod/v4';
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.mjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.mjs';
2
2
  import 'moleculer';
3
3
  import 'bson';
4
4
  import 'zod/v4';
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.cjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.cjs';
2
2
  import { SignOptions, PrivateKey, VerifyOptions, JwtHeader, SigningKeyCallback } from 'jsonwebtoken';
3
3
  import { Options, JwksClient } from 'jwks-rsa';
4
4
  import { Context } from 'moleculer';
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.mjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.mjs';
2
2
  import { SignOptions, PrivateKey, VerifyOptions, JwtHeader, SigningKeyCallback } from 'jsonwebtoken';
3
3
  import { Options, JwksClient } from 'jwks-rsa';
4
4
  import { Context } from 'moleculer';
@@ -139,6 +139,9 @@ function QueueEventsClient(queueName, opts) {
139
139
  * Same as addJob but will also wait for the job to finish before returning.
140
140
  */
141
141
  async addAndWait(qName, name, data, jOpts, ttl) {
142
+ if (!("addJob" in this)) {
143
+ throw new Error(`Missing QueueClient mixin on service ${this.name}`);
144
+ }
142
145
  const job = await this.addJob(qName, name, data, jOpts);
143
146
  return job.waitUntilFinished(this.getQueueEvents(qName), ttl);
144
147
  },
@@ -146,6 +149,9 @@ function QueueEventsClient(queueName, opts) {
146
149
  * Same as addBulkJob but will also wait for the jobs to finish before returning.
147
150
  */
148
151
  async addBulkAndWait(qName, name, data, jOpts, ttl) {
152
+ if (!("addBulkJob" in this)) {
153
+ throw new Error(`Missing QueueClient mixin on service ${this.name}`);
154
+ }
149
155
  const jobs = await this.addBulkJob(qName, name, data, jOpts);
150
156
  const q = this.getQueueEvents(qName);
151
157
  return Promise.all(jobs.map((j) => j.waitUntilFinished(q, ttl)));
@@ -219,7 +225,7 @@ function QueueFlowProducerMixin(opts) {
219
225
  this[kConnection$1] = connection;
220
226
  },
221
227
  async stopped() {
222
- await this.$flowProducer?.close();
228
+ await this.getFlowProducer()?.close();
223
229
  this[kConnection$1]?.disconnect();
224
230
  }
225
231
  });
@@ -406,7 +412,7 @@ function QueueWorker(queueName, opts, processorOptions = {}) {
406
412
  }
407
413
  },
408
414
  async stopped() {
409
- await this.$worker?.close();
415
+ await this.getWorker()?.close();
410
416
  this[kConnection]?.disconnect();
411
417
  }
412
418
  });
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.cjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.cjs';
2
2
  import { Redis } from 'ioredis';
3
3
  import { QueueOptions, Queue, JobsOptions, Job, QueueEventsOptions, QueueEvents, QueueBaseOptions, FlowProducer, RepeatOptions, WorkerOptions, Worker } from 'bullmq';
4
4
  import { Service } from 'moleculer';
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.mjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.mjs';
2
2
  import { Redis } from 'ioredis';
3
3
  import { QueueOptions, Queue, JobsOptions, Job, QueueEventsOptions, QueueEvents, QueueBaseOptions, FlowProducer, RepeatOptions, WorkerOptions, Worker } from 'bullmq';
4
4
  import { Service } from 'moleculer';
@@ -137,6 +137,9 @@ function QueueEventsClient(queueName, opts) {
137
137
  * Same as addJob but will also wait for the job to finish before returning.
138
138
  */
139
139
  async addAndWait(qName, name, data, jOpts, ttl) {
140
+ if (!("addJob" in this)) {
141
+ throw new Error(`Missing QueueClient mixin on service ${this.name}`);
142
+ }
140
143
  const job = await this.addJob(qName, name, data, jOpts);
141
144
  return job.waitUntilFinished(this.getQueueEvents(qName), ttl);
142
145
  },
@@ -144,6 +147,9 @@ function QueueEventsClient(queueName, opts) {
144
147
  * Same as addBulkJob but will also wait for the jobs to finish before returning.
145
148
  */
146
149
  async addBulkAndWait(qName, name, data, jOpts, ttl) {
150
+ if (!("addBulkJob" in this)) {
151
+ throw new Error(`Missing QueueClient mixin on service ${this.name}`);
152
+ }
147
153
  const jobs = await this.addBulkJob(qName, name, data, jOpts);
148
154
  const q = this.getQueueEvents(qName);
149
155
  return Promise.all(jobs.map((j) => j.waitUntilFinished(q, ttl)));
@@ -217,7 +223,7 @@ function QueueFlowProducerMixin(opts) {
217
223
  this[kConnection$1] = connection;
218
224
  },
219
225
  async stopped() {
220
- await this.$flowProducer?.close();
226
+ await this.getFlowProducer()?.close();
221
227
  this[kConnection$1]?.disconnect();
222
228
  }
223
229
  });
@@ -404,7 +410,7 @@ function QueueWorker(queueName, opts, processorOptions = {}) {
404
410
  }
405
411
  },
406
412
  async stopped() {
407
- await this.$worker?.close();
413
+ await this.getWorker()?.close();
408
414
  this[kConnection]?.disconnect();
409
415
  }
410
416
  });
@@ -36,8 +36,8 @@ function RedisMixin(options, { reuseClient = true, getOptions } = {}) {
36
36
  this.setClientToStore(
37
37
  "redis",
38
38
  key,
39
- this.redis,
40
- () => this.redis?.disconnect()
39
+ this.getRedis(),
40
+ () => this.getRedis()?.disconnect()
41
41
  );
42
42
  }
43
43
  },
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.cjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.cjs';
2
2
  import { RedisOptions, Redis } from 'ioredis';
3
3
  import { Service } from 'moleculer';
4
4
  import 'bson';
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.mjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.mjs';
2
2
  import { RedisOptions, Redis } from 'ioredis';
3
3
  import { Service } from 'moleculer';
4
4
  import 'bson';
@@ -34,8 +34,8 @@ function RedisMixin(options, { reuseClient = true, getOptions } = {}) {
34
34
  this.setClientToStore(
35
35
  "redis",
36
36
  key,
37
- this.redis,
38
- () => this.redis?.disconnect()
37
+ this.getRedis(),
38
+ () => this.getRedis()?.disconnect()
39
39
  );
40
40
  }
41
41
  },
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.cjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.cjs';
2
2
  import { Service } from 'moleculer';
3
3
  import { RedisOptions, Redis } from 'ioredis';
4
4
  import Redlock from 'redlock';
@@ -1,4 +1,4 @@
1
- import { a as CustomServiceSchema } from '../types-CSx6iC1f.mjs';
1
+ import { a as CustomServiceSchema } from '../types-DLBNHgt4.mjs';
2
2
  import { Service } from 'moleculer';
3
3
  import { RedisOptions, Redis } from 'ioredis';
4
4
  import Redlock from 'redlock';
@@ -1,8 +1,8 @@
1
- import Moleculer__default, { RestSchema, ActionVisibility, Service, ActionCacheOptions, Context, TracingActionOptions, BulkheadOptions, BrokerCircuitBreakerOptions, RetryPolicyOptions, FallbackHandler, ActionHooks, Validators, ActionHandler, ActionSchema, ServiceEvent, ServiceDependency, ServiceHooks, GenericObject, ServiceBroker, Endpoint } from 'moleculer';
1
+ import { ActionSchema, Context, Validators, Middleware, EventSchema, Service, ServiceHooks, Logger, ServiceBroker, ActionEndpoint, EventEndpoint, Span } from 'moleculer';
2
2
  import { ObjectId } from 'bson';
3
3
  import { ZodType, z } from 'zod/v4';
4
4
  import { Options, ErrorObject } from 'ajv/dist/2019.js';
5
- import { LoggerOptions, Logger } from 'pino';
5
+ import { LoggerOptions, Logger as Logger$1 } from 'pino';
6
6
  import { PrettyOptions } from 'pino-pretty';
7
7
 
8
8
  type UnionToIntersection$1<U> = (U extends any ? (_: U) => void : never) extends (_: infer I) => void ? I : never;
@@ -333,24 +333,14 @@ interface Document {
333
333
  'x-express-openapi-validation-strict'?: boolean;
334
334
  }
335
335
 
336
- interface CustomActionSchema<T = unknown> {
337
- name?: string;
338
- rest?: RestSchema | RestSchema[] | string | string[];
339
- visibility?: ActionVisibility;
340
- service?: Service;
341
- cache?: boolean | ActionCacheOptions;
342
- handler?: (ctx: Context<never, never>) => Promise<T> | T;
343
- tracing?: boolean | TracingActionOptions;
344
- bulkhead?: BulkheadOptions;
345
- circuitBreaker?: BrokerCircuitBreakerOptions;
346
- retryPolicy?: RetryPolicyOptions;
347
- fallback?: string | FallbackHandler;
348
- hooks?: ActionHooks;
336
+ interface CustomActionSchema<T = unknown> extends Omit<ActionSchema, 'params' | 'handler'> {
349
337
  params?: unknown;
338
+ handler?: (ctx: Context<never, never>) => Promise<T> | T;
350
339
  disableTransforms?: boolean;
351
340
  openAPINames?: string[] | null;
352
341
  openapi?: OperationObject;
353
342
  bodySchemaRefName?: string;
343
+ rest?: string | string[];
354
344
  }
355
345
  type Alias = {
356
346
  actionName: string;
@@ -383,6 +373,9 @@ interface Transformer<T, U> {
383
373
  findTransforms: (schema: ValidationSchema) => TransformField[];
384
374
  }
385
375
 
376
+ type ZodActionOrEventSchema = {
377
+ params?: ZodType;
378
+ };
386
379
  /**
387
380
  * Use zod for schema validation.
388
381
  * DO NOT support Async refinements/transforms yet.
@@ -390,19 +383,32 @@ interface Transformer<T, U> {
390
383
  * Transforms MUST BE handled by the consumer directly.
391
384
  */
392
385
  declare class ZodValidator extends Validators.Base {
393
- compile(): () => void;
386
+ constructor();
387
+ compile(): Validators.Base.CheckerFunction;
394
388
  validate<S extends ZodType>(params: unknown, schema: S, ctx?: Context): z.output<S>;
395
389
  /**
396
390
  * Override BaseValidator middleware to handle our custom compile function.
397
391
  */
398
- middleware(): (handler: ActionHandler, action: ActionSchema) => unknown;
392
+ middleware(): {
393
+ name: string;
394
+ localAction: (handler: any, action: ZodActionOrEventSchema) => any;
395
+ localEvent: (handler: any, event: ZodActionOrEventSchema) => any;
396
+ };
397
+ convertSchemaToMoleculer(): Record<string, unknown>;
399
398
  }
400
399
  declare module 'moleculer' {
401
- interface BaseValidator {
402
- validate<S extends ZodType>(params: unknown, schema: S): z.output<S>;
400
+ namespace Validators {
401
+ interface Base {
402
+ validate<S extends ZodType>(params: unknown, schema: S): z.output<S>;
403
+ }
403
404
  }
404
405
  }
405
406
 
407
+ type AjvValidatorCheckFnOption = {
408
+ meta: {
409
+ ctx: Context;
410
+ };
411
+ };
406
412
  /**
407
413
  * Moleculer validator using Ajv/zod for schema validation.
408
414
  *
@@ -417,7 +423,6 @@ declare module 'moleculer' {
417
423
  declare class AjvValidator<Mode extends string> extends Validators.Base {
418
424
  private readonly modes;
419
425
  private readonly defaultMode;
420
- private readonly broker;
421
426
  readonly zodValidator?: ZodValidator;
422
427
  /**
423
428
  * Cache of compiled validation functions.
@@ -438,7 +443,7 @@ declare class AjvValidator<Mode extends string> extends Validators.Base {
438
443
  *
439
444
  * Compiling a schema is quite expensive, so it will only be done once per schema.
440
445
  */
441
- compile(schema: ValidationSchema, mode?: Mode): (params: unknown, ctx?: Context) => boolean;
446
+ compile(schema: ValidationSchema, mode?: Mode): (params: unknown, opts?: AjvValidatorCheckFnOption) => boolean;
442
447
  /**
443
448
  * For debugging purposes, log the validation errors.
444
449
  * This is only enabled if the DETAILED_AJV_VALIDATION_ERRORS env var is set to 'yes'.
@@ -448,11 +453,14 @@ declare class AjvValidator<Mode extends string> extends Validators.Base {
448
453
  * We wrap the localAction and localEvent methods to add validation to the actions and events handlers.
449
454
  * Note that we lazy compile schemas in order to avoid a performance hit on startup.
450
455
  */
451
- middleware(): (handler: ActionHandler, action: ActionSchema) => unknown;
456
+ middleware(): Middleware;
457
+ convertSchemaToMoleculer(): Record<string, unknown>;
452
458
  }
453
459
  declare module 'moleculer' {
454
- interface BaseValidator {
455
- validate(params: unknown, schema: ValidationSchema): true;
460
+ namespace Validators {
461
+ interface Base {
462
+ validate(params: unknown, schema: ValidationSchema): true;
463
+ }
456
464
  }
457
465
  }
458
466
 
@@ -460,7 +468,7 @@ type Unpacked<T> = T extends (infer U)[] ? U : never;
460
468
  type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
461
469
  type OptionallyArray<T> = T | T[];
462
470
 
463
- type ServiceEventSchema = ServiceEvent & {
471
+ type ServiceEventSchema = EventSchema & {
464
472
  params?: unknown;
465
473
  };
466
474
 
@@ -483,7 +491,7 @@ type CallbackServiceThis<Return, Settings, Methods, Mixins, Parameters extends u
483
491
  interface CustomServiceSchema<Settings, Methods, Mixins> {
484
492
  name: string;
485
493
  version?: string | number;
486
- dependencies?: OptionallyArray<string | ServiceDependency>;
494
+ dependencies?: OptionallyArray<string | Service.ServiceDependency>;
487
495
  metadata?: Record<string, unknown>;
488
496
  settings?: Settings;
489
497
  hooks?: ServiceHooks;
@@ -503,9 +511,9 @@ interface CustomServiceSchema<Settings, Methods, Mixins> {
503
511
  * This class replace the default Context class in Moleculer to:
504
512
  * - Add a ctx.logger instance with the trace.id and span.id in the bindings
505
513
  */
506
- declare class ContextFactory<P = unknown, M extends object = {}, L = GenericObject> extends Context<P, M, L> {
507
- constructor(broker: ServiceBroker, endpoint: Endpoint);
508
- startSpan(name: string, opts?: Moleculer__default.GenericObject): Moleculer__default.Span;
514
+ declare class ContextFactory<P = unknown, M extends object = {}, L = Record<string, unknown>, H = Record<string, unknown>> extends Context<P, M, L, H> {
515
+ constructor(broker: ServiceBroker, endpoint: ActionEndpoint | EventEndpoint);
516
+ startSpan(name: string, opts?: Record<string, unknown>): Span;
509
517
  /**
510
518
  * Get a logger for this specific span of the context.
511
519
  */
@@ -513,7 +521,7 @@ declare class ContextFactory<P = unknown, M extends object = {}, L = GenericObje
513
521
  }
514
522
  declare module 'moleculer' {
515
523
  interface Context {
516
- logger: Moleculer__default.LoggerInstance;
524
+ logger: Logger;
517
525
  }
518
526
  }
519
527
 
@@ -545,7 +553,7 @@ type MoleculerLoggerConfigOptions = {
545
553
  *
546
554
  * @default createLogger()
547
555
  */
548
- logger?: Logger;
556
+ logger?: Logger$1;
549
557
  /**
550
558
  * Name of the field added for context logging. `false` disable the field
551
559
  * @default 'trace.id'
@@ -1,8 +1,8 @@
1
- import Moleculer__default, { RestSchema, ActionVisibility, Service, ActionCacheOptions, Context, TracingActionOptions, BulkheadOptions, BrokerCircuitBreakerOptions, RetryPolicyOptions, FallbackHandler, ActionHooks, Validators, ActionHandler, ActionSchema, ServiceEvent, ServiceDependency, ServiceHooks, GenericObject, ServiceBroker, Endpoint } from 'moleculer';
1
+ import { ActionSchema, Context, Validators, Middleware, EventSchema, Service, ServiceHooks, Logger, ServiceBroker, ActionEndpoint, EventEndpoint, Span } from 'moleculer';
2
2
  import { ObjectId } from 'bson';
3
3
  import { ZodType, z } from 'zod/v4';
4
4
  import { Options, ErrorObject } from 'ajv/dist/2019.js';
5
- import { LoggerOptions, Logger } from 'pino';
5
+ import { LoggerOptions, Logger as Logger$1 } from 'pino';
6
6
  import { PrettyOptions } from 'pino-pretty';
7
7
 
8
8
  type UnionToIntersection$1<U> = (U extends any ? (_: U) => void : never) extends (_: infer I) => void ? I : never;
@@ -333,24 +333,14 @@ interface Document {
333
333
  'x-express-openapi-validation-strict'?: boolean;
334
334
  }
335
335
 
336
- interface CustomActionSchema<T = unknown> {
337
- name?: string;
338
- rest?: RestSchema | RestSchema[] | string | string[];
339
- visibility?: ActionVisibility;
340
- service?: Service;
341
- cache?: boolean | ActionCacheOptions;
342
- handler?: (ctx: Context<never, never>) => Promise<T> | T;
343
- tracing?: boolean | TracingActionOptions;
344
- bulkhead?: BulkheadOptions;
345
- circuitBreaker?: BrokerCircuitBreakerOptions;
346
- retryPolicy?: RetryPolicyOptions;
347
- fallback?: string | FallbackHandler;
348
- hooks?: ActionHooks;
336
+ interface CustomActionSchema<T = unknown> extends Omit<ActionSchema, 'params' | 'handler'> {
349
337
  params?: unknown;
338
+ handler?: (ctx: Context<never, never>) => Promise<T> | T;
350
339
  disableTransforms?: boolean;
351
340
  openAPINames?: string[] | null;
352
341
  openapi?: OperationObject;
353
342
  bodySchemaRefName?: string;
343
+ rest?: string | string[];
354
344
  }
355
345
  type Alias = {
356
346
  actionName: string;
@@ -383,6 +373,9 @@ interface Transformer<T, U> {
383
373
  findTransforms: (schema: ValidationSchema) => TransformField[];
384
374
  }
385
375
 
376
+ type ZodActionOrEventSchema = {
377
+ params?: ZodType;
378
+ };
386
379
  /**
387
380
  * Use zod for schema validation.
388
381
  * DO NOT support Async refinements/transforms yet.
@@ -390,19 +383,32 @@ interface Transformer<T, U> {
390
383
  * Transforms MUST BE handled by the consumer directly.
391
384
  */
392
385
  declare class ZodValidator extends Validators.Base {
393
- compile(): () => void;
386
+ constructor();
387
+ compile(): Validators.Base.CheckerFunction;
394
388
  validate<S extends ZodType>(params: unknown, schema: S, ctx?: Context): z.output<S>;
395
389
  /**
396
390
  * Override BaseValidator middleware to handle our custom compile function.
397
391
  */
398
- middleware(): (handler: ActionHandler, action: ActionSchema) => unknown;
392
+ middleware(): {
393
+ name: string;
394
+ localAction: (handler: any, action: ZodActionOrEventSchema) => any;
395
+ localEvent: (handler: any, event: ZodActionOrEventSchema) => any;
396
+ };
397
+ convertSchemaToMoleculer(): Record<string, unknown>;
399
398
  }
400
399
  declare module 'moleculer' {
401
- interface BaseValidator {
402
- validate<S extends ZodType>(params: unknown, schema: S): z.output<S>;
400
+ namespace Validators {
401
+ interface Base {
402
+ validate<S extends ZodType>(params: unknown, schema: S): z.output<S>;
403
+ }
403
404
  }
404
405
  }
405
406
 
407
+ type AjvValidatorCheckFnOption = {
408
+ meta: {
409
+ ctx: Context;
410
+ };
411
+ };
406
412
  /**
407
413
  * Moleculer validator using Ajv/zod for schema validation.
408
414
  *
@@ -417,7 +423,6 @@ declare module 'moleculer' {
417
423
  declare class AjvValidator<Mode extends string> extends Validators.Base {
418
424
  private readonly modes;
419
425
  private readonly defaultMode;
420
- private readonly broker;
421
426
  readonly zodValidator?: ZodValidator;
422
427
  /**
423
428
  * Cache of compiled validation functions.
@@ -438,7 +443,7 @@ declare class AjvValidator<Mode extends string> extends Validators.Base {
438
443
  *
439
444
  * Compiling a schema is quite expensive, so it will only be done once per schema.
440
445
  */
441
- compile(schema: ValidationSchema, mode?: Mode): (params: unknown, ctx?: Context) => boolean;
446
+ compile(schema: ValidationSchema, mode?: Mode): (params: unknown, opts?: AjvValidatorCheckFnOption) => boolean;
442
447
  /**
443
448
  * For debugging purposes, log the validation errors.
444
449
  * This is only enabled if the DETAILED_AJV_VALIDATION_ERRORS env var is set to 'yes'.
@@ -448,11 +453,14 @@ declare class AjvValidator<Mode extends string> extends Validators.Base {
448
453
  * We wrap the localAction and localEvent methods to add validation to the actions and events handlers.
449
454
  * Note that we lazy compile schemas in order to avoid a performance hit on startup.
450
455
  */
451
- middleware(): (handler: ActionHandler, action: ActionSchema) => unknown;
456
+ middleware(): Middleware;
457
+ convertSchemaToMoleculer(): Record<string, unknown>;
452
458
  }
453
459
  declare module 'moleculer' {
454
- interface BaseValidator {
455
- validate(params: unknown, schema: ValidationSchema): true;
460
+ namespace Validators {
461
+ interface Base {
462
+ validate(params: unknown, schema: ValidationSchema): true;
463
+ }
456
464
  }
457
465
  }
458
466
 
@@ -460,7 +468,7 @@ type Unpacked<T> = T extends (infer U)[] ? U : never;
460
468
  type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
461
469
  type OptionallyArray<T> = T | T[];
462
470
 
463
- type ServiceEventSchema = ServiceEvent & {
471
+ type ServiceEventSchema = EventSchema & {
464
472
  params?: unknown;
465
473
  };
466
474
 
@@ -483,7 +491,7 @@ type CallbackServiceThis<Return, Settings, Methods, Mixins, Parameters extends u
483
491
  interface CustomServiceSchema<Settings, Methods, Mixins> {
484
492
  name: string;
485
493
  version?: string | number;
486
- dependencies?: OptionallyArray<string | ServiceDependency>;
494
+ dependencies?: OptionallyArray<string | Service.ServiceDependency>;
487
495
  metadata?: Record<string, unknown>;
488
496
  settings?: Settings;
489
497
  hooks?: ServiceHooks;
@@ -503,9 +511,9 @@ interface CustomServiceSchema<Settings, Methods, Mixins> {
503
511
  * This class replace the default Context class in Moleculer to:
504
512
  * - Add a ctx.logger instance with the trace.id and span.id in the bindings
505
513
  */
506
- declare class ContextFactory<P = unknown, M extends object = {}, L = GenericObject> extends Context<P, M, L> {
507
- constructor(broker: ServiceBroker, endpoint: Endpoint);
508
- startSpan(name: string, opts?: Moleculer__default.GenericObject): Moleculer__default.Span;
514
+ declare class ContextFactory<P = unknown, M extends object = {}, L = Record<string, unknown>, H = Record<string, unknown>> extends Context<P, M, L, H> {
515
+ constructor(broker: ServiceBroker, endpoint: ActionEndpoint | EventEndpoint);
516
+ startSpan(name: string, opts?: Record<string, unknown>): Span;
509
517
  /**
510
518
  * Get a logger for this specific span of the context.
511
519
  */
@@ -513,7 +521,7 @@ declare class ContextFactory<P = unknown, M extends object = {}, L = GenericObje
513
521
  }
514
522
  declare module 'moleculer' {
515
523
  interface Context {
516
- logger: Moleculer__default.LoggerInstance;
524
+ logger: Logger;
517
525
  }
518
526
  }
519
527
 
@@ -545,7 +553,7 @@ type MoleculerLoggerConfigOptions = {
545
553
  *
546
554
  * @default createLogger()
547
555
  */
548
- logger?: Logger;
556
+ logger?: Logger$1;
549
557
  /**
550
558
  * Name of the field added for context logging. `false` disable the field
551
559
  * @default 'trace.id'
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "type": "git",
7
7
  "url": "https://github.com/treatwell/moleculer-essentials"
8
8
  },
9
- "version": "2.0.0-beta.3",
9
+ "version": "2.0.0-beta.5",
10
10
  "main": "./dist/index.cjs",
11
11
  "module": "./dist/index.mjs",
12
12
  "types": "./dist/index.d.cts",
@@ -118,7 +118,7 @@
118
118
  "ioredis": "^5.2.3",
119
119
  "jsonwebtoken": "^9.0.2",
120
120
  "jwks-rsa": "^3.0.1",
121
- "moleculer": "^0.14.33",
121
+ "moleculer": "^0.15.0",
122
122
  "mongodb": "^6.15.0 || ^7.1.0",
123
123
  "redlock": "^4.2.0",
124
124
  "zod": "^3.25.0 || ^4.0.0"
@@ -164,7 +164,7 @@
164
164
  "jiti": "^2.6.1",
165
165
  "jsonwebtoken": "^9.0.3",
166
166
  "jwks-rsa": "^4.0.1",
167
- "moleculer": "^0.14.35",
167
+ "moleculer": "^0.15.0",
168
168
  "mongodb": "^7.1.1",
169
169
  "mongodb-memory-server": "^11.0.1",
170
170
  "pkgroll": "2.27.0",