zero-query 0.9.1 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -19,9 +19,13 @@ import { morph, morphElement } from './src/diff.js';
19
19
  import { safeEval } from './src/expression.js';
20
20
  import {
21
21
  debounce, throttle, pipe, once, sleep,
22
- escapeHtml, html, trust, uuid, camelCase, kebabCase,
22
+ escapeHtml, stripHtml, html, trust, TrustedHTML, uuid, camelCase, kebabCase,
23
23
  deepClone, deepMerge, isEqual, param, parseQuery,
24
- storage, session, bus,
24
+ storage, session, EventBus, bus,
25
+ range, unique, chunk, groupBy,
26
+ pick, omit, getPath, setPath, isEmpty,
27
+ capitalize, truncate, clamp,
28
+ memoize, retry, timeout,
25
29
  } from './src/utils.js';
26
30
  import { ZQueryError, ErrorCode, onError, reportError, guardCallback, validate } from './src/errors.js';
27
31
 
@@ -61,6 +65,8 @@ Object.defineProperty($, 'name', {
61
65
  value: query.name, writable: true, configurable: true
62
66
  });
63
67
  $.children = query.children;
68
+ $.qs = query.qs;
69
+ $.qsa = query.qsa;
64
70
 
65
71
  // --- Collection selector ---------------------------------------------------
