File size: 9,036 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
 *  Chahua Development Thailand
 *  บริษัทชาหัวประเทศไทย  
 *  CEO: Saharath C.
 *  www.chahuadev.com
 *  chahuadev@gmail.com
 *
 * /**
 * HUB - Central Event Hub (Pub/Sub System) V.11.0.0
 *
 * ศูนย์กลางการสื่อสารระหว่างโมดูลทั้งหมดในแอปพลิเคชัน
 * ทำงานในรูปแบบ Publish/Subscribe เพื่อลดการพึ่งพากัน (Decoupling)
 *
 *  Features:
 *  on(event, fn):     ลงทะเบียนเพื่อ "ฟัง" เหตุการณ์
 *  emit(event, data): "ส่ง" เหตุการณ์ออกไปให้ผู้ฟังทั้งหมด
 *  once(event, fn):   ลงทะเบียนฟังเหตุการณ์แค่ครั้งเดียวแล้วลบออก
 *  off(event, fn):    ยกเลิกการฟังเหตุการณ์
 *  emitAsync(event, data): emit แบบรอให้ callback ที่เป็น async ทำงานจนเสร็จ
 *  Wildcard Listener ('*'): ดักฟังทุกเหตุการณ์ที่เกิดขึ้นใน Hub
 *
 * by Chahuadev Studio V.11.0.0 Enterprise Architecture
 */

class CallbackHub {
    constructor() {
        this.handlers = {};
        this.debug_mode = process.env.HUB_DEBUG === 'true' || false;
        
        console.log(' Event Hub initialized - Pub/Sub System V.11.0.0');
    }

    /**
     * ลงทะเบียนฟังก์ชัน (callback) เพื่อรอฟังเหตุการณ์ (event)
     * @param {string} eventName - ชื่อเหตุการณ์ที่ต้องการฟัง (เช่น 'license.loaded' หรือ '*' เพื่อฟังทุกอย่าง)
     * @param {Function} callback - ฟังก์ชันที่จะถูกเรียกใช้เมื่อมีเหตุการณ์เกิดขึ้น
     */
    on(eventName, callback) {
        if (!this.handlers[eventName]) {
            this.handlers[eventName] = [];
        }
        this.handlers[eventName].push(callback);
        
        if (this.debug_mode) {
            console.log(` Hub: Listener registered for "${eventName}" (${this.handlers[eventName].length} total)`);
        }
    }

    /**
     * ลงทะเบียนฟังก์ชันเพื่อรอฟังเหตุการณ์แค่ "ครั้งเดียว"
     * หลังจากทำงานเสร็จ callback จะถูกลบออกไปโดยอัตโนมัติ
     * @param {string} eventName - ชื่อเหตุการณ์
     * @param {Function} callback - ฟังก์ชันที่จะถูกเรียกใช้
     */
    once(eventName, callback) {
        const onceWrapper = (data) => {
            callback(data);
            this.off(eventName, onceWrapper);
            if (this.debug_mode) {
                console.log(` Hub: Once listener for "${eventName}" executed and removed`);
            }
        };
        this.on(eventName, onceWrapper);
    }

    /**
     * ยกเลิกการลงทะเบียน callback
     * @param {string} eventName - ชื่อเหตุการณ์
     * @param {Function} callback - ฟังก์ชันที่ต้องการยกเลิก
     */
    off(eventName, callback) {
        if (this.handlers[eventName]) {
            const initialLength = this.handlers[eventName].length;
            this.handlers[eventName] = this.handlers[eventName].filter(cb => cb !== callback);
            
            if (this.debug_mode && this.handlers[eventName].length < initialLength) {
                console.log(` Hub: Listener removed from "${eventName}" (${this.handlers[eventName].length} remaining)`);
            }
        }
    }

