@gesslar/toolkit 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,206 +0,0 @@
1
- import { setTimeout as timeoutPromise } from "timers/promises"
2
- import Collection from "./Collection.js"
3
- import Data from "./Data.js"
4
- import Sass from "./Sass.js"
5
- import Valid from "./Valid.js"
6
-
7
- /**
8
- * Generic base class for managing hooks with configurable event types.
9
- * Provides common functionality for hook registration, execution, and lifecycle management.
10
- * Designed to be extended by specific implementations.
11
- */
12
- export default class BaseHookManager {
13
- #hooksFile = null
14
- #log = null
15
- #hooks = null
16
- #action = null
17
- #timeout = 1000 // Default 1 second timeout
18
- #allowedEvents = []
19
-
20
- /**
21
- * @param {object} config - Configuration object
22
- * @param {string|object} config.action - Action identifier or instance
23
- * @param {object} config.hooksFile - File object containing hooks
24
- * @param {object} config.logger - Logger instance
25
- * @param {number} [config.timeOut=1000] - Hook execution timeout in milliseconds
26
- * @param {string[]} [config.allowedEvents=[]] - Array of allowed event types for validation
27
- */
28
- constructor({action, hooksFile, logger, timeOut = 1000, allowedEvents = []}) {
29
- this.#action = action
30
- this.#hooksFile = hooksFile
31
- this.#log = logger
32
- this.#timeout = timeOut
33
- this.#allowedEvents = allowedEvents
34
- }
35
-
36
- get action() {
37
- return this.#action
38
- }
39
-
40
- get hooksFile() {
41
- return this.#hooksFile
42
- }
43
-
44
- get hooks() {
45
- return this.#hooks
46
- }
47
-
48
- get log() {
49
- return this.#log
50
- }
51
-
52
- get timeout() {
53
- return this.#timeout
54
- }
55
-
56
- get allowedEvents() {
57
- return this.#allowedEvents
58
- }
59
-
60
- get setup() {
61
- return this.hooks?.setup || null
62
- }
63
-
64
- get cleanup() {
65
- return this.hooks?.cleanup || null
66
- }
67
-
68
- /**
69
- * Static factory method to create and initialize a hook manager.
70
- * Override loadHooks() in subclasses to customize hook loading logic.
71
- *
72
- * @param {object} config - Same as constructor config
73
- * @returns {Promise<BaseHookManager|null>} Initialized hook manager or null if no hooks found
74
- */
75
- static async new(config) {
76
- const instance = new this(config)
77
- const debug = instance.log.newDebug()
78
-
79
- debug("Creating new HookManager instance with args: `%o`", 2, config)
80
-
81
- const hooksFile = instance.hooksFile
82
-
83
- debug("Loading hooks from `%s`", 2, hooksFile.uri)
84
-
85
- debug("Checking hooks file exists: %j", 2, hooksFile)
86
-
87
- try {
88
- const hooksFileContent = await import(hooksFile.uri)
89
- debug("Hooks file loaded successfully", 2)
90
-
91
- if (!hooksFileContent)
92
- throw new Error(`Hooks file is empty: ${hooksFile.uri}`)
93
-
94
- const hooks = await instance.loadHooks(hooksFileContent)
95
-
96
- if (Data.isEmpty(hooks))
97
- return null
98
-
99
- debug("Hooks found for action: `%s`", 2, instance.action)
100
-
101
- if (!hooks)
102
- return null
103
-
104
- // Attach common properties to hooks
105
- hooks.log = instance.log
106
- hooks.timeout = instance.timeout
107
- instance.#hooks = hooks
108
-
109
- debug("Hooks loaded successfully for `%s`", 2, instance.action)
110
-
111
- return instance
112
- } catch (error) {
113
- debug("Failed to load hooks: %s", 1, error.message)
114
- return null
115
- }
116
- }
117
-
118
- /**
119
- * Load hooks from the imported hooks file content.
120
- * Override in subclasses to customize hook loading logic.
121
- *
122
- * @param {object} hooksFileContent - Imported hooks file content
123
- * @returns {Promise<object|null>} Loaded hooks object or null if no hooks found
124
- * @protected
125
- */
126
- async loadHooks(hooksFileContent) {
127
- const hooks = hooksFileContent.default || hooksFileContent.Hooks
128
-
129
- if (!hooks)
130
- throw new Error(`\`${this.hooksFile.uri}\` contains no hooks.`)
131
-
132
- // Default implementation: look for hooks by action name
133
- const hooksObj = hooks[this.action]
134
-
135
- return hooksObj || null
136
- }
137
-
138
- /**
139
- * Trigger a hook by event name.
140
- *
141
- * @param {string} event - The type of hook to trigger
142
- * @param {object} args - The hook arguments as an object
143
- * @returns {Promise<unknown>} The result of the hook
144
- */
145
- async on(event, args) {
146
- const debug = this.log.newDebug()
147
-
148
- debug("Triggering hook for event `%s`", 4, event)
149
-
150
- if (!event)
151
- throw new Error("Event type is required for hook invocation")
152
-
153
- // Validate event type if allowed events are configured
154
- if (this.#allowedEvents.length > 0 && !this.#allowedEvents.includes(event))
155
- throw new Error(`Invalid event type: ${event}. Allowed events: ${this.#allowedEvents.join(", ")}`)
156
-
157
- const hook = this.hooks?.[event]
158
-
159
- if (hook) {
160
- Valid.type(hook, "function", `Hook "${event}" is not a function`)
161
-
162
- const hookExecution = hook.call(this.hooks, args)
163
- const hookTimeout = this.timeout
164
-
165
- const expireAsync = () =>
166
- timeoutPromise(
167
- hookTimeout,
168
- new Error(`Hook execution exceeded timeout of ${hookTimeout}ms`)
169
- )
170
-
171
- const result = await Promise.race([hookExecution, expireAsync()])
172
-
173
- if (result?.status === "error")
174
- throw Sass.new(result.error)
175
-
176
- debug("Hook executed successfully for event: `%s`", 4, event)
177
-
178
- return result
179
- } else {
180
- debug("No hook found for event: `%s`", 4, event)
181
- return null
182
- }
183
- }
184
-
185
- /**
186
- * Check if a hook exists for the given event.
187
- *
188
- * @param {string} event - Event name to check
189
- * @returns {boolean} True if hook exists
190
- */
191
- hasHook(event) {
192
- return !!(this.hooks?.[event])
193
- }
194
-
195
- /**
196
- * Get all available hook events.
197
- *
198
- * @returns {string[]} Array of available hook event names
199
- */
200
- getAvailableEvents() {
201
- return this.hooks ? Object.keys(this.hooks).filter(key =>
202
- typeof this.hooks[key] === 'function' &&
203
- !['setup', 'cleanup', 'log', 'timeout'].includes(key)
204
- ) : []
205
- }
206
- }