@bluelibs/runner 4.6.1 → 4.7.0-alpha

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 (156) hide show
  1. package/AI.md +319 -579
  2. package/README.md +886 -731
  3. package/dist/browser/index.cjs +1438 -251
  4. package/dist/browser/index.cjs.map +1 -1
  5. package/dist/browser/index.mjs +1433 -252
  6. package/dist/browser/index.mjs.map +1 -1
  7. package/dist/context.d.ts +31 -0
  8. package/dist/define.d.ts +9 -0
  9. package/dist/definers/builders/core.d.ts +30 -0
  10. package/dist/definers/builders/event.d.ts +12 -0
  11. package/dist/definers/builders/hook.d.ts +20 -0
  12. package/dist/definers/builders/middleware.d.ts +39 -0
  13. package/dist/definers/builders/resource.d.ts +40 -0
  14. package/dist/definers/builders/tag.d.ts +10 -0
  15. package/dist/definers/builders/task.d.ts +37 -0
  16. package/dist/definers/builders/task.phantom.d.ts +27 -0
  17. package/dist/definers/builders/utils.d.ts +4 -0
  18. package/dist/definers/defineEvent.d.ts +2 -0
  19. package/dist/definers/defineHook.d.ts +6 -0
  20. package/dist/definers/defineOverride.d.ts +17 -0
  21. package/dist/definers/defineResource.d.ts +2 -0
  22. package/dist/definers/defineResourceMiddleware.d.ts +2 -0
  23. package/dist/definers/defineTag.d.ts +12 -0
  24. package/dist/definers/defineTask.d.ts +18 -0
  25. package/dist/definers/defineTaskMiddleware.d.ts +2 -0
  26. package/dist/definers/tools.d.ts +47 -0
  27. package/dist/defs.d.ts +29 -0
  28. package/dist/edge/index.cjs +1438 -251
  29. package/dist/edge/index.cjs.map +1 -1
  30. package/dist/edge/index.mjs +1433 -252
  31. package/dist/edge/index.mjs.map +1 -1
  32. package/dist/errors.d.ts +104 -0
  33. package/dist/globals/globalEvents.d.ts +8 -0
  34. package/dist/globals/globalMiddleware.d.ts +31 -0
  35. package/dist/globals/globalResources.d.ts +32 -0
  36. package/dist/globals/globalTags.d.ts +11 -0
  37. package/dist/globals/middleware/cache.middleware.d.ts +27 -0
  38. package/dist/globals/middleware/requireContext.middleware.d.ts +6 -0
  39. package/dist/globals/middleware/retry.middleware.d.ts +21 -0
  40. package/dist/globals/middleware/timeout.middleware.d.ts +9 -0
  41. package/dist/globals/middleware/tunnel.middleware.d.ts +2 -0
  42. package/dist/globals/resources/debug/debug.resource.d.ts +7 -0
  43. package/dist/globals/resources/debug/debug.tag.d.ts +2 -0
  44. package/dist/globals/resources/debug/debugConfig.resource.d.ts +22 -0
  45. package/dist/globals/resources/debug/executionTracker.middleware.d.ts +50 -0
  46. package/dist/globals/resources/debug/globalEvent.hook.d.ts +27 -0
  47. package/dist/globals/resources/debug/hook.hook.d.ts +30 -0
  48. package/dist/globals/resources/debug/index.d.ts +6 -0
  49. package/dist/globals/resources/debug/middleware.hook.d.ts +30 -0
  50. package/dist/globals/resources/debug/types.d.ts +25 -0
  51. package/dist/globals/resources/debug/utils.d.ts +2 -0
  52. package/dist/globals/resources/queue.resource.d.ts +10 -0
  53. package/dist/globals/resources/tunnel/ejson-extensions.d.ts +1 -0
  54. package/dist/globals/resources/tunnel/error-utils.d.ts +1 -0
  55. package/dist/globals/resources/tunnel/plan.d.ts +19 -0
  56. package/dist/globals/resources/tunnel/protocol.d.ts +40 -0
  57. package/dist/globals/resources/tunnel/serializer.d.ts +9 -0
  58. package/dist/globals/resources/tunnel/tunnel.policy.tag.d.ts +18 -0
  59. package/dist/globals/resources/tunnel/tunnel.tag.d.ts +2 -0
  60. package/dist/globals/resources/tunnel/types.d.ts +17 -0
  61. package/dist/globals/tunnels/index.d.ts +23 -0
  62. package/dist/globals/types.d.ts +1 -0
  63. package/dist/http-client.d.ts +23 -0
  64. package/dist/http-fetch-tunnel.resource.d.ts +22 -0
  65. package/dist/index.d.ts +99 -0
  66. package/dist/models/DependencyProcessor.d.ts +48 -0
  67. package/dist/models/EventManager.d.ts +153 -0
  68. package/dist/models/LogPrinter.d.ts +55 -0
  69. package/dist/models/Logger.d.ts +85 -0
  70. package/dist/models/MiddlewareManager.d.ts +86 -0
  71. package/dist/models/OverrideManager.d.ts +13 -0
  72. package/dist/models/Queue.d.ts +26 -0
  73. package/dist/models/ResourceInitializer.d.ts +20 -0
  74. package/dist/models/RunResult.d.ts +35 -0
  75. package/dist/models/Semaphore.d.ts +61 -0
  76. package/dist/models/Store.d.ts +69 -0
  77. package/dist/models/StoreRegistry.d.ts +43 -0
  78. package/dist/models/StoreValidator.d.ts +8 -0
  79. package/dist/models/TaskRunner.d.ts +27 -0
  80. package/dist/models/UnhandledError.d.ts +11 -0
  81. package/dist/models/index.d.ts +11 -0
  82. package/dist/models/utils/findCircularDependencies.d.ts +16 -0
  83. package/dist/models/utils/safeStringify.d.ts +3 -0
  84. package/dist/node/exposure/allowList.d.ts +3 -0
  85. package/dist/node/exposure/authenticator.d.ts +6 -0
  86. package/dist/node/exposure/cors.d.ts +4 -0
  87. package/dist/node/exposure/createNodeExposure.d.ts +2 -0
  88. package/dist/node/exposure/exposureServer.d.ts +18 -0
  89. package/dist/node/exposure/httpResponse.d.ts +10 -0
  90. package/dist/node/exposure/logging.d.ts +4 -0
  91. package/dist/node/exposure/multipart.d.ts +27 -0
  92. package/dist/node/exposure/requestBody.d.ts +11 -0
  93. package/dist/node/exposure/requestContext.d.ts +17 -0
  94. package/dist/node/exposure/requestHandlers.d.ts +24 -0
  95. package/dist/node/exposure/resourceTypes.d.ts +60 -0
  96. package/dist/node/exposure/router.d.ts +17 -0
  97. package/dist/node/exposure/serverLifecycle.d.ts +13 -0
  98. package/dist/node/exposure/types.d.ts +31 -0
  99. package/dist/node/exposure/utils.d.ts +17 -0
  100. package/dist/node/exposure.resource.d.ts +12 -0
  101. package/dist/node/files.d.ts +9 -0
  102. package/dist/node/http-smart-client.model.d.ts +22 -0
  103. package/dist/node/index.d.ts +1 -0
  104. package/dist/node/inputFile.model.d.ts +22 -0
  105. package/dist/node/inputFile.utils.d.ts +14 -0
  106. package/dist/node/mixed-http-client.node.d.ts +27 -0
  107. package/dist/node/node.cjs +11168 -0
  108. package/dist/node/node.cjs.map +1 -0
  109. package/dist/node/node.d.ts +6 -0
  110. package/dist/node/node.mjs +11099 -0
  111. package/dist/node/node.mjs.map +1 -0
  112. package/dist/node/platform/createFile.d.ts +9 -0
  113. package/dist/node/tunnel.allowlist.d.ts +7 -0
  114. package/dist/node/upload/manifest.d.ts +22 -0
  115. package/dist/platform/adapters/browser.d.ts +14 -0
  116. package/dist/platform/adapters/edge.d.ts +5 -0
  117. package/dist/platform/adapters/node-als.d.ts +1 -0
  118. package/dist/platform/adapters/node.d.ts +15 -0
  119. package/dist/platform/adapters/universal-generic.d.ts +14 -0
  120. package/dist/platform/adapters/universal.d.ts +17 -0
  121. package/dist/platform/createFile.d.ts +10 -0
  122. package/dist/platform/createWebFile.d.ts +11 -0
  123. package/dist/platform/factory.d.ts +2 -0
  124. package/dist/platform/index.d.ts +27 -0
  125. package/dist/platform/types.d.ts +29 -0
  126. package/dist/processHooks.d.ts +2 -0
  127. package/dist/run.d.ts +14 -0
  128. package/dist/testing.d.ts +25 -0
  129. package/dist/tools/getCallerFile.d.ts +1 -0
  130. package/dist/tunnels/buildUniversalManifest.d.ts +24 -0
  131. package/dist/types/contracts.d.ts +63 -0
  132. package/dist/types/event.d.ts +74 -0
  133. package/dist/types/hook.d.ts +23 -0
  134. package/dist/types/inputFile.d.ts +34 -0
  135. package/dist/types/meta.d.ts +18 -0
  136. package/dist/types/resource.d.ts +87 -0
  137. package/dist/types/resourceMiddleware.d.ts +47 -0
  138. package/dist/types/runner.d.ts +55 -0
  139. package/dist/types/storeTypes.d.ts +40 -0
  140. package/dist/types/symbols.d.ts +28 -0
  141. package/dist/types/tag.d.ts +46 -0
  142. package/dist/types/task.d.ts +50 -0
  143. package/dist/types/taskMiddleware.d.ts +48 -0
  144. package/dist/types/utilities.d.ts +111 -0
  145. package/dist/universal/index.cjs +1438 -251
  146. package/dist/universal/index.cjs.map +1 -1
  147. package/dist/universal/index.mjs +1433 -252
  148. package/dist/universal/index.mjs.map +1 -1
  149. package/package.json +32 -4
  150. package/dist/index.d.mts +0 -1747
  151. package/dist/index.unused.js +0 -4466
  152. package/dist/index.unused.js.map +0 -1
  153. package/dist/node/index.cjs +0 -4498
  154. package/dist/node/index.cjs.map +0 -1
  155. package/dist/node/index.mjs +0 -4466
  156. package/dist/node/index.mjs.map +0 -1
