@xylabs/creatable 5.0.80 → 5.0.81
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 +929 -128
- package/dist/neutral/AbstractCreatable.d.ts +83 -0
- package/dist/neutral/AbstractCreatable.d.ts.map +1 -1
- package/dist/neutral/Creatable.d.ts +17 -0
- package/dist/neutral/Creatable.d.ts.map +1 -1
- package/dist/neutral/Factory.d.ts +17 -0
- package/dist/neutral/Factory.d.ts.map +1 -1
- package/dist/neutral/index.mjs +86 -0
- package/dist/neutral/index.mjs.map +1 -1
- package/dist/neutral/lib/getFunctionName.d.ts +5 -0
- package/dist/neutral/lib/getFunctionName.d.ts.map +1 -1
- package/dist/neutral/lib/getRootFunction.d.ts +6 -0
- package/dist/neutral/lib/getRootFunction.d.ts.map +1 -1
- package/dist/neutral/model/CreatableInstance.d.ts +6 -0
- package/dist/neutral/model/CreatableInstance.d.ts.map +1 -1
- package/dist/neutral/model/CreatableParams.d.ts +5 -0
- package/dist/neutral/model/CreatableParams.d.ts.map +1 -1
- package/dist/neutral/model/CreatableStatusReporter.d.ts +6 -0
- package/dist/neutral/model/CreatableStatusReporter.d.ts.map +1 -1
- package/package.json +11 -14
- package/src/AbstractCreatable.ts +0 -269
- package/src/Creatable.ts +0 -69
- package/src/Factory.ts +0 -38
- package/src/index.ts +0 -4
- package/src/lib/getFunctionName.ts +0 -18
- package/src/lib/getRootFunction.ts +0 -8
- package/src/lib/index.ts +0 -2
- package/src/model/CreatableInstance.ts +0 -12
- package/src/model/CreatableParams.ts +0 -13
- package/src/model/CreatableStatusReporter.ts +0 -11
- package/src/model/Labels.ts +0 -33
- package/src/model/index.ts +0 -4
|
@@ -5,36 +5,119 @@ import type { Promisable } from '@xylabs/promise';
|
|
|
5
5
|
import { SpanConfig } from '@xylabs/telemetry';
|
|
6
6
|
import { type Creatable, CreatableFactory } from './Creatable.ts';
|
|
7
7
|
import type { CreatableInstance, CreatableName, CreatableParams, CreatableStatus, Labels, RequiredCreatableParams } from './model/index.ts';
|
|
8
|
+
/**
|
|
9
|
+
* Base class for objects that follow an asynchronous creation and lifecycle pattern.
|
|
10
|
+
* Instances must be created via the static `create` method rather than direct construction.
|
|
11
|
+
* Provides start/stop lifecycle management with status tracking and telemetry support.
|
|
12
|
+
*/
|
|
8
13
|
export declare class AbstractCreatable<TParams extends CreatableParams = CreatableParams, TEventData extends EventData = EventData> extends BaseEmitter<Partial<TParams & RequiredCreatableParams>, TEventData> {
|
|
14
|
+
/** Optional default logger for this instance. */
|
|
9
15
|
defaultLogger?: Logger;
|
|
10
16
|
protected _startPromise: Promisable<boolean> | undefined;
|
|
11
17
|
private _status;
|
|
12
18
|
private _statusMutex;
|
|
13
19
|
private _validatedParams?;
|
|
14
20
|
constructor(key: unknown, params: Partial<TParams & RequiredCreatableParams>);
|
|
21
|
+
/** The name identifier for this creatable instance. */
|
|
15
22
|
get name(): CreatableName;
|
|
23
|
+
/** The validated and merged parameters for this instance. */
|
|
16
24
|
get params(): TParams & RequiredCreatableParams;
|
|
25
|
+
/** Whether this instance can be started (must be in 'created' or 'stopped' status). */
|
|
17
26
|
get startable(): boolean;
|
|
27
|
+
/** The current lifecycle status of this instance, or null if not yet initialized. */
|
|
18
28
|
get status(): CreatableStatus | null;
|
|
29
|
+
/** The status reporter used to broadcast lifecycle changes. */
|
|
19
30
|
get statusReporter(): import("./model/CreatableStatusReporter.ts").CreatableStatusReporter<void> | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* Asynchronously creates a new instance by processing params, constructing,
|
|
33
|
+
* and running both static and instance createHandlers.
|
|
34
|
+
* @param inParams - Optional partial parameters to configure the instance
|
|
35
|
+
* @returns The fully initialized instance
|
|
36
|
+
*/
|
|
20
37
|
static create<T extends CreatableInstance>(this: Creatable<T>, inParams?: Partial<T['params']>): Promise<T>;
|
|
38
|
+
/**
|
|
39
|
+
* Static hook called during creation to perform additional initialization.
|
|
40
|
+
* Override in subclasses to customize post-construction setup.
|
|
41
|
+
* @param instance - The newly constructed instance
|
|
42
|
+
* @returns The instance, potentially modified
|
|
43
|
+
*/
|
|
21
44
|
static createHandler<T extends CreatableInstance>(this: Creatable<T>, instance: T): Promisable<T>;
|
|
45
|
+
/**
|
|
46
|
+
* Static hook called during creation to validate and transform params.
|
|
47
|
+
* Override in subclasses to add default values or validation.
|
|
48
|
+
* @param params - The raw partial params provided to `create`
|
|
49
|
+
* @returns The processed params ready for construction
|
|
50
|
+
*/
|
|
22
51
|
static paramsHandler<T extends CreatableInstance>(this: Creatable<T>, params?: Partial<T['params']>): Promisable<T['params']>;
|
|
52
|
+
/** Instance-level creation hook. Override in subclasses to perform setup after construction. */
|
|
23
53
|
createHandler(): Promisable<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Validates and returns the merged params, ensuring required fields are present.
|
|
56
|
+
* Override in subclasses to add custom validation logic.
|
|
57
|
+
* @param params - The raw partial params to validate
|
|
58
|
+
* @returns The validated params
|
|
59
|
+
*/
|
|
24
60
|
paramsValidator(params: Partial<TParams & RequiredCreatableParams>): TParams & RequiredCreatableParams;
|
|
61
|
+
/**
|
|
62
|
+
* Executes a function within a telemetry span.
|
|
63
|
+
* @param name - The span name
|
|
64
|
+
* @param fn - The function to execute within the span
|
|
65
|
+
*/
|
|
25
66
|
span<T>(name: string, fn: () => T): T;
|
|
67
|
+
/**
|
|
68
|
+
* Executes an async function within a telemetry span.
|
|
69
|
+
* @param name - The span name
|
|
70
|
+
* @param fn - The async function to execute within the span
|
|
71
|
+
* @param config - Optional span configuration
|
|
72
|
+
*/
|
|
26
73
|
spanAsync<T>(name: string, fn: () => Promise<T>, config?: SpanConfig): Promise<T>;
|
|
74
|
+
/**
|
|
75
|
+
* Starts the instance, transitioning through 'starting' to 'started' status.
|
|
76
|
+
* Thread-safe via mutex. Returns true if already started or started successfully.
|
|
77
|
+
*/
|
|
27
78
|
start(): Promise<boolean>;
|
|
79
|
+
/**
|
|
80
|
+
* Checks whether this instance is currently started.
|
|
81
|
+
* Takes an action if not started, based on the notStartedAction parameter.
|
|
82
|
+
* @param notStartedAction - What to do if not started: 'error'/'throw' throws, 'warn'/'log' logs, 'none' is silent
|
|
83
|
+
* @returns True if started, false otherwise
|
|
84
|
+
*/
|
|
28
85
|
started(notStartedAction?: 'error' | 'throw' | 'warn' | 'log' | 'none'): boolean;
|
|
86
|
+
/**
|
|
87
|
+
* Async version of `started` that can optionally auto-start the instance.
|
|
88
|
+
* @param notStartedAction - What to do if not started and auto-start is disabled
|
|
89
|
+
* @param tryStart - If true, attempts to start the instance automatically
|
|
90
|
+
* @returns True if the instance is or becomes started
|
|
91
|
+
*/
|
|
29
92
|
startedAsync(notStartedAction?: 'error' | 'throw' | 'warn' | 'log' | 'none', tryStart?: boolean): Promise<boolean>;
|
|
93
|
+
/**
|
|
94
|
+
* Stops the instance, transitioning through 'stopping' to 'stopped' status.
|
|
95
|
+
* Thread-safe via mutex. Returns true if already stopped or stopped successfully.
|
|
96
|
+
*/
|
|
30
97
|
stop(): Promise<boolean>;
|
|
98
|
+
/**
|
|
99
|
+
* Asserts that the given function has not been overridden in a subclass.
|
|
100
|
+
* Used to enforce the handler pattern (override `startHandler` not `start`).
|
|
101
|
+
*/
|
|
31
102
|
protected _noOverride(functionName?: string): void;
|
|
103
|
+
/** Sets the lifecycle status and reports it via the status reporter. */
|
|
32
104
|
protected setStatus(value: Exclude<CreatableStatus, 'error'>, progress?: number): void;
|
|
33
105
|
protected setStatus(value: Extract<CreatableStatus, 'error'>, error?: Error): void;
|
|
106
|
+
/** Override in subclasses to define start behavior. Throw an error on failure. */
|
|
34
107
|
protected startHandler(): Promisable<void>;
|
|
108
|
+
/** Override in subclasses to define stop behavior. Throw an error on failure. */
|
|
35
109
|
protected stopHandler(): Promisable<void>;
|
|
36
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Extends AbstractCreatable with a static `factory` method for creating
|
|
113
|
+
* pre-configured CreatableFactory instances.
|
|
114
|
+
*/
|
|
37
115
|
export declare class AbstractCreatableWithFactory<TParams extends CreatableParams = CreatableParams, TEventData extends EventData = EventData> extends AbstractCreatable<TParams, TEventData> {
|
|
116
|
+
/**
|
|
117
|
+
* Creates a factory that produces instances of this class with pre-configured params and labels.
|
|
118
|
+
* @param params - Default parameters for instances created by the factory
|
|
119
|
+
* @param labels - Labels to assign to created instances
|
|
120
|
+
*/
|
|
38
121
|
static factory<T extends CreatableInstance>(this: Creatable<T>, params?: Partial<T['params']>, labels?: Labels): CreatableFactory<T>;
|
|
39
122
|
}
|
|
40
123
|
//# sourceMappingURL=AbstractCreatable.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractCreatable.d.ts","sourceRoot":"","sources":["../../src/AbstractCreatable.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EACL,UAAU,EACX,MAAM,mBAAmB,CAAA;AAO1B,OAAO,EACL,KAAK,SAAS,EAAa,gBAAgB,EAC5C,MAAM,gBAAgB,CAAA;AAGvB,OAAO,KAAK,EACV,iBAAiB,EAAE,aAAa,EAAE,eAAe,EACjD,eAAe,EACf,MAAM,EACN,uBAAuB,EACxB,MAAM,kBAAkB,CAAA;AAKzB,qBACa,iBAAiB,CAAC,OAAO,SAAS,eAAe,GAAG,eAAe,EAC9E,UAAU,SAAS,SAAS,GAAG,SAAS,CAAE,SAAQ,WAAW,CAAC,OAAO,CAAC,OAAO,GAAG,uBAAuB,CAAC,EAAE,UAAU,CAAC;IACrH,aAAa,CAAC,EAAE,MAAM,CAAA;IAEtB,SAAS,CAAC,aAAa,EAAE,UAAU,CAAC,OAAO,CAAC,GAAG,SAAS,CAAA;IACxD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CAAC;IACxF;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,CAAC,SAAS,iBAAiB,EACxC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,EAClB,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAC7B,MAAM,CAAC,EAAE,MAAM,GACd,gBAAgB,CAAC,CAAC,CAAC;CAGvB"}
|
|
@@ -2,17 +2,34 @@ import type { Logger } from '@xylabs/logger';
|
|
|
2
2
|
import type { Promisable } from '@xylabs/promise';
|
|
3
3
|
import type { AbstractCreatable } from './AbstractCreatable.ts';
|
|
4
4
|
import type { CreatableInstance, CreatableParams, Labels, RequiredCreatableParams } from './model/index.ts';
|
|
5
|
+
/**
|
|
6
|
+
* A factory interface for creating instances of a Creatable with pre-configured parameters.
|
|
7
|
+
* Unlike the full Creatable, this only exposes the `create` method.
|
|
8
|
+
*/
|
|
5
9
|
export interface CreatableFactory<T extends CreatableInstance = CreatableInstance> extends Omit<Creatable<T>, 'create' | 'createHandler' | 'paramsHandler' | 'defaultLogger' | 'factory'> {
|
|
10
|
+
/** Creates a new instance, merging the provided params with the factory's defaults. */
|
|
6
11
|
create(this: CreatableFactory<T>, params?: Partial<T['params']>): Promise<T>;
|
|
7
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* Static interface for classes that support asynchronous creation.
|
|
15
|
+
* Provides the `create`, `createHandler`, and `paramsHandler` static methods
|
|
16
|
+
* used to construct instances through the creatable lifecycle.
|
|
17
|
+
*/
|
|
8
18
|
export interface Creatable<T extends CreatableInstance = CreatableInstance> {
|
|
19
|
+
/** Optional default logger shared across instances created by this class. */
|
|
9
20
|
defaultLogger?: Logger;
|
|
21
|
+
/** Constructs a new raw instance. Should not be called directly; use `create` instead. */
|
|
10
22
|
new (key: unknown, params: Partial<CreatableParams>): T & AbstractCreatable<T['params']>;
|
|
23
|
+
/** Asynchronously creates and initializes a new instance with the given params. */
|
|
11
24
|
create<T extends CreatableInstance>(this: Creatable<T>, params?: Partial<T['params']>): Promise<T>;
|
|
25
|
+
/** Hook called after construction to perform additional initialization on the instance. */
|
|
12
26
|
createHandler<T extends CreatableInstance>(this: Creatable<T>, instance: T): Promisable<T>;
|
|
27
|
+
/** Hook called to validate and transform params before instance construction. */
|
|
13
28
|
paramsHandler<T extends CreatableInstance>(this: Creatable<T>, params?: Partial<T['params']>): Promisable<T['params'] & RequiredCreatableParams>;
|
|
14
29
|
}
|
|
30
|
+
/** Extends Creatable with a `factory` method that produces pre-configured CreatableFactory instances. */
|
|
15
31
|
export interface CreatableWithFactory<T extends CreatableInstance = CreatableInstance> extends Creatable<T> {
|
|
32
|
+
/** Creates a factory with the given default params and labels. */
|
|
16
33
|
factory<T extends CreatableInstance>(this: Creatable<T>, params?: Partial<T['params']>, labels?: Labels): CreatableFactory<T>;
|
|
17
34
|
}
|
|
18
35
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Creatable.d.ts","sourceRoot":"","sources":["../../src/Creatable.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAEjD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC/D,OAAO,KAAK,EACV,iBAAiB,EAAE,eAAe,EAAE,MAAM,EAC1C,uBAAuB,EACxB,MAAM,kBAAkB,CAAA;AAEzB,MAAM,WAAW,gBAAgB,CAAC,CAAC,SAAS,iBAAiB,GAAG,iBAAiB,CAC/E,SAAQ,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,QAAQ,GAAG,eAAe,GAAG,eAAe,GAAG,eAAe,GAAG,SAAS,CAAC;IAEtG,MAAM,CACJ,IAAI,EAAE,gBAAgB,CAAC,CAAC,CAAC,EACzB,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,CAA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index.ts';
|
|
3
|
+
/**
|
|
4
|
+
* A concrete factory that wraps a Creatable class with default parameters and labels.
|
|
5
|
+
* Instances are created by merging caller-provided params over the factory defaults.
|
|
6
|
+
*/
|
|
3
7
|
export declare class Factory<T extends CreatableInstance = CreatableInstance> implements CreatableFactory<T> {
|
|
8
|
+
/** The Creatable class this factory delegates creation to. */
|
|
4
9
|
creatable: Creatable<T>;
|
|
10
|
+
/** Default parameters merged into every `create` call. */
|
|
5
11
|
defaultParams?: Partial<T['params']>;
|
|
12
|
+
/** Labels identifying resources created by this factory. */
|
|
6
13
|
labels?: Labels;
|
|
7
14
|
constructor(creatable: Creatable<T>, params?: Partial<T['params']>, labels?: Labels);
|
|
15
|
+
/**
|
|
16
|
+
* Creates a new Factory instance with the given default params and labels.
|
|
17
|
+
* @param creatableModule - The Creatable class to wrap
|
|
18
|
+
* @param params - Default parameters for new instances
|
|
19
|
+
* @param labels - Labels to assign to created instances
|
|
20
|
+
*/
|
|
8
21
|
static withParams<T extends CreatableInstance>(creatableModule: Creatable<T>, params?: Partial<T['params']>, labels?: Labels): Factory<T>;
|
|
22
|
+
/**
|
|
23
|
+
* Creates a new instance, merging the provided params over the factory defaults.
|
|
24
|
+
* @param params - Optional parameters to override the factory defaults
|
|
25
|
+
*/
|
|
9
26
|
create(params?: Partial<T['params']>): Promise<T>;
|
|
10
27
|
}
|
|
11
28
|
//# sourceMappingURL=Factory.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Factory.d.ts","sourceRoot":"","sources":["../../src/Factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAA;AACtE,OAAO,KAAK,EACV,iBAAiB,EAAE,MAAM,EAC1B,MAAM,kBAAkB,CAAA;AAEzB,qBAAa,OAAO,CAAC,CAAC,SAAS,iBAAiB,GAAG,iBAAiB,CAAE,YAAW,gBAAgB,CAAC,CAAC,CAAC;I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AC,CAAC,QAAQ,CAAC,CAAC,EAC7B,MAAM,GAAE,MAAW;IAOrB;;;;;OAKG;IACH,MAAM,CAAC,UAAU,CAAC,CAAC,SAAS,iBAAiB,EAC3C,eAAe,EAAE,SAAS,CAAC,CAAC,CAAC,EAC7B,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAC7B,MAAM,GAAE,MAAW;IAKrB;;;OAGG;IACH,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAOlD"}
|
package/dist/neutral/index.mjs
CHANGED
|
@@ -38,17 +38,30 @@ function creatableFactory() {
|
|
|
38
38
|
|
|
39
39
|
// src/Factory.ts
|
|
40
40
|
var Factory = class _Factory {
|
|
41
|
+
/** The Creatable class this factory delegates creation to. */
|
|
41
42
|
creatable;
|
|
43
|
+
/** Default parameters merged into every `create` call. */
|
|
42
44
|
defaultParams;
|
|
45
|
+
/** Labels identifying resources created by this factory. */
|
|
43
46
|
labels;
|
|
44
47
|
constructor(creatable2, params, labels = {}) {
|
|
45
48
|
this.creatable = creatable2;
|
|
46
49
|
this.defaultParams = params;
|
|
47
50
|
this.labels = Object.assign({}, creatable2.labels ?? {}, labels ?? {});
|
|
48
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Creates a new Factory instance with the given default params and labels.
|
|
54
|
+
* @param creatableModule - The Creatable class to wrap
|
|
55
|
+
* @param params - Default parameters for new instances
|
|
56
|
+
* @param labels - Labels to assign to created instances
|
|
57
|
+
*/
|
|
49
58
|
static withParams(creatableModule, params, labels = {}) {
|
|
50
59
|
return new _Factory(creatableModule, params, labels);
|
|
51
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Creates a new instance, merging the provided params over the factory defaults.
|
|
63
|
+
* @param params - Optional parameters to override the factory defaults
|
|
64
|
+
*/
|
|
52
65
|
create(params) {
|
|
53
66
|
const mergedParams = {
|
|
54
67
|
...this.defaultParams,
|
|
@@ -88,6 +101,7 @@ function getRootFunction(obj, funcName) {
|
|
|
88
101
|
var AbstractCreatableConstructorKey = /* @__PURE__ */ Symbol.for("AbstractCreatableConstructor");
|
|
89
102
|
var CREATABLE_NOT_STARTED = "Creatable not Started";
|
|
90
103
|
var AbstractCreatable = class extends BaseEmitter {
|
|
104
|
+
/** Optional default logger for this instance. */
|
|
91
105
|
defaultLogger;
|
|
92
106
|
_startPromise;
|
|
93
107
|
_status = null;
|
|
@@ -97,22 +111,33 @@ var AbstractCreatable = class extends BaseEmitter {
|
|
|
97
111
|
assertEx(key === AbstractCreatableConstructorKey, () => "AbstractCreatable should not be instantiated directly, use the static create method instead");
|
|
98
112
|
super(params);
|
|
99
113
|
}
|
|
114
|
+
/** The name identifier for this creatable instance. */
|
|
100
115
|
get name() {
|
|
101
116
|
return this.params.name;
|
|
102
117
|
}
|
|
118
|
+
/** The validated and merged parameters for this instance. */
|
|
103
119
|
get params() {
|
|
104
120
|
this._validatedParams = this._validatedParams ?? this.paramsValidator(super.params);
|
|
105
121
|
return this._validatedParams;
|
|
106
122
|
}
|
|
123
|
+
/** Whether this instance can be started (must be in 'created' or 'stopped' status). */
|
|
107
124
|
get startable() {
|
|
108
125
|
return this.status === "created" || this.status === "stopped";
|
|
109
126
|
}
|
|
127
|
+
/** The current lifecycle status of this instance, or null if not yet initialized. */
|
|
110
128
|
get status() {
|
|
111
129
|
return this._status;
|
|
112
130
|
}
|
|
131
|
+
/** The status reporter used to broadcast lifecycle changes. */
|
|
113
132
|
get statusReporter() {
|
|
114
133
|
return this.params.statusReporter;
|
|
115
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Asynchronously creates a new instance by processing params, constructing,
|
|
137
|
+
* and running both static and instance createHandlers.
|
|
138
|
+
* @param inParams - Optional partial parameters to configure the instance
|
|
139
|
+
* @returns The fully initialized instance
|
|
140
|
+
*/
|
|
116
141
|
static async create(inParams = {}) {
|
|
117
142
|
const params = await this.paramsHandler(inParams);
|
|
118
143
|
const name = params.name ?? this.name;
|
|
@@ -129,21 +154,51 @@ var AbstractCreatable = class extends BaseEmitter {
|
|
|
129
154
|
throw isError(ex) ? ex : new Error(`Error creating: ${name}`);
|
|
130
155
|
}
|
|
131
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Static hook called during creation to perform additional initialization.
|
|
159
|
+
* Override in subclasses to customize post-construction setup.
|
|
160
|
+
* @param instance - The newly constructed instance
|
|
161
|
+
* @returns The instance, potentially modified
|
|
162
|
+
*/
|
|
132
163
|
static createHandler(instance) {
|
|
133
164
|
return instance;
|
|
134
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* Static hook called during creation to validate and transform params.
|
|
168
|
+
* Override in subclasses to add default values or validation.
|
|
169
|
+
* @param params - The raw partial params provided to `create`
|
|
170
|
+
* @returns The processed params ready for construction
|
|
171
|
+
*/
|
|
135
172
|
static paramsHandler(params = {}) {
|
|
136
173
|
return { ...params };
|
|
137
174
|
}
|
|
175
|
+
/** Instance-level creation hook. Override in subclasses to perform setup after construction. */
|
|
138
176
|
createHandler() {
|
|
139
177
|
assertEx(this._status === "creating", () => `createHandler can not be called [status = ${this.status}]`);
|
|
140
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* Validates and returns the merged params, ensuring required fields are present.
|
|
181
|
+
* Override in subclasses to add custom validation logic.
|
|
182
|
+
* @param params - The raw partial params to validate
|
|
183
|
+
* @returns The validated params
|
|
184
|
+
*/
|
|
141
185
|
paramsValidator(params) {
|
|
142
186
|
return { ...params, name: params.name };
|
|
143
187
|
}
|
|
188
|
+
/**
|
|
189
|
+
* Executes a function within a telemetry span.
|
|
190
|
+
* @param name - The span name
|
|
191
|
+
* @param fn - The function to execute within the span
|
|
192
|
+
*/
|
|
144
193
|
span(name, fn) {
|
|
145
194
|
return spanRoot(name, fn, this.tracer);
|
|
146
195
|
}
|
|
196
|
+
/**
|
|
197
|
+
* Executes an async function within a telemetry span.
|
|
198
|
+
* @param name - The span name
|
|
199
|
+
* @param fn - The async function to execute within the span
|
|
200
|
+
* @param config - Optional span configuration
|
|
201
|
+
*/
|
|
147
202
|
async spanAsync(name, fn, config = {}) {
|
|
148
203
|
return await spanRootAsync(name, fn, {
|
|
149
204
|
...config,
|
|
@@ -151,6 +206,10 @@ var AbstractCreatable = class extends BaseEmitter {
|
|
|
151
206
|
logger: config.logger ?? this.defaultLogger
|
|
152
207
|
});
|
|
153
208
|
}
|
|
209
|
+
/**
|
|
210
|
+
* Starts the instance, transitioning through 'starting' to 'started' status.
|
|
211
|
+
* Thread-safe via mutex. Returns true if already started or started successfully.
|
|
212
|
+
*/
|
|
154
213
|
async start() {
|
|
155
214
|
this._noOverride("start");
|
|
156
215
|
if (this.status === "started") {
|
|
@@ -173,6 +232,12 @@ var AbstractCreatable = class extends BaseEmitter {
|
|
|
173
232
|
}
|
|
174
233
|
});
|
|
175
234
|
}
|
|
235
|
+
/**
|
|
236
|
+
* Checks whether this instance is currently started.
|
|
237
|
+
* Takes an action if not started, based on the notStartedAction parameter.
|
|
238
|
+
* @param notStartedAction - What to do if not started: 'error'/'throw' throws, 'warn'/'log' logs, 'none' is silent
|
|
239
|
+
* @returns True if started, false otherwise
|
|
240
|
+
*/
|
|
176
241
|
started(notStartedAction = "log") {
|
|
177
242
|
if (isString(this.status) && this.status === "started") {
|
|
178
243
|
return true;
|
|
@@ -203,6 +268,12 @@ var AbstractCreatable = class extends BaseEmitter {
|
|
|
203
268
|
return false;
|
|
204
269
|
}
|
|
205
270
|
}
|
|
271
|
+
/**
|
|
272
|
+
* Async version of `started` that can optionally auto-start the instance.
|
|
273
|
+
* @param notStartedAction - What to do if not started and auto-start is disabled
|
|
274
|
+
* @param tryStart - If true, attempts to start the instance automatically
|
|
275
|
+
* @returns True if the instance is or becomes started
|
|
276
|
+
*/
|
|
206
277
|
async startedAsync(notStartedAction = "log", tryStart = true) {
|
|
207
278
|
if (isString(this.status) && this.status === "started") {
|
|
208
279
|
return true;
|
|
@@ -226,6 +297,10 @@ var AbstractCreatable = class extends BaseEmitter {
|
|
|
226
297
|
}
|
|
227
298
|
return await this._startPromise;
|
|
228
299
|
}
|
|
300
|
+
/**
|
|
301
|
+
* Stops the instance, transitioning through 'stopping' to 'stopped' status.
|
|
302
|
+
* Thread-safe via mutex. Returns true if already stopped or stopped successfully.
|
|
303
|
+
*/
|
|
229
304
|
async stop() {
|
|
230
305
|
this._noOverride("stop");
|
|
231
306
|
if (this.status === "stopped") {
|
|
@@ -247,6 +322,10 @@ var AbstractCreatable = class extends BaseEmitter {
|
|
|
247
322
|
}
|
|
248
323
|
});
|
|
249
324
|
}
|
|
325
|
+
/**
|
|
326
|
+
* Asserts that the given function has not been overridden in a subclass.
|
|
327
|
+
* Used to enforce the handler pattern (override `startHandler` not `start`).
|
|
328
|
+
*/
|
|
250
329
|
_noOverride(functionName = getFunctionName(3)) {
|
|
251
330
|
const thisFunc = this[functionName];
|
|
252
331
|
const rootFunc = getRootFunction(this, functionName);
|
|
@@ -269,8 +348,10 @@ var AbstractCreatable = class extends BaseEmitter {
|
|
|
269
348
|
this.statusReporter?.report(this.name, value);
|
|
270
349
|
}
|
|
271
350
|
}
|
|
351
|
+
/** Override in subclasses to define start behavior. Throw an error on failure. */
|
|
272
352
|
startHandler() {
|
|
273
353
|
}
|
|
354
|
+
/** Override in subclasses to define stop behavior. Throw an error on failure. */
|
|
274
355
|
stopHandler() {
|
|
275
356
|
}
|
|
276
357
|
};
|
|
@@ -278,6 +359,11 @@ AbstractCreatable = __decorateClass([
|
|
|
278
359
|
creatable()
|
|
279
360
|
], AbstractCreatable);
|
|
280
361
|
var AbstractCreatableWithFactory = class extends AbstractCreatable {
|
|
362
|
+
/**
|
|
363
|
+
* Creates a factory that produces instances of this class with pre-configured params and labels.
|
|
364
|
+
* @param params - Default parameters for instances created by the factory
|
|
365
|
+
* @param labels - Labels to assign to created instances
|
|
366
|
+
*/
|
|
281
367
|
static factory(params, labels) {
|
|
282
368
|
return Factory.withParams(this, params, labels);
|
|
283
369
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/AbstractCreatable.ts","../../src/Creatable.ts","../../src/Factory.ts","../../src/lib/getFunctionName.ts","../../src/lib/getRootFunction.ts","../../src/model/Labels.ts"],"sourcesContent":["import { assertEx } from '@xylabs/assert'\nimport type { EventData } from '@xylabs/events'\nimport { BaseEmitter } from '@xylabs/events'\nimport { type Logger } from '@xylabs/logger'\nimport type { Promisable } from '@xylabs/promise'\nimport {\n SpanConfig, spanRoot, spanRootAsync,\n} from '@xylabs/telemetry'\nimport {\n isError, isNumber, isString,\n isUndefined,\n} from '@xylabs/typeof'\nimport { Mutex } from 'async-mutex'\n\nimport {\n type Creatable, creatable, CreatableFactory,\n} from './Creatable.ts'\nimport { Factory } from './Factory.ts'\nimport { getFunctionName, getRootFunction } from './lib/index.ts'\nimport type {\n CreatableInstance, CreatableName, CreatableParams,\n CreatableStatus,\n Labels,\n RequiredCreatableParams,\n} from './model/index.ts'\n\nconst AbstractCreatableConstructorKey = Symbol.for('AbstractCreatableConstructor')\nconst CREATABLE_NOT_STARTED = 'Creatable not Started' as const\n\n@creatable()\nexport class AbstractCreatable<TParams extends CreatableParams = CreatableParams,\n TEventData extends EventData = EventData> extends BaseEmitter<Partial<TParams & RequiredCreatableParams>, TEventData> {\n defaultLogger?: Logger\n\n protected _startPromise: Promisable<boolean> | undefined\n private _status: CreatableStatus | null = null\n private _statusMutex = new Mutex()\n private _validatedParams?: TParams & RequiredCreatableParams\n\n constructor(key: unknown, params: Partial<TParams & RequiredCreatableParams>) {\n assertEx(key === AbstractCreatableConstructorKey, () => 'AbstractCreatable should not be instantiated directly, use the static create method instead')\n super(params)\n }\n\n get name(): CreatableName {\n return this.params.name as CreatableName\n }\n\n override get params(): TParams & RequiredCreatableParams {\n this._validatedParams = this._validatedParams ?? this.paramsValidator(super.params)\n return this._validatedParams\n }\n\n get startable() {\n return this.status === 'created' || this.status === 'stopped'\n }\n\n get status(): CreatableStatus | null {\n return this._status\n }\n\n get statusReporter() {\n return this.params.statusReporter\n }\n\n static async create<T extends CreatableInstance>(\n this: Creatable<T>,\n inParams: Partial<T['params']> = {},\n ): Promise<T> {\n const params = await this.paramsHandler(inParams)\n const name: CreatableName = params.name ?? this.name as CreatableName\n try {\n const instance = new this(AbstractCreatableConstructorKey, params)\n instance.setStatus('creating')\n const initializedInstance = await this.createHandler(instance)\n await instance.createHandler()\n instance.setStatus('created')\n return initializedInstance\n } catch (ex) {\n params.statusReporter?.report(name, 'error', isError(ex) ? ex : new Error(`Error creating: ${name}`))\n params.logger?.error(`Error creating creatable [${name}]: ${(isError(ex) ? `${ex.message} ${ex.stack}` : ex)}`)\n throw isError(ex) ? ex : new Error(`Error creating: ${name}`)\n }\n }\n\n static createHandler<T extends CreatableInstance>(\n this: Creatable<T>,\n instance: T,\n ): Promisable<T> {\n return instance\n }\n\n static paramsHandler<T extends CreatableInstance>(\n this: Creatable<T>,\n params: Partial<T['params']> = {},\n ): Promisable<T['params']> {\n return { ...params }\n }\n\n createHandler(): Promisable<void> {\n assertEx(this._status === 'creating', () => `createHandler can not be called [status = ${this.status}]`)\n }\n\n paramsValidator(params: Partial<TParams & RequiredCreatableParams>): TParams & RequiredCreatableParams {\n return { ...params, name: params.name } as TParams & RequiredCreatableParams\n }\n\n span<T>(name: string, fn: () => T): T {\n return spanRoot(name, fn, this.tracer)\n }\n\n async spanAsync<T>(name: string, fn: () => Promise<T>, config: SpanConfig = {}): Promise<T> {\n return await spanRootAsync(name, fn, {\n ...config, tracer: config.tracer ?? this.tracer, logger: config.logger ?? this.defaultLogger,\n })\n }\n\n async start(): Promise<boolean> {\n this._noOverride('start')\n if (this.status === 'started') {\n return true\n }\n return await this._statusMutex.runExclusive(async () => {\n try {\n // check again in case it changed\n if (this.status === 'started') {\n return true\n }\n assertEx(this.startable, () => `Creatable [${this.name}] is not startable in status [${this.status}]`)\n this.setStatus('starting')\n await this.startHandler()\n this.setStatus('started')\n return true\n } catch (ex) {\n this.setStatus('error', isError(ex) ? ex : new Error(`Error starting: ${ex}`))\n this.logger?.error(`Error starting creatable [${this.name}]: ${(isError(ex) ? `${ex.message} ${ex.stack}` : ex)}`)\n return false\n }\n })\n }\n\n started(notStartedAction: 'error' | 'throw' | 'warn' | 'log' | 'none' = 'log'): boolean {\n if (isString(this.status) && this.status === 'started') {\n return true\n } else {\n const message = () => `${CREATABLE_NOT_STARTED} [${this.name}] current state: ${this.status}`\n switch (notStartedAction) {\n case 'error': {\n throw new Error(message())\n }\n case 'throw': {\n throw new Error(message())\n }\n case 'warn': {\n this.logger?.warn(message())\n break\n }\n case 'log': {\n this.logger?.log(message())\n break\n }\n case 'none': {\n break\n }\n default: {\n throw new Error(`Unknown notStartedAction: ${notStartedAction}`)\n }\n }\n return false\n }\n }\n\n async startedAsync(notStartedAction: 'error' | 'throw' | 'warn' | 'log' | 'none' = 'log', tryStart = true): Promise<boolean> {\n if (isString(this.status) && this.status === 'started') {\n return true\n } else if (this.status === 'created' || this.status === 'stopped' || this.status === 'starting') {\n // using promise as mutex\n this._startPromise = this._startPromise ?? (async () => {\n if (tryStart) {\n try {\n return await this.start()\n } finally {\n this._startPromise = undefined\n }\n }\n return this.started(notStartedAction)\n })()\n } else {\n const message = `${CREATABLE_NOT_STARTED} [${this.name}] current state: ${this.status}`\n throw new Error(message)\n }\n\n if (isUndefined(this._startPromise)) {\n throw new Error(`Failed to create start promise: ${this.status}`)\n }\n return await this._startPromise\n }\n\n async stop(): Promise<boolean> {\n this._noOverride('stop')\n if (this.status === 'stopped') {\n return true\n }\n return await this._statusMutex.runExclusive(async () => {\n try {\n // check again in case it changed\n if (this.status === 'stopped') {\n return true\n }\n assertEx(this.status === 'started', () => `Creatable [${this.name}] is not stoppable in status [${this.status}]`)\n this.setStatus('stopping')\n await this.stopHandler()\n this.setStatus('stopped')\n return true\n } catch (ex) {\n this.setStatus('error', isError(ex) ? ex : new Error(`Error stopping: ${ex}`))\n return false\n }\n })\n }\n\n protected _noOverride(functionName = getFunctionName(3)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const thisFunc = (this as any)[functionName]\n\n const rootFunc = getRootFunction(this, functionName)\n assertEx(thisFunc === rootFunc, () => `Override not allowed for [${functionName}] - override ${functionName}Handler instead`)\n }\n\n protected setStatus(value: Exclude<CreatableStatus, 'error'>, progress?: number): void\n protected setStatus(value: Extract<CreatableStatus, 'error'>, error?: Error): void\n protected setStatus(value: CreatableStatus, progressOrError?: number | Error): void {\n this._status = value\n if (value !== null) {\n if (value === 'error') {\n if (isError(progressOrError)) {\n this.statusReporter?.report(this.name, value, progressOrError)\n return\n }\n } else {\n if (isNumber(progressOrError)) {\n this.statusReporter?.report(this.name, value, progressOrError)\n return\n }\n }\n this.statusReporter?.report(this.name, value)\n }\n }\n\n protected startHandler(): Promisable<void> {\n // when overriding this, throw an error on failure\n }\n\n protected stopHandler(): Promisable<void> {\n // when overriding this, throw an error on failure\n }\n}\n\n@creatable()\nexport class AbstractCreatableWithFactory<TParams extends CreatableParams = CreatableParams,\n TEventData extends EventData = EventData> extends AbstractCreatable<TParams, TEventData> {\n static factory<T extends CreatableInstance>(\n this: Creatable<T>,\n params?: Partial<T['params']>,\n labels?: Labels,\n ): CreatableFactory<T> {\n return Factory.withParams<T>(this, params, labels)\n }\n}\n","import type { Logger } from '@xylabs/logger'\nimport type { Promisable } from '@xylabs/promise'\n\nimport type { AbstractCreatable } from './AbstractCreatable.ts'\nimport type {\n CreatableInstance, CreatableParams, Labels,\n RequiredCreatableParams,\n} from './model/index.ts'\n\nexport interface CreatableFactory<T extends CreatableInstance = CreatableInstance>\n extends Omit<Creatable<T>, 'create' | 'createHandler' | 'paramsHandler' | 'defaultLogger' | 'factory'> {\n\n create(\n this: CreatableFactory<T>,\n params?: Partial<T['params']>): Promise<T>\n}\n\nexport interface Creatable<T extends CreatableInstance = CreatableInstance> {\n\n defaultLogger?: Logger\n\n new(key: unknown, params: Partial<CreatableParams>): T & AbstractCreatable<T['params']>\n\n create<T extends CreatableInstance>(\n this: Creatable<T>,\n params?: Partial<T['params']>): Promise<T>\n\n createHandler<T extends CreatableInstance>(\n this: Creatable<T>,\n instance: T\n ): Promisable<T>\n\n paramsHandler<T extends CreatableInstance>(\n this: Creatable<T>, params?: Partial<T['params']>): Promisable<T['params'] & RequiredCreatableParams>\n}\n\nexport interface CreatableWithFactory<T extends CreatableInstance = CreatableInstance> extends Creatable<T> {\n factory<T extends CreatableInstance>(\n this: Creatable<T>,\n params?: Partial<T['params']>,\n labels?: Labels): CreatableFactory<T>\n}\n\n/**\n * Class annotation to be used to decorate Modules which support\n * an asynchronous creation pattern\n * @returns The decorated Module requiring it implement the members\n * of the CreatableModule as statics properties/methods\n */\nexport function creatable<T extends CreatableInstance>() {\n return <U extends Creatable<T>>(constructor: U) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n constructor\n }\n}\n\n/**\n * Class annotation to be used to decorate Modules which support\n * an asynchronous creation factory pattern\n * @returns The decorated Module requiring it implement the members\n * of the CreatableModule as statics properties/methods\n */\n\nexport function creatableFactory() {\n return <U extends CreatableFactory>(constructor: U) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n constructor\n }\n}\n","import { type Creatable, type CreatableFactory } from './Creatable.ts'\nimport type {\n CreatableInstance, Labels, WithOptionalLabels,\n} from './model/index.ts'\n\nexport class Factory<T extends CreatableInstance = CreatableInstance> implements CreatableFactory<T> {\n creatable: Creatable<T>\n\n defaultParams?: Partial<T['params']>\n\n labels?: Labels\n\n constructor(\n creatable: Creatable<T>,\n params?: Partial<T['params']>,\n labels: Labels = {},\n ) {\n this.creatable = creatable\n this.defaultParams = params\n this.labels = Object.assign({}, (creatable as WithOptionalLabels).labels ?? {}, labels ?? {})\n }\n\n static withParams<T extends CreatableInstance>(\n creatableModule: Creatable<T>,\n params?: Partial<T['params']>,\n labels: Labels = {},\n ) {\n return new Factory<T>(creatableModule, params, labels)\n }\n\n create(params?: Partial<T['params']>): Promise<T> {\n const mergedParams: T['params'] = {\n ...this.defaultParams,\n ...params,\n } as T['params']\n return this.creatable.create<T>(mergedParams)\n }\n}\n","import { isNumber } from '@xylabs/typeof'\n\nexport function getFunctionName(depth = 2) {\n const error = new Error('Stack')\n let newIndex: number | undefined\n const stackParts = error.stack?.split('\\n')[depth]?.split(' ')\n const funcName\n = stackParts?.find((item, index) => {\n if (item.length > 0 && item !== 'at') {\n // check if constructor\n if (item === 'new') {\n newIndex = index\n }\n return true\n }\n }) ?? '<unknown>'\n return isNumber(newIndex) ? `${funcName} ${stackParts?.[newIndex + 1]}` : funcName\n}\n","export function getRootFunction(obj: unknown, funcName: string) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let anyObj = obj as any\n while (anyObj.__proto__?.[funcName]) {\n anyObj = anyObj.__proto__\n }\n return anyObj[funcName]\n}\n","/**\n * Object used to represent labels identifying a resource.\n */\nexport interface Labels {\n [key: string]: string | undefined\n}\n\n/**\n * Interface for objects that have labels.\n */\nexport interface WithLabels<T extends Labels = Labels> {\n labels: T\n}\n\n/**\n * Interface for objects that have labels.\n */\nexport interface WithOptionalLabels<T extends Labels = Labels> {\n labels?: T\n}\n\n/**\n * Returns true if the source object has all the labels from the required set\n * @param source Source object to check against\n * @param required Set of labels to check for in source\n * @returns True of the source object has all the labels from the required set\n */\nexport const hasAllLabels = (source?: Labels, required?: Labels): boolean => {\n if (!required) return true\n return Object.entries(required).every(([key, value]) => {\n return source?.hasOwnProperty(key as keyof typeof source) && source?.[key as keyof typeof source] === value\n })\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAEzB,SAAS,mBAAmB;AAG5B;AAAA,EACc;AAAA,EAAU;AAAA,OACjB;AACP;AAAA,EACE;AAAA,EAAS,YAAAA;AAAA,EAAU;AAAA,EACnB;AAAA,OACK;AACP,SAAS,aAAa;;;ACqCf,SAAS,YAAyC;AACvD,SAAO,CAAyB,gBAAmB;AAEjD;AAAA,EACF;AACF;AASO,SAA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C7D;AAAA,QACF;AAAA,MACF;AACA,WAAK,gBAAgB,OAAO,KAAK,MAAM,KAAK;AAAA,IAC9C;AAAA,EACF;AAAA,EAEU,eAAiC;AAAA,EAE3C;AAAA,EAEU,cAAgC;AAAA,EAE1C;AACF;AAlOa,oBAAN;AAAA,EADN,UAAU;AAAA,GACE;AAqON,IAAM,+BAAN,cAC6C,kBAAuC;AAAA,EACzF,OAAO,QAEL,QACA,QACqB;AACrB,WAAO,QAAQ,WAAc,MAAM,QAAQ,MAAM;AAAA,EACnD;AACF;AATa,+BAAN;AAAA,EADN,UAAU;AAAA,GACE;;;AKxON,IAAM,eAAe,CAAC,QAAiB,aAA+B;AAC3E,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO,OAAO,QAAQ,QAAQ,EAAE,MAAM,CAAC,CAAC,KAAK,KAAK,MAAM;AACtD,WAAO,QAAQ,eAAe,GAA0B,KAAK,SAAS,GAA0B,MAAM;AAAA,EACxG,CAAC;AACH;","names":["isNumber","creatable","isNumber"]}
|
|
1
|
+
{"version":3,"sources":["../../src/AbstractCreatable.ts","../../src/Creatable.ts","../../src/Factory.ts","../../src/lib/getFunctionName.ts","../../src/lib/getRootFunction.ts","../../src/model/Labels.ts"],"sourcesContent":["import { assertEx } from '@xylabs/assert'\nimport type { EventData } from '@xylabs/events'\nimport { BaseEmitter } from '@xylabs/events'\nimport { type Logger } from '@xylabs/logger'\nimport type { Promisable } from '@xylabs/promise'\nimport {\n SpanConfig, spanRoot, spanRootAsync,\n} from '@xylabs/telemetry'\nimport {\n isError, isNumber, isString,\n isUndefined,\n} from '@xylabs/typeof'\nimport { Mutex } from 'async-mutex'\n\nimport {\n type Creatable, creatable, CreatableFactory,\n} from './Creatable.ts'\nimport { Factory } from './Factory.ts'\nimport { getFunctionName, getRootFunction } from './lib/index.ts'\nimport type {\n CreatableInstance, CreatableName, CreatableParams,\n CreatableStatus,\n Labels,\n RequiredCreatableParams,\n} from './model/index.ts'\n\nconst AbstractCreatableConstructorKey = Symbol.for('AbstractCreatableConstructor')\nconst CREATABLE_NOT_STARTED = 'Creatable not Started' as const\n\n/**\n * Base class for objects that follow an asynchronous creation and lifecycle pattern.\n * Instances must be created via the static `create` method rather than direct construction.\n * Provides start/stop lifecycle management with status tracking and telemetry support.\n */\n@creatable()\nexport class AbstractCreatable<TParams extends CreatableParams = CreatableParams,\n TEventData extends EventData = EventData> extends BaseEmitter<Partial<TParams & RequiredCreatableParams>, TEventData> {\n /** Optional default logger for this instance. */\n defaultLogger?: Logger\n\n protected _startPromise: Promisable<boolean> | undefined\n private _status: CreatableStatus | null = null\n private _statusMutex = new Mutex()\n private _validatedParams?: TParams & RequiredCreatableParams\n\n constructor(key: unknown, params: Partial<TParams & RequiredCreatableParams>) {\n assertEx(key === AbstractCreatableConstructorKey, () => 'AbstractCreatable should not be instantiated directly, use the static create method instead')\n super(params)\n }\n\n /** The name identifier for this creatable instance. */\n get name(): CreatableName {\n return this.params.name as CreatableName\n }\n\n /** The validated and merged parameters for this instance. */\n override get params(): TParams & RequiredCreatableParams {\n this._validatedParams = this._validatedParams ?? this.paramsValidator(super.params)\n return this._validatedParams\n }\n\n /** Whether this instance can be started (must be in 'created' or 'stopped' status). */\n get startable() {\n return this.status === 'created' || this.status === 'stopped'\n }\n\n /** The current lifecycle status of this instance, or null if not yet initialized. */\n get status(): CreatableStatus | null {\n return this._status\n }\n\n /** The status reporter used to broadcast lifecycle changes. */\n get statusReporter() {\n return this.params.statusReporter\n }\n\n /**\n * Asynchronously creates a new instance by processing params, constructing,\n * and running both static and instance createHandlers.\n * @param inParams - Optional partial parameters to configure the instance\n * @returns The fully initialized instance\n */\n static async create<T extends CreatableInstance>(\n this: Creatable<T>,\n inParams: Partial<T['params']> = {},\n ): Promise<T> {\n const params = await this.paramsHandler(inParams)\n const name: CreatableName = params.name ?? this.name as CreatableName\n try {\n const instance = new this(AbstractCreatableConstructorKey, params)\n instance.setStatus('creating')\n const initializedInstance = await this.createHandler(instance)\n await instance.createHandler()\n instance.setStatus('created')\n return initializedInstance\n } catch (ex) {\n params.statusReporter?.report(name, 'error', isError(ex) ? ex : new Error(`Error creating: ${name}`))\n params.logger?.error(`Error creating creatable [${name}]: ${(isError(ex) ? `${ex.message} ${ex.stack}` : ex)}`)\n throw isError(ex) ? ex : new Error(`Error creating: ${name}`)\n }\n }\n\n /**\n * Static hook called during creation to perform additional initialization.\n * Override in subclasses to customize post-construction setup.\n * @param instance - The newly constructed instance\n * @returns The instance, potentially modified\n */\n static createHandler<T extends CreatableInstance>(\n this: Creatable<T>,\n instance: T,\n ): Promisable<T> {\n return instance\n }\n\n /**\n * Static hook called during creation to validate and transform params.\n * Override in subclasses to add default values or validation.\n * @param params - The raw partial params provided to `create`\n * @returns The processed params ready for construction\n */\n static paramsHandler<T extends CreatableInstance>(\n this: Creatable<T>,\n params: Partial<T['params']> = {},\n ): Promisable<T['params']> {\n return { ...params }\n }\n\n /** Instance-level creation hook. Override in subclasses to perform setup after construction. */\n createHandler(): Promisable<void> {\n assertEx(this._status === 'creating', () => `createHandler can not be called [status = ${this.status}]`)\n }\n\n /**\n * Validates and returns the merged params, ensuring required fields are present.\n * Override in subclasses to add custom validation logic.\n * @param params - The raw partial params to validate\n * @returns The validated params\n */\n paramsValidator(params: Partial<TParams & RequiredCreatableParams>): TParams & RequiredCreatableParams {\n return { ...params, name: params.name } as TParams & RequiredCreatableParams\n }\n\n /**\n * Executes a function within a telemetry span.\n * @param name - The span name\n * @param fn - The function to execute within the span\n */\n span<T>(name: string, fn: () => T): T {\n return spanRoot(name, fn, this.tracer)\n }\n\n /**\n * Executes an async function within a telemetry span.\n * @param name - The span name\n * @param fn - The async function to execute within the span\n * @param config - Optional span configuration\n */\n async spanAsync<T>(name: string, fn: () => Promise<T>, config: SpanConfig = {}): Promise<T> {\n return await spanRootAsync(name, fn, {\n ...config, tracer: config.tracer ?? this.tracer, logger: config.logger ?? this.defaultLogger,\n })\n }\n\n /**\n * Starts the instance, transitioning through 'starting' to 'started' status.\n * Thread-safe via mutex. Returns true if already started or started successfully.\n */\n async start(): Promise<boolean> {\n this._noOverride('start')\n if (this.status === 'started') {\n return true\n }\n return await this._statusMutex.runExclusive(async () => {\n try {\n // check again in case it changed\n if (this.status === 'started') {\n return true\n }\n assertEx(this.startable, () => `Creatable [${this.name}] is not startable in status [${this.status}]`)\n this.setStatus('starting')\n await this.startHandler()\n this.setStatus('started')\n return true\n } catch (ex) {\n this.setStatus('error', isError(ex) ? ex : new Error(`Error starting: ${ex}`))\n this.logger?.error(`Error starting creatable [${this.name}]: ${(isError(ex) ? `${ex.message} ${ex.stack}` : ex)}`)\n return false\n }\n })\n }\n\n /**\n * Checks whether this instance is currently started.\n * Takes an action if not started, based on the notStartedAction parameter.\n * @param notStartedAction - What to do if not started: 'error'/'throw' throws, 'warn'/'log' logs, 'none' is silent\n * @returns True if started, false otherwise\n */\n started(notStartedAction: 'error' | 'throw' | 'warn' | 'log' | 'none' = 'log'): boolean {\n if (isString(this.status) && this.status === 'started') {\n return true\n } else {\n const message = () => `${CREATABLE_NOT_STARTED} [${this.name}] current state: ${this.status}`\n switch (notStartedAction) {\n case 'error': {\n throw new Error(message())\n }\n case 'throw': {\n throw new Error(message())\n }\n case 'warn': {\n this.logger?.warn(message())\n break\n }\n case 'log': {\n this.logger?.log(message())\n break\n }\n case 'none': {\n break\n }\n default: {\n throw new Error(`Unknown notStartedAction: ${notStartedAction}`)\n }\n }\n return false\n }\n }\n\n /**\n * Async version of `started` that can optionally auto-start the instance.\n * @param notStartedAction - What to do if not started and auto-start is disabled\n * @param tryStart - If true, attempts to start the instance automatically\n * @returns True if the instance is or becomes started\n */\n async startedAsync(notStartedAction: 'error' | 'throw' | 'warn' | 'log' | 'none' = 'log', tryStart = true): Promise<boolean> {\n if (isString(this.status) && this.status === 'started') {\n return true\n } else if (this.status === 'created' || this.status === 'stopped' || this.status === 'starting') {\n // using promise as mutex\n this._startPromise = this._startPromise ?? (async () => {\n if (tryStart) {\n try {\n return await this.start()\n } finally {\n this._startPromise = undefined\n }\n }\n return this.started(notStartedAction)\n })()\n } else {\n const message = `${CREATABLE_NOT_STARTED} [${this.name}] current state: ${this.status}`\n throw new Error(message)\n }\n\n if (isUndefined(this._startPromise)) {\n throw new Error(`Failed to create start promise: ${this.status}`)\n }\n return await this._startPromise\n }\n\n /**\n * Stops the instance, transitioning through 'stopping' to 'stopped' status.\n * Thread-safe via mutex. Returns true if already stopped or stopped successfully.\n */\n async stop(): Promise<boolean> {\n this._noOverride('stop')\n if (this.status === 'stopped') {\n return true\n }\n return await this._statusMutex.runExclusive(async () => {\n try {\n // check again in case it changed\n if (this.status === 'stopped') {\n return true\n }\n assertEx(this.status === 'started', () => `Creatable [${this.name}] is not stoppable in status [${this.status}]`)\n this.setStatus('stopping')\n await this.stopHandler()\n this.setStatus('stopped')\n return true\n } catch (ex) {\n this.setStatus('error', isError(ex) ? ex : new Error(`Error stopping: ${ex}`))\n return false\n }\n })\n }\n\n /**\n * Asserts that the given function has not been overridden in a subclass.\n * Used to enforce the handler pattern (override `startHandler` not `start`).\n */\n protected _noOverride(functionName = getFunctionName(3)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const thisFunc = (this as any)[functionName]\n\n const rootFunc = getRootFunction(this, functionName)\n assertEx(thisFunc === rootFunc, () => `Override not allowed for [${functionName}] - override ${functionName}Handler instead`)\n }\n\n /** Sets the lifecycle status and reports it via the status reporter. */\n protected setStatus(value: Exclude<CreatableStatus, 'error'>, progress?: number): void\n protected setStatus(value: Extract<CreatableStatus, 'error'>, error?: Error): void\n protected setStatus(value: CreatableStatus, progressOrError?: number | Error): void {\n this._status = value\n if (value !== null) {\n if (value === 'error') {\n if (isError(progressOrError)) {\n this.statusReporter?.report(this.name, value, progressOrError)\n return\n }\n } else {\n if (isNumber(progressOrError)) {\n this.statusReporter?.report(this.name, value, progressOrError)\n return\n }\n }\n this.statusReporter?.report(this.name, value)\n }\n }\n\n /** Override in subclasses to define start behavior. Throw an error on failure. */\n protected startHandler(): Promisable<void> {\n // when overriding this, throw an error on failure\n }\n\n /** Override in subclasses to define stop behavior. Throw an error on failure. */\n protected stopHandler(): Promisable<void> {\n // when overriding this, throw an error on failure\n }\n}\n\n/**\n * Extends AbstractCreatable with a static `factory` method for creating\n * pre-configured CreatableFactory instances.\n */\n@creatable()\nexport class AbstractCreatableWithFactory<TParams extends CreatableParams = CreatableParams,\n TEventData extends EventData = EventData> extends AbstractCreatable<TParams, TEventData> {\n /**\n * Creates a factory that produces instances of this class with pre-configured params and labels.\n * @param params - Default parameters for instances created by the factory\n * @param labels - Labels to assign to created instances\n */\n static factory<T extends CreatableInstance>(\n this: Creatable<T>,\n params?: Partial<T['params']>,\n labels?: Labels,\n ): CreatableFactory<T> {\n return Factory.withParams<T>(this, params, labels)\n }\n}\n","import type { Logger } from '@xylabs/logger'\nimport type { Promisable } from '@xylabs/promise'\n\nimport type { AbstractCreatable } from './AbstractCreatable.ts'\nimport type {\n CreatableInstance, CreatableParams, Labels,\n RequiredCreatableParams,\n} from './model/index.ts'\n\n/**\n * A factory interface for creating instances of a Creatable with pre-configured parameters.\n * Unlike the full Creatable, this only exposes the `create` method.\n */\nexport interface CreatableFactory<T extends CreatableInstance = CreatableInstance>\n extends Omit<Creatable<T>, 'create' | 'createHandler' | 'paramsHandler' | 'defaultLogger' | 'factory'> {\n\n /** Creates a new instance, merging the provided params with the factory's defaults. */\n create(\n this: CreatableFactory<T>,\n params?: Partial<T['params']>): Promise<T>\n}\n\n/**\n * Static interface for classes that support asynchronous creation.\n * Provides the `create`, `createHandler`, and `paramsHandler` static methods\n * used to construct instances through the creatable lifecycle.\n */\nexport interface Creatable<T extends CreatableInstance = CreatableInstance> {\n\n /** Optional default logger shared across instances created by this class. */\n defaultLogger?: Logger\n\n /** Constructs a new raw instance. Should not be called directly; use `create` instead. */\n new(key: unknown, params: Partial<CreatableParams>): T & AbstractCreatable<T['params']>\n\n /** Asynchronously creates and initializes a new instance with the given params. */\n create<T extends CreatableInstance>(\n this: Creatable<T>,\n params?: Partial<T['params']>): Promise<T>\n\n /** Hook called after construction to perform additional initialization on the instance. */\n createHandler<T extends CreatableInstance>(\n this: Creatable<T>,\n instance: T\n ): Promisable<T>\n\n /** Hook called to validate and transform params before instance construction. */\n paramsHandler<T extends CreatableInstance>(\n this: Creatable<T>, params?: Partial<T['params']>): Promisable<T['params'] & RequiredCreatableParams>\n}\n\n/** Extends Creatable with a `factory` method that produces pre-configured CreatableFactory instances. */\nexport interface CreatableWithFactory<T extends CreatableInstance = CreatableInstance> extends Creatable<T> {\n /** Creates a factory with the given default params and labels. */\n factory<T extends CreatableInstance>(\n this: Creatable<T>,\n params?: Partial<T['params']>,\n labels?: Labels): CreatableFactory<T>\n}\n\n/**\n * Class annotation to be used to decorate Modules which support\n * an asynchronous creation pattern\n * @returns The decorated Module requiring it implement the members\n * of the CreatableModule as statics properties/methods\n */\nexport function creatable<T extends CreatableInstance>() {\n return <U extends Creatable<T>>(constructor: U) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n constructor\n }\n}\n\n/**\n * Class annotation to be used to decorate Modules which support\n * an asynchronous creation factory pattern\n * @returns The decorated Module requiring it implement the members\n * of the CreatableModule as statics properties/methods\n */\n\nexport function creatableFactory() {\n return <U extends CreatableFactory>(constructor: U) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n constructor\n }\n}\n","import { type Creatable, type CreatableFactory } from './Creatable.ts'\nimport type {\n CreatableInstance, Labels, WithOptionalLabels,\n} from './model/index.ts'\n\n/**\n * A concrete factory that wraps a Creatable class with default parameters and labels.\n * Instances are created by merging caller-provided params over the factory defaults.\n */\nexport class Factory<T extends CreatableInstance = CreatableInstance> implements CreatableFactory<T> {\n /** The Creatable class this factory delegates creation to. */\n creatable: Creatable<T>\n\n /** Default parameters merged into every `create` call. */\n defaultParams?: Partial<T['params']>\n\n /** Labels identifying resources created by this factory. */\n labels?: Labels\n\n constructor(\n creatable: Creatable<T>,\n params?: Partial<T['params']>,\n labels: Labels = {},\n ) {\n this.creatable = creatable\n this.defaultParams = params\n this.labels = Object.assign({}, (creatable as WithOptionalLabels).labels ?? {}, labels ?? {})\n }\n\n /**\n * Creates a new Factory instance with the given default params and labels.\n * @param creatableModule - The Creatable class to wrap\n * @param params - Default parameters for new instances\n * @param labels - Labels to assign to created instances\n */\n static withParams<T extends CreatableInstance>(\n creatableModule: Creatable<T>,\n params?: Partial<T['params']>,\n labels: Labels = {},\n ) {\n return new Factory<T>(creatableModule, params, labels)\n }\n\n /**\n * Creates a new instance, merging the provided params over the factory defaults.\n * @param params - Optional parameters to override the factory defaults\n */\n create(params?: Partial<T['params']>): Promise<T> {\n const mergedParams: T['params'] = {\n ...this.defaultParams,\n ...params,\n } as T['params']\n return this.creatable.create<T>(mergedParams)\n }\n}\n","import { isNumber } from '@xylabs/typeof'\n\n/**\n * Extracts the function name from the call stack at the given depth.\n * @param depth - The stack frame depth to inspect (default: 2)\n * @returns The function name, or '\\<unknown\\>' if it cannot be determined\n */\nexport function getFunctionName(depth = 2) {\n const error = new Error('Stack')\n let newIndex: number | undefined\n const stackParts = error.stack?.split('\\n')[depth]?.split(' ')\n const funcName\n = stackParts?.find((item, index) => {\n if (item.length > 0 && item !== 'at') {\n // check if constructor\n if (item === 'new') {\n newIndex = index\n }\n return true\n }\n }) ?? '<unknown>'\n return isNumber(newIndex) ? `${funcName} ${stackParts?.[newIndex + 1]}` : funcName\n}\n","/**\n * Walks the prototype chain to find the root (base-most) definition of a named function.\n * @param obj - The object to start searching from\n * @param funcName - The name of the function to locate\n * @returns The function from the highest prototype in the chain that defines it\n */\nexport function getRootFunction(obj: unknown, funcName: string) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let anyObj = obj as any\n while (anyObj.__proto__?.[funcName]) {\n anyObj = anyObj.__proto__\n }\n return anyObj[funcName]\n}\n","/**\n * Object used to represent labels identifying a resource.\n */\nexport interface Labels {\n [key: string]: string | undefined\n}\n\n/**\n * Interface for objects that have labels.\n */\nexport interface WithLabels<T extends Labels = Labels> {\n labels: T\n}\n\n/**\n * Interface for objects that have labels.\n */\nexport interface WithOptionalLabels<T extends Labels = Labels> {\n labels?: T\n}\n\n/**\n * Returns true if the source object has all the labels from the required set\n * @param source Source object to check against\n * @param required Set of labels to check for in source\n * @returns True of the source object has all the labels from the required set\n */\nexport const hasAllLabels = (source?: Labels, required?: Labels): boolean => {\n if (!required) return true\n return Object.entries(required).every(([key, value]) => {\n return source?.hasOwnProperty(key as keyof typeof source) && source?.[key as keyof typeof source] === value\n })\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAEzB,SAAS,mBAAmB;AAG5B;AAAA,EACc;AAAA,EAAU;AAAA,OACjB;AACP;AAAA,EACE;AAAA,EAAS,YAAAA;AAAA,EAAU;AAAA,EACnB;AAAA,OACK;AACP,SAAS,aAAa;;;ACsDf,SAAS,YAAyC;AACvD,SAAO,CAAyB,gBAAmB;AAEjD;AAAA,EACF;AACF;AASO,SAAS,mBAAmB;AACjC,SAAO,CAA6B,gBAAmB;AAErD;AAAA,EACF;AACF;;;AC5EO,IAAM,UAAN,MAAM,SAAwF;AAAA;AAAA,EAEnG;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA,EAEA,YACEC,YACA,QACA,SAAiB,CAAC,GAClB;AACA,SAAK,YAAYA;AACjB,SAAK,gBAAgB;AACrB,SAAK,SAAS,OAAO,OAAO,CAAC,GAAIA,WAAiC,UAAU,CAAC,GAAG,UAAU,CAAC,CAAC;AAAA,EAC9F;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,WACL,iBACA,QACA,SAAiB,CAAC,GAClB;AACA,WAAO,IAAI,SAAW,iBAAiB,QAAQ,MAAM;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,QAA2C;AAChD,UAAM,eAA4B;AAAA,MAChC,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK,UAAU,O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,cAAgC;AAAA,EAE1C;AACF;AAvSa,oBAAN;AAAA,EADN,UAAU;AAAA,GACE;AA8SN,IAAM,+BAAN,cAC6C,kBAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMzF,OAAO,QAEL,QACA,QACqB;AACrB,WAAO,QAAQ,WAAc,MAAM,QAAQ,MAAM;AAAA,EACnD;AACF;AAda,+BAAN;AAAA,EADN,UAAU;AAAA,GACE;;;AKtTN,IAAM,eAAe,CAAC,QAAiB,aAA+B;AAC3E,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO,OAAO,QAAQ,QAAQ,EAAE,MAAM,CAAC,CAAC,KAAK,KAAK,MAAM;AACtD,WAAO,QAAQ,eAAe,GAA0B,KAAK,SAAS,GAA0B,MAAM;AAAA,EACxG,CAAC;AACH;","names":["isNumber","creatable","isNumber"]}
|
|
@@ -1,2 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extracts the function name from the call stack at the given depth.
|
|
3
|
+
* @param depth - The stack frame depth to inspect (default: 2)
|
|
4
|
+
* @returns The function name, or '\<unknown\>' if it cannot be determined
|
|
5
|
+
*/
|
|
1
6
|
export declare function getFunctionName(depth?: number): string;
|
|
2
7
|
//# sourceMappingURL=getFunctionName.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getFunctionName.d.ts","sourceRoot":"","sources":["../../../src/lib/getFunctionName.ts"],"names":[],"mappings":"AAEA,wBAAgB,eAAe,CAAC,KAAK,SAAI,UAexC"}
|
|
1
|
+
{"version":3,"file":"getFunctionName.d.ts","sourceRoot":"","sources":["../../../src/lib/getFunctionName.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,SAAI,UAexC"}
|
|
@@ -1,2 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Walks the prototype chain to find the root (base-most) definition of a named function.
|
|
3
|
+
* @param obj - The object to start searching from
|
|
4
|
+
* @param funcName - The name of the function to locate
|
|
5
|
+
* @returns The function from the highest prototype in the chain that defines it
|
|
6
|
+
*/
|
|
1
7
|
export declare function getRootFunction(obj: unknown, funcName: string): any;
|
|
2
8
|
//# sourceMappingURL=getRootFunction.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getRootFunction.d.ts","sourceRoot":"","sources":["../../../src/lib/getRootFunction.ts"],"names":[],"mappings":"AAAA,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAO7D"}
|
|
1
|
+
{"version":3,"file":"getRootFunction.d.ts","sourceRoot":"","sources":["../../../src/lib/getRootFunction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAO7D"}
|
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import type { EventData, EventEmitter } from '@xylabs/events';
|
|
2
2
|
import type { CreatableName, CreatableParams } from './CreatableParams.ts';
|
|
3
|
+
/** Represents a created instance with a managed lifecycle (start/stop) and event emission. */
|
|
3
4
|
export interface CreatableInstance<TParams extends CreatableParams = CreatableParams, TEventData extends EventData = EventData> extends EventEmitter<TEventData> {
|
|
5
|
+
/** The event data type associated with this instance. */
|
|
4
6
|
eventData: TEventData;
|
|
7
|
+
/** The name identifier for this instance. */
|
|
5
8
|
name: CreatableName;
|
|
9
|
+
/** The parameters used to configure this instance. */
|
|
6
10
|
params: TParams;
|
|
11
|
+
/** Starts the instance. Resolves to true if started successfully. */
|
|
7
12
|
start: () => Promise<boolean>;
|
|
13
|
+
/** Stops the instance. Resolves to true if stopped successfully. */
|
|
8
14
|
stop: () => Promise<boolean>;
|
|
9
15
|
}
|
|
10
16
|
//# sourceMappingURL=CreatableInstance.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CreatableInstance.d.ts","sourceRoot":"","sources":["../../../src/model/CreatableInstance.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAE7D,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAE1E,MAAM,WAAW,iBAAiB,CAAC,OAAO,SAAS,eAAe,GAAG,eAAe,EAClF,UAAU,SAAS,SAAS,GAAG,SAAS,CAAE,SAAQ,YAAY,CAAC,UAAU,CAAC;IAC1E,SAAS,EAAE,UAAU,CAAA;IACrB,IAAI,EAAE,aAAa,CAAA;IACnB,MAAM,EAAE,OAAO,CAAA;IACf,KAAK,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;IAC7B,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;CAC7B"}
|
|
1
|
+
{"version":3,"file":"CreatableInstance.d.ts","sourceRoot":"","sources":["../../../src/model/CreatableInstance.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAE7D,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAE1E,8FAA8F;AAC9F,MAAM,WAAW,iBAAiB,CAAC,OAAO,SAAS,eAAe,GAAG,eAAe,EAClF,UAAU,SAAS,SAAS,GAAG,SAAS,CAAE,SAAQ,YAAY,CAAC,UAAU,CAAC;IAC1E,yDAAyD;IACzD,SAAS,EAAE,UAAU,CAAA;IACrB,6CAA6C;IAC7C,IAAI,EAAE,aAAa,CAAA;IACnB,sDAAsD;IACtD,MAAM,EAAE,OAAO,CAAA;IACf,qEAAqE;IACrE,KAAK,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;IAC7B,oEAAoE;IACpE,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;CAC7B"}
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import type { BaseClassName } from '@xylabs/base';
|
|
2
2
|
import type { BaseEmitterParams } from '@xylabs/events';
|
|
3
3
|
import type { CreatableStatus, CreatableStatusReporter } from './CreatableStatusReporter.ts';
|
|
4
|
+
/** A branded string type used as the name identifier for creatables. */
|
|
4
5
|
export type CreatableName = Exclude<string, 'creatable-name-reserved-32546239486'> & BaseClassName;
|
|
6
|
+
/** The minimum required parameters for constructing a creatable. */
|
|
5
7
|
export interface RequiredCreatableParams<TAdditionalStatus extends CreatableStatus | void = void> extends BaseEmitterParams {
|
|
8
|
+
/** Optional name identifying this creatable instance. */
|
|
6
9
|
name?: CreatableName;
|
|
10
|
+
/** Optional reporter for broadcasting status changes. */
|
|
7
11
|
statusReporter?: CreatableStatusReporter<TAdditionalStatus>;
|
|
8
12
|
}
|
|
13
|
+
/** Parameters for creating a creatable instance, combining required params with emitter params. */
|
|
9
14
|
export interface CreatableParams extends RequiredCreatableParams, BaseEmitterParams {
|
|
10
15
|
}
|
|
11
16
|
//# sourceMappingURL=CreatableParams.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CreatableParams.d.ts","sourceRoot":"","sources":["../../../src/model/CreatableParams.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAEvD,OAAO,KAAK,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAA;AAE5F,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,EAAE,qCAAqC,CAAC,GAAG,aAAa,CAAA;AAElG,MAAM,WAAW,uBAAuB,CAAC,iBAAiB,SAAS,eAAe,GAAG,IAAI,GAAG,IAAI,CAAE,SAAQ,iBAAiB;IACzH,IAAI,CAAC,EAAE,aAAa,CAAA;IACpB,cAAc,CAAC,EAAE,uBAAuB,CAAC,iBAAiB,CAAC,CAAA;CAC5D;AAED,MAAM,WAAW,eAAgB,SAAQ,uB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