66
72
  /**
@@ -129,8 +135,10 @@ $.pipe = pipe;
129
135
  $.once = once;
130
136
  $.sleep = sleep;
131
137
  $.escapeHtml = escapeHtml;
138
+ $.stripHtml = stripHtml;
132
139
  $.html = html;
133
140
  $.trust = trust;
141
+ $.TrustedHTML = TrustedHTML;
134
142
  $.uuid = uuid;
135
143
  $.camelCase = camelCase;
136
144
  $.kebabCase = kebabCase;
@@ -141,7 +149,23 @@ $.param = param;
141
149
  $.parseQuery = parseQuery;
142
150
  $.storage = storage;
143
151
  $.session = session;
152
+ $.EventBus = EventBus;
144
153
  $.bus = bus;
154
+ $.range = range;
155
+ $.unique = unique;
156
+ $.chunk = chunk;
157
+ $.groupBy = groupBy;
158
+ $.pick = pick;
159
+ $.omit = omit;
160
+ $.getPath = getPath;
161
+ $.setPath = setPath;
162
+ $.isEmpty = isEmpty;
163
+ $.capitalize = capitalize;
164
+ $.truncate = truncate;
165
+ $.clamp = clamp;
166
+ $.memoize = memoize;
167
+ $.retry = retry;
168
+ $.timeout = timeout;
145
169
 
146
170
  // --- Error handling --------------------------------------------------------
147
171
  $.onError = onError;
@@ -189,9 +213,13 @@ export {
189
213
  http,
190
214
  ZQueryError, ErrorCode, onError, reportError, guardCallback, validate,
191
215
  debounce, throttle, pipe, once, sleep,
192
- escapeHtml, html, trust, uuid, camelCase, kebabCase,
216
+ escapeHtml, stripHtml, html, trust, TrustedHTML, uuid, camelCase, kebabCase,
193
217
  deepClone, deepMerge, isEqual, param, parseQuery,
194
- storage, session, bus,
218
+ storage, session, EventBus, bus,
219
+ range, unique, chunk, groupBy,
220
+ pick, omit, getPath, setPath, isEmpty,
221
+ capitalize, truncate, clamp,
222
+ memoize, retry, timeout,
195
223
  };
196
224
 
197
225
  export default $;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zero-query",
3
- "version": "0.9.1",
3
+ "version": "0.9.5",
4
4
  "description": "Lightweight modern frontend library — jQuery-like selectors, reactive components, SPA router, and state management with zero dependencies.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
package/src/component.js CHANGED
@@ -620,15 +620,44 @@ class Component {
620
620
  const handler = (e) => {
621
621
  // Read bindings from live map — always up to date after re-renders
622
622
  const currentBindings = this._eventBindings?.get(event) || [];
623
- for (const { selector, methodExpr, modifiers, el } of currentBindings) {
624
- if (!e.target.closest(selector)) continue;
623
+
624
+ // Collect matching bindings with their matched elements, then sort
625
+ // deepest-first so .stop correctly prevents ancestor handlers
626
+ // (mimics real DOM bubbling order within delegated events).
627
+ const hits = [];
628
+ for (const binding of currentBindings) {
629
+ const matched = e.target.closest(binding.selector);
630
+ if (!matched) continue;
631
+ hits.push({ ...binding, matched });
632
+ }
633
+ hits.sort((a, b) => {
634
+ if (a.matched === b.matched) return 0;
635
+ return a.matched.contains(b.matched) ? 1 : -1;
636
+ });
637
+
638
+ let stoppedAt = null; // Track elements that called .stop
639
+ for (const { selector, methodExpr, modifiers, el, matched } of hits) {
640
+
641
+ // In delegated events, .stop should prevent ancestor bindings from
642
+ // firing — stopPropagation alone only stops real DOM bubbling.
643
+ if (stoppedAt) {
644
+ let blocked = false;
645
+ for (const stopped of stoppedAt) {
646
+ if (matched.contains(stopped) && matched !== stopped) { blocked = true; break; }
647
+ }
648
+ if (blocked) continue;
649
+ }
625
650
 
626
651
  // .self — only fire if target is the element itself
627
652
  if (modifiers.includes('self') && e.target !== el) continue;
628
653
 
629
654
  // Handle modifiers
630
655
  if (modifiers.includes('prevent')) e.preventDefault();
631
- if (modifiers.includes('stop')) e.stopPropagation();
656
+ if (modifiers.includes('stop')) {
657
+ e.stopPropagation();
658
+ if (!stoppedAt) stoppedAt = [];
659
+ stoppedAt.push(matched);
660
+ }
632
661
 
633
662
  // Build the invocation function
634
663
  const invoke = (evt) => {
package/src/core.js CHANGED
@@ -863,6 +863,8 @@ query.children = (parentId) => {
863
863
  const p = document.getElementById(parentId);
864
864
  return new ZQueryCollection(p ? Array.from(p.children) : []);
865
865
  };
866
+ query.qs = (sel, ctx = document) => ctx.querySelector(sel);
867
+ query.qsa = (sel, ctx = document) => Array.from(ctx.querySelectorAll(sel));
866
868
 
867
869
  // Create element shorthand — returns ZQueryCollection for chaining
868
870
  query.create = (tag, attrs = {}, ...children) => {
@@ -870,7 +872,7 @@ query.create = (tag, attrs = {}, ...children) => {
870
872
  for (const [k, v] of Object.entries(attrs)) {
871
873
  if (k === 'class') el.className = v;
872
874
  else if (k === 'style' && typeof v === 'object') Object.assign(el.style, v);
873
- else if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v);
875
+ else if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2).toLowerCase(), v);
874
876
  else if (k === 'data' && typeof v === 'object') Object.entries(v).forEach(([dk, dv]) => { el.dataset[dk] = dv; });
875
877
  else el.setAttribute(k, v);
876
878
  }
package/src/expression.js CHANGED
@@ -169,6 +169,11 @@ function tokenize(expr) {
169
169
  tokens.push({ t: T.OP, v: ch });
170
170
  i++; continue;
171
171
  }
172
+ // Spread operator: ...
173
+ if (ch === '.' && i + 2 < len && expr[i + 1] === '.' && expr[i + 2] === '.') {
174
+ tokens.push({ t: T.OP, v: '...' });
175
+ i += 3; continue;
176
+ }
172
177
  if ('()[]{},.?:'.includes(ch)) {
173
178
  tokens.push({ t: T.PUNC, v: ch });
174
179
  i++; continue;
@@ -232,7 +237,7 @@ class Parser {
232
237
  this.next(); // consume ?
233
238
  const truthy = this.parseExpression(0);
234
239
  this.expect(T.PUNC, ':');
235
- const falsy = this.parseExpression(1);
240
+ const falsy = this.parseExpression(0);
236
241
  left = { type: 'ternary', cond: left, truthy, falsy };
237
242
  continue;
238
243
  }
@@ -373,7 +378,12 @@ class Parser {
373
378
  this.expect(T.PUNC, '(');
374
379
  const args = [];
375
380
  while (!(this.peek().t === T.PUNC && this.peek().v === ')') && this.peek().t !== T.EOF) {
376
- args.push(this.parseExpression(0));
381
+ if (this.peek().t === T.OP && this.peek().v === '...') {
382
+ this.next();
383
+ args.push({ type: 'spread', arg: this.parseExpression(0) });
384
+ } else {
385
+ args.push(this.parseExpression(0));
386
+ }
377
387
  if (this.peek().t === T.PUNC && this.peek().v === ',') this.next();
378
388
  }
379
389
  this.expect(T.PUNC, ')');
@@ -449,7 +459,12 @@ class Parser {
449
459
  this.next();
450
460
  const elements = [];
451
461
  while (!(this.peek().t === T.PUNC && this.peek().v === ']') && this.peek().t !== T.EOF) {
452
- elements.push(this.parseExpression(0));
462
+ if (this.peek().t === T.OP && this.peek().v === '...') {
463
+ this.next();
464
+ elements.push({ type: 'spread', arg: this.parseExpression(0) });
465
+ } else {
466
+ elements.push(this.parseExpression(0));
467
+ }
453
468
  if (this.peek().t === T.PUNC && this.peek().v === ',') this.next();
454
469
  }
455
470
  this.expect(T.PUNC, ']');
@@ -461,6 +476,14 @@ class Parser {
461
476
  this.next();
462
477
  const properties = [];
463
478
  while (!(this.peek().t === T.PUNC && this.peek().v === '}') && this.peek().t !== T.EOF) {
479
+ // Spread in object: { ...obj }
480
+ if (this.peek().t === T.OP && this.peek().v === '...') {
481
+ this.next();
482
+ properties.push({ spread: true, value: this.parseExpression(0) });
483
+ if (this.peek().t === T.PUNC && this.peek().v === ',') this.next();
484
+ continue;
485
+ }
486
+
464
487
  const keyTok = this.next();
465
488
  let key;
466
489
  if (keyTok.t === T.IDENT || keyTok.t === T.STR) key = keyTok.v;
@@ -492,7 +515,13 @@ class Parser {
492
515
 
493
516
  // new keyword
494
517
  if (tok.v === 'new') {
495
- const classExpr = this.parsePostfix();
518
+ let classExpr = this.parsePrimary();
519
+ // Handle member access (e.g. ns.MyClass) without consuming call args
520
+ while (this.peek().t === T.PUNC && this.peek().v === '.') {
521
+ this.next();
522
+ const prop = this.next();
523
+ classExpr = { type: 'member', obj: classExpr, prop: prop.v, computed: false };
524
+ }
496
525
  let args = [];
497
526
  if (this.peek().t === T.PUNC && this.peek().v === '(') {
498
527
  args = this._parseArgs();
@@ -604,6 +633,12 @@ function evaluate(node, scope) {
604
633
  if (name === 'encodeURIComponent') return encodeURIComponent;
605
634
  if (name === 'decodeURIComponent') return decodeURIComponent;
606
635
  if (name === 'console') return console;
636
+ if (name === 'Map') return Map;
637
+ if (name === 'Set') return Set;
638
+ if (name === 'RegExp') return RegExp;
639
+ if (name === 'Error') return Error;
640
+ if (name === 'URL') return URL;
641
+ if (name === 'URLSearchParams') return URLSearchParams;
607
642
  return undefined;
608
643
  }
609
644
 
@@ -642,10 +677,21 @@ function evaluate(node, scope) {
642
677
  }
643
678
 
644
679
  case 'optional_call': {
645
- const callee = evaluate(node.callee, scope);
680
+ const calleeNode = node.callee;
681
+ const args = _evalArgs(node.args, scope);
682
+ // Method call: obj?.method() — bind `this` to obj
683
+ if (calleeNode.type === 'member' || calleeNode.type === 'optional_member') {
684
+ const obj = evaluate(calleeNode.obj, scope);
685
+ if (obj == null) return undefined;
686
+ const prop = calleeNode.computed ? evaluate(calleeNode.prop, scope) : calleeNode.prop;
687
+ if (!_isSafeAccess(obj, prop)) return undefined;
688
+ const fn = obj[prop];
689
+ if (typeof fn !== 'function') return undefined;
690
+ return fn.apply(obj, args);
691
+ }
692
+ const callee = evaluate(calleeNode, scope);
646
693
  if (callee == null) return undefined;
647
694
  if (typeof callee !== 'function') return undefined;
648
- const args = node.args.map(a => evaluate(a, scope));
649
695
  return callee(...args);
650
696
  }
651
697
 
@@ -655,7 +701,7 @@ function evaluate(node, scope) {
655
701
  // Only allow safe constructors
656
702
  if (Ctor === Date || Ctor === Array || Ctor === Map || Ctor === Set ||
657
703
  Ctor === RegExp || Ctor === Error || Ctor === URL || Ctor === URLSearchParams) {
658
- const args = node.args.map(a => evaluate(a, scope));
704
+ const args = _evalArgs(node.args, scope);
659
705
  return new Ctor(...args);
660
706
  }
661
707
  return undefined;
@@ -685,13 +731,32 @@ function evaluate(node, scope) {
685
731
  return cond ? evaluate(node.truthy, scope) : evaluate(node.falsy, scope);
686
732
  }
687
733
 
688
- case 'array':
689
- return node.elements.map(e => evaluate(e, scope));
734
+ case 'array': {
735
+ const arr = [];
736
+ for (const e of node.elements) {
737
+ if (e.type === 'spread') {
738
+ const iterable = evaluate(e.arg, scope);
739
+ if (iterable != null && typeof iterable[Symbol.iterator] === 'function') {
740
+ for (const v of iterable) arr.push(v);
741
+ }
742
+ } else {
743
+ arr.push(evaluate(e, scope));
744
+ }
745
+ }
746
+ return arr;
747
+ }
690
748
 
691
749
  case 'object': {
692
750
  const obj = {};
693
- for (const { key, value } of node.properties) {
694
- obj[key] = evaluate(value, scope);
751
+ for (const prop of node.properties) {
752
+ if (prop.spread) {
753
+ const source = evaluate(prop.value, scope);
754
+ if (source != null && typeof source === 'object') {
755
+ Object.assign(obj, source);
756
+ }
757
+ } else {
758
+ obj[prop.key] = evaluate(prop.value, scope);
759
+ }
695
760
  }
696
761
  return obj;
697
762
  }
@@ -712,12 +777,30 @@ function evaluate(node, scope) {
712
777
  }
713
778
  }
714
779
 
780
+ /**
781
+ * Evaluate a list of argument AST nodes, flattening any spread elements.
782
+ */
783
+ function _evalArgs(argNodes, scope) {
784
+ const result = [];
785
+ for (const a of argNodes) {
786
+ if (a.type === 'spread') {
787
+ const iterable = evaluate(a.arg, scope);
788
+ if (iterable != null && typeof iterable[Symbol.iterator] === 'function') {
789
+ for (const v of iterable) result.push(v);
790
+ }
791
+ } else {
792
+ result.push(evaluate(a, scope));
793
+ }
794
+ }
795
+ return result;
796
+ }
797
+
715
798
  /**
716
799
  * Resolve and execute a function call safely.
717
800
  */
