@weave-js/core 0.15.3 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/index.mjs +0 -0
  2. package/lib/broker/context.js +4 -11
  3. package/lib/broker/defaultOptions.js +3 -2
  4. package/lib/broker/index.js +80 -26
  5. package/lib/broker/public.d.ts +2 -1
  6. package/lib/buildRuntime.js +30 -13
  7. package/lib/cache/adapters/index.js +14 -0
  8. package/lib/cache/lock.js +17 -0
  9. package/lib/errorHandler.js +27 -2
  10. package/lib/errors.js +11 -1
  11. package/lib/helper/defineAction.js +22 -7
  12. package/lib/helper/defineBrokerOptions.js +26 -8
  13. package/lib/helper/defineService.js +29 -5
  14. package/lib/index.js +69 -19
  15. package/lib/logger/format/asHumanReadable.js +4 -4
  16. package/lib/metrics/common.js +1 -1
  17. package/lib/metrics/exporter/base.js +2 -2
  18. package/lib/metrics/exporter/event.js +15 -13
  19. package/lib/metrics/exporter/index.js +1 -1
  20. package/lib/metrics/index.js +28 -0
  21. package/lib/middlewares/bulkhead/index.js +3 -3
  22. package/lib/middlewares/cache/index.js +6 -5
  23. package/lib/middlewares/context-tracker/index.js +12 -5
  24. package/lib/middlewares/index.js +18 -0
  25. package/lib/middlewares/tracing/tags.js +2 -2
  26. package/lib/middlewares/validator/index.js +2 -2
  27. package/lib/registry/actionEndpoint.js +5 -5
  28. package/lib/registry/collections/actionCollection.js +2 -2
  29. package/lib/registry/collections/endpointCollection.js +5 -5
  30. package/lib/registry/collections/eventCollection.js +5 -5
  31. package/lib/registry/collections/nodeCollection.js +2 -2
  32. package/lib/registry/collections/serviceCollection.js +2 -2
  33. package/lib/registry/node.js +1 -1
  34. package/lib/registry/registry.js +24 -15
  35. package/lib/registry/service/parseAction.js +11 -2
  36. package/lib/registry/service/parseEvent.js +2 -1
  37. package/lib/registry/service/service.js +29 -8
  38. package/lib/registry/serviceItem.js +2 -2
  39. package/lib/runtime/initActionInvoker.js +5 -1
  40. package/lib/runtime/initCache.js +4 -0
  41. package/lib/runtime/initContextFactory.js +6 -15
  42. package/lib/runtime/initEventbus.js +25 -4
  43. package/lib/runtime/initLogger.js +30 -10
  44. package/lib/runtime/initMetrics.js +18 -8
  45. package/lib/runtime/initRegistry.js +1 -1
  46. package/lib/runtime/initServiceManager.js +4 -0
  47. package/lib/runtime/initTracing.js +5 -1
  48. package/lib/runtime/initTransport.js +1 -1
  49. package/lib/runtime/initUuidFactory.js +1 -5
  50. package/lib/runtime/initValidator.js +1 -6
  51. package/lib/tracing/collectors/base.js +21 -3
  52. package/lib/tracing/collectors/event.js +10 -0
  53. package/lib/tracing/collectors/index.js +34 -1
  54. package/lib/transport/adapters/adapterBase.js +14 -4
  55. package/lib/transport/adapters/fromURI.js +31 -23
  56. package/lib/transport/createTransport.js +30 -13
  57. package/lib/transport/messageHandlers.js +3 -3
  58. package/lib/utils/index.js +17 -1
  59. package/lib/utils/options.js +70 -2
  60. package/lib/utils/restoreError.js +25 -0
  61. package/lib/utils/wrap-handler.js +22 -0
  62. package/package.json +2 -1
  63. package/types/index.d.ts +958 -0
  64. /package/lib/{types.js → types.__js} +0 -0
package/index.mjs ADDED
File without changes
@@ -5,25 +5,18 @@
5
5
  */
