zero-query 0.4.9 → 0.6.3

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.
@@ -0,0 +1,317 @@
1
+ /**
2
+ * cli/commands/dev/overlay.js — Client-side error overlay + SSE live-reload
3
+ *
4
+ * Returns an HTML <script> snippet that is injected before </body> in
5
+ * every HTML response served by the dev server. Responsibilities:
6
+ *
7
+ * 1. Error Overlay — full-screen dark overlay with code frames, stack
8
+ * traces, and ZQueryError metadata. Dismissable via Esc or ×.
9
+ * 2. Runtime error hooks — window.onerror, unhandledrejection, AND
10
+ * the zQuery $.onError() hook so framework-level errors are
11
+ * surfaced in the overlay automatically.
12
+ * 3. SSE connection — listens for reload / css / error:syntax /
13
+ * error:clear events from the dev server watcher.
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ // The snippet is a self-contained IIFE — no external dependencies.
19
+ // It must work in all browsers that support EventSource (IE11 excluded).
20
+
21
+ const OVERLAY_SCRIPT = `<script>
22
+ (function(){
23
+ // =====================================================================
24
+ // Error overlay
25
+ // =====================================================================
26
+ var overlayEl = null;
27
+
28
+ var OVERLAY_CSS =
29
+ 'position:fixed;top:0;left:0;width:100%;height:100%;' +
30
+ 'background:rgba(0,0,0,0.92);color:#fff;z-index:2147483647;' +
31
+ 'font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;' +
32
+ 'font-size:13px;overflow-y:auto;padding:0;margin:0;box-sizing:border-box;';
33
+
34
+ var HEADER_CSS =
35
+ 'padding:20px 24px 12px;border-bottom:1px solid rgba(255,255,255,0.1);' +
36
+ 'display:flex;align-items:flex-start;justify-content:space-between;';
37
+
38
+ var BADGE_CSS =
39
+ 'display:inline-block;padding:3px 8px;border-radius:4px;font-size:11px;' +
40
+ 'font-weight:700;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px;';
41
+
42
+ // Map ZQueryError code prefixes to colours so devs can see at a glance
43
+ // which subsystem produced the error.
44
+ var CODE_COLORS = {
45
+ 'ZQ_REACTIVE': '#9b59b6',
46
+ 'ZQ_SIGNAL': '#9b59b6',
47
+ 'ZQ_EFFECT': '#9b59b6',
48
+ 'ZQ_EXPR': '#2980b9',
49
+ 'ZQ_COMP': '#16a085',
50
+ 'ZQ_ROUTER': '#d35400',
51
+ 'ZQ_STORE': '#8e44ad',
52
+ 'ZQ_HTTP': '#2c3e50',
53
+ 'ZQ_DEV': '#e74c3c',
54
+ 'ZQ_INVALID': '#7f8c8d',
55
+ };
56
+
57
+ function badgeColor(data) {
58
+ if (data.code) {
59
+ var keys = Object.keys(CODE_COLORS);
60
+ for (var i = 0; i < keys.length; i++) {
61
+ if (data.code.indexOf(keys[i]) === 0) return CODE_COLORS[keys[i]];
62
+ }
63
+ }
64
+ if (data.type && /syntax|parse/i.test(data.type)) return '#e74c3c';
65
+ return '#e67e22';
66
+ }
67
+
68
+ function esc(s) {
69
+ var d = document.createElement('div');
70
+ d.appendChild(document.createTextNode(s));
71
+ return d.innerHTML;
72
+ }
73
+
74
+ function createOverlay(data) {
75
+ removeOverlay();
76
+ var wrap = document.createElement('div');
77
+ wrap.id = '__zq_error_overlay';
78
+ wrap.setAttribute('style', OVERLAY_CSS);
79
+ wrap.setAttribute('tabindex', '-1');
80
+
81
+ var color = badgeColor(data);
82
+ var html = '';
83
+
84
+ // ----- header row -----
85
+ html += '<div style="' + HEADER_CSS + '">';
86
+ html += '<div>';
87
+
88
+ // Error code badge (if present)
89
+ if (data.code) {
90
+ html += '<span style="' + BADGE_CSS + 'background:' + color + ';margin-right:6px;">' + esc(data.code) + '</span>';
91
+ }
92
+ // Type badge
93
+ html += '<span style="' + BADGE_CSS + 'background:' + (data.code ? 'rgba(255,255,255,0.1)' : color) + ';">' + esc(data.type || 'Error') + '</span>';
94
+
95
+ // Message
96
+ html += '<div style="font-size:18px;font-weight:600;line-height:1.4;color:#ff6b6b;margin-top:4px;">';
97
+ html += esc(data.message || 'Unknown error');
98
+ html += '</div></div>';
99
+
100
+ // Close button
101
+ html += '<button id="__zq_close" style="' +
102
+ 'background:none;border:1px solid rgba(255,255,255,0.2);color:#999;' +
103
+ 'font-size:20px;cursor:pointer;border-radius:6px;width:32px;height:32px;' +
104
+ 'display:flex;align-items:center;justify-content:center;flex-shrink:0;' +
105
+ 'margin-left:16px;transition:all 0.15s;"' +
106
+ ' onmouseover="this.style.color=\\'#fff\\';this.style.borderColor=\\'rgba(255,255,255,0.5)\\'"' +
107
+ ' onmouseout="this.style.color=\\'#999\\';this.style.borderColor=\\'rgba(255,255,255,0.2)\\'"' +
108
+ '>&times;</button>';
109
+ html += '</div>';
110
+
111
+ // ----- file location -----
112
+ if (data.file) {
113
+ html += '<div style="padding:10px 24px;color:#8be9fd;font-size:13px;">';
114
+ html += '<span style="color:#888;">File: </span>' + esc(data.file);
115
+ if (data.line) html += '<span style="color:#888;">:</span>' + data.line;
116
+ if (data.column) html += '<span style="color:#888;">:</span>' + data.column;
117
+ html += '</div>';
118
+ }
119
+
120
+ // ----- ZQueryError context (key/value pairs) -----
121
+ if (data.context && typeof data.context === 'object' && Object.keys(data.context).length) {
122
+ html += '<div style="padding:8px 24px;display:flex;flex-wrap:wrap;gap:8px;">';
123
+ var ctxKeys = Object.keys(data.context);
124
+ for (var ci = 0; ci < ctxKeys.length; ci++) {
125
+ var k = ctxKeys[ci], v = data.context[k];
126
+ html += '<span style="background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.08);' +
127
+ 'padding:3px 10px;border-radius:4px;font-size:12px;">' +
128
+ '<span style="color:#888;">' + esc(k) + ': </span>' +
129
+ '<span style="color:#f1fa8c;">' + esc(typeof v === 'object' ? JSON.stringify(v) : String(v)) + '</span>' +
130
+ '</span>';
131
+ }
132
+ html += '</div>';
133
+ }
134
+
135
+ // ----- code frame -----
136
+ if (data.frame) {
137
+ html += '<pre style="' +
138
+ 'margin:0;padding:16px 24px;background:rgba(255,255,255,0.04);' +
139
+ 'border-top:1px solid rgba(255,255,255,0.06);' +
140
+ 'border-bottom:1px solid rgba(255,255,255,0.06);' +
141
+ 'overflow-x:auto;line-height:1.6;font-size:13px;">';
142
+ var lines = data.frame.split('\\n');
143
+ for (var fi = 0; fi < lines.length; fi++) {
144
+ var fl = lines[fi];
145
+ if (fl.charAt(0) === '>') {
146
+ html += '<span style="color:#ff6b6b;font-weight:600;">' + esc(fl) + '</span>\\n';
147
+ } else if (fl.indexOf('^') !== -1 && fl.trim().replace(/[\\s|^]/g, '') === '') {
148
+ html += '<span style="color:#e74c3c;font-weight:700;">' + esc(fl) + '</span>\\n';
149
+ } else {
150
+ html += '<span style="color:#999;">' + esc(fl) + '</span>\\n';
151
+ }
152
+ }
153
+ html += '</pre>';
154
+ }
155
+
156
+ // ----- stack trace -----
157
+ if (data.stack) {
158
+ html += '<div style="padding:16px 24px;">';
159
+ html += '<div style="color:#888;font-size:11px;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px;">Stack Trace</div>';
160
+ html += '<pre style="margin:0;color:#bbb;font-size:12px;line-height:1.7;white-space:pre-wrap;word-break:break-word;">';
161
+ html += esc(data.stack);
162
+ html += '</pre></div>';
163
+ }
164
+
165
+ // ----- tip -----
166
+ html += '<div style="padding:16px 24px;color:#555;font-size:11px;border-top:1px solid rgba(255,255,255,0.06);">';
167
+ html += 'Fix the error and save \\u2014 the overlay will clear automatically. Press <kbd style="' +
168
+ 'background:rgba(255,255,255,0.1);padding:1px 6px;border-radius:3px;font-size:11px;' +
169
+ '">Esc</kbd> to dismiss.';
170
+ html += '</div>';
171
+
172
+ wrap.innerHTML = html;
173
+ document.body.appendChild(wrap);
174
+ overlayEl = wrap;
175
+
176
+ var closeBtn = document.getElementById('__zq_close');
177
+ if (closeBtn) closeBtn.addEventListener('click', removeOverlay);
178
+ wrap.addEventListener('keydown', function(e) { if (e.key === 'Escape') removeOverlay(); });
179
+ wrap.focus();
180
+ }
181
+
182
+ function removeOverlay() {
183
+ if (overlayEl && overlayEl.parentNode) overlayEl.parentNode.removeChild(overlayEl);
184
+ overlayEl = null;
185
+ }
186
+
187
+ // =====================================================================
188
+ // Console helper
189
+ // =====================================================================
190
+ function logToConsole(data) {
191
+ var label = data.code ? data.code + ' ' : '';
192
+ var msg = '\\n%c zQuery DevError %c ' + label + data.type + ': ' + data.message;
193
+ if (data.file) msg += '\\n at ' + data.file + (data.line ? ':' + data.line : '') + (data.column ? ':' + data.column : '');
194
+ console.error(msg, 'background:#e74c3c;color:#fff;padding:2px 6px;border-radius:3px;font-weight:700;', 'color:inherit;');
195
+ if (data.frame) console.error(data.frame);
196
+ }
197
+
198
+ function cleanStack(stack) {
199
+ return stack.split('\\n')
200
+ .filter(function(l) { return l.indexOf('__zq_') === -1 && l.indexOf('EventSource') === -1; })
201
+ .map(function(l) { return l.replace(location.origin, ''); })
202
+ .join('\\n');
203
+ }
204
+
205
+ // =====================================================================
206
+ // Runtime error hooks
207
+ // =====================================================================
208
+ window.addEventListener('error', function(e) {
209
+ if (!e.filename) return;
210
+ var err = e.error || {};
211
+ var data = {
212
+ code: err.code || '',
213
+ type: (err.constructor && err.constructor.name) || 'Error',
214
+ message: e.message || String(err),
215
+ file: e.filename.replace(location.origin, ''),
216
+ line: e.lineno || 0,
217
+ column: e.colno || 0,
218
+ context: err.context || null,
219
+ stack: err.stack ? cleanStack(err.stack) : ''
220
+ };
221
+ createOverlay(data);
222
+ logToConsole(data);
223
+ });
224
+
225
+ window.addEventListener('unhandledrejection', function(e) {
226
+ var err = e.reason || {};
227
+ var data = {
228
+ code: err.code || '',
229
+ type: err.name === 'ZQueryError' ? 'ZQueryError' : 'Unhandled Promise Rejection',
230
+ message: err.message || String(err),
231
+ context: err.context || null,
232
+ stack: err.stack ? cleanStack(err.stack) : ''
233
+ };
234
+ createOverlay(data);
235
+ logToConsole(data);
236
+ });
237
+
238
+ // =====================================================================
239
+ // Hook into zQuery's $.onError() when the library is loaded
240
+ // =====================================================================
241
+ function hookZQueryErrors() {
242
+ // $.onError is set by the framework — wait for it
243
+ if (typeof $ !== 'undefined' && typeof $.onError === 'function') {
244
+ $.onError(function(zqErr) {
245
+ var data = {
246
+ code: zqErr.code || '',
247
+ type: 'ZQueryError',
248
+ message: zqErr.message,
249
+ context: zqErr.context || null,
250
+ stack: zqErr.stack ? cleanStack(zqErr.stack) : ''
251
+ };
252
+ createOverlay(data);
253
+ logToConsole(data);
254
+ });
255
+ return;
256
+ }
257
+ // Retry until the library has loaded (max ~5s)
258
+ if (hookZQueryErrors._tries < 50) {
259
+ hookZQueryErrors._tries++;
260
+ setTimeout(hookZQueryErrors, 100);
261
+ }
262
+ }
263
+ hookZQueryErrors._tries = 0;
264
+ // Defer so the page's own scripts load first
265
+ if (document.readyState === 'loading') {
266
+ document.addEventListener('DOMContentLoaded', hookZQueryErrors);
267
+ } else {
268
+ setTimeout(hookZQueryErrors, 0);
269
+ }
270
+
271
+ // =====================================================================
272
+ // SSE connection (live-reload + server-pushed errors)
273
+ // =====================================================================
274
+ var es, reconnectTimer;
275
+
276
+ function connect() {
277
+ es = new EventSource('/__zq_reload');
278
+
279
+ es.addEventListener('reload', function() {
280
+ removeOverlay();
281
+ location.reload();
282
+ });
283
+
284
+ es.addEventListener('css', function() {
285
+ var sheets = document.querySelectorAll('link[rel="stylesheet"]');
286
+ sheets.forEach(function(l) {
287
+ var href = l.getAttribute('href');
288
+ if (!href) return;
289
+ var sep = href.indexOf('?') >= 0 ? '&' : '?';
290
+ l.setAttribute('href', href.replace(/[?&]_zqr=\\\\d+/, '') + sep + '_zqr=' + Date.now());
291
+ });
292
+ });
293
+
294
+ es.addEventListener('error:syntax', function(e) {
295
+ try { var data = JSON.parse(e.data); createOverlay(data); logToConsole(data); } catch(_){}
296
+ });
297
+
298
+ es.addEventListener('error:runtime', function(e) {
299
+ try { var data = JSON.parse(e.data); createOverlay(data); logToConsole(data); } catch(_){}
300
+ });
301
+
302
+ es.addEventListener('error:clear', function() {
303
+ removeOverlay();
304
+ });
305
+
306
+ es.onerror = function() {
307
+ es.close();
308
+ clearTimeout(reconnectTimer);
309
+ reconnectTimer = setTimeout(connect, 2000);
310
+ };
311
+ }
312
+
313
+ connect();
314
+ })();
315
+ </script>`;
316
+
317
+ module.exports = OVERLAY_SCRIPT;
@@ -0,0 +1,129 @@
1
+ /**
2
+ * cli/commands/dev/server.js — HTTP server & SSE broadcasting
3
+ *
4
+ * Creates the zero-http app, serves static files, injects the
5
+ * error-overlay snippet into HTML responses, and manages the
6
+ * SSE connection pool for live-reload events.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const OVERLAY_SCRIPT = require('./overlay');
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // SSE client pool
17
+ // ---------------------------------------------------------------------------
18
+
19
+ class SSEPool {
20
+ constructor() {
21
+ this._clients = new Set();
22
+ }
23
+
24
+ add(sse) {
25
+ this._clients.add(sse);
26
+ sse.on('close', () => this._clients.delete(sse));
27
+ }
28
+
29
+ broadcast(eventType, data) {
30
+ for (const sse of this._clients) {
31
+ try { sse.event(eventType, data || ''); } catch { this._clients.delete(sse); }
32
+ }
33
+ }
34
+
35
+ closeAll() {
36
+ for (const sse of this._clients) {
37
+ try { sse.close(); } catch { /* ignore */ }
38
+ }
39
+ this._clients.clear();
40
+ }
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Server factory
45
+ // ---------------------------------------------------------------------------
46
+
47
+ /**
48
+ * @param {object} opts
49
+ * @param {string} opts.root — absolute path to project root
50
+ * @param {string} opts.htmlEntry — e.g. 'index.html'
51
+ * @param {number} opts.port
52
+ * @param {boolean} opts.noIntercept — skip zquery.min.js auto-resolve
53
+ * @returns {{ app, pool: SSEPool, listen: Function }}
54
+ */
55
+ function createServer({ root, htmlEntry, port, noIntercept }) {
56
+ let zeroHttp;
57
+ try {
58
+ zeroHttp = require('zero-http');
59
+ } catch {
60
+ console.error(`\n \u2717 zero-http is required for the dev server.`);
61
+ console.error(` Install it: npm install zero-http --save-dev\n`);
62
+ process.exit(1);
63
+ }
64
+
65
+ const { createApp, static: serveStatic } = zeroHttp;
66
+
67
+ const app = createApp();
68
+ const pool = new SSEPool();
69
+
70
+ // ---- SSE endpoint ----
71
+ app.get('/__zq_reload', (req, res) => {
72
+ const sse = res.sse({ keepAlive: 30000, keepAliveComment: 'ping' });
73
+ pool.add(sse);
74
+ });
75
+
76
+ // ---- Auto-resolve zquery.min.js ----
77
+ const pkgRoot = path.resolve(__dirname, '..', '..', '..');
78
+
79
+ app.use((req, res, next) => {
80
+ if (noIntercept) return next();
81
+ const basename = path.basename(req.url.split('?')[0]).toLowerCase();
82
+ if (basename !== 'zquery.min.js') return next();
83
+
84
+ const candidates = [
85
+ path.join(pkgRoot, 'dist', 'zquery.min.js'),
86
+ path.join(root, 'node_modules', 'zero-query', 'dist', 'zquery.min.js'),
87
+ ];
88
+ for (const p of candidates) {
89
+ if (fs.existsSync(p)) {
90
+ res.set('Content-Type', 'application/javascript; charset=utf-8');
91
+ res.set('Cache-Control', 'no-cache');
92
+ res.send(fs.readFileSync(p, 'utf-8'));
93
+ return;
94
+ }
95
+ }
96
+ next();
97
+ });
98
+
99
+ // ---- Static files ----
100
+ app.use(serveStatic(root, { index: false, dotfiles: 'ignore' }));
101
+
102
+ // ---- SPA fallback — inject overlay/SSE snippet ----
103
+ app.get('*', (req, res) => {
104
+ if (path.extname(req.url) && path.extname(req.url) !== '.html') {
105
+ res.status(404).send('Not Found');
106
+ return;
107
+ }
108
+ const indexPath = path.join(root, htmlEntry);
109
+ if (!fs.existsSync(indexPath)) {
110
+ res.status(404).send(`${htmlEntry} not found`);
111
+ return;
112
+ }
113
+ let html = fs.readFileSync(indexPath, 'utf-8');
114
+ if (html.includes('</body>')) {
115
+ html = html.replace('</body>', OVERLAY_SCRIPT + '\n</body>');
116
+ } else {
117
+ html += OVERLAY_SCRIPT;
118
+ }
119
+ res.html(html);
120
+ });
121
+
122
+ function listen(cb) {
123
+ app.listen(port, cb);
124
+ }
125
+
126
+ return { app, pool, listen };
127
+ }
128
+
129
+ module.exports = { createServer, SSEPool };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * cli/commands/dev/validator.js — JS syntax validation
3
+ *
4
+ * Pre-validates JavaScript files on save using Node's VM module.
5
+ * Returns structured error descriptors with code frames compatible
6
+ * with the browser error overlay.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const fs = require('fs');
12
+ const vm = require('vm');
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Code frame generator
16
+ // ---------------------------------------------------------------------------
17
+
18
+ /**
19
+ * Build a code frame showing ~4 lines of context around the error
20
+ * with a caret pointer at the offending column.
21
+ *
22
+ * @param {string} source — full file contents
23
+ * @param {number} line — 1-based line number
24
+ * @param {number} column — 1-based column number
25
+ * @returns {string}
26
+ */
27
+ function generateCodeFrame(source, line, column) {
28
+ const lines = source.split('\n');
29
+ const start = Math.max(0, line - 4);
30
+ const end = Math.min(lines.length, line + 3);
31
+ const pad = String(end).length;
32
+ const frame = [];
33
+
34
+ for (let i = start; i < end; i++) {
35
+ const num = String(i + 1).padStart(pad);
36
+ const marker = i === line - 1 ? '>' : ' ';
37
+ frame.push(`${marker} ${num} | ${lines[i]}`);
38
+ if (i === line - 1 && column > 0) {
39
+ frame.push(` ${' '.repeat(pad)} | ${' '.repeat(column - 1)}^`);
40
+ }
41
+ }
42
+ return frame.join('\n');
43
+ }
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // JS validation
47
+ // ---------------------------------------------------------------------------
48
+
49
+ /**
50
+ * Validate a JavaScript file for syntax errors.
51
+ *
52
+ * Strips ESM import/export statements (preserving line numbers) so the
53
+ * VM can parse module-style code, then compiles via vm.Script.
54
+ *
55
+ * @param {string} filePath — absolute path to the file
56
+ * @param {string} relPath — display-friendly relative path
57
+ * @returns {object|null} — error descriptor, or null if valid
58
+ */
59
+ function validateJS(filePath, relPath) {
60
+ let source;
61
+ try { source = fs.readFileSync(filePath, 'utf-8'); } catch { return null; }
62
+
63
+ const normalized = source.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
64
+ const stripped = normalized.split('\n').map(line => {
65
+ if (/^\s*import\s+.*from\s+['"]/.test(line)) return ' '.repeat(line.length);
66
+ if (/^\s*import\s+['"]/.test(line)) return ' '.repeat(line.length);
67
+ if (/^\s*export\s*\{/.test(line)) return ' '.repeat(line.length);
68
+ line = line.replace(/^(\s*)export\s+default\s+/, '$1');
69
+ line = line.replace(/^(\s*)export\s+(const|let|var|function|class|async\s+function)\s/, '$1$2 ');
70
+ line = line.replace(/import\.meta\.url/g, "'__meta__'");
71
+ line = line.replace(/import\.meta/g, '({})');
72
+ return line;
73
+ }).join('\n');
74
+
75
+ try {
76
+ new vm.Script(stripped, { filename: relPath });
77
+ return null;
78
+ } catch (err) {
79
+ const line = err.stack ? parseInt((err.stack.match(/:(\d+)/) || [])[1]) || 0 : 0;
80
+ const col = err.stack ? parseInt((err.stack.match(/:(\d+):(\d+)/) || [])[2]) || 0 : 0;
81
+ const frame = line > 0 ? generateCodeFrame(source, line, col) : '';
82
+ return {
83
+ code: 'ZQ_DEV_SYNTAX',
84
+ type: err.constructor.name || 'SyntaxError',
85
+ message: err.message,
86
+ file: relPath,
87
+ line,
88
+ column: col,
89
+ frame,
90
+ };
91
+ }
92
+ }
93
+
94
+ module.exports = { generateCodeFrame, validateJS };
@@ -0,0 +1,114 @@
1
+ /**
2
+ * cli/commands/dev/watcher.js — File system watcher
3
+ *
4
+ * Recursively watches the project root for file changes, validates
5
+ * JS files for syntax errors, and broadcasts reload / CSS hot-swap /
6
+ * error events through the SSE pool.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ const { validateJS } = require('./validator');
15
+ const { logCSS, logReload, logError } = require('./logger');
16
+
17
+ const IGNORE_DIRS = new Set(['node_modules', '.git', 'dist', '.cache']);
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Helpers
21
+ // ---------------------------------------------------------------------------
22
+
23
+ function shouldWatch(filename) {
24
+ return !!filename && !filename.startsWith('.');
25
+ }
26
+
27
+ function isIgnored(filepath) {
28
+ return filepath.split(path.sep).some(p => IGNORE_DIRS.has(p));
29
+ }
30
+
31
+ /** Recursively collect every directory under `dir` (excluding ignored). */
32
+ function collectWatchDirs(dir) {
33
+ const dirs = [dir];
34
+ try {
35
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
36
+ if (!entry.isDirectory() || IGNORE_DIRS.has(entry.name)) continue;
37
+ dirs.push(...collectWatchDirs(path.join(dir, entry.name)));
38
+ }
39
+ } catch { /* unreadable dir — skip */ }
40
+ return dirs;
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Watcher factory
45
+ // ---------------------------------------------------------------------------
46
+
47
+ /**
48
+ * Start watching `root` for file changes.
49
+ *
50
+ * @param {object} opts
51
+ * @param {string} opts.root — absolute project root
52
+ * @param {SSEPool} opts.pool — SSE broadcast pool
53
+ * @returns {{ dirs: string[], destroy: Function }}
54
+ */
55
+ function startWatcher({ root, pool }) {
56
+ const watchDirs = collectWatchDirs(root);
57
+ const watchers = [];
58
+
59
+ let debounceTimer;
60
+ let currentError = null; // track which file has an active error
61
+
62
+ for (const dir of watchDirs) {
63
+ try {
64
+ const watcher = fs.watch(dir, (_, filename) => {
65
+ if (!shouldWatch(filename)) return;
66
+ const fullPath = path.join(dir, filename || '');
67
+ if (isIgnored(fullPath)) return;
68
+
69
+ clearTimeout(debounceTimer);
70
+ debounceTimer = setTimeout(() => {
71
+ const rel = path.relative(root, fullPath).replace(/\\/g, '/');
72
+ const ext = path.extname(filename).toLowerCase();
73
+
74
+ // ---- CSS hot-swap ----
75
+ if (ext === '.css') {
76
+ logCSS(rel);
77
+ pool.broadcast('css', rel);
78
+ return;
79
+ }
80
+
81
+ // ---- JS syntax check ----
82
+ if (ext === '.js') {
83
+ const err = validateJS(fullPath, rel);
84
+ if (err) {
85
+ currentError = rel;
86
+ logError(err);
87
+ pool.broadcast('error:syntax', JSON.stringify(err));
88
+ return;
89
+ }
90
+ // File was fixed — clear previous overlay
91
+ if (currentError === rel) {
92
+ currentError = null;
93
+ pool.broadcast('error:clear', '');
94
+ }
95
+ }
96
+
97
+ // ---- Full reload ----
98
+ logReload(rel);
99
+ pool.broadcast('reload', rel);
100
+ }, 100);
101
+ });
102
+ watchers.push(watcher);
103
+ } catch { /* dir became inaccessible — skip */ }
104
+ }
105
+
106
+ function destroy() {
107
+ clearTimeout(debounceTimer);
108
+ watchers.forEach(w => w.close());
109
+ }
110
+
111
+ return { dirs: watchDirs, destroy };
112
+ }
113
+
114
+ module.exports = { startWatcher, collectWatchDirs };