718
801
  function _resolveCall(node, scope) {
719
802
  const callee = node.callee;
720
- const args = node.args.map(a => evaluate(a, scope));
803
+ const args = _evalArgs(node.args, scope);
721
804
 
722
805
  // Method call: obj.method() — bind `this` to obj
723
806
  if (callee.type === 'member' || callee.type === 'optional_member') {
@@ -791,8 +874,9 @@ function _evalBinary(node, scope) {
791
874
  * @returns {*} — evaluation result, or undefined on error
792
875
  */
793
876
 
794
- // AST cache — avoids re-tokenizing and re-parsing the same expression string.
795
- // Bounded to prevent unbounded memory growth in long-lived apps.
877
+ // AST cache (LRU) — avoids re-tokenizing and re-parsing the same expression.
878
+ // Uses Map insertion-order: on hit, delete + re-set moves entry to the end.
879
+ // Eviction removes the least-recently-used (first) entry when at capacity.
796
880
  const _astCache = new Map();
797
881
  const _AST_CACHE_MAX = 512;
798
882
 
@@ -812,9 +896,12 @@ export function safeEval(expr, scope) {
812
896
  // Fall through to full parser for built-in globals (Math, JSON, etc.)
813
897
  }
814
898
 
815
- // Check AST cache
899
+ // Check AST cache (LRU: move to end on hit)
816
900
  let ast = _astCache.get(trimmed);
817
- if (!ast) {
901
+ if (ast) {
902
+ _astCache.delete(trimmed);
903
+ _astCache.set(trimmed, ast);
904
+ } else {
818
905
  const tokens = tokenize(trimmed);
819
906
  const parser = new Parser(tokens, scope);
820
907
  ast = parser.parse();
package/src/http.js CHANGED
@@ -84,8 +84,9 @@ async function request(method, url, data, options = {}) {
84
84
  } else {
85
85
  fetchOpts.signal = controller.signal;
86
86
  }
87
+ let _timedOut = false;
87
88
  if (timeout > 0) {
88
- timer = setTimeout(() => controller.abort(), timeout);
89
+ timer = setTimeout(() => { _timedOut = true; controller.abort(); }, timeout);
89
90
  }
90
91
 
91
92
  // Run request interceptors
@@ -145,7 +146,10 @@ async function request(method, url, data, options = {}) {
145
146
  } catch (err) {
146
147
  if (timer) clearTimeout(timer);
147
148
  if (err.name === 'AbortError') {
148
- throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);
149
+ if (_timedOut) {
150
+ throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);
151
+ }
152
+ throw new Error(`Request aborted: ${method} ${fullURL}`);
149
153
  }
150
154
  throw err;
151
155
  }
package/src/router.js CHANGED
@@ -583,7 +583,12 @@ class Router {
583
583
  if (typeof matched.component === 'string') {
584
584
  const container = document.createElement(matched.component);
585
585
  this._el.appendChild(container);
586
- this._instance = mount(container, matched.component, props);
586
+ try {
587
+ this._instance = mount(container, matched.component, props);
588
+ } catch (err) {
589
+ reportError(ErrorCode.COMP_NOT_FOUND, `Failed to mount component for route "${matched.path}"`, { component: matched.component, path: matched.path }, err);
590
+ return;
591
+ }
587
592
  if (_routeStart) window.__zqRenderHook(this._el, performance.now() - _routeStart, 'route', matched.component);
588
593
  }
589
594
  // If component is a render function
package/src/utils.js CHANGED
@@ -79,6 +79,10 @@ export function escapeHtml(str) {
79
79
  return String(str).replace(/[&<>"']/g, c => map[c]);
80
80
  }
81
81
 
82
+ export function stripHtml(str) {
83
+ return String(str).replace(/<[^>]*>/g, '');
84
+ }
85
+
82
86
  /**
83
87
  * Template tag for auto-escaping interpolated values
84
88
  * Usage: $.html`<div>${userInput}</div>`
@@ -94,7 +98,7 @@ export function html(strings, ...values) {
94
98
  /**
95
99
  * Mark HTML as trusted (skip escaping in $.html template)
96
100
  */
97
- class TrustedHTML {
101
+ export class TrustedHTML {
98
102
  constructor(html) { this._html = html; }
99
103
  toString() { return this._html; }
100
104
  }
@@ -124,7 +128,10 @@ export function camelCase(str) {
124
128
  * CamelCase to kebab-case
125
129
  */
126
130
  export function kebabCase(str) {
127
- return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
131
+ return str
132
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
133
+ .replace(/([a-z\d])([A-Z])/g, '$1-$2')
134
+ .toLowerCase();
128
135
  }
129
136
 
130
137
 
@@ -165,15 +172,19 @@ export function deepMerge(target, ...sources) {
165
172
  /**
166
173
  * Simple object equality check
167
174
  */
168
- export function isEqual(a, b) {
175
+ export function isEqual(a, b, _seen) {
169
176
  if (a === b) return true;
170
177
  if (typeof a !== typeof b) return false;
171
178
  if (typeof a !== 'object' || a === null || b === null) return false;
172
179
  if (Array.isArray(a) !== Array.isArray(b)) return false;
180
+ // Guard against circular references
181
+ if (!_seen) _seen = new Set();
182
+ if (_seen.has(a)) return true;
183
+ _seen.add(a);
173
184
  const keysA = Object.keys(a);
174
185
  const keysB = Object.keys(b);
175
186
  if (keysA.length !== keysB.length) return false;
176
- return keysA.every(k => isEqual(a[k], b[k]));
187
+ return keysA.every(k => isEqual(a[k], b[k], _seen));
177
188
  }
178
189
 
179
190
 
@@ -249,7 +260,7 @@ export const session = {
249
260
  // ---------------------------------------------------------------------------
250
261
  // Event bus (pub/sub)
251
262
  // ---------------------------------------------------------------------------
252
- class EventBus {
263
+ export class EventBus {
253
264
  constructor() { this._handlers = new Map(); }
254
265
 
255
266
  on(event, fn) {
@@ -275,3 +286,178 @@ class EventBus {
275
286
  }
276
287
 
277
288
  export const bus = new EventBus();
289
+
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // Array utilities
293
+ // ---------------------------------------------------------------------------
294
+
295
+ export function range(startOrEnd, end, step) {
296
+ let s, e, st;
297
+ if (end === undefined) { s = 0; e = startOrEnd; st = 1; }
298
+ else { s = startOrEnd; e = end; st = step !== undefined ? step : 1; }
299
+ if (st === 0) return [];
300
+ const result = [];
301
+ if (st > 0) { for (let i = s; i < e; i += st) result.push(i); }
302
+ else { for (let i = s; i > e; i += st) result.push(i); }
303
+ return result;
304
+ }
305
+
306
+ export function unique(arr, keyFn) {
307
+ if (!keyFn) return [...new Set(arr)];
308
+ const seen = new Set();
309
+ return arr.filter(item => {
310
+ const k = keyFn(item);
311
+ if (seen.has(k)) return false;
312
+ seen.add(k);
313
+ return true;
314
+ });
315
+ }
316
+
317
+ export function chunk(arr, size) {
318
+ const result = [];
319
+ for (let i = 0; i < arr.length; i += size) result.push(arr.slice(i, i + size));
320
+ return result;
321
+ }
322
+
323
+ export function groupBy(arr, keyFn) {
324
+ const result = {};
325
+ for (const item of arr) {
326
+ const k = keyFn(item);
327
+ (result[k] ??= []).push(item);
328
+ }
329
+ return result;
330
+ }
331
+
332
+
333
+ // ---------------------------------------------------------------------------
334
+ // Object utilities
335
+ // ---------------------------------------------------------------------------
336
+
337
+ export function pick(obj, keys) {
338
+ const result = {};
339
+ for (const k of keys) { if (k in obj) result[k] = obj[k]; }
340
+ return result;
341
+ }
342
+
343
+ export function omit(obj, keys) {
344
+ const exclude = new Set(keys);
345
+ const result = {};
346
+ for (const k of Object.keys(obj)) { if (!exclude.has(k)) result[k] = obj[k]; }
347
+ return result;
348
+ }
349
+
350
+ export function getPath(obj, path, fallback) {
351
+ const keys = path.split('.');
352
+ let cur = obj;
353
+ for (const k of keys) {
354
+ if (cur == null || typeof cur !== 'object') return fallback;
355
+ cur = cur[k];
356
+ }
357
+ return cur === undefined ? fallback : cur;
358
+ }
359
+
360
+ export function setPath(obj, path, value) {
361
+ const keys = path.split('.');
362
+ let cur = obj;
363
+ for (let i = 0; i < keys.length - 1; i++) {
364
+ const k = keys[i];
365
+ if (cur[k] == null || typeof cur[k] !== 'object') cur[k] = {};
366
+ cur = cur[k];
367
+ }
368
+ cur[keys[keys.length - 1]] = value;
369
+ return obj;
370
+ }
371
+
372
+ export function isEmpty(val) {
373
+ if (val == null) return true;
374
+ if (typeof val === 'string' || Array.isArray(val)) return val.length === 0;
375
+ if (val instanceof Map || val instanceof Set) return val.size === 0;
376
+ if (typeof val === 'object') return Object.keys(val).length === 0;
377
+ return false;
378
+ }
379
+
380
+
381
+ // ---------------------------------------------------------------------------
382
+ // String utilities
383
+ // ---------------------------------------------------------------------------
384
+
385
+ export function capitalize(str) {
386
+ if (!str) return '';
387
+ return str[0].toUpperCase() + str.slice(1).toLowerCase();
388
+ }
389
+
390
+ export function truncate(str, maxLen, suffix = '…') {
391
+ if (str.length <= maxLen) return str;
392
+ const end = Math.max(0, maxLen - suffix.length);
393
+ return str.slice(0, end) + suffix;
394
+ }
395
+
396
+
397
+ // ---------------------------------------------------------------------------
398
+ // Number utilities
399
+ // ---------------------------------------------------------------------------
400
+
401
+ export function clamp(val, min, max) {
402
+ return val < min ? min : val > max ? max : val;
403
+ }
404
+
405
+
406
+ // ---------------------------------------------------------------------------
407
+ // Function utilities
408
+ // ---------------------------------------------------------------------------
409
+
410
+ export function memoize(fn, keyFnOrOpts) {
411
+ let keyFn, maxSize = 0;
412
+ if (typeof keyFnOrOpts === 'function') keyFn = keyFnOrOpts;
413
+ else if (keyFnOrOpts && typeof keyFnOrOpts === 'object') maxSize = keyFnOrOpts.maxSize || 0;
414
+
415
+ const cache = new Map();
416
+
417
+ const memoized = (...args) => {
418
+ const key = keyFn ? keyFn(...args) : args[0];
419
+ if (cache.has(key)) return cache.get(key);
420
+ const result = fn(...args);
421
+ cache.set(key, result);
422
+ if (maxSize > 0 && cache.size > maxSize) {
423
+ cache.delete(cache.keys().next().value);
424
+ }
425
+ return result;
426
+ };
427
+
428
+ memoized.clear = () => cache.clear();
429
+ return memoized;
430
+ }
431
+
432
+
433
+ // ---------------------------------------------------------------------------
434
+ // Async utilities
435
+ // ---------------------------------------------------------------------------
436
+
437
+ export function retry(fn, opts = {}) {
438
+ const { attempts = 3, delay = 1000, backoff = 1 } = opts;
439
+ return new Promise((resolve, reject) => {
440
+ let attempt = 0, currentDelay = delay;
441
+ const tryOnce = () => {
442
+ attempt++;
443
+ fn(attempt).then(resolve, (err) => {
444
+ if (attempt >= attempts) return reject(err);
445
+ const d = currentDelay;
446
+ currentDelay *= backoff;
447
+ setTimeout(tryOnce, d);
448
+ });
449
+ };
450
+ tryOnce();
451
+ });
452
+ }
453
+
454
+ export function timeout(promise, ms, message) {
455
+ let timer;
456
+ const race = Promise.race([
457
+ promise,
458
+ new Promise((_, reject) => {
459
+ timer = setTimeout(() => reject(new Error(message || `Timed out after ${ms}ms`)), ms);
460
+ })
461
+ ]);
462
+ return race.finally(() => clearTimeout(timer));
463
+ }