    /**
     * ส่งสัญญาณ (emit) เหตุการณ์ออกไป
     * จะเรียก callback ทุกตัวที่ลงทะเบียนไว้กับ event นี้แบบ non-blocking
     * @param {string} eventName - ชื่อเหตุการณ์
     * @param {*} [data] - ข้อมูลที่ต้องการส่งไปกับเหตุการณ์
     */
    emit(eventName, data) {
        let listenersNotified = 0;
        
        // ส่งให้ผู้ฟังที่เจาะจง event นี้
        if (this.handlers[eventName]) {
            this.handlers[eventName].forEach(fn => {
                try {
                    fn(data);
                    listenersNotified++;
                } catch (err) {
                    console.error(` Hub: Callback error on "${eventName}":`, err);
                }
            });
        }

        // ส่งให้ผู้ฟังแบบ Wildcard ('*') ด้วย
        if (this.handlers['*']) {
            this.handlers['*'].forEach(fn => {
                try {
                    fn({ event: eventName, data: data });
                    listenersNotified++;
                } catch (err) {
                    console.error(` Hub: Wildcard callback error on "${eventName}":`, err);
                }
            });
        }

        if (this.debug_mode) {
            console.log(` Hub: Event "${eventName}" emitted to ${listenersNotified} listener(s)`);
        }
    }

    /**
     * ส่งสัญญาณ (emit) เหตุการณ์และรอให้ callback ที่เป็น async ทำงานจนเสร็จ
     * @param {string} eventName - ชื่อเหตุการณ์
     * @param {*} [data] - ข้อมูลที่ต้องการส่งไปกับเหตุการณ์
     * @returns {Promise<void>}
     */
    async emitAsync(eventName, data) {
        const promises = [];

        // ผู้ฟังที่เจาะจง event
        if (this.handlers[eventName]) {
            this.handlers[eventName].forEach(fn => {
                promises.push(Promise.resolve().then(() => fn(data)).catch(err => {
                     console.error(` Hub: Async callback error on "${eventName}":`, err);
                }));
            });
        }
        
        // ผู้ฟังแบบ Wildcard ('*')
        if (this.handlers['*']) {
             this.handlers['*'].forEach(fn => {
                promises.push(Promise.resolve().then(() => fn({ event: eventName, data: data })).catch(err => {
                     console.error(` Hub: Async wildcard callback error on "${eventName}":`, err);
                }));
            });
        }
        
        if (this.debug_mode) {
            console.log(` Hub: Async event "${eventName}" emitted to ${promises.length} listener(s)`);
        }
        
        await Promise.all(promises);
    }

    /**
     * แสดงรายชื่อ event ทั้งหมดที่มีการลงทะเบียนไว้
     */
    debug() {
        console.log(' Hub: Registered Event Handlers:');
        for (const eventName in this.handlers) {
            console.log(`  - ${eventName} (${this.handlers[eventName].length} listener(s))`);
        }
        
        const totalEvents = Object.keys(this.handlers).length;
        const totalListeners = Object.values(this.handlers).reduce((sum, handlers) => sum + handlers.length, 0);
        console.log(` Hub: Total ${totalEvents} events, ${totalListeners} listeners`);
    }

    /**
     * เปิด/ปิด debug mode
     * @param {boolean} enabled - เปิดหรือปิด debug mode
     */
    setDebugMode(enabled) {
        this.debug_mode = enabled;
        console.log(` Hub: Debug mode ${enabled ? 'ENABLED' : 'DISABLED'}`);
    }

    /**
     * ลบ listeners ทั้งหมดของ event หนึ่งๆ
     * @param {string} eventName - ชื่อเหตุการณ์ที่ต้องการลบ listeners
     */
    removeAllListeners(eventName) {
        if (this.handlers[eventName]) {
            const count = this.handlers[eventName].length;
            delete this.handlers[eventName];
            if (this.debug_mode) {
                console.log(` Hub: Removed all ${count} listeners for "${eventName}"`);
            }
        }
    }

    /**
     * ลบ listeners ทั้งหมด
     */
    removeAll() {
        const eventCount = Object.keys(this.handlers).length;
        this.handlers = {};
        console.log(` Hub: Removed all listeners (${eventCount} events cleared)`);
    }
}

// สร้างและ Export เป็น Singleton Instance เพื่อให้ทุกไฟล์ได้ใช้ตัวเดียวกัน
module.exports = new CallbackHub();