6
6
  'use strict';
7
7
 
8
- /**
9
- * @typedef {import('../types').Context} Context
10
- * @typedef {import('../types').Runtime} Runtime
11
- * @typedef {import('../types').ContextPromise} ContextPromise
12
- * @typedef {import('../types').Endpoint} Endpoint
13
- */
14
-
15
8
  const { uuid, isFunction, isStream, isStreamObjectMode } = require('@weave-js/utils');
16
9
  const { WeaveMaxCallLevelError, WeaveError } = require('../errors');
17
10
 
18
11
  /**
19
12
  * Create a new context object
20
- * @param {Runtime} runtime Runtime reference
21
- * @returns {Context} Context
13
+ * @param {import('../../types').Runtime} runtime Runtime reference
14
+ * @returns {import('../../types').Context} Context
22
15
  */
23
16
  exports.createContext = (runtime) => {
24
17
  const spanStack = [];
25
18
 
26
- /** @type {Context} */
19
+ /** @type {import('../../types').Context} */
27
20
  const context = {
28
21
  id: null,
29
22
  nodeId: runtime.nodeId || null,
@@ -119,7 +112,7 @@ exports.createContext = (runtime) => {
119
112
  },
120
113
  /**
121
114
  * Copy the current context.
122
- * @returns {Context} New copied context
115
+ * @returns {import('../../types').Context} New copied context
123
116
  */
124
117
  copy () {
125
118
  const contextCopy = exports.createContext(runtime);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @typedef {import('../types.js').BrokerOptions} BrokerOptions
2
+ * @typedef {import('../types.__js').BrokerOptions} BrokerOptions
3
3
  */
4
4
 
5
5
  /*
@@ -56,7 +56,8 @@ exports.getDefaultOptions = () => {
56
56
  maxChunkSize: 256 * 1024,
57
57
  streams: {
58
58
  handleBackpressure: true
59
- }
59
+ },
60
+ rejectLargePayloadSize: false,
60
61
  },
61
62
  errorHandler: undefined,
62
63
  loadInternalMiddlewares: true,
@@ -1,9 +1,11 @@
1
1
  /**
2
- * @typedef {import('../types.js').Runtime} Runtime
3
- * @typedef {import('../types.js').BrokerOptions} BrokerOptions
4
- * @typedef {import('../types.js').Broker} Broker
5
- * @typedef {import('../types.js').Transport} Transport
6
- */
2
+ * @typedef {import('../../types').Runtime} Runtime
3
+ * @typedef {import('../../types').BrokerOptions} BrokerOptions
4
+ * @typedef {import('../../types').Broker} Broker
5
+ * @typedef {import('../../types').Transport} Transport
6
+ * @typedef {import('../../types').Service} Service
7
+ * @typedef {import('../../types').ServiceSchema} ServiceSchema
8
+ */
7
9
 
8
10
  const { isFunction } = require('@weave-js/utils');
9
11
  const path = require('path');
@@ -11,10 +13,10 @@ const glob = require('glob');
11
13
  const Middlewares = require('../middlewares');
12
14
 
13
15
  /**
14
- * Creates a new Weave Broker instance
15
- * @param {Runtime} runtime - Weave runtime.
16
- * @returns {Broker} Broker instance
17
- */
16
+ * Creates a new Weave Broker instance from the provided runtime
17
+ * @param {Runtime} runtime - Initialized Weave runtime containing all core components
18
+ * @returns {Broker} A fully configured Broker instance ready for use
19
+ */
18
20
  exports.createBrokerInstance = (runtime) => {
19
21
  const {
20
22
  version,
@@ -82,19 +84,30 @@ exports.createBrokerInstance = (runtime) => {
82
84
  broker.createService = services.createService.bind(broker);
83
85
 
84
86
  /**
85
- * Global error handler of the broker.
86
- * @param {*} error Error
87
+ * Global error handler for the broker. Processes non-fatal errors and passes them to the configured error handler.
88
+ * @param {Error} error - The error to handle
87
89
  * @returns {void}
88
- */
90
+ */
89
91
  broker.handleError = runtime.handleError;
90
92
 
93
+ /**
94
+ * Fatal error handler that triggers graceful shutdown. Should only be used for unrecoverable errors.
95
+ * @param {string} [message] - Error message describing the fatal condition
96
+ * @param {Error} [error] - The underlying error that caused the fatal condition
97
+ * @param {boolean} [killProcess=true] - Whether to terminate the process after cleanup
98
+ * @returns {void}
99
+ */
91
100
  broker.fatalError = runtime.fatalError;
92
101
 
93
102
  /**
94
- * Load and register a service from file.
95
- * @param {string} filename Path to the service file.
96
- * @returns {Service} Service
97
- */
103
+ * Loads and registers a service from a file path. The file should export a service schema.
104
+ * @param {string} filename - Absolute or relative path to the service file
105
+ * @returns {Service} The created and registered service instance
106
+ * @throws {Error} When the service file cannot be loaded or contains invalid schema
107
+ * @example
108
+ * // Load a service from a file
109
+ * const service = broker.loadService('./services/math.service.js');
110
+ */
98
111
  broker.loadService = function (filename) {
99
112
  const filePath = path.resolve(filename);
100
113
  const schema = require(filePath);
@@ -129,12 +142,37 @@ exports.createBrokerInstance = (runtime) => {
129
142
  await transport.connect();
130
143
  }
131
144
 
132
- try {
133
- await Promise.all(services.serviceList.map(service => service.start()));
134
- } catch (error) {
135
- log.error(error, 'Unable to start all services');
145
+ // Start services using Promise.allSettled to continue even if some fail
146
+ const serviceStartResults = await Promise.allSettled(
147
+ services.serviceList.map(service => service.start())
148
+ );
149
+
150
+ const failedServices = serviceStartResults
151
+ .map((result, index) => ({ result, service: services.serviceList[index] }))
152
+ .filter(({ result }) => result.status === 'rejected');
153
+
154
+ if (failedServices.length > 0) {
155
+ const errorMessage = `Failed to start ${failedServices.length} of ${services.serviceList.length} services`;
156
+
157
+ failedServices.forEach(({ result, service }) => {
158
+ log.error(result.reason, `Unable to start service "${service.name}"`);
159
+ });
160
+
136
161
  clearInterval(options.waitForServiceInterval);
137
- throw error;
162
+
163
+ // If critical services failed, throw error to prevent startup
164
+ if (failedServices.some(({ service }) => service.schema.critical !== false)) {
165
+ const criticalFailures = failedServices.filter(({ service }) => service.schema.critical !== false);
166
+
167
+ // If only one service failed, preserve the original error message for compatibility
168
+ if (criticalFailures.length === 1 && services.serviceList.length === 1) {
169
+ throw criticalFailures[0].result.reason;
170
+ } else {
171
+ throw new Error(`${errorMessage}. Critical services failed: ${criticalFailures.map(({ service }) => service.name).join(', ')}`);
172
+ }
173
+ } else {
174
+ log.warn(`${errorMessage}, but continuing startup as no critical services failed`);
175
+ }
138
176
  }
139
177
 
140
178
  runtime.state.isStarted = true;
@@ -165,11 +203,27 @@ exports.createBrokerInstance = (runtime) => {
165
203
 
166
204
  await middlewareHandler.callHandlersAsync('stopping', [runtime], true);
167
205
 
168
- try {
169
- await Promise.all(services.serviceList.map(service => service.stop()));
170
- } catch (error) {
171
- log.error(error, 'Unable to stop all services.');
172
- throw error;
206
+ // Stop services using Promise.allSettled to attempt stopping all services
207
+ const serviceStopResults = await Promise.allSettled(
208
+ services.serviceList.map(service => service.stop())
209
+ );
210
+
211
+ const failedStops = serviceStopResults
212
+ .map((result, index) => ({ result, service: services.serviceList[index] }))
213
+ .filter(({ result }) => result.status === 'rejected');
214
+
215
+ if (failedStops.length > 0) {
216
+ failedStops.forEach(({ result, service }) => {
217
+ log.error(result.reason, `Unable to stop service "${service.name}"`);
218
+ });
219
+
220
+ // If only one service and it failed, preserve original error for compatibility
221
+ if (failedStops.length === 1 && services.serviceList.length === 1) {
222
+ throw failedStops[0].result.reason;
223
+ } else {
224
+ log.error(`Failed to stop ${failedStops.length} of ${services.serviceList.length} services, but continuing shutdown`);
225
+ // Continue with shutdown process rather than throwing
226
+ }
173
227
  }
174
228
 
175
229
  if (transport) {
@@ -75,6 +75,8 @@ export type TransportOptions = {
75
75
  maxOfflineTime: number;
76
76
  maxChunkSize: number;
77
77
  streams: TransportStreamOptions;
78
+ maxPayloadSize: number;
79
+ rejectLargePayloadSize: boolean;
78
80
  }
79
81
 
80
82
  export type TransportStreamOptions = {
@@ -117,4 +119,3 @@ export type Broker = {
117
119
  handleError(err: Error): void;
118
120
  fatalError(err: Error): void;
119
121
  }
120
-
@@ -1,9 +1,3 @@
1
- /**
2
- * @typedef {import('./types.js').BrokerOptions} BrokerOptions
3
- * @typedef {import('./types.js').Runtime} Runtime
4
- * @typedef {import('./types.js').Broker} Broker
5
- */
6
-
7
1
  const { initLogger } = require('./runtime/initLogger');
8
2
  const { initMiddlewareHandler } = require('./runtime/initMiddlewareManager');
9
3
  const { initRegistry } = require('./runtime/initRegistry');
@@ -23,20 +17,43 @@ const { version } = require('../package.json');
23
17
  const EventEmitter = require('eventemitter2');
24
18
 
25
19
  /**
26
- * Build runtime object
27
- * @param {BrokerOptions} options Broker options
28
- * @return {Runtime} Runtime
29
- */
20
+ * Initializes and builds the complete Weave runtime with all core components
21
+ *
22
+ * The runtime contains all the core subsystems needed for a Weave broker:
23
+ * - Logger: Configurable logging system
24
+ * - Middleware: Request/response processing pipeline
25
+ * - Registry: Service discovery and load balancing
26
+ * - Context Factory: Request context creation
27
+ * - Event Bus: Pub/sub messaging system
28
+ * - Transport: Network communication layer
29
+ * - Cache: Distributed caching
30
+ * - Metrics: Performance monitoring
31
+ * - Tracing: Distributed tracing
32
+ *
33
+ * @param {import('../types').BrokerOptions} options - Broker configuration options
34
+ * @returns {import('../types').Runtime} Fully initialized runtime instance
35
+ * @example
36
+ * const runtime = initRuntime({
37
+ * nodeId: 'my-service',
38
+ * logger: { level: 'info' },
39
+ * transport: { adapter: 'TCP' }
40
+ * });
41
+ */
30
42
  exports.initRuntime = (options) => {
31
43
  /**
32
- * Event bus
33
- * @returns {EventEmitter} Service object.
34
- */
44
+ * Internal event bus for broker communication
45
+ * Supports wildcard patterns and high listener count for complex service topologies
46
+ * @type {EventEmitter}
47
+ */
35
48
  const bus = new EventEmitter({
36
49
  wildcard: true,
37
50
  maxListeners: 1000
38
51
  });
39
52
 
53
+ /**
54
+ * Core runtime object containing all initialized subsystems
55
+ * @type {import('../types').Runtime}
56
+ */
40
57
  const runtime = {
41
58
  nodeId: options.nodeId,
42
59
  version,
@@ -4,6 +4,20 @@
4
4
  * Copyright 2021 Fachwerk
5
5
  */
6
6
 
7
+ /**
8
+ * Built-in cache adapter implementations
9
+ *
10
+ * Provides various caching backends:
11
+ * - Base: Abstract base cache implementation
12
+ * - InMemory: High-performance in-memory cache with LRU eviction
13
+ *
14
+ * Additional adapters available as separate packages:
15
+ * - Redis: Distributed Redis cache
16
+ * - Memcached: Memcached integration
17
+ * - File: File-based persistent cache
18
+ *
19
+ * @namespace CacheAdapters
20
+ */
7
21
  module.exports = {
8
22
  ...require('./base'),
9
23
  ...require('./inMemory')
package/lib/cache/lock.js CHANGED
@@ -1,10 +1,20 @@
1
1
  const createLock = () => {
2
2
  const locked = new Map();
3
+ const timeouts = new Map();
3
4
 
4
5
  function acquire (key, ttl) {
5
6
  const lockedItems = locked.get(key);
6
7
  if (!lockedItems) {
7
8
  locked.set(key, []);
9
+
10
+ // Set up TTL timeout if provided
11
+ if (ttl && ttl > 0) {
12
+ const timeoutId = setTimeout(() => {
13
+ release(key);
14
+ }, ttl);
15
+ timeouts.set(key, timeoutId);
16
+ }
17
+
8
18
  return Promise.resolve();
9
19
  } else {
10
20
  return new Promise((resolve) => lockedItems.push(resolve));
@@ -18,6 +28,13 @@ const createLock = () => {
18
28
  function release (key) {
19
29
  const lockedItems = locked.get(key);
20
30
  if (lockedItems) {
31
+ // Clear TTL timeout if exists
32
+ const timeoutId = timeouts.get(key);
33
+ if (timeoutId) {
34
+ clearTimeout(timeoutId);
35
+ timeouts.delete(key);
36
+ }
37
+
21
38
  if (lockedItems.length > 0) {
22
39
  lockedItems.shift()();
23
40
  } else {
@@ -6,7 +6,7 @@ exports.errorHandler = ({ options }, error) => {
6
6
  };
7
7
 
8
8
  exports.fatalErrorHandler = (runtime, message, error, killProcess = true) => {
9
- const { options, log } = runtime;
9
+ const { options, log, broker } = runtime;
10
10
  if (options.logger.enabled) {
11
11
  log.fatal({ error }, message);
12
12
  } else {
@@ -14,6 +14,31 @@ exports.fatalErrorHandler = (runtime, message, error, killProcess = true) => {
14
14
  }
15
15
 
16
16
  if (killProcess) {
17
- process.exit(1);
17
+ // Graceful shutdown instead of immediate process.exit
18
+ if (broker && runtime.state && runtime.state.isStarted) {
19
+ log.warn('Attempting graceful shutdown due to fatal error...');
20
+
21
+ // Set a timeout to prevent hanging indefinitely
22
+ const shutdownTimeout = setTimeout(() => {
23
+ log.error('Graceful shutdown timed out, forcing exit');
24
+ process.exit(1);
25
+ }, 10000); // 10 second timeout
26
+
27
+ broker.stop()
28
+ .then(() => {
29
+ clearTimeout(shutdownTimeout);
30
+ log.info('Graceful shutdown completed');
31
+ process.exit(1);
32
+ })
33
+ .catch((shutdownError) => {
34
+ clearTimeout(shutdownTimeout);
35
+ log.error('Graceful shutdown failed:', shutdownError);
36
+ process.exit(1);
37
+ });
38
+ } else {
39
+ // Fallback to immediate exit if broker not available or not started
40
+ log.warn('Broker not started or unavailable, performing immediate exit');
41
+ process.exit(1);
42
+ }
18
43
  }
19
44
  };
package/lib/errors.js CHANGED
@@ -141,6 +141,15 @@ class WeaveGracefulStopTimeoutError extends WeaveError {
141
141
  }
142
142
  }
143
143
 
144
+ class WeavePacketSizeLimitExceeded extends WeaveError {
145
+ constructor(messageType, packageSize, limit) {
146
+ super(
147
+ `Packet size limit exceeded: ${packageSize} bytes (max ${limit}). Type: ${messageType}`,
148
+ { code: 'WEAVE_PACKAGE_SIZE_LIMIT_EXCEEDED' }
149
+ )
150
+ }
151
+ }
152
+
144
153
  module.exports = {
145
154
  WeaveBrokerOptionsError,
146
155
  WeaveMaxCallLevelError,
@@ -151,5 +160,6 @@ module.exports = {
151
160
  WeaveRetryableError,
152
161
  WeaveServiceNotAvailableError,
153
162
  WeaveServiceNotFoundError,
154
- WeaveGracefulStopTimeoutError
163
+ WeaveGracefulStopTimeoutError,
164
+ WeavePacketSizeLimitExceeded
155
165
  };
@@ -1,14 +1,29 @@
1
- /* istanbul ignore next */
2
-
3
1
  /**
4
- * @typedef {import('../types.js').ServiceActionDefinition} ServiceActionDefinition
2
+ * @import { ServiceActionSchema,TypeMap } from '@weave-js/core'
5
3
  */
6
4
 
7
5
  /**
8
- * Create and register a new service action.
9
- * @param {ServiceActionDefinition} actionDefinition - Schema of the the action
10
- * @returns {ServiceActionDefinition} Action definition
6
+ * Helper function to define a service action with proper TypeScript inference
7
+ *
8
+ * This is a type helper that provides compile-time type checking and IntelliSense
9
+ * for action definitions. It performs no runtime processing - just returns the
10
+ * action definition as-is while providing type safety.
11
+ *
12
+ * @template {{ [key: string]: { type: keyof TypeMap } } } TParamsSchema
13
+ * @param {ServiceActionSchema<TParamsSchema>} actionDefinition - Action schema with typed parameters
14
+ * @returns {ServiceActionSchema<TParamsSchema>} - Same action schema with preserved types
15
+ * @example
16
+ * const myAction = defineAction({
17
+ * params: {
18
+ * name: { type: 'string', required: true },
19
+ * age: { type: 'number', min: 0 }
20
+ * },
21
+ * handler: (ctx) => {
22
+ * // ctx.params is properly typed as { name: string, age?: number }
23
+ * return `Hello ${ctx.params.name}`;
24
+ * }
25
+ * });
11
26
  */
12
- module.exports = function (actionDefinition) {
27
+ module.exports = function defineAction (actionDefinition) {
13
28
  return actionDefinition;
14
29
  };
@@ -1,13 +1,31 @@
1
- /* istanbul ignore next */
1
+ /** @import { BrokerOptions } from '@weave-js/core' */
2
2
 
3
3
  /**
4
- * @typedef {import('../types.js').BrokerOptions} BrokerOptions
5
- */
6
-
7
- /**
8
- * Create and register a new service
9
- * @param {BrokerOptions} options - Broker options
10
- * @returns {BrokerOptions} Broker options
4
+ * Helper function to define broker options with proper TypeScript inference
5
+ *
6
+ * This is a type helper that provides compile-time type checking and IntelliSense
7
+ * for broker configuration. It performs no runtime processing - just returns the
8
+ * options as-is while providing type safety and configuration validation.
9
+ *
10
+ * @param {BrokerOptions} options - Complete broker configuration options
11
+ * @returns {BrokerOptions} Same broker options with preserved types
12
+ * @example
13
+ * const brokerConfig = defineBrokerOptions({
14
+ * nodeId: 'my-node',
15
+ * logger: {
16
+ * level: 'info',
17
+ * format: 'human'
18
+ * },
19
+ * transport: {
20
+ * adapter: 'TCP',
21
+ * options: {
22
+ * port: 3000
23
+ * }
24
+ * },
25
+ * cache: {
26
+ * adapter: 'Memory'
27
+ * }
28
+ * });
11
29
  */
12
30
  module.exports = function (options) {
13
31
  return options;
@@ -2,13 +2,37 @@
2
2
  /* istanbul ignore next */
3
3
 
4
4
  /**
5
- * @typedef {import('../types.js').ServiceSchema} ServiceSchema
6
- */
5
+ * @import * as Weave from '@weave-js/core'
6
+ */
7
7
 
8
8
  /**
9
- * Create and register a new service
10
- * @param {ServiceSchema} serviceSchema - Schema of the Service
11
- * @returns {ServiceSchema} Service schema
9
+ * Helper function to define a service schema with proper TypeScript inference
10
+ *
11
+ * This is a type helper that provides compile-time type checking and IntelliSense
12
+ * for service definitions. It performs no runtime processing - just returns the
13
+ * service schema as-is while providing type safety and better developer experience.
14
+ *
15
+ * @param {Weave.ServiceSchema} serviceSchema - Complete service schema definition
16
+ * @returns {Weave.ServiceSchema} Same service schema with preserved types
17
+ * @example
18
+ * const userService = defineService({
19
+ * name: 'users',
20
+ * actions: {
21
+ * create: {
22
+ * params: {
23
+ * name: { type: 'string', required: true },
24
+ * email: { type: 'email', required: true }
25
+ * },
26
+ * handler: (ctx) => {
27
+ * // ctx.params is properly typed
28
+ * return this.createUser(ctx.params.name, ctx.params.email);
29
+ * }
30
+ * }
31
+ * },
32
+ * methods: {
33
+ * createUser: (name, email) => ({ id: 1, name, email })
34
+ * }
35
+ * });
12
36
  */
13
37
  module.exports = function (serviceSchema) {
14
38
  return serviceSchema;
package/lib/index.js CHANGED
@@ -1,55 +1,105 @@
1
- /**
2
- * @typedef {import('./types.js').BrokerOptions} BrokerOptions
3
- * @typedef {import('./types.js').Runtime} Runtime
4
- * @typedef {import('./types.js').Broker} Broker
5
- */
6
-
7
1
  const { getDefaultOptions } = require('./broker/defaultOptions');
8
2
  const { defaultsDeep } = require('@weave-js/utils');
9
3
  const { initRuntime } = require('./buildRuntime');
10
4
  const { createBrokerInstance } = require('./broker');
11
5
 
12
6
  /**
13
- * @type {BrokerOptions} options Broker options
14
- */
7
+ * Default broker configuration options
8
+ * @type {import('../types').BrokerOptions}
9
+ */
15
10
  exports.defaultOptions = getDefaultOptions();
16
11
 
17
12
  /**
18
- * Build runtime object
19
- * @param {BrokerOptions} options Broker options
20
- * @return {Broker} Broker instance
21
- */
13
+ * Creates a new Weave broker instance with the provided configuration
14
+ * @param {import('../types').BrokerOptions} [options] - Broker configuration options
15
+ * @returns {import('../types').Broker} A new Broker instance
16
+ * @example
17
+ * const { createBroker } = require('@weave-js/core');
18
+ *
19
+ * const broker = createBroker({
20
+ * nodeId: 'my-service',
21
+ * logger: { level: 'info' },
22
+ * transport: { adapter: 'TCP' }
23
+ * });
24
+ *
25
+ * broker.start();
26
+ */
22
27
  exports.createBroker = (options) => {
23
28
  const defaultOptions = getDefaultOptions();
24
29
 
25
30
  options = defaultsDeep(options, defaultOptions);
26
31
 
27
32
  const runtime = initRuntime(options);
33
+ const broker = createBrokerInstance(runtime);
34
+
35
+ // Establish circular reference for graceful shutdown in fatal errors
36
+ runtime.broker = broker;
28
37
 
29
- return createBrokerInstance(runtime);
38
+ return broker;
30
39
  };
31
40
 
32
41
  /**
33
- * @deprecated since version 0.9.0
34
- * @param {import('./types.js').BrokerOptions} options Broker options.
35
- * @returns {import('./types.js').Broker} Broker instance
36
- */
42
+ * @deprecated since version 0.9.0 - Use createBroker instead
43
+ * @param {import('../types').BrokerOptions} [options] - Broker configuration options
44
+ * @returns {import('../types').Broker} A new Broker instance
45
+ */
37
46
  exports.Weave = exports.createBroker;
38
47
 
48
+ /**
49
+ * Weave error classes and utilities
50
+ * @namespace
51
+ */
39
52
  exports.Errors = require('./errors');
40
53
 
54
+ /**
55
+ * Weave constants and internal identifiers
56
+ * @namespace
57
+ */
41
58
  exports.Constants = require('./constants');
42
59
 
60
+ /**
61
+ * Cache adapter implementations
62
+ * @namespace
63
+ */
43
64
  exports.Cache = require('./cache/adapters');
44
65
 
45
66
  /**
46
- * @deprecated since version 0.10.0
47
- */
67
+ * @deprecated since version 0.10.0 - Use TracingAdapters instead
68
+ */
48
69
  exports.createBaseTracingCollector = require('./tracing/collectors/base').createBaseTracingCollector;
70
+
71
+ /**
72
+ * Transport adapter implementations
73
+ * @namespace
74
+ */
49
75
  exports.TransportAdapters = require('./transport/adapters');
76
+
77
+ /**
78
+ * Tracing collector implementations
79
+ * @namespace
80
+ */
50
81
  exports.TracingAdapters = require('./tracing/collectors');
82
+
83
+ /**
84
+ * Cache adapter implementations (alias for Cache)
85
+ * @namespace
86
+ */
51
87
  exports.CacheAdapters = require('./cache/adapters');
52
88
 
89
+ /**
90
+ * Helper function for type-safe broker option definitions
91
+ * @function
92
+ */
53
93
  exports.defineBrokerOptions = require('./helper/defineBrokerOptions');
94
+
95
+ /**
96
+ * Helper function for type-safe service definitions
97
+ * @function
98
+ */
54
99
  exports.defineService = require('./helper/defineService');
100
+
101
+ /**
102
+ * Helper function for type-safe action definitions
103
+ * @function
104
+ */
55
105
  exports.defineAction = require('./helper/defineAction');
@@ -1,7 +1,7 @@
1
1
  const { green, magenta, red, yellow, gray, cyan } = require('../utils/colorize');
2
2
  const os = require('os');
3
3
 
4
- exports.asHumanReadable = ({ levels, options }, originObj, message, number, time) => {
4
+ exports.asHumanReadable = (runtime, originObj, message, number, time) => {
5
5
  let logResult = '';
6
6
 
7
7
  const logLevelColors = {
@@ -13,7 +13,7 @@ exports.asHumanReadable = ({ levels, options }, originObj, message, number, time
13
13
  verbose: gray
14
14
  };
15
15
 
16
- const currentLabel = levels.labels[number];
16
+ const currentLabel = runtime.levels.labels[number];
17
17
 
18
18
  const color = logLevelColors[currentLabel] || yellow;
19
19
  // Log level label
@@ -22,8 +22,8 @@ exports.asHumanReadable = ({ levels, options }, originObj, message, number, time
22
22
  // date time
23
23
  logResult += ' [' + new Date(time).toISOString() + '] ';
24
24
 
25
- if (options.base.pid && options.base.hostname) {
26
- logResult += ` (${options.base.pid} on ${options.base.hostname})`;
25
+ if (runtime.options.base.pid && runtime.options.base.hostname) {
26
+ logResult += ` (${runtime.options.base.pid} on ${runtime.options.base.hostname})`;
27
27
  }
28
28
 
29
29
  if (message) {