package/dist/index.d.mts DELETED
@@ -1,1747 +0,0 @@
1
- interface TimeoutMiddlewareConfig {
2
- /**
3
- * Maximum time in milliseconds before the wrapped operation is aborted
4
- * and a timeout error is thrown. Defaults to 5000ms.
5
- */
6
- ttl: number;
7
- }
8
-
9
- /**
10
- * Configuration options for the retry middleware
11
- */
12
- interface RetryMiddlewareConfig {
13
- /**
14
- * Maximum number of retry attempts (default: 3)
15
- */
16
- retries?: number;
17
- /**
18
- * Callback to determine if retry should stop based on error
19
- * @default () => false (retry all errors)
20
- */
21
- stopRetryIf?: (error: Error) => boolean;
22
- /**
23
- * Custom delay strategy function
24
- * @default Exponential backoff starting at 100ms
25
- */
26
- delayStrategy?: (attempt: number, error: Error) => number;
27
- }
28
-
29
- declare const CONTRACT: unique symbol;
30
- type CONTRACT = typeof CONTRACT;
31
- interface IContractable<TConfig = any, TInput = void, TOutput = void> {
32
- readonly __containsContract: true;
33
- readonly [CONTRACT]: {
34
- config: TConfig;
35
- input: TInput;
36
- output: TOutput;
37
- };
38
- }
39
- type NonVoid<T> = [T] extends [void] ? never : T;
40
- type IsTuple<T extends readonly unknown[]> = number extends T["length"] ? false : true;
41
- type UnionToIntersection$1<U> = (U extends any ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
42
- type Simplify<T> = {
43
- [K in keyof T]: T[K];
44
- } & {};
45
- type IsUnknown<T> = unknown extends T ? [T] extends [unknown] ? true : false : false;
46
- type UnknownToNever<T> = IsUnknown<T> extends true ? never : T;
47
- type ExtractContractOf<T, Kind extends "input" | "output"> = T extends IContractable<any, infer I, infer O> ? UnknownToNever<Kind extends "input" ? NonVoid<I> : NonVoid<O>> : never;
48
- type FilterContractsKind<TItems extends readonly unknown[], Kind extends "input" | "output", Acc extends readonly unknown[] = []> = TItems extends readonly [infer H, ...infer R] ? ExtractContractOf<H, Kind> extends never ? FilterContractsKind<R, Kind, Acc> : FilterContractsKind<R, Kind, [...Acc, ExtractContractOf<H, Kind>]> : Acc;
49
- type ExtractContractsFromCollection<TItems extends readonly unknown[], Kind extends "input" | "output"> = IsTuple<TItems> extends true ? FilterContractsKind<TItems, Kind> : Array<ExtractContractOf<TItems[number], Kind>>;
50
- type ExtractInputTypeFromContracts<TItems extends readonly unknown[]> = ExtractContractsFromCollection<TItems, "input">;
51
- type ExtractOutputTypeFromContracts<TItems extends readonly unknown[]> = ExtractContractsFromCollection<TItems, "output">;
52
- type ContractsUnionInputs<TItems extends readonly unknown[]> = ExtractInputTypeFromContracts<TItems> extends readonly (infer U)[] ? U : never;
53
- type ContractsUnionOutputs<TItems extends readonly unknown[]> = ExtractOutputTypeFromContracts<TItems> extends readonly (infer U)[] ? U : never;
54
- type ContractsIntersectionInputs<TItems extends readonly unknown[]> = UnionToIntersection$1<ContractsUnionInputs<TItems>>;
55
- type ContractsIntersectionOutputs<TItems extends readonly unknown[]> = UnionToIntersection$1<ContractsUnionOutputs<TItems>>;
56
- type HasInputContracts<TItems extends readonly unknown[]> = [
57
- ContractsUnionInputs<TItems>
58
- ] extends [never] ? false : true;
59
- type HasOutputContracts<TItems extends readonly unknown[]> = [
60
- ContractsUnionOutputs<TItems>
61
- ] extends [never] ? false : true;
62
- type IsNever<T> = [T] extends [never] ? true : false;
63
- type KeysWithNever<T> = T extends object ? {
64
- [K in keyof T]-?: [T[K]] extends [never] ? K : never;
65
- }[keyof T] : never;
66
- type HasNeverProperty<T> = KeysWithNever<T> extends never ? false : true;
67
- type IsImpossibleIntersection<T> = IsNever<T> extends true ? true : HasNeverProperty<T> extends true ? true : false;
68
- type InputContractViolationError<TItems extends readonly unknown[], TActual> = {
69
- message: "Value does not satisfy all input contracts";
70
- expected: Simplify<ContractsIntersectionInputs<TItems>>;
71
- received: TActual;
72
- };
73
- type OutputContractViolationError<TItems extends readonly unknown[], TActual> = {
74
- message: "Value does not satisfy all output contracts";
75
- expected: Simplify<ContractsIntersectionOutputs<TItems>>;
76
- received: TActual;
77
- };
78
- type EnsureInputSatisfiesContracts<TItems extends readonly unknown[], TValue> = [ContractsUnionInputs<TItems>] extends [never] ? TValue : TValue extends Promise<infer U> ? Promise<U extends ContractsIntersectionInputs<TItems> ? U : InputContractViolationError<TItems, U>> : TValue extends ContractsIntersectionInputs<TItems> ? TValue : InputContractViolationError<TItems, TValue>;
79
- type EnsureOutputSatisfiesContracts<TItems extends readonly unknown[], TResponse> = [ContractsUnionOutputs<TItems>] extends [never] ? TResponse : TResponse extends Promise<infer U> ? Promise<U extends ContractsIntersectionOutputs<TItems> ? U : OutputContractViolationError<TItems, U>> : TResponse extends ContractsIntersectionOutputs<TItems> ? TResponse : OutputContractViolationError<TItems, TResponse>;
80
- type InferInputOrViolationFromContracts<TItems extends readonly unknown[]> = HasInputContracts<TItems> extends false ? void : ContractsIntersectionInputs<TItems> extends infer I ? IsImpossibleIntersection<I> extends true ? InputContractViolationError<TItems, Simplify<I extends never ? never : I>> : Simplify<I> : never;
81
-
82
- /**
83
- * Common metadata you can attach to tasks/resources/events/middleware.
84
- * Useful for docs, filtering and middleware decisions.
85
- */
86
- interface IMeta {
87
- title?: string;
88
- description?: string;
89
- }
90
- interface ITaskMeta extends IMeta {
91
- }
92
- interface IResourceMeta extends IMeta {
93
- }
94
- interface IEventMeta extends IMeta {
95
- }
96
- interface IMiddlewareMeta extends IMeta {
97
- }
98
- interface ITagMeta extends IMeta {
99
- }
100
-
101
- interface ITaggable {
102
- tags: TagType[];
103
- }
104
- interface ITagDefinition<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> {
105
- id: string;
106
- meta?: ITagMeta;
107
- configSchema?: IValidationSchema<TConfig>;
108
- /**
109
- * Utilizing config at definition level stores its defaults
110
- */
111
- config?: TConfig;
112
- }
113
- interface ITag<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> extends ITagDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract>, IContractable<TConfig, TEnforceInputContract, TEnforceOutputContract> {
114
- /**
115
- * A special validation property.
116
- * It resolves to `true` if TConfig only has optional keys, otherwise `false`.
117
- */
118
- readonly __configHasOnlyOptionalKeys: RequiredKeys<TConfig> extends never ? true : false;
119
- config?: TConfig;
120
- /**
121
- * Checks if the tag exists in a taggable or a list of tags.
122
- */
123
- exists(target: ITaggable | TagType[]): boolean;
124
- /**
125
- * Creates a configured instance of the tag.
126
- */
127
- with(config: TConfig): ITagConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract>;
128
- /**
129
- * Extracts the configuration of the tag from a taggable or a list of tags.
130
- */
131
- extract(target: ITaggable | TagType[]): TConfig | undefined;
132
- [symbolFilePath]: string;
133
- [symbolTag]: true;
134
- }
135
- type ITagWithOptionalConfig<TValue, TEnforceInputContract, TEnforceOutputContract> = ITag<any, TEnforceInputContract, TEnforceOutputContract> & {
136
- readonly __configHasOnlyOptionalKeys: true;
137
- };
138
- interface ITagConfigured<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> extends ITag<TConfig, TEnforceInputContract, TEnforceOutputContract> {
139
- [symbolTagConfigured]: true;
140
- config: TConfig;
141
- }
142
- type TagType = ITag<void, any, any> | ITagWithOptionalConfig<any, any, any> | ITagConfigured<any, any, any>;
143
-
144
- /**
145
- * Internal brand symbols used to tag created objects at runtime and help with
146
- * type‑narrowing. Prefer the `isTask`/`isResource`/`isEvent`/`isMiddleware`
147
- * helpers instead of touching these directly.
148
- * @internal
149
- */
150
- declare const symbolTask: unique symbol;
151
- declare const symbolResource: unique symbol;
152
- declare const symbolResourceWithConfig: unique symbol;
153
- declare const symbolEvent: unique symbol;
154
- declare const symbolMiddleware: unique symbol;
155
- /** New brands for separated middleware kinds */
156
- declare const symbolTaskMiddleware: unique symbol;
157
- declare const symbolResourceMiddleware: unique symbol;
158
- declare const symbolMiddlewareConfigured: unique symbol;
159
- /** @internal Marks hook definitions (event listeners without middleware) */
160
- declare const symbolHook: unique symbol;
161
- /** @internal Marks a tag definition */
162
- declare const symbolTag: unique symbol;
163
- declare const symbolTagConfigured: unique symbol;
164
- /** @internal Marks an optional dependency wrapper */
165
- declare const symbolOptionalDependency: unique symbol;
166
- /** @internal Path to aid anonymous id generation and error messages */
167
- declare const symbolFilePath: unique symbol;
168
-
169
- type IsAny<T> = 0 extends 1 & T ? true : false;
170
- type IsUnspecified<T> = [T] extends [undefined] ? true : [T] extends [void] ? true : IsAny<T> extends true ? true : false;
171
- interface IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = {}, TContext = any, THooks = any, TRegisterableItems = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> {
172
- /** Stable identifier. */
173
- id: string;
174
- /** Static or lazy dependency map. Receives `config` when provided. */
175
- dependencies?: TDependencies | ((config: TConfig) => TDependencies);
176
- /**
177
- * Register other registerables (resources/tasks/middleware/events). Accepts a
178
- * static array or a function of `config` to support dynamic wiring.
179
- */
180
- register?: Array<RegisterableItems> | ((config: TConfig) => Array<RegisterableItems>);
181
- /**
182
- * Initialize and return the resource value. Called once during boot.
183
- */
184
- init?: (config: HasInputContracts<[...TTags, ...TMiddleware]> extends true ? IsUnspecified<TConfig> extends true ? InferInputOrViolationFromContracts<[...TTags, ...TMiddleware]> : EnsureInputSatisfiesContracts<[...TTags, ...TMiddleware], TConfig> : TConfig, dependencies: ResourceDependencyValuesType<TDependencies>, context: TContext) => HasOutputContracts<[...TTags, ...TMiddleware]> extends true ? EnsureOutputSatisfiesContracts<[...TTags, ...TMiddleware], TValue> : TValue;
185
- /**
186
- * Optional validation schema for the resource's resolved value.
187
- * When provided, the value will be validated immediately after `init` resolves,
188
- * without considering middleware.
189
- */
190
- resultSchema?: IValidationSchema<TValue extends Promise<infer U> ? U : TValue>;
191
- /**
192
- * Clean-up function for the resource. This is called when the resource is no longer needed.
193
- *
194
- * @param value The value of the resource (undefined if no init method)
195
- * @param config The configuration it received
196
- * @param dependencies The dependencies it needed
197
- * @returns Promise<void>
198
- */
199
- dispose?: (this: any, value: TValue extends Promise<infer U> ? U : TValue, config: TConfig, dependencies: ResourceDependencyValuesType<TDependencies>, context: TContext) => Promise<void>;
200
- meta?: TMeta;
201
- /**
202
- * Optional validation schema for runtime config validation.
203
- * When provided, resource config will be validated when .with() is called.
204
- */
205
- configSchema?: IValidationSchema<TConfig>;
206
- /**
207
- * Safe overrides to swap behavior while preserving identities. See
208
- * README: Overrides.
209
- */
210
- overrides?: Array<OverridableElements>;
211
- /** Middleware applied around init/dispose. */
212
- middleware?: TMiddleware;
213
- /**
214
- * Create a private, mutable context shared between `init` and `dispose`.
215
- */
216
- context?: () => TContext;
217
- /**
218
- * This is optional and used from an index resource to get the correct caller.
219
- * This is the reason we allow it here as well.
220
- */
221
- [symbolFilePath]?: string;
222
- tags?: TTags;
223
- }
224
- interface IResource<TConfig = void, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = any, TContext = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> extends IResourceDefinition<TConfig, TValue, TDependencies, TContext, any, any, TMeta, TTags, TMiddleware> {
225
- id: string;
226
- with(config: HasInputContracts<[...TTags, ...TMiddleware]> extends true ? IsUnspecified<TConfig> extends true ? InferInputOrViolationFromContracts<[...TTags, ...TMiddleware]> : TConfig : TConfig): IResourceWithConfig<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
227
- register: Array<RegisterableItems> | ((config: TConfig) => Array<RegisterableItems>);
228
- overrides: Array<OverridableElements>;
229
- middleware: TMiddleware;
230
- [symbolFilePath]: string;
231
- [symbolResource]: true;
232
- /** Return an optional dependency wrapper for this resource. */
233
- optional: () => IOptionalDependency<IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>>;
234
- tags: TTags;
235
- }
236
- interface IResourceWithConfig<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = any, TContext = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends IResourceMiddleware<any, any, any, any>[] = IResourceMiddleware[]> {
237
- [symbolResourceWithConfig]: true;
238
- /** The id of the underlying resource. */
239
- id: string;
240
- /** The underlying resource definition. */
241
- resource: IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
242
- /** The configuration captured by `.with(config)`. */
243
- config: TConfig;
244
- }
245
-
246
- interface ITaskDefinition<TInput = undefined, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
247
- id: string;
248
- /**
249
- * Access other tasks/resources/events. Can be an object or a function when
250
- * you need late or config‑dependent resolution.
251
- */
252
- dependencies?: TDependencies | (() => TDependencies);
253
- /** Middleware applied around task execution. */
254
- middleware?: TMiddleware;
255
- /** Optional metadata used for docs, filtering and tooling. */
256
- meta?: TMeta;
257
- /**
258
- * Optional validation schema for runtime input validation.
259
- * When provided, task input will be validated before execution.
260
- */
261
- inputSchema?: IValidationSchema<TInput>;
262
- /**
263
- * Optional validation schema for the task result.
264
- * When provided, the result will be validated immediately after the task's
265
- * `run` resolves, without considering middleware.
266
- */
267
- resultSchema?: IValidationSchema<TOutput extends Promise<infer U> ? U : never>;
268
- run: (input: HasInputContracts<[...TTags, ...TMiddleware]> extends true ? ([TInput] extends [undefined] ? InferInputOrViolationFromContracts<[...TTags, ...TMiddleware]> : EnsureInputSatisfiesContracts<[
269
- ...TTags,
270
- ...TMiddleware
271
- ], TInput>) : TInput, dependencies: DependencyValuesType<TDependencies>) => HasOutputContracts<[...TTags, ...TMiddleware]> extends true ? EnsureOutputSatisfiesContracts<[...TTags, ...TMiddleware], TOutput> : TOutput;
272
- /**
273
- * Tags applied to the task that might define its behvaiour or impact the systems.
274
- */
275
- tags?: TTags;
276
- }
277
- interface ITask<TInput = any, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> extends ITaskDefinition<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware> {
278
- [symbolFilePath]: string;
279
- [symbolTask]: true;
280
- id: string;
281
- dependencies: TDependencies | (() => TDependencies);
282
- computedDependencies?: DependencyValuesType<TDependencies>;
283
- middleware: TMiddleware;
284
- /** Return an optional dependency wrapper for this task. */
285
- optional: () => IOptionalDependency<ITask<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>>;
286
- tags: TTags;
287
- }
288
-
289
- interface ITaskMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
290
- id: string;
291
- /** Static or lazy dependency map. */
292
- dependencies?: TDependencies | ((config: TConfig) => TDependencies);
293
- /**
294
- * Optional validation schema for runtime config validation.
295
- * When provided, middleware config will be validated when .with() is called.
296
- */
297
- configSchema?: IValidationSchema<TConfig>;
298
- /**
299
- * The middleware body, called with task execution input.
300
- */
301
- run: (input: ITaskMiddlewareExecutionInput<TEnforceInputContract extends void ? any : TEnforceInputContract, TEnforceOutputContract extends void ? any : TEnforceOutputContract>, dependencies: DependencyValuesType<TDependencies>, config: TConfig) => Promise<any>;
302
- meta?: IMiddlewareMeta;
303
- tags?: TagType[];
304
- everywhere?: boolean | ((task: ITask<any, any, any, any>) => boolean);
305
- }
306
- interface ITaskMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends ITaskMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>, IContractable<TConfig, TEnforceInputContract, TEnforceOutputContract> {
307
- [symbolTaskMiddleware]: true;
308
- [symbolFilePath]: string;
309
- id: string;
310
- dependencies: TDependencies | (() => TDependencies);
311
- /** Current configuration object (empty by default). */
312
- config: TConfig;
313
- /** Configure the middleware and return a marked, configured instance. */
314
- with: (config: TConfig) => ITaskMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
315
- tags: TagType[];
316
- }
317
- interface ITaskMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends ITaskMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies> {
318
- [symbolMiddlewareConfigured]: true;
319
- config: TConfig;
320
- }
321
- interface ITaskMiddlewareExecutionInput<TTaskInput = any, TTaskOutput = any> {
322
- /** Task hook */
323
- task: {
324
- definition: ITask<TTaskInput, any, any, any>;
325
- input: TTaskInput;
326
- };
327
- next: (taskInput?: TTaskInput) => Promise<TTaskOutput>;
328
- }
329
- type TaskMiddlewareAttachmentType = ITaskMiddleware<void, any, any, any> | ITaskMiddleware<{
330
- [K in any]?: any;
331
- }, any, any, any> | ITaskMiddlewareConfigured<any, any, any, any>;
332
-
333
- interface IResourceMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
334
- id: string;
335
- /** Static or lazy dependency map. */
336
- dependencies?: TDependencies | ((config: TConfig) => TDependencies);
337
- /**
338
- * Optional validation schema for runtime config validation.
339
- * When provided, middleware config will be validated when .with() is called.
340
- */
341
- configSchema?: IValidationSchema<TConfig>;
342
- /**
343
- * The middleware body, called with resource execution input.
344
- */
345
- run: (input: IResourceMiddlewareExecutionInput<TEnforceInputContract extends void ? any : TEnforceInputContract, TEnforceOutputContract extends void ? any : TEnforceOutputContract>, dependencies: DependencyValuesType<TDependencies>, config: TConfig) => Promise<any>;
346
- meta?: IMiddlewareMeta;
347
- tags?: TagType[];
348
- everywhere?: boolean | ((resource: IResource<any, any, any, any, any>) => boolean);
349
- }
350
- interface IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>, IContractable<TConfig, TEnforceInputContract, TEnforceOutputContract> {
351
- [symbolResourceMiddleware]: true;
352
- id: string;
353
- dependencies: TDependencies | (() => TDependencies);
354
- /** Current configuration object (empty by default). */
355
- config: TConfig;
356
- /** Configure the middleware and return a marked, configured instance. */
357
- with: (config: TConfig) => IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
358
- [symbolFilePath]: string;
359
- tags: TagType[];
360
- }
361
- interface IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies> {
362
- [symbolMiddlewareConfigured]: true;
363
- }
364
- interface IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutput = any> {
365
- /** Resource hook */
366
- resource: {
367
- definition: IResource<TResourceConfig, any, any, any, any>;
368
- config: TResourceConfig;
369
- };
370
- next: (resourceConfig?: TResourceConfig) => Promise<TResourceOutput>;
371
- }
372
- type ResourceMiddlewareAttachmentType = IResourceMiddleware<void, any, any, any> | IResourceMiddleware<{
373
- [K in any]?: any;
374
- }, any, any, any> | IResourceMiddlewareConfigured<any, any, any, any>;
375
-
376
- type OnType = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
377
- interface IHookDefinition<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> {
378
- id: string;
379
- dependencies?: TDependencies | (() => TDependencies);
380
- on: TOn;
381
- /** Listener execution order. Lower numbers run first. */
382
- order?: number;
383
- meta?: TMeta;
384
- run: (event: IEventEmission<TOn extends "*" ? any : TOn extends readonly IEventDefinition<any>[] ? CommonPayload<TOn> : ExtractEventPayload<TOn>>, dependencies: DependencyValuesType<TDependencies>) => Promise<any>;
385
- tags?: TagType[];
386
- }
387
- interface IHook<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> extends IHookDefinition<TDependencies, TOn, TMeta> {
388
- id: string;
389
- dependencies: TDependencies | (() => TDependencies);
390
- [symbolFilePath]: string;
391
- [symbolHook]: true;
392
- tags: TagType[];
393
- }
394
-
395
- type EventHandlerType<T = any> = (event: IEventEmission<T>) => any | Promise<any>;
396
- declare function onAnyOf<T extends readonly IEventDefinition<any>[]>(...defs: T): T;
397
- /**
398
- * Runtime guard that checks if an emission belongs to one of the given event defs.
399
- * Narrows payload type to the intersection of the provided events' payloads.
400
- */
401
- declare function isOneOf<TDefs extends readonly IEventDefinition<any>[]>(emission: IEventEmission<any>, defs: TDefs): emission is IEventEmission<CommonPayload<TDefs>>;
402
- interface IEventDefinition<TPayload = void> {
403
- id: string;
404
- meta?: IEventMeta;
405
- /**
406
- * Optional validation schema for runtime payload validation.
407
- * When provided, event payload will be validated when emitted.
408
- */
409
- payloadSchema?: IValidationSchema<TPayload>;
410
- tags?: TagType[];
411
- }
412
- /**
413
- * The definioten of the event.
414
- * This is different from the event emission.
415
- */
416
- interface IEvent<TPayload = any> extends IEventDefinition<TPayload> {
417
- id: string;
418
- /**
419
- * We use this event to discriminate between resources with just 'id' and 'events' as they collide. This is a workaround, should be redone using classes and instanceof.
420
- */
421
- [symbolEvent]: true;
422
- [symbolFilePath]: string;
423
- /** Return an optional dependency wrapper for this event. */
424
- optional: () => IOptionalDependency<IEvent<TPayload>>;
425
- tags: TagType[];
426
- }
427
- /**
428
- * This represents the object that is passed to event handlers
429
- */
430
- interface IEventEmission<TPayload = any> {
431
- /**
432
- * The ID of the event. This is the same as the event's ID.
433
- * This is useful for global event listeners.
434
- */
435
- id: string;
436
- /**
437
- * The data that the event carries. It can be anything.
438
- */
439
- data: TPayload;
440
- /**
441
- * The timestamp when the event was created.
442
- */
443
- timestamp: Date;
444
- /**
445
- * The source of the event. This can be useful for debugging.
446
- */
447
- source: string;
448
- /**
449
- * Metadata associated with the event definition.
450
- */
451
- meta: IEventMeta;
452
- /**
453
- * Stops propagation to remaining event listeners.
454
- */
455
- stopPropagation(): void;
456
- /**
457
- * Returns true if propagation has been stopped.
458
- */
459
- isPropagationStopped(): boolean;
460
- /**
461
- * The tags that the event carries.
462
- */
463
- tags: TagType[];
464
- }
465
-
466
- /**
467
- * Generic validation schema interface that can be implemented by any validation library.
468
- * Compatible with Zod, Yup, Joi, and other validation libraries.
469
- */
470
- interface IValidationSchema<T = any> {
471
- /**
472
- * Parse and validate the input data.
473
- * Should throw an error if validation fails.
474
- * Can transform the data if the schema supports transformations.
475
- */
476
- parse(input: unknown): T;
477
- }
478
- /**
479
- * Core public TypeScript types for BlueLibs Runner.
480
- *
481
- * This file contains the strongly-typed contract for tasks, resources, events
482
- * and middleware. It mirrors the mental model described in the README:
483
- * - Tasks are functions
484
- * - Resources are singletons (with init/dispose hooks)
485
- * - Events are simple, strongly-typed emissions
486
- * - Middleware can target both tasks and resources
487
- *
488
- * DX goals:
489
- * - Crystal‑clear generics and helper types that infer dependency shapes
490
- * - Friendly JSDoc you can hover in editors to understand usage instantly
491
- * - Safe overrides and strong typing around config and register mechanics
492
- */
493
- type RequiredKeys<T> = {
494
- [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
495
- }[keyof T];
496
- /**
497
- * The reason we accept null and undefined is because we want to be able to offer beautiful DX:
498
- * overrides: [
499
- * process.env.NODE_ENV === 'production' ? prodEmailer : null,
500
- * ]
501
- */
502
- type OverridableElements = IResource<any, any, any, any, any> | ITask<any, any, any, any> | ITaskMiddleware<any> | IResourceMiddleware<any, any> | IResourceWithConfig<any, any, any> | IHook<any, any> | undefined | null;
503
- /**
504
- * A mapping of dependency keys to Runner definitions. Used in `dependencies`
505
- * for tasks and resources. Values are later transformed into the actual
506
- * callable/value shape by `DependencyValuesType`.
507
- */
508
- type DependencyMapType = Record<string, ITask<any, any, any, any, any, any> | IResource<any, any, any, any, any, any, any> | IEvent<any> | IOptionalDependency<ITask<any, any, any, any, any, any>> | IOptionalDependency<IResource<any, any, any, any, any, any, any>> | IOptionalDependency<IEvent<any>>>;
509
- /** Wrapper type marking a dependency as optional at wiring time */
510
- interface IOptionalDependency<T> {
511
- /** The wrapped dependency definition */
512
- inner: T;
513
- /** Brand symbol for optional dependency */
514
- [symbolOptionalDependency]: true;
515
- }
516
- type ExtractTaskInput<T> = T extends ITask<infer I, any, infer D> ? I : never;
517
- type ExtractTaskOutput<T> = T extends ITask<any, infer O, infer D> ? O : never;
518
- type ExtractResourceConfig<T> = T extends IResource<infer C, any, any> ? C : never;
519
- type ExtractResourceValue<T> = T extends IResource<any, infer V, infer D> ? V extends Promise<infer U> ? U : V : never;
520
- type ExtractEventPayload<T> = T extends IEventDefinition<infer P> ? P : T extends IEvent<infer P> ? P : never;
521
- type UnionToIntersection<U> = (U extends any ? (x: U) => any : never) extends (x: infer I) => any ? I : never;
522
- type CommonPayload<T extends readonly IEventDefinition<any>[] | IEventDefinition<any>> = T extends readonly IEventDefinition<any>[] ? {
523
- [K in keyof ExtractEventPayload<T[number]>]: UnionToIntersection<ExtractEventPayload<T[number]> extends any ? ExtractEventPayload<T[number]>[K] : never>;
524
- } : ExtractEventPayload<T>;
525
- /**
526
- * Task dependencies transform into callable functions: call with the task input
527
- * and you receive the task output.
528
- */
529
- type TaskDependency<I, O> = (...args: I extends null | void ? [] : [I]) => O;
530
- /**
531
- * Resource dependencies resolve to the resource's value directly.
532
- */
533
- type ResourceDependency<V> = V;
534
- /**
535
- * Event dependencies resolve to an emitter function. If the payload type is
536
- * `void`, the function can be called with zero args (or an empty object).
537
- */
538
- type EventDependency<P> = P extends void ? (() => Promise<void>) & ((input?: Record<string, never>) => Promise<void>) : (input: P) => Promise<void>;
539
- /**
540
- * Transforms a dependency definition into the usable shape inside `run`/`init`:
541
- * - Task -> callable function
542
- * - Resource -> resolved value
543
- * - Event -> emit function
544
- */
545
- type DependencyValueType<T> = T extends ITask<any, any, any> ? TaskDependency<ExtractTaskInput<T>, ExtractTaskOutput<T>> : T extends IResource<any, any> ? ResourceDependency<ExtractResourceValue<T>> : T extends IEventDefinition<any> ? EventDependency<ExtractEventPayload<T>> : T extends IOptionalDependency<infer U> ? DependencyValueType<U> | undefined : never;
546
- type DependencyValuesType<T extends DependencyMapType> = {
547
- [K in keyof T]: DependencyValueType<T[K]>;
548
- };
549
- type TaskLocalInterceptor<TInput, TOutput> = (next: (input: TInput) => TOutput, input: TInput) => TOutput;
550
- type TaskDependencyWithIntercept<TInput, TOutput> = TaskDependency<TInput, TOutput> & {
551
- intercept: (middleware: TaskLocalInterceptor<TInput, TOutput>) => void;
552
- };
553
- /** Resource-context dependency typing where tasks expose intercept() */
554
- type ResourceDependencyValueType<T> = T extends ITask<any, any, any> ? TaskDependencyWithIntercept<ExtractTaskInput<T>, ExtractTaskOutput<T>> : T extends IResource<any, any> ? ResourceDependency<ExtractResourceValue<T>> : T extends IEventDefinition<any> ? EventDependency<ExtractEventPayload<T>> : T extends IOptionalDependency<infer U> ? ResourceDependencyValueType<U> | undefined : never;
555
- type ResourceDependencyValuesType<T extends DependencyMapType> = {
556
- [K in keyof T]: ResourceDependencyValueType<T[K]>;
557
- };
558
- /**
559
- * Anything you can put inside a resource's `register: []`.
560
- * - Resources (with or without `.with()`)
561
- * - Tasks
562
- * - Middleware
563
- * - Events
564
- */
565
- type RegisterableItems<T = any> = IResourceWithConfig<any, any, any, any, any, any, any> | IResource<void, any, any, any, any, any, any> | IResource<{
566
- [K in any]?: any;
567
- }, any, any, any, any, any, any> | ITask<any, any, any, any> | IHook<any, any> | ITaskMiddleware<any, any, any, any> | IResourceMiddleware<any, any, any, any> | IEvent<any> | ITag<any, any, any>;
568
-
569
- type DebugConfig = {
570
- logResourceConfig: boolean;
571
- logResourceValue: boolean;
572
- logResourceBeforeRun: boolean;
573
- logResourceAfterRun: boolean;
574
- logTaskBeforeRun: boolean;
575
- logTaskInput: boolean;
576
- logTaskOutput: boolean;
577
- logTaskAfterRun: boolean;
578
- logMiddlewareBeforeRun: boolean;
579
- logMiddlewareAfterRun: boolean;
580
- logEventEmissionOnRun: boolean;
581
- logEventEmissionInput: boolean;
582
- logHookTriggered: boolean;
583
- logHookCompleted: boolean;
584
- };
585
- declare const allFalse: DebugConfig;
586
- declare const levelNormal: DebugConfig;
587
- declare const levelVerbose: DebugConfig;
588
- /**
589
- * If you choose to specify your own config, all values will be set to false by default and extended by your config.
590
- */
591
- type DebugFriendlyConfig = "normal" | "verbose" | Partial<DebugConfig>;
592
- declare const getConfig: (config: DebugFriendlyConfig, taggable?: ITaggable) => DebugConfig;
593
-
594
- type PrintStrategy$1 = "pretty" | "plain" | "json" | "json_pretty";
595
- type LogLevels$1 = "trace" | "debug" | "info" | "warn" | "error" | "critical";
596
- interface PrintableLog {
597
- level: LogLevels$1;
598
- source?: string;
599
- message: any;
600
- timestamp: Date;
601
- error?: {
602
- name: string;
603
- message: string;
604
- stack?: string;
605
- };
606
- data?: Record<string, any>;
607
- context?: Record<string, any>;
608
- }
609
- type ColorTheme = {
610
- trace: string;
611
- debug: string;
612
- info: string;
613
- warn: string;
614
- error: string;
615
- critical: string;
616
- reset: string;
617
- bold: string;
618
- dim: string;
619
- blue: string;
620
- cyan: string;
621
- gray: string;
622
- };
623
- declare class LogPrinter {
624
- private strategy;
625
- private colors;
626
- constructor(options: {
627
- strategy: PrintStrategy$1;
628
- useColors: boolean;
629
- colorTheme?: Partial<ColorTheme>;
630
- });
631
- print(log: PrintableLog): void;
632
- private pickWriter;
633
- private formatTime;
634
- private formatLevel;
635
- private formatSource;
636
- private formatMessage;
637
- private formatError;
638
- private formatData;
639
- private formatContext;
640
- private normalizeForJson;
641
- private static NO_COLORS;
642
- private static writers;
643
- static setWriters(writers: Partial<{
644
- log: (msg: any) => void;
645
- error?: (msg: any) => void;
646
- }>): void;
647
- static resetWriters(): void;
648
- }
649
-
650
- type LogLevels = "trace" | "debug" | "info" | "warn" | "error" | "critical";
651
- interface ILogInfo {
652
- source?: string;
653
- error?: unknown | Error;
654
- data?: Record<string, any>;
655
- context?: Record<string, any>;
656
- [key: string]: any;
657
- }
658
- interface ILog {
659
- level: LogLevels;
660
- source?: string;
661
- message: any;
662
- timestamp: Date;
663
- error?: {
664
- name: string;
665
- message: string;
666
- stack?: string;
667
- };
668
- data?: Record<string, any>;
669
- context?: Record<string, any>;
670
- }
671
- type PrintStrategy = PrintStrategy$1;
672
- declare class Logger {
673
- private printThreshold;
674
- private printStrategy;
675
- private bufferLogs;
676
- private buffer;
677
- private boundContext;
678
- private isLocked;
679
- private useColors;
680
- private printer;
681
- private source?;
682
- private rootLogger?;
683
- localListeners: Array<(log: ILog) => void | Promise<void>>;
684
- static Severity: {
685
- trace: number;
686
- debug: number;
687
- info: number;
688
- warn: number;
689
- error: number;
690
- critical: number;
691
- };
692
- constructor(options: {
693
- printThreshold: null | LogLevels;
694
- printStrategy: PrintStrategy;
695
- bufferLogs: boolean;
696
- useColors?: boolean;
697
- }, boundContext?: Record<string, any>, source?: string, printer?: LogPrinter);
698
- private detectColorSupport;
699
- /**
700
- * Creates a new logger instance with additional bound context
701
- */
702
- with({ source, additionalContext: context, }: {
703
- source?: string;
704
- additionalContext?: Record<string, any>;
705
- }): Logger;
706
- /**
707
- * Core logging method with structured LogInfo
708
- */
709
- log(level: LogLevels, message: any, logInfo?: ILogInfo): Promise<void>;
710
- private extractErrorInfo;
711
- info(message: any, logInfo?: ILogInfo): Promise<void>;
712
- error(message: any, logInfo?: ILogInfo): Promise<void>;
713
- warn(message: any, logInfo?: ILogInfo): Promise<void>;
714
- debug(message: any, logInfo?: ILogInfo): Promise<void>;
715
- trace(message: any, logInfo?: ILogInfo): Promise<void>;
716
- critical(message: any, logInfo?: ILogInfo): Promise<void>;
717
- /**
718
- * Direct print for tests and advanced scenarios. Delegates to LogPrinter.
719
- */
720
- print(log: ILog): void;
721
- /**
722
- * @param listener - A listener that will be triggered for every log.
723
- */
724
- onLog(listener: (log: ILog) => any): void;
725
- /**
726
- * Marks the logger as ready.
727
- * This is used to trigger the local listeners and print the buffered logs (if they exists)
728
- * @returns A promise that resolves when the logger is ready.
729
- */
730
- lock(): Promise<void>;
731
- private canPrint;
732
- private triggerLogListeners;
733
- }
734
-
735
- type UnhandledErrorKind = "process" | "task" | "middleware" | "resourceInit" | "hook" | "run";
736
- interface OnUnhandledErrorInfo {
737
- error: unknown;
738
- kind?: UnhandledErrorKind;
739
- source?: string;
740
- }
741
- type OnUnhandledError = (info: OnUnhandledErrorInfo) => void | Promise<void>;
742
- declare function createDefaultUnhandledError(logger: Logger): OnUnhandledError;
743
- declare function bindProcessErrorHandler(handler: OnUnhandledError): (error: unknown, source: "uncaughtException" | "unhandledRejection") => void | Promise<void>;
744
- declare function safeReportUnhandledError(handler: OnUnhandledError, info: OnUnhandledErrorInfo): Promise<void>;
745
-
746
- type RunOptions = {
747
- /**
748
- * Defaults to undefined. If true, we introduce logging to the console.
749
- */
750
- debug?: DebugFriendlyConfig;
751
- /**
752
- * Configure logging settings.
753
- */
754
- logs?: {
755
- /**
756
- * Defaults to info. Use null to disable logging.
757
- */
758
- printThreshold?: null | LogLevels;
759
- /**
760
- * Defaults to PRETTY. How to print the logs.
761
- */
762
- printStrategy?: PrintStrategy;
763
- /**
764
- * Defaults to false. If true, we buffer logs until the root resource is ready.
765
- * This provides you with the chance to see the logs before the root resource is ready.
766
- */
767
- bufferLogs?: boolean;
768
- };
769
- /**
770
- * When true (default), installs a central error boundary that catches uncaught errors
771
- * from process-level events and routes them to `onUnhandledError`.
772
- */
773
- errorBoundary?: boolean;
774
- /**
775
- * When true (default), installs SIGINT/SIGTERM handlers that call dispose() on the root allowing for graceful shutdown.
776
- */
777
- shutdownHooks?: boolean;
778
- /**
779
- * Custom handler for any unhandled error caught by Runner. Defaults to logging via the created logger.
780
- */
781
- onUnhandledError?: OnUnhandledError;
782
- /**
783
- * Defaults to false.
784
- *
785
- * Dry run mode. When true, the runner will setup the system, ensure there are no errors, but will not start the system.
786
- * Your resources will not be initialized, and no events will be emitted. This is useful for testing and debugging.
787
- *
788
- * Note: this cannot catch init() errors that happen within resources.
789
- */
790
- dryRun?: boolean;
791
- /**
792
- * Defaults to true.
793
- * When set, forces runtime cycle detection for event emissions. Disable if you're sure
794
- * you don't have event deadlocks to improve event emission performance.
795
- */
796
- runtimeCycleDetection?: boolean;
797
- };
798
-
799
- interface ICacheInstance {
800
- set(key: string, value: any): void;
801
- get(key: string): any;
802
- clear(): void;
803
- }
804
-
805
- type ResourceStoreElementType<C = any, V extends Promise<any> = any, D extends DependencyMapType = {}, TContext = any> = {
806
- resource: IResource<C, V, D>;
807
- computedDependencies?: ResourceDependencyValuesType<D>;
808
- config: C;
809
- value: V;
810
- context: TContext;
811
- isInitialized?: boolean;
812
- };
813
- type TaskStoreElementType<Input = any, Output extends Promise<any> = any, D extends DependencyMapType = any> = {
814
- task: ITask<Input, Output, D>;
815
- computedDependencies: DependencyValuesType<D>;
816
- isInitialized: boolean;
817
- interceptors?: Array<TaskLocalInterceptor<any, any>>;
818
- };
819
- type HookStoreElementType<D extends DependencyMapType = any, TOn extends "*" | IEventDefinition = any> = {
820
- hook: IHook<D, TOn>;
821
- computedDependencies: DependencyValuesType<D>;
822
- };
823
- type TaskMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = {
824
- middleware: ITaskMiddleware<any, TDeps>;
825
- computedDependencies: DependencyValuesType<TDeps>;
826
- isInitialized: boolean;
827
- };
828
- type ResourceMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = {
829
- middleware: IResourceMiddleware<any, TDeps>;
830
- computedDependencies: DependencyValuesType<TDeps>;
831
- isInitialized: boolean;
832
- };
833
- type EventStoreElementType = {
834
- event: IEvent<any>;
835
- };
836
-
837
- /**
838
- * Core public TypeScript types for BlueLibs Runner.
839
- *
840
- * This file contains the strongly-typed contract for tasks, resources, events
841
- * and middleware. It mirrors the mental model described in the README:
842
- * - Tasks are functions
843
- * - Resources are singletons (with init/dispose hooks)
844
- * - Hooks are event listeners without middleware
845
- * - Events are simple, strongly-typed emissions
846
- * - Middleware can target both tasks and resources (taskMiddleware, resourceMiddleware)
847
- *
848
- * DX goals:
849
- * - Crystal‑clear generics and helper types that infer dependency shapes
850
- * - Friendly JSDoc you can hover in editors to understand usage instantly
851
- * - Safe overrides and strong typing around config and register mechanics
852
- */
853
-
854
- type defs_CommonPayload<T extends readonly IEventDefinition<any>[] | IEventDefinition<any>> = CommonPayload<T>;
855
- type defs_DependencyMapType = DependencyMapType;
856
- type defs_DependencyValueType<T> = DependencyValueType<T>;
857
- type defs_DependencyValuesType<T extends DependencyMapType> = DependencyValuesType<T>;
858
- type defs_EventHandlerType<T = any> = EventHandlerType<T>;
859
- type defs_EventStoreElementType = EventStoreElementType;
860
- type defs_ExtractEventPayload<T> = ExtractEventPayload<T>;
861
- type defs_ExtractResourceConfig<T> = ExtractResourceConfig<T>;
862
- type defs_ExtractResourceValue<T> = ExtractResourceValue<T>;
863
- type defs_ExtractTaskInput<T> = ExtractTaskInput<T>;
864
- type defs_ExtractTaskOutput<T> = ExtractTaskOutput<T>;
865
- type defs_HookStoreElementType<D extends DependencyMapType = any, TOn extends "*" | IEventDefinition = any> = HookStoreElementType<D, TOn>;
866
- type defs_ICacheInstance = ICacheInstance;
867
- type defs_IEvent<TPayload = any> = IEvent<TPayload>;
868
- type defs_IEventDefinition<TPayload = void> = IEventDefinition<TPayload>;
869
- type defs_IEventEmission<TPayload = any> = IEventEmission<TPayload>;
870
- type defs_IEventMeta = IEventMeta;
871
- type defs_IHook<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> = IHook<TDependencies, TOn, TMeta>;
872
- type defs_IHookDefinition<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> = IHookDefinition<TDependencies, TOn, TMeta>;
873
- type defs_IMeta = IMeta;
874
- type defs_IMiddlewareMeta = IMiddlewareMeta;
875
- type defs_IOptionalDependency<T> = IOptionalDependency<T>;
876
- type defs_IResource<TConfig = void, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = any, TContext = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> = IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
877
- type defs_IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = {}, TContext = any, THooks = any, TRegisterableItems = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> = IResourceDefinition<TConfig, TValue, TDependencies, TContext, THooks, TRegisterableItems, TMeta, TTags, TMiddleware>;
878
- type defs_IResourceMeta = IResourceMeta;
879
- type defs_IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
880
- type defs_IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
881
- type defs_IResourceMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
882
- type defs_IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutput = any> = IResourceMiddlewareExecutionInput<TResourceConfig, TResourceOutput>;
883
- type defs_IResourceWithConfig<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = any, TContext = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends IResourceMiddleware<any, any, any, any>[] = IResourceMiddleware[]> = IResourceWithConfig<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
884
- type defs_ITag<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITag<TConfig, TEnforceInputContract, TEnforceOutputContract>;
885
- type defs_ITagConfigured<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITagConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract>;
886
- type defs_ITagDefinition<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITagDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract>;
887
- type defs_ITagMeta = ITagMeta;
888
- type defs_ITaggable = ITaggable;
889
- type defs_ITask<TInput = any, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> = ITask<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>;
890
- type defs_ITaskDefinition<TInput = undefined, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> = ITaskDefinition<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>;
891
- type defs_ITaskMeta = ITaskMeta;
892
- type defs_ITaskMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = ITaskMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
893
- type defs_ITaskMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = ITaskMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
894
- type defs_ITaskMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = ITaskMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
895
- type defs_ITaskMiddlewareExecutionInput<TTaskInput = any, TTaskOutput = any> = ITaskMiddlewareExecutionInput<TTaskInput, TTaskOutput>;
896
- type defs_IValidationSchema<T = any> = IValidationSchema<T>;
897
- type defs_OverridableElements = OverridableElements;
898
- type defs_RegisterableItems<T = any> = RegisterableItems<T>;
899
- type defs_RequiredKeys<T> = RequiredKeys<T>;
900
- type defs_ResourceDependencyValueType<T> = ResourceDependencyValueType<T>;
901
- type defs_ResourceDependencyValuesType<T extends DependencyMapType> = ResourceDependencyValuesType<T>;
902
- type defs_ResourceMiddlewareAttachmentType = ResourceMiddlewareAttachmentType;
903
- type defs_ResourceMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = ResourceMiddlewareStoreElementType<TDeps>;
904
- type defs_ResourceStoreElementType<C = any, V extends Promise<any> = any, D extends DependencyMapType = {}, TContext = any> = ResourceStoreElementType<C, V, D, TContext>;
905
- type defs_RunOptions = RunOptions;
906
- type defs_TagType = TagType;
907
- type defs_TaskDependencyWithIntercept<TInput, TOutput> = TaskDependencyWithIntercept<TInput, TOutput>;
908
- type defs_TaskLocalInterceptor<TInput, TOutput> = TaskLocalInterceptor<TInput, TOutput>;
909
- type defs_TaskMiddlewareAttachmentType = TaskMiddlewareAttachmentType;
910
- type defs_TaskMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = TaskMiddlewareStoreElementType<TDeps>;
911
- type defs_TaskStoreElementType<Input = any, Output extends Promise<any> = any, D extends DependencyMapType = any> = TaskStoreElementType<Input, Output, D>;
912
- type defs_UnionToIntersection<U> = UnionToIntersection<U>;
913
- declare const defs_isOneOf: typeof isOneOf;
914
- declare const defs_onAnyOf: typeof onAnyOf;
915
- declare const defs_symbolEvent: typeof symbolEvent;
916
- declare const defs_symbolFilePath: typeof symbolFilePath;
917
- declare const defs_symbolHook: typeof symbolHook;
918
- declare const defs_symbolMiddleware: typeof symbolMiddleware;
919
- declare const defs_symbolMiddlewareConfigured: typeof symbolMiddlewareConfigured;
920
- declare const defs_symbolOptionalDependency: typeof symbolOptionalDependency;
921
- declare const defs_symbolResource: typeof symbolResource;
922
- declare const defs_symbolResourceMiddleware: typeof symbolResourceMiddleware;
923
- declare const defs_symbolResourceWithConfig: typeof symbolResourceWithConfig;
924
- declare const defs_symbolTag: typeof symbolTag;
925
- declare const defs_symbolTagConfigured: typeof symbolTagConfigured;
926
- declare const defs_symbolTask: typeof symbolTask;
927
- declare const defs_symbolTaskMiddleware: typeof symbolTaskMiddleware;
928
- declare namespace defs {
929
- export { type defs_CommonPayload as CommonPayload, type defs_DependencyMapType as DependencyMapType, type defs_DependencyValueType as DependencyValueType, type defs_DependencyValuesType as DependencyValuesType, type defs_EventHandlerType as EventHandlerType, type defs_EventStoreElementType as EventStoreElementType, type defs_ExtractEventPayload as ExtractEventPayload, type defs_ExtractResourceConfig as ExtractResourceConfig, type defs_ExtractResourceValue as ExtractResourceValue, type defs_ExtractTaskInput as ExtractTaskInput, type defs_ExtractTaskOutput as ExtractTaskOutput, type defs_HookStoreElementType as HookStoreElementType, type defs_ICacheInstance as ICacheInstance, type defs_IEvent as IEvent, type defs_IEventDefinition as IEventDefinition, type defs_IEventEmission as IEventEmission, type defs_IEventMeta as IEventMeta, type defs_IHook as IHook, type defs_IHookDefinition as IHookDefinition, type defs_IMeta as IMeta, type defs_IMiddlewareMeta as IMiddlewareMeta, type defs_IOptionalDependency as IOptionalDependency, type defs_IResource as IResource, type defs_IResourceDefinition as IResourceDefinition, type defs_IResourceMeta as IResourceMeta, type defs_IResourceMiddleware as IResourceMiddleware, type defs_IResourceMiddlewareConfigured as IResourceMiddlewareConfigured, type defs_IResourceMiddlewareDefinition as IResourceMiddlewareDefinition, type defs_IResourceMiddlewareExecutionInput as IResourceMiddlewareExecutionInput, type defs_IResourceWithConfig as IResourceWithConfig, type defs_ITag as ITag, type defs_ITagConfigured as ITagConfigured, type defs_ITagDefinition as ITagDefinition, type defs_ITagMeta as ITagMeta, type defs_ITaggable as ITaggable, type defs_ITask as ITask, type defs_ITaskDefinition as ITaskDefinition, type defs_ITaskMeta as ITaskMeta, type defs_ITaskMiddleware as ITaskMiddleware, type defs_ITaskMiddlewareConfigured as ITaskMiddlewareConfigured, type defs_ITaskMiddlewareDefinition as ITaskMiddlewareDefinition, type defs_ITaskMiddlewareExecutionInput as ITaskMiddlewareExecutionInput, type defs_IValidationSchema as IValidationSchema, type defs_OverridableElements as OverridableElements, type defs_RegisterableItems as RegisterableItems, type defs_RequiredKeys as RequiredKeys, type defs_ResourceDependencyValueType as ResourceDependencyValueType, type defs_ResourceDependencyValuesType as ResourceDependencyValuesType, type defs_ResourceMiddlewareAttachmentType as ResourceMiddlewareAttachmentType, type defs_ResourceMiddlewareStoreElementType as ResourceMiddlewareStoreElementType, type defs_ResourceStoreElementType as ResourceStoreElementType, type defs_RunOptions as RunOptions, type defs_TagType as TagType, type defs_TaskDependencyWithIntercept as TaskDependencyWithIntercept, type defs_TaskLocalInterceptor as TaskLocalInterceptor, type defs_TaskMiddlewareAttachmentType as TaskMiddlewareAttachmentType, type defs_TaskMiddlewareStoreElementType as TaskMiddlewareStoreElementType, type defs_TaskStoreElementType as TaskStoreElementType, type defs_UnionToIntersection as UnionToIntersection, defs_isOneOf as isOneOf, defs_onAnyOf as onAnyOf, defs_symbolEvent as symbolEvent, defs_symbolFilePath as symbolFilePath, defs_symbolHook as symbolHook, defs_symbolMiddleware as symbolMiddleware, defs_symbolMiddlewareConfigured as symbolMiddlewareConfigured, defs_symbolOptionalDependency as symbolOptionalDependency, defs_symbolResource as symbolResource, defs_symbolResourceMiddleware as symbolResourceMiddleware, defs_symbolResourceWithConfig as symbolResourceWithConfig, defs_symbolTag as symbolTag, defs_symbolTagConfigured as symbolTagConfigured, defs_symbolTask as symbolTask, defs_symbolTaskMiddleware as symbolTaskMiddleware };
930
- }
931
-
932
- /**
933
- * Base error class for all BlueLibs Runner errors
934
- */
935
- declare class RuntimeError extends Error {
936
- constructor(message: string);
937
- }
938
- /**
939
- * Error thrown when attempting to register a component with a duplicate ID
940
- */
941
- declare class DuplicateRegistrationError extends RuntimeError {
942
- constructor(type: string, id: string);
943
- }
944
- /**
945
- * Error thrown when a dependency is not found in the registry
946
- */
947
- declare class DependencyNotFoundError extends RuntimeError {
948
- constructor(key: string);
949
- }
950
- /**
951
- * Error thrown when an unknown item type is encountered
952
- */
953
- declare class UnknownItemTypeError extends RuntimeError {
954
- constructor(item: any);
955
- }
956
- /**
957
- * Error thrown whenever a requested context is not available.
958
- */
959
- declare class ContextError extends Error {
960
- constructor(message: string);
961
- }
962
- /**
963
- * Error thrown when circular dependencies are detected
964
- */
965
- declare class CircularDependenciesError extends RuntimeError {
966
- constructor(cycles: string[]);
967
- }
968
- /**
969
- * Error thrown when an event is not found in the registry
970
- */
971
- declare class EventNotFoundError extends RuntimeError {
972
- constructor(id: string);
973
- }
974
- /**
975
- * Error thrown when a resource is not found in the store
976
- */
977
- declare class ResourceNotFoundError extends RuntimeError {
978
- constructor(id: string);
979
- }
980
- declare class MiddlewareNotRegisteredError extends RuntimeError {
981
- constructor(type: "task" | "resource", source: string, middlewareId: string);
982
- }
983
- /**
984
- * Error thrown when a tag is not found in the registry
985
- */
986
- declare class TagNotFoundError extends RuntimeError {
987
- constructor(id: string);
988
- }
989
- /**
990
- * Error thrown when attempting to modify a locked component
991
- */
992
- declare class LockedError extends RuntimeError {
993
- constructor(what: string);
994
- }
995
- /**
996
- * Error thrown when attempting to initialize a store that's already initialized
997
- */
998
- declare class StoreAlreadyInitializedError extends RuntimeError {
999
- constructor();
1000
- }
1001
- /**
1002
- * Error thrown when validation fails for task input, resource config, middleware config, or event payload
1003
- */
1004
- declare class ValidationError extends RuntimeError {
1005
- constructor(type: string, id: string, originalError: Error | string);
1006
- }
1007
- /**
1008
- * Error thrown when an event emission cycle is detected
1009
- */
1010
- declare class EventCycleError extends RuntimeError {
1011
- constructor(path: Array<{
1012
- id: string;
1013
- source: string;
1014
- }>);
1015
- }
1016
- /**
1017
- * Error thrown when a compile-time event emission cycle is detected
1018
- */
1019
- declare class EventEmissionCycleError extends RuntimeError {
1020
- constructor(cycles: string[]);
1021
- }
1022
- /**
1023
- * Error thrown when a platform function is not supported in the current environment.
1024
- */
1025
- declare class PlatformUnsupportedFunction extends RuntimeError {
1026
- constructor(functionName: string);
1027
- }
1028
-
1029
- type errors_CircularDependenciesError = CircularDependenciesError;
1030
- declare const errors_CircularDependenciesError: typeof CircularDependenciesError;
1031
- type errors_ContextError = ContextError;
1032
- declare const errors_ContextError: typeof ContextError;
1033
- type errors_DependencyNotFoundError = DependencyNotFoundError;
1034
- declare const errors_DependencyNotFoundError: typeof DependencyNotFoundError;
1035
- type errors_DuplicateRegistrationError = DuplicateRegistrationError;
1036
- declare const errors_DuplicateRegistrationError: typeof DuplicateRegistrationError;
1037
- type errors_EventCycleError = EventCycleError;
1038
- declare const errors_EventCycleError: typeof EventCycleError;
1039
- type errors_EventEmissionCycleError = EventEmissionCycleError;
1040
- declare const errors_EventEmissionCycleError: typeof EventEmissionCycleError;
1041
- type errors_EventNotFoundError = EventNotFoundError;
1042
- declare const errors_EventNotFoundError: typeof EventNotFoundError;
1043
- type errors_LockedError = LockedError;
1044
- declare const errors_LockedError: typeof LockedError;
1045
- type errors_MiddlewareNotRegisteredError = MiddlewareNotRegisteredError;
1046
- declare const errors_MiddlewareNotRegisteredError: typeof MiddlewareNotRegisteredError;
1047
- type errors_PlatformUnsupportedFunction = PlatformUnsupportedFunction;
1048
- declare const errors_PlatformUnsupportedFunction: typeof PlatformUnsupportedFunction;
1049
- type errors_ResourceNotFoundError = ResourceNotFoundError;
1050
- declare const errors_ResourceNotFoundError: typeof ResourceNotFoundError;
1051
- type errors_RuntimeError = RuntimeError;
1052
- declare const errors_RuntimeError: typeof RuntimeError;
1053
- type errors_StoreAlreadyInitializedError = StoreAlreadyInitializedError;
1054
- declare const errors_StoreAlreadyInitializedError: typeof StoreAlreadyInitializedError;
1055
- type errors_TagNotFoundError = TagNotFoundError;
1056
- declare const errors_TagNotFoundError: typeof TagNotFoundError;
1057
- type errors_UnknownItemTypeError = UnknownItemTypeError;
1058
- declare const errors_UnknownItemTypeError: typeof UnknownItemTypeError;
1059
- type errors_ValidationError = ValidationError;
1060
- declare const errors_ValidationError: typeof ValidationError;
1061
- declare namespace errors {
1062
- export { errors_CircularDependenciesError as CircularDependenciesError, errors_ContextError as ContextError, errors_DependencyNotFoundError as DependencyNotFoundError, errors_DuplicateRegistrationError as DuplicateRegistrationError, errors_EventCycleError as EventCycleError, errors_EventEmissionCycleError as EventEmissionCycleError, errors_EventNotFoundError as EventNotFoundError, errors_LockedError as LockedError, errors_MiddlewareNotRegisteredError as MiddlewareNotRegisteredError, errors_PlatformUnsupportedFunction as PlatformUnsupportedFunction, errors_ResourceNotFoundError as ResourceNotFoundError, errors_RuntimeError as RuntimeError, errors_StoreAlreadyInitializedError as StoreAlreadyInitializedError, errors_TagNotFoundError as TagNotFoundError, errors_UnknownItemTypeError as UnknownItemTypeError, errors_ValidationError as ValidationError };
1063
- }
1064
-
1065
- /**
1066
- * The generic Context object returned by `createContext`.
1067
- */
1068
- interface Context<T> {
1069
- /** unique symbol used as key in the AsyncLocalStorage map */
1070
- readonly id: symbol;
1071
- /** Retrieve the current context value or throw */
1072
- use(): T;
1073
- /**
1074
- * Provide a value for this context during the lifetime of `fn()`
1075
- */
1076
- provide<R>(value: T, fn: () => Promise<R> | R): Promise<R> | R;
1077
- /**
1078
- * Generates a middleware that guarantees the context exists (and optionally
1079
- * enforces that certain keys are present on the context object).
1080
- */
1081
- require<K extends keyof T = never>(keys?: K[]): ITaskMiddlewareConfigured<{
1082
- context: Context<T>;
1083
- }>;
1084
- }
1085
- /**
1086
- * Create a new typed Context. The result contains helpers similar to React’s
1087
- * Context API but adapted for async usage in Runner.
1088
- */
1089
- declare function createContext<T>(name?: string): Context<T>;
1090
-
1091
- /**
1092
- * Options for configuring event listeners
1093
- */
1094
- interface IEventHandlerOptions<T = any> {
1095
- order?: number;
1096
- filter?: (event: IEventEmission<T>) => boolean;
1097
- /**
1098
- * Represents the listener ID. Use this to avoid a listener calling himself.
1099
- */
1100
- id?: string;
1101
- }
1102
- /**
1103
- * Interceptor for event emissions
1104
- */
1105
- type EventEmissionInterceptor = (next: (event: IEventEmission<any>) => Promise<void>, event: IEventEmission<any>) => Promise<void>;
1106
- /**
1107
- * Interceptor for hook execution
1108
- */
1109
- type HookExecutionInterceptor = (next: (hook: IHook<any, any>, event: IEventEmission<any>) => Promise<any>, hook: IHook<any, any>, event: IEventEmission<any>) => Promise<any>;
1110
- /**
1111
- * EventManager handles event emission, listener registration, and event processing.
1112
- * It supports both specific event listeners and global listeners that handle all events.
1113
- * Listeners are processed in order based on their priority.
1114
- */
1115
- declare class EventManager {
1116
- #private;
1117
- private listeners;
1118
- private globalListeners;
1119
- private cachedMergedListeners;
1120
- private globalListenersCacheValid;
1121
- private emissionInterceptors;
1122
- private hookInterceptors;
1123
- private readonly emissionStack;
1124
- private readonly currentHookIdContext;
1125
- private readonly runtimeCycleDetection;
1126
- constructor(options?: {
1127
- runtimeCycleDetection?: boolean;
1128
- });
1129
- /**
1130
- * Gets the current lock status of the EventManager
1131
- */
1132
- get isLocked(): boolean;
1133
- /**
1134
- * Locks the EventManager, preventing any further modifications to listeners
1135
- */
1136
- lock(): void;
1137
- /**
1138
- * Emits an event to all registered listeners for that event type.
1139
- * Listeners are processed in order of priority and can stop event propagation.
1140
- *
1141
- * @param eventDefinition - The event definition to emit
1142
- * @param data - The event payload data
1143
- * @param source - The source identifier of the event emitter
1144
- */
1145
- emit<TInput>(eventDefinition: IEvent<TInput>, data: TInput, source: string): Promise<void>;
1146
- /**
1147
- * Registers an event listener for specific event(s).
1148
- * Listeners are ordered by priority and executed in ascending order.
1149
- *
1150
- * @param event - The event definition(s) to listen for
1151
- * @param handler - The callback function to handle the event
1152
- * @param options - Configuration options for the listener
1153
- */
1154
- addListener<T>(event: IEvent<T> | Array<IEvent<T>>, handler: EventHandlerType<T>, options?: IEventHandlerOptions<T>): void;
1155
- /**
1156
- * Registers a global event listener that handles all events.
1157
- * Global listeners are mixed with specific listeners and ordered by priority.
1158
- *
1159
- * @param handler - The callback function to handle events
1160
- * @param options - Configuration options for the listener
1161
- */
1162
- addGlobalListener(handler: EventHandlerType, options?: IEventHandlerOptions): void;
1163
- /**
1164
- * Checks if there are any listeners registered for the given event
1165
- *
1166
- * @param eventDefinition - The event definition to check
1167
- * @returns true if listeners exist, false otherwise
1168
- */
1169
- hasListeners<T>(eventDefinition: IEvent<T>): boolean;
1170
- /**
1171
- * Adds an interceptor for all event emissions
1172
- * Interceptors are executed in the order they are added, with the ability to
1173
- * modify, log, or prevent event emissions
1174
- *
1175
- * @param interceptor - The interceptor function to add
1176
- */
1177
- intercept(interceptor: EventEmissionInterceptor): void;
1178
- /**
1179
- * Adds an interceptor for hook execution
1180
- * Interceptors are executed in the order they are added, with the ability to
1181
- * modify, log, or prevent hook execution
1182
- *
1183
- * @param interceptor - The interceptor function to add
1184
- */
1185
- interceptHook(interceptor: HookExecutionInterceptor): void;
1186
- /**
1187
- * Executes a hook with all registered hook interceptors applied
1188
- * This method should be used by TaskRunner when executing hooks
1189
- *
1190
- * @param hook - The hook to execute
1191
- * @param event - The event that triggered the hook
1192
- * @param computedDependencies - The computed dependencies for the hook
1193
- * @returns Promise resolving to the hook execution result
1194
- */
1195
- executeHookWithInterceptors(hook: IHook<any, any>, event: IEventEmission<any>, computedDependencies: DependencyValuesType<any>): Promise<any>;
1196
- /**
1197
- * Throws an error if the EventManager is locked
1198
- */
1199
- private checkLock;
1200
- /**
1201
- * Merges two sorted arrays of listeners while maintaining order.
1202
- * Used to combine event-specific listeners with global listeners.
1203
- *
1204
- * @param a - First array of listeners
1205
- * @param b - Second array of listeners
1206
- * @returns Merged and sorted array of listeners
1207
- */
1208
- private mergeSortedListeners;
1209
- /**
1210
- * Inserts a new listener into a sorted array using binary search.
1211
- * Maintains order based on listener priority.
1212
- *
1213
- * @param listeners - Array to insert into
1214
- * @param newListener - Listener to insert
1215
- */
1216
- private insertListener;
1217
- /**
1218
- * Returns true if the given emission carries the tag that marks
1219
- * it as excluded from global ("*") listeners.
1220
- *
1221
- * @param event - The event emission to check
1222
- * @returns true if event should exclude global listeners
1223
- */
1224
- private isExcludedFromGlobal;
1225
- /**
1226
- * Retrieves cached merged listeners for an event, or creates them if not cached.
1227
- * Combines event-specific listeners with global listeners and sorts them by priority.
1228
- *
1229
- * @param eventId - The event ID to get listeners for
1230
- * @returns Array of merged listeners sorted by priority
1231
- */
1232
- private getCachedMergedListeners;
1233
- /**
1234
- * Invalidates the cached merged listeners.
1235
- * If eventId is provided, only invalidates cache for that specific event.
1236
- * Otherwise, invalidates the global cache.
1237
- *
1238
- * @param eventId - Optional specific event ID to invalidate
1239
- */
1240
- private invalidateCache;
1241
- }
1242
-
1243
- declare class TaskRunner {
1244
- protected readonly store: Store;
1245
- protected readonly eventManager: EventManager;
1246
- protected readonly logger: Logger;
1247
- protected readonly runnerStore: Map<string | symbol, (input: any) => Promise<any>>;
1248
- constructor(store: Store, eventManager: EventManager, logger: Logger);
1249
- private readonly middlewareManager;
1250
- /**
1251
- * Begins the execution of an task. These are registered tasks and all sanity checks have been performed at this stage to ensure consistency of the object.
1252
- * This function can throw only if any of the event listeners or run function throws
1253
- * @param task the task to be run
1254
- * @param input the input to be passed to the task
1255
- */
1256
- run<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>, input?: TInput): Promise<TOutput | undefined>;
1257
- /**
1258
- * Creates the function with the chain of middleware.
1259
- * @param task
1260
- * @param input
1261
- * @param taskDependencies
1262
- * @returns
1263
- */
1264
- protected createRunnerWithMiddleware<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: any) => Promise<TOutput | (TOutput extends Promise<infer U> ? U : never)>;
1265
- }
1266
-
1267
- /**
1268
- * Interceptor for task middleware execution
1269
- */
1270
- type TaskMiddlewareInterceptor = (next: (input: ITaskMiddlewareExecutionInput<any>) => Promise<any>, input: ITaskMiddlewareExecutionInput<any>) => Promise<any>;
1271
- /**
1272
- * Interceptor for resource middleware execution
1273
- */
1274
- type ResourceMiddlewareInterceptor = (next: (input: IResourceMiddlewareExecutionInput<any>) => Promise<any>, input: IResourceMiddlewareExecutionInput<any>) => Promise<any>;
1275
- /**
1276
- * Centralizes middleware composition and execution for both tasks and resources.
1277
- * Keeps observability emissions and unhandled error routing consistent.
1278
- */
1279
- declare class MiddlewareManager {
1280
- #private;
1281
- protected readonly store: Store;
1282
- protected readonly eventManager: EventManager;
1283
- protected readonly logger: Logger;
1284
- private taskMiddlewareInterceptors;
1285
- private resourceMiddlewareInterceptors;
1286
- private perMiddlewareInterceptors;
1287
- private perResourceMiddlewareInterceptors;
1288
- constructor(store: Store, eventManager: EventManager, logger: Logger);
1289
- /**
1290
- * Gets the current lock status of the MiddlewareManager
1291
- */
1292
- get isLocked(): boolean;
1293
- /**
1294
- * Locks the MiddlewareManager, preventing any further modifications to interceptors
1295
- */
1296
- lock(): void;
1297
- /**
1298
- * Throws an error if the MiddlewareManager is locked
1299
- */
1300
- private checkLock;
1301
- /**
1302
- * Adds an interceptor for task or resource middleware execution
1303
- * Interceptors are executed in the order they are added, with the ability to
1304
- * modify, log, or prevent middleware execution
1305
- *
1306
- * @param kind - The type of middleware to intercept ("task" or "resource")
1307
- * @param interceptor - The interceptor function to add
1308
- */
1309
- intercept(kind: "task" | "resource", interceptor: TaskMiddlewareInterceptor | ResourceMiddlewareInterceptor): void;
1310
- /**
1311
- * Adds an interceptor for a specific middleware instance with better type safety
1312
- * This method automatically determines the type and provides type-safe access
1313
- *
1314
- * @param middleware - The middleware instance to intercept
1315
- * @param interceptor - The interceptor function with proper typing
1316
- */
1317
- interceptMiddleware(middleware: ITaskMiddleware<any, any, any, any> | IResourceMiddleware<any, any, any, any>, interceptor: TaskMiddlewareInterceptor | ResourceMiddlewareInterceptor): void;
1318
- /**
1319
- * Wrap a middleware with its specific interceptors in onion style
1320
- */
1321
- private wrapMiddlewareWithInterceptors;
1322
- /**
1323
- * Wrap a resource middleware with its specific interceptors in onion style
1324
- */
1325
- private wrapResourceMiddlewareWithInterceptors;
1326
- /**
1327
- * Compose a runner for a task with its local interceptors and applicable middlewares.
1328
- * Returns a function that accepts the task input and resolves to the task output.
1329
- */
1330
- composeTaskRunner<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: any) => Promise<TOutput | (TOutput extends Promise<infer U> ? U : never)>;
1331
- /**
1332
- * Run a resource init wrapped with its applicable middlewares.
1333
- */
1334
- runResourceInit<C, V extends Promise<any>, D extends DependencyMapType, TContext>(resource: IResource<C, V, D, TContext>, config: C, dependencies: any, context: TContext): Promise<V | undefined>;
1335
- private getApplicableTaskMiddlewares;
1336
- private getApplicableResourceMiddlewares;
1337
- /**
1338
- * @param task
1339
- * @returns
1340
- */
1341
- getEverywhereMiddlewareForTasks(task: ITask<any, any, any, any>): ITaskMiddleware[];
1342
- /**
1343
- * Returns all global middleware for resource, which do not depend on the target resource.
1344
- */
1345
- getEverywhereMiddlewareForResources(target: IResource<any, any, any, any>): IResourceMiddleware[];
1346
- }
1347
-
1348
- /**
1349
- * Store class which is used to store all the resources, tasks, middleware and events.
1350
- */
1351
- declare class Store {
1352
- #private;
1353
- protected readonly eventManager: EventManager;
1354
- protected readonly logger: Logger;
1355
- readonly onUnhandledError: OnUnhandledError;
1356
- root: ResourceStoreElementType;
1357
- private registry;
1358
- private overrideManager;
1359
- private validator;
1360
- private taskRunner?;
1361
- private middlewareManager;
1362
- constructor(eventManager: EventManager, logger: Logger, onUnhandledError: OnUnhandledError);
1363
- get tasks(): Map<string, TaskStoreElementType>;
1364
- get hooks(): Map<string, HookStoreElementType>;
1365
- get resources(): Map<string, ResourceStoreElementType>;
1366
- get events(): Map<string, EventStoreElementType>;
1367
- get taskMiddlewares(): Map<string, TaskMiddlewareStoreElementType>;
1368
- get resourceMiddlewares(): Map<string, ResourceMiddlewareStoreElementType>;
1369
- get tags(): Map<string, ITag<void, void, void>>;
1370
- get overrides(): Map<string, IResourceMiddleware<any, void, void, any> | ITask<any, any, {}, any, TagType[], TaskMiddlewareAttachmentType[]> | IHook<{}, any, any> | IResource<void, Promise<any>, any, any, any, TagType[], ResourceMiddlewareAttachmentType[]> | ITaskMiddleware<any, void, void, any> | IResourceWithConfig<any, Promise<any>, any, any, any, TagType[], IResourceMiddleware<any, void, void, any>[]>>;
1371
- get overrideRequests(): Set<{
1372
- source: string;
1373
- override: RegisterableItems;
1374
- }>;
1375
- getMiddlewareManager(): MiddlewareManager;
1376
- get isLocked(): boolean;
1377
- lock(): void;
1378
- checkLock(): void;
1379
- private registerGlobalComponents;
1380
- setTaskRunner(taskRunner: TaskRunner): void;
1381
- private setupRootResource;
1382
- validateDependencyGraph(): void;
1383
- validateEventEmissionGraph(): void;
1384
- initializeStore(root: IResource<any, any, any, any, any>, config: any): void;
1385
- dispose(): Promise<void>;
1386
- /**
1387
- * Internal, avoid using this method directly.
1388
- */
1389
- processOverrides(): void;
1390
- /**
1391
- * Internal, avoid using this method directly.
1392
- * @param item
1393
- * @returns
1394
- */
1395
- storeGenericItem<C>(item: RegisterableItems): void;
1396
- /**
1397
- * Returns all tasks with the given tag.
1398
- * @param tag - The tag to filter by.
1399
- * @returns The tasks with the given tag.
1400
- */
1401
- getTasksWithTag(tag: string | ITag<any, any, any>): ITask<any, any, any, any, TagType[], TaskMiddlewareAttachmentType[]>[];
1402
- /**
1403
- * Returns all resources with the given tag.
1404
- * @param tag - The tag to filter by.
1405
- * @returns The resources with the given tag.
1406
- */
1407
- getResourcesWithTag(tag: string | ITag<any, any, any>): IResource<any, any, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>[];
1408
- }
1409
-
1410
- declare class ResourceInitializer {
1411
- protected readonly store: Store;
1412
- protected readonly eventManager: EventManager;
1413
- protected readonly logger: Logger;
1414
- constructor(store: Store, eventManager: EventManager, logger: Logger);
1415
- private readonly middlewareManager;
1416
- /**
1417
- * Begins the execution of an task. These are registered tasks and all sanity checks have been performed at this stage to ensure consistency of the object.
1418
- * This function can throw only if any of the event listeners or run function throws
1419
- */
1420
- initializeResource<TConfig = null, TValue extends Promise<any> = Promise<any>, TDeps extends DependencyMapType = {}, TContext = any>(resource: IResource<TConfig, TValue, TDeps>, config: TConfig, dependencies: ResourceDependencyValuesType<TDeps>): Promise<{
1421
- value: TValue;
1422
- context: TContext;
1423
- }>;
1424
- initWithMiddleware<C, V extends Promise<any>, D extends DependencyMapType, TContext>(resource: IResource<C, V, D, TContext>, config: C, dependencies: ResourceDependencyValuesType<D>, context: TContext): Promise<V | undefined>;
1425
- }
1426
-
1427
- /**
1428
- * This class is responsible of setting up dependencies with their respective computedValues.
1429
- * Note that all elements must have been previously registered otherwise errors will be thrown
1430
- * when trying to depend on something not in the store.
1431
- */
1432
- declare class DependencyProcessor {
1433
- protected readonly store: Store;
1434
- protected readonly eventManager: EventManager;
1435
- protected readonly taskRunner: TaskRunner;
1436
- protected readonly resourceInitializer: ResourceInitializer;
1437
- protected readonly logger: Logger;
1438
- constructor(store: Store, eventManager: EventManager, taskRunner: TaskRunner, logger: Logger);
1439
- /**
1440
- * This function is going to go through all the resources, tasks and middleware to compute their required dependencies.
1441
- */
1442
- computeAllDependencies(): Promise<void>;
1443
- private computeTaskDependencies;
1444
- initializeUninitializedResources(): Promise<void>;
1445
- /**
1446
- * Processes dependencies and hooks
1447
- * @param resource
1448
- */
1449
- protected processResourceDependencies<TD extends DependencyMapType>(resource: ResourceStoreElementType<any, any, TD>): Promise<void>;
1450
- private wrapResourceDependencies;
1451
- private makeTaskWithIntercept;
1452
- initializeRoot(): Promise<void>;
1453
- /**
1454
- * Processes all hooks, should run before emission of any event.
1455
- */
1456
- attachListeners(): void;
1457
- extractDependencies<T extends DependencyMapType>(map: T, source: string): Promise<DependencyValuesType<T>>;
1458
- extractDependency(object: any, source: string): Promise<any>;
1459
- /**
1460
- * Converts the event into a running functions with real inputs
1461
- * @param object
1462
- * @returns
1463
- */
1464
- extractEventDependency(object: IEvent<any>, source: string): (input: any) => Promise<void>;
1465
- extractTaskDependency(object: ITask<any, any, {}>): Promise<(input: unknown) => Promise<any>>;
1466
- extractResourceDependency(object: IResource<any, any, any>): Promise<any>;
1467
- }
1468
-
1469
- /**
1470
- * A semaphore that limits the number of concurrent operations.
1471
- * Used to prevent connection pool exhaustion by limiting concurrent
1472
- * database operations to the pool size.
1473
- */
1474
- declare class Semaphore {
1475
- private permits;
1476
- private readonly waitingQueue;
1477
- private disposed;
1478
- private readonly maxPermits;
1479
- constructor(maxPermits: number);
1480
- /**
1481
- * Acquire a permit. If no permits are available, waits until one becomes available.
1482
- */
1483
- acquire(options?: {
1484
- timeout?: number;
1485
- signal?: AbortSignal;
1486
- }): Promise<void>;
1487
- /**
1488
- * Release a permit, allowing waiting operations to proceed.
1489
- */
1490
- release(): void;
1491
- private removeFromQueue;
1492
- /**
1493
- * Execute a function with a permit, automatically releasing it afterwards.
1494
- */
1495
- withPermit<T>(fn: () => Promise<T>, options?: {
1496
- timeout?: number;
1497
- signal?: AbortSignal;
1498
- }): Promise<T>;
1499
- /**
1500
- * Dispose the semaphore, rejecting all waiting operations and preventing new ones.
1501
- */
1502
- dispose(): void;
1503
- /**
1504
- * Get current number of available permits (for debugging)
1505
- */
1506
- getAvailablePermits(): number;
1507
- /**
1508
- * Get current number of waiting operations (for debugging)
1509
- */
1510
- getWaitingCount(): number;
1511
- /**
1512
- * Get maximum number of permits
1513
- */
1514
- getMaxPermits(): number;
1515
- /**
1516
- * Check if the semaphore has been disposed
1517
- */
1518
- isDisposed(): boolean;
1519
- /**
1520
- * Get metrics about the current state of the semaphore
1521
- */
1522
- getMetrics(): {
1523
- availablePermits: number;
1524
- waitingCount: number;
1525
- maxPermits: number;
1526
- utilization: number;
1527
- disposed: boolean;
1528
- };
1529
- }
1530
-
1531
- /**
1532
- * Cooperative task queue.
1533
- * • Tasks run one‑after‑another (FIFO ordering).
1534
- * • Dead‑lock detection prevents nesting.
1535
- * • dispose() drains or cancels outstanding tasks, then rejects new ones.
1536
- */
1537
- declare class Queue {
1538
- private tail;
1539
- private disposed;
1540
- private abortController;
1541
- private readonly executionContext;
1542
- private readonly hasAsyncLocalStorage;
1543
- /**
1544
- * Schedule an asynchronous task.
1545
- * @param task – receives an AbortSignal so it can cancel early if desired.
1546
- */
1547
- run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;
1548
- /**
1549
- * Disposes the queue.
1550
- * @param options.cancel – if true, broadcasts AbortSignal to running task.
1551
- * default: false (waits for tasks to finish).
1552
- */
1553
- dispose(options?: {
1554
- cancel?: boolean;
1555
- }): Promise<void>;
1556
- }
1557
-
1558
- declare class RunResult<V> {
1559
- readonly value: V;
1560
- readonly logger: Logger;
1561
- readonly store: Store;
1562
- private readonly eventManager;
1563
- private readonly taskRunner;
1564
- private readonly disposeFn;
1565
- constructor(value: V, logger: Logger, store: Store, eventManager: EventManager, taskRunner: TaskRunner, disposeFn: () => Promise<void>);
1566
- /**
1567
- * Run a task within the context of the run result.
1568
- * @param task - The task to run.
1569
- * @param args - The arguments to pass to the task.
1570
- * @returns The result of the task.
1571
- */
1572
- runTask: <I = undefined, O extends Promise<any> = any, D extends DependencyMapType = any>(task: ITask<I, O, D> | string, ...args: I extends undefined | void ? [] : [I]) => Promise<O | undefined>;
1573
- /**
1574
- * Emit an event within the context of the run result.
1575
- * @param event - The event to emit.
1576
- * @param payload - The payload to emit.
1577
- */
1578
- emitEvent: <P>(event: IEvent<P> | string, payload?: P extends undefined | void ? undefined : P) => Promise<void>;
1579
- /**
1580
- * Get the value of a resource from the run result.
1581
- * @param resource - The resource to get the value of.
1582
- * @returns The value of the resource.
1583
- */
1584
- getResourceValue: <Output extends Promise<any>>(resource: string | IResource<any, Output, any, any, any>) => Output extends Promise<infer U> ? U : Output;
1585
- dispose: () => Promise<void>;
1586
- }
1587
-
1588
- /**
1589
- * Define a task.
1590
- * Generates a strongly-typed task object with id, dependencies,
1591
- * middleware, and metadata.
1592
- *
1593
- * @typeParam Input - Input type accepted by the task's `run` function.
1594
- * @typeParam Output - Promise type returned by the `run` function.
1595
- * @typeParam Deps - Dependency map type this task requires.
1596
- * @typeParam TOn - Event type or "*" this task listens to.
1597
- * @typeParam TMeta - Arbitrary metadata type carried by the task.
1598
- * @param taskConfig - The task definition config.
1599
- * @returns A branded task definition usable by the runner.
1600
- */
1601
- declare function defineTask<Input = undefined, Output extends Promise<any> = any, Deps extends DependencyMapType = any, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]>(taskConfig: ITaskDefinition<Input, Output, Deps, TMeta, TTags, TMiddleware>): ITask<Input, Output, Deps, TMeta, TTags, TMiddleware>;
1602
-
1603
- /**
1604
- * Define a hook (event listeners).
1605
- * Same shape as task with mandatory `on` and without `middleware`.
1606
- */
1607
- declare function defineHook<D extends DependencyMapType = any, TOn extends "*" | IEventDefinition<any> | readonly IEventDefinition<any>[] = any, TMeta extends ITaskMeta = any>(hookDef: IHookDefinition<D, TOn, TMeta>): IHook<D, TOn, TMeta>;
1608
-
1609
- declare function defineResource<TConfig = void, TValue extends Promise<any> = Promise<any>, TDeps extends DependencyMapType = {}, TPrivate = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]>(constConfig: IResourceDefinition<TConfig, TValue, TDeps, TPrivate, any, any, TMeta, TTags, TMiddleware>): IResource<TConfig, TValue, TDeps, TPrivate, TMeta, TTags, TMiddleware>;
1610
-
1611
- declare function defineEvent<TPayload = void>(config: IEventDefinition<TPayload>): IEvent<TPayload>;
1612
-
1613
- declare function defineTaskMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any>(middlewareDef: ITaskMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>): ITaskMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
1614
-
1615
- declare function defineResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any>(middlewareDef: IResourceMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>): IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
1616
-
1617
- /**
1618
- * Override helper that preserves the original `id` and returns the same type.
1619
- * You can override any property except `id`. The override is shallow-merged over the base.
1620
- *
1621
- * @param base - The base definition to override.
1622
- * @param patch - Properties to override (except `id`).
1623
- * @returns A definition of the same kind with overrides applied.
1624
- */
1625
- type AnyTask = ITask<any, any, any, any, any, any>;
1626
- type AnyResource = IResource<any, any, any, any, any, any, any>;
1627
- type AnyTaskMiddleware = ITaskMiddleware<any, any, any, any>;
1628
- type AnyResourceMiddleware = IResourceMiddleware<any, any, any, any>;
1629
- type AnyHook = IHook<any, any, any>;
1630
- type OverridePatch<T> = T extends AnyTask ? Omit<Partial<T>, "id"> & Pick<T, "run"> : T extends AnyResource ? Omit<Partial<T>, "id"> & Pick<T, "init"> : T extends AnyTaskMiddleware ? Omit<Partial<T>, "id"> : T extends AnyResourceMiddleware ? Omit<Partial<T>, "id"> & Pick<T, "run"> : T extends AnyHook ? Omit<Partial<T>, "id" | "on"> & Pick<T, "run"> : never;
1631
- declare function defineOverride<T extends AnyTask | AnyResource | AnyTaskMiddleware | AnyResourceMiddleware | AnyHook>(base: T, patch: OverridePatch<T>): T;
1632
-
1633
- /**
1634
- * Create a tag definition.
1635
- * - `.with(config)` to create configured instances
1636
- * - `.extract(tags)` to extract this tag from a list of tags or a taggable's meta
1637
- *
1638
- * @typeParam TConfig - Configuration type carried by configured tags.
1639
- * @typeParam TEnforceContract - Optional helper type to enforce a contract when tags are used.
1640
- * @param definition - The tag definition (id).
1641
- * @returns A tag object with helpers to configure and extract.
1642
- */
1643
- declare function defineTag<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void>(definition: ITagDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract>): ITag<TConfig, TEnforceInputContract, TEnforceOutputContract>;
1644
-
1645
- /**
1646
- * This is the central function that kicks off you runner. You can run as many resources as you want in a single process, they will run in complete isolation.
1647
- *
1648
- * @param resourceOrResourceWithConfig - The resource or resource with config to run.
1649
- * @param options - The options for the run.
1650
- * @returns A promise that resolves to the result of the run.
1651
- */
1652
- declare function run<C, V extends Promise<any>>(resourceOrResourceWithConfig: IResourceWithConfig<C, V> | IResource<void, V, any, any> | IResource<{
1653
- [K in any]?: any;
1654
- }, V, any, any>, // For optional config
1655
- options?: RunOptions): Promise<RunResult<V extends Promise<infer U> ? U : V>>;
1656
-
1657
- /**
1658
- * Helper to create a minimal test harness resource that wraps a root app (or any registerable)
1659
- * and exposes convenient testing utilities while running the full ecosystem
1660
- * (registration, overrides, middleware, events) without modifying the core API.
1661
- * @deprecated Use `run` instead with your testResource, as it provides the necessary toolkit.
1662
- */
1663
- declare function createTestResource(root: RegisterableItems, options?: {
1664
- overrides?: Array<IResource | ITask | ITaskMiddleware | IResourceMiddleware | IResourceWithConfig>;
1665
- }): IResource<void, Promise<ReturnType<typeof buildTestFacade>>>;
1666
- declare function buildTestFacade(deps: {
1667
- taskRunner: TaskRunner;
1668
- store: Store;
1669
- logger: Logger;
1670
- eventManager: EventManager;
1671
- }): {
1672
- runTask: <I, O extends Promise<any>, D extends DependencyMapType>(task: ITask<I, O, D>, ...args: I extends undefined ? [] : [I]) => Promise<Awaited<O> | undefined>;
1673
- getResource: (id: string) => any;
1674
- taskRunner: TaskRunner;
1675
- store: Store;
1676
- logger: Logger;
1677
- eventManager: EventManager;
1678
- };
1679
-
1680
- declare const globals: {
1681
- events: {
1682
- readonly ready: IEvent<void>;
1683
- };
1684
- resources: {
1685
- store: IResource<void, Promise<Store>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
1686
- middlewareManager: IResource<void, Promise<MiddlewareManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
1687
- eventManager: IResource<void, Promise<EventManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
1688
- taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
1689
- logger: IResource<void, Promise<Logger>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
1690
- cache: IResource<{
1691
- defaultOptions?: any;
1692
- }, Promise<{
1693
- map: Map<string, ICacheInstance>;
1694
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
1695
- defaultOptions: any;
1696
- }>, {
1697
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
1698
- }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
1699
- queue: IResource<void, Promise<{
1700
- map: Map<string, Queue>;
1701
- run: <T>(id: string, task: (signal: AbortSignal) => Promise<T>) => Promise<T>;
1702
- }>, {}, {
1703
- map: Map<string, Queue>;
1704
- }, {
1705
- title: string;
1706
- description: string;
1707
- }, TagType[], ResourceMiddlewareAttachmentType[]>;
1708
- };
1709
- middleware: {
1710
- requireContext: ITaskMiddleware<{
1711
- context: Context<any>;
1712
- }, void, void, any>;
1713
- task: {
1714
- requireContext: ITaskMiddleware<{
1715
- context: Context<any>;
1716
- }, void, void, any>;
1717
- cache: ITaskMiddleware<any, void, void, {
1718
- cache: IResource<{
1719
- defaultOptions?: any;
1720
- }, Promise<{
1721
- map: Map<string, ICacheInstance>;
1722
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
1723
- defaultOptions: any;
1724
- }>, {
1725
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
1726
- }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
1727
- }>;
1728
- retry: ITaskMiddleware<RetryMiddlewareConfig, void, void, any>;
1729
- timeout: ITaskMiddleware<TimeoutMiddlewareConfig, void, void, any>;
1730
- };
1731
- resource: {
1732
- retry: IResourceMiddleware<RetryMiddlewareConfig, void, void, any>;
1733
- timeout: IResourceMiddleware<TimeoutMiddlewareConfig, void, void, any>;
1734
- };
1735
- };
1736
- tags: {
1737
- system: ITag<{
1738
- metadata?: Record<string, any>;
1739
- }, void, void>;
1740
- excludeFromGlobalHooks: ITag<{
1741
- metadata?: Record<string, any>;
1742
- }, void, void>;
1743
- debug: ITag<DebugFriendlyConfig, void, void>;
1744
- };
1745
- };
1746
-
1747
- export { type CommonPayload, type Context, type DebugConfig, type DebugFriendlyConfig, type DependencyMapType, DependencyProcessor, type DependencyValueType, type DependencyValuesType, errors as Errors, type EventEmissionInterceptor, type EventHandlerType, EventManager, type EventStoreElementType, type ExtractEventPayload, type ExtractResourceConfig, type ExtractResourceValue, type ExtractTaskInput, type ExtractTaskOutput, type HookExecutionInterceptor, type HookStoreElementType, type ICacheInstance, type IEvent, type IEventDefinition, type IEventEmission, type IEventHandlerOptions, type IEventMeta, type IHook, type IHookDefinition, type ILog, type ILogInfo, type IMeta, type IMiddlewareMeta, type IOptionalDependency, type IResource, type IResourceDefinition, type IResourceMeta, type IResourceMiddleware, type IResourceMiddlewareConfigured, type IResourceMiddlewareDefinition, type IResourceMiddlewareExecutionInput, type IResourceWithConfig, type ITag, type ITagConfigured, type ITagDefinition, type ITagMeta, type ITaggable, type ITask, type ITaskDefinition, type ITaskMeta, type ITaskMiddleware, type ITaskMiddlewareConfigured, type ITaskMiddlewareDefinition, type ITaskMiddlewareExecutionInput, type IValidationSchema, type LogLevels, Logger, MiddlewareManager, type OnUnhandledError, type OnUnhandledErrorInfo, type OverridableElements, type PrintStrategy, Queue, type RegisterableItems, type RequiredKeys, type ResourceDependencyValueType, type ResourceDependencyValuesType, ResourceInitializer, type ResourceMiddlewareAttachmentType, type ResourceMiddlewareInterceptor, type ResourceMiddlewareStoreElementType, type ResourceStoreElementType, type RunOptions, RunResult, Semaphore, Store, type TagType, type TaskDependencyWithIntercept, type TaskLocalInterceptor, type TaskMiddlewareAttachmentType, type TaskMiddlewareInterceptor, type TaskMiddlewareStoreElementType, TaskRunner, type TaskStoreElementType, type UnhandledErrorKind, type UnionToIntersection, allFalse, bindProcessErrorHandler, createContext, createDefaultUnhandledError, createTestResource, defs as definitions, defineEvent as event, getConfig, globals, defineHook as hook, isOneOf, levelNormal, levelVerbose, onAnyOf, defineOverride as override, defineResource as resource, defineResourceMiddleware as resourceMiddleware, run, safeReportUnhandledError, symbolEvent, symbolFilePath, symbolHook, symbolMiddleware, symbolMiddlewareConfigured, symbolOptionalDependency, symbolResource, symbolResourceMiddleware, symbolResourceWithConfig, symbolTag, symbolTagConfigured, symbolTask, symbolTaskMiddleware, defineTag as tag, defineTask as task, defineTaskMiddleware as taskMiddleware };