@lmjs/core 2.2.1 → 2.3.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.
package/src/_re.js CHANGED
@@ -105,6 +105,14 @@ var _mountedSubviewEngines = [];
105
105
  // own HST_FORMAT_VERSION comment for the full rationale.
106
106
  var EXPECTED_HST_FORMAT_VERSION = 1;
107
107
 
108
+ // V1 let a pure dotted path address array items and digit-led keys: `{{rows.0.name}}`, `{{sections.x.specs.2.Value}}`.
109
+ // That is not valid JavaScript, so eval() threw a SyntaxError (dev mode logged it as an error) and only the
110
+ // dotted-path fallback in lookup() produced the value. Rewriting the digit-led segments makes eval succeed directly.
111
+ function _numericPathToBrackets(expr) {
112
+ if (typeof expr !== 'string' || !/\.\d/.test(expr) || !/^\s*[A-Za-z_$][\w$]*(?:\.[\w$]+)+\s*$/.test(expr)) return expr;
113
+ return expr.replace(/\.(\d[\w$]*)/g, "['$1']");
114
+ }
115
+
108
116
  var _entityDecodeEl;
109
117
  function decodeHtmlEntities(str) {
110
118
  if (!str || str.indexOf('&') === -1) return str;
@@ -166,13 +174,16 @@ function reportLumenError(info) {
166
174
 
167
175
 
168
176
  function _x(_x) {
169
- var currPath = [];
177
+ // Native array mutators (shift/splice/sort/...) perform many internal
178
+ // writes; each proxy carries its OWN path, and a mutator runs as one
179
+ // write that dispatches once, with the final state.
180
+ const _ARRAY_MUTATORS = { push: 1, pop: 1, shift: 1, unshift: 1, splice: 1, sort: 1, reverse: 1, fill: 1, copyWithin: 1 };
170
181
  // 2026-09-17: generalized from a position-specific check
171
182
  // (`currPath[1] == "vars"`, only ever matched a flat `_vt.<root>.vars`
172
183
  // write) to a real owner-walk — needed for per-instance subview
173
184
  // scoping (`_vt.View.views[i].vars`, and its nested form
174
185
  // `_vt.View.views[0].views[2].vars`), where "vars" can sit at any
175
- // depth. `path` is currPath *without* the trailing "vars" segment.
186
+ // depth. `currPath` is the writing proxy's own path (captured when that proxy was created).
176
187
  // `Global` is a real special case, not a bug in this generalization:
177
188
  // it has no `._re` of its own (see the object literal below — just
178
189
  // `{vars:{}}`) since Global-var writes need to re-render whichever
@@ -181,8 +192,8 @@ function _x(_x) {
181
192
  // or any views[i]/views[i].views[j]/... chain) is walked against the
182
193
  // raw (non-proxied) tree — using the outer `_x` param directly, not
183
194
  // the `_vt` proxy — so this traversal itself can't re-enter these
184
- // traps and corrupt the in-flight currPath.
185
- function _dispatchVarsUpdate(key) {
195
+ // traps.
196
+ function _dispatchVarsUpdate(key, currPath) {
186
197
  // "vars" can be anywhere in currPath, not just at index 1 — find
187
198
  // it. The var name to update() is whatever comes right after it
188
199
  // in currPath (e.g. `_vt.View.vars["obj"].nested = x` — the write
@@ -305,6 +316,7 @@ function _x(_x) {
305
316
  }
306
317
  sve.update(varName);
307
318
  }
319
+ _updateReactiveEngines(varName);
308
320
  return;
309
321
  }
310
322
  let owner = _x;
@@ -312,92 +324,128 @@ function _x(_x) {
312
324
  owner = owner[rootPath[i]];
313
325
  }
314
326
  if (owner && owner._re) owner._re.update(varName);
327
+ // A sub-view reads its ancestors' variables by name (getVal() falls through to them), as V1 sub-views read
328
+ // the page's globals. Re-render the sub-views mounted under the view that changed; each one only touches
329
+ // effects / loops / conditions that actually read `varName`.
330
+ for (let msi = _mountedSubviewEngines.length - 1; msi >= 0; msi--) {
331
+ const sve = _mountedSubviewEngines[msi];
332
+ if (!sve || sve === (owner && owner._re)) continue;
333
+ const sveNode = sve._RealDOM && sve._RealDOM[0];
334
+ if (sveNode && !sveNode.isConnected) { _mountedSubviewEngines.splice(msi, 1); continue; }
335
+ const sp = sve.view && sve.view.scopePath;
336
+ if (!sp || sp.length <= rootPath.length) continue;
337
+ let under = true;
338
+ for (let i = 0; i < rootPath.length; i++) if (String(sp[i]) !== String(rootPath[i])) { under = false; break; }
339
+ if (under) sve.update(varName);
340
+ }
341
+ _updateReactiveEngines(varName);
315
342
  }
316
- const handler = {
317
- get(target, key) {
318
- if (key == "__isProxy") return true;
319
- // 2026-09-14: reset must fire on ANY root key, not just "View" —
320
- // this closure's currPath is shared by the whole _vt proxy tree,
321
- // so a stale tail from a prior _vt.Global read (which never hit
322
- // "View" to reset it) would otherwise get prepended to the next
323
- // chain and corrupt which key set()'s update(key) fires for.
324
- // 2026-09-18: generalized from a hardcoded `key == "View" ||
325
- // key == "Global"` name list (which needed editing every time a
326
- // new permanent root, e.g. "Widgets", got added) to the one
327
- // thing that's actually invariant: `target === _x` is only ever
328
- // true for THIS proxy's own outermost target (the raw root
329
- // object this whole closure was built from) — any nested proxy
330
- // in the tree wraps some OTHER object as its target, never `_x`
331
- // itself. So this fires on any fresh top-level access
332
- // (`_vt.View`, `_vt.Global`, `_vt.Widgets`, ...) regardless of
333
- // the key name, with nothing new to maintain per root added.
334
- if (target === _x) currPath = [];
335
- currPath.push(key);
336
- if (typeof target[key] === 'object' && target[key] !== null && key != "_re") {
337
- // cl("salsaa", target, key)
338
- return new Proxy(target[key], handler);
339
- } else {
340
- // cl("tartat", target, key);
341
- return target[key] ?? (key == 'target' ? target : undefined) ?? undefined;
342
- }
343
- },
344
- set(target, key, value) {
345
-
346
- // cl(["hiiiiii", key, value]);
347
- // console.log(`${key} set from ${target[key]} to ${value}`, target, Object.keys({ target })[0]);
348
- target[key] = value;
349
- // var _View = currPath[1] == "views" ? currPath[2] : "";
350
-
351
- try {
352
- // `_vt.View._re` genuinely doesn't exist yet during
353
- // index.js's own bootstrap (before any view has mounted —
354
- // see index-bootstrap.js) — that's the normal case now,
355
- // not an error, so it's guarded (inside _dispatchVarsUpdate)
356
- // rather than left to throw into the catch below.
357
- _dispatchVarsUpdate(key);
358
- } catch (e) {
359
- cl(e);
360
- }
361
-
362
- currPath = [];
363
- return true;
364
- },
365
- deleteProperty(target, key) {
366
- if (!(key in target)) {
367
- return false;
368
- }
369
- delete target[key];
370
-
371
- try {
372
- _dispatchVarsUpdate(key);
373
- } catch (e) {
374
- cl(e);
375
- }
376
- return true;
377
- },
378
- ownKeys(target) {
379
- return Reflect.ownKeys(target);
380
- },
381
- has(target, key) {
382
- return key in target;
383
- },
384
- defineProperty(target, key, descriptor) {
385
- if (descriptor && "value" in descriptor) {
386
- target[key] = descriptor.value;
343
+ // Decides without reading any property of `v` (a brand check via Symbol.toStringTag pokes foreign Proxy
344
+ // traps with a Symbol key; the SDK's `cookies` proxy throws on that): arrays, plain objects and instances of
345
+ // user classes are wrapped; anything whose prototype chain has a native constructor (Date, Promise, Map, DOM...) is not.
346
+ function _isWrappable(v) {
347
+ if (Array.isArray(v)) return true;
348
+ try {
349
+ for (let p = Object.getPrototypeOf(v); p && p !== Object.prototype; p = Object.getPrototypeOf(p)) {
350
+ const c = Object.prototype.hasOwnProperty.call(p, 'constructor') ? p.constructor : null;
351
+ if (typeof c !== 'function') continue;
352
+ if (c.name === 'Object') return true;
353
+ if (/\[native code\]/.test(Function.prototype.toString.call(c))) return false;
387
354
  }
388
- return target;
389
- },
390
- getOwnPropertyDescriptor(target, key) {
391
- const value = target[key];
392
- return key in target
393
- ? {
394
- value,
395
- enumerable: true,
396
- configurable: true,
355
+ } catch (e) { return false; }
356
+ return true;
357
+ }
358
+ let _batch = 0;
359
+ function makeHandler(path) {
360
+ // One proxy per (child object, key): rebuilding a Proxy + handler on every read was the
361
+ // dominant cost of reading reactive state, and made `rows === rows` false.
362
+ const childProxies = new WeakMap();
363
+ return {
364
+ get(target, key, receiver) {
365
+ if (key == "__isProxy") return true;
366
+ if (typeof key === 'symbol') return target[key];
367
+ if (_ARRAY_MUTATORS[key] === 1 && Array.isArray(target) && typeof target[key] === 'function') {
368
+ return function () {
369
+ let res;
370
+ _batch++;
371
+ try { res = Array.prototype[key].apply(target, arguments); } finally { _batch--; }
372
+ if (!_batch) {
373
+ try { _dispatchVarsUpdate(key, path); } catch (e) { cl(e); }
374
+ }
375
+ return res === target ? receiver : res;
376
+ };
397
377
  }
398
- : undefined;
399
- },
400
- };
378
+ const v = target[key];
379
+ if (typeof v === 'object' && v !== null && key != "_re") {
380
+ const hit = childProxies.get(v);
381
+ if (hit && hit.key === key) return hit.proxy;
382
+ // Only plain objects/arrays are wrapped: methods of Promise/Date/Map/Set/RegExp/DOM nodes
383
+ // need their real object as `this` and throw "incompatible receiver" under a Proxy.
384
+ // The one exception is a subview host element (isSub): generated subview code writes its
385
+ // locals as `_vt.View.views[n].vars[x] = ...`, and that write is only observed through the proxy.
386
+ if (!_isWrappable(v) && v.isSub !== true) return v;
387
+ const proxy = new Proxy(v, makeHandler(path.concat(key)));
388
+ childProxies.set(v, { key, proxy });
389
+ return proxy;
390
+ }
391
+ return v ?? (key == 'target' ? target : undefined) ?? undefined;
392
+ },
393
+ set(target, key, value) {
394
+ target[key] = value;
395
+ if (!_batch) {
396
+ try {
397
+ // `_vt.View._re` genuinely doesn't exist yet during
398
+ // index.js's own bootstrap (before any view has mounted),
399
+ // so the dispatch guards for it rather than throwing.
400
+ _dispatchVarsUpdate(key, path);
401
+ } catch (e) {
402
+ cl(e);
403
+ }
404
+ }
405
+ return true;
406
+ },
407
+ deleteProperty(target, key) {
408
+ if (!(key in target)) {
409
+ return false;
410
+ }
411
+ delete target[key];
412
+ if (!_batch) {
413
+ try {
414
+ _dispatchVarsUpdate(key, path);
415
+ } catch (e) {
416
+ cl(e);
417
+ }
418
+ }
419
+ return true;
420
+ },
421
+ ownKeys(target) {
422
+ return Reflect.ownKeys(target);
423
+ },
424
+ has(target, key) {
425
+ return key in target;
426
+ },
427
+ defineProperty(target, key, descriptor) {
428
+ if (descriptor && "value" in descriptor) {
429
+ target[key] = descriptor.value;
430
+ }
431
+ return target;
432
+ },
433
+ getOwnPropertyDescriptor(target, key) {
434
+ // Proxy invariant: a non-configurable target property (an array's 'length') must be reported as it really is, or V8 throws.
435
+ const real = Reflect.getOwnPropertyDescriptor(target, key);
436
+ if (real && !real.configurable) return real;
437
+ const value = target[key];
438
+ return key in target
439
+ ? {
440
+ value,
441
+ enumerable: true,
442
+ configurable: true,
443
+ }
444
+ : undefined;
445
+ },
446
+ };
447
+ }
448
+ const handler = makeHandler([]);
401
449
  var x = new Proxy(_x, handler);
402
450
  return x;
403
451
  }
@@ -490,13 +538,10 @@ function touch(name) {
490
538
  //
491
539
  // _deepReactive(obj, onChange) is a small, SEPARATE reactive-Proxy
492
540
  // mechanism from _x()/_vt's — deliberately not reusing it, because _x()'s
493
- // update-dispatch relies on a single shared, mutable `currPath` array that
494
- // assumes a get-then-set chain happens atomically right before each write
495
- // (e.g. `_vt.Global.vars.globals.Me = x` in one expression). `globals` is
496
- // held onto as a long-lived reference (the bare identifier itself, and
497
- // window.globals) and mutated arbitrarily later, with unrelated _vt
498
- // traffic likely happening in between — exactly the case that assumption
499
- // doesn't hold for. So this wraps any object/array recursively (memoized
541
+ // update-dispatch was originally built on a single shared, mutable path
542
+ // array (since replaced by a per-proxy path), and `globals` is held onto as
543
+ // a long-lived reference (the bare identifier itself, and window.globals)
544
+ // mutated arbitrarily later. So this wraps any object/array recursively (memoized
500
545
  // per underlying target via a WeakMap, so repeated reads of the same
501
546
  // nested value return the same Proxy instance — real object-identity
502
547
  // comparisons on a Global var's own sub-objects still work) and fires
@@ -586,24 +631,66 @@ function _resolveScopePathTarget(scopePath) {
586
631
  for (let i = 0; i < scopePath.length; i++) target = target[scopePath[i]];
587
632
  return target;
588
633
  }
589
- function _evalEventScopedExpr(ownerRe, expr) {
590
- if (!ownerRe || !ownerRe.view) return eval(expr);
591
- let ownVars = ownerRe.view.vars || {};
592
- let widgetsVars = _mergedWidgetsVars();
634
+ // `locals` are the handler's own arguments (ev, el, n, arg1..3). V1 eval'd inline handlers inside
635
+ // evalEvAttr(), so those names were in scope and shadowed any global of the same name.
636
+ function _evalEventScopedExpr(ownerRe, expr, locals) {
637
+ locals = locals || {};
638
+ let hasOwner = !!(ownerRe && ownerRe.view);
639
+ // Every engine from the owner up (a :for row -> the view that holds the loop -> ...): a handler reads and writes
640
+ // a name where it lives, so `@click="picked = r"` on a row reads the row's `r` and writes the view's `picked`.
641
+ // A level that IS the view at its scopePath is read/written through the live _vt proxy, so nested writes
642
+ // (`city.name = 'x'`, `list.push(1)`) re-render; a row's own scope is written in place and the row updated.
643
+ let levels = [];
644
+ for (let e = hasOwner ? ownerRe : null, n = 0; e && e.view && n < 50; e = e.view._pv, n++) {
645
+ let live = null;
646
+ if (e.view.scopePath) {
647
+ try {
648
+ let _sv = _resolveScopePathTarget(e.view.scopePath);
649
+ if (_sv && _sv._re === e) live = _sv.vars;
650
+ } catch (err) { live = null; }
651
+ }
652
+ levels.push({ re: e, vars: e.view.vars || {}, live: live });
653
+ }
654
+ function levelOf(key) {
655
+ for (let i = 0; i < levels.length; i++) if (Object.prototype.hasOwnProperty.call(levels[i].vars, key)) return levels[i];
656
+ return null;
657
+ }
658
+ let widgetsVars = hasOwner ? _mergedWidgetsVars() : {};
659
+ // The owner's own functions (nearest view up the parent chain) win over window: with the same sub-view mounted
660
+ // twice, `@click="inc()"` must call the clicked instance's inc, not whichever instance's script ran last.
661
+ function ownFn(key) {
662
+ for (let i = 0; i < levels.length; i++) {
663
+ const fns = levels[i].re.view.fns;
664
+ if (fns && Object.prototype.hasOwnProperty.call(fns, key) && typeof fns[key] === 'function') return fns[key];
665
+ }
666
+ return undefined;
667
+ }
593
668
  let scopeProxy = new Proxy({}, {
594
669
  has(target, key) {
595
670
  if (typeof key === 'symbol') return false;
596
- return ownVars.hasOwnProperty(key) || widgetsVars.hasOwnProperty(key) || _vt.Global.vars.hasOwnProperty(key);
671
+ if (locals.hasOwnProperty(key)) return true;
672
+ if (!hasOwner) return false;
673
+ if (ownFn(key)) return true;
674
+ return !!levelOf(key) || widgetsVars.hasOwnProperty(key) || _vt.Global.vars.hasOwnProperty(key);
597
675
  },
598
676
  get(target, key) {
599
- if (ownVars.hasOwnProperty(key)) return ownVars[key];
600
- if (widgetsVars.hasOwnProperty(key)) return widgetsVars[key];
677
+ if (locals.hasOwnProperty(key)) return locals[key];
678
+ const f = ownFn(key);
679
+ if (f) return f;
680
+ const lv = levelOf(key);
681
+ if (lv) return lv.live ? lv.live[key] : lv.vars[key];
682
+ if (widgetsVars.hasOwnProperty(key)) {
683
+ for (const wname in _vt.Widgets) if (_vt.Widgets[wname].vars.hasOwnProperty(key)) return _vt.Widgets[wname].vars[key];
684
+ }
601
685
  return _vt.Global.vars[key];
602
686
  },
603
687
  set(target, key, value) {
688
+ if (locals.hasOwnProperty(key)) { locals[key] = value; return true; }
604
689
  try {
605
- if (ownVars.hasOwnProperty(key) && ownerRe.view.scopePath) {
606
- _resolveScopePathTarget(ownerRe.view.scopePath).vars[key] = value;
690
+ const lv = levelOf(key);
691
+ if (lv) {
692
+ if (lv.live) lv.live[key] = value;
693
+ else { lv.vars[key] = value; try { lv.re.update(key); } catch (e2) { cl(e2); } }
607
694
  } else if (widgetsVars.hasOwnProperty(key)) {
608
695
  for (const wname in _vt.Widgets) {
609
696
  if (_vt.Widgets[wname].vars.hasOwnProperty(key)) {
@@ -630,11 +717,25 @@ function _evalEventScopedExpr(ownerRe, expr) {
630
717
  // still wins a name collision, matching _lookupInWidgets()'s own semantics
631
718
  // exactly (both must agree, since getVal()/evalExp() use one and
632
719
  // concatVarsAtLevel()/lookup()/scopedEval() use the other for the same read).
720
+ var _scopedEvalFns = new Map();
721
+ var _SVG_NS = "http://www.w3.org/2000/svg";
722
+ // xlink:href / xmlns:* on an SVG element only take effect when set in their namespace.
723
+ function _lmSetAttr(el, name, val) {
724
+ if (el && el.namespaceURI === _SVG_NS) {
725
+ if (name.indexOf("xlink:") === 0) return el.setAttributeNS("http://www.w3.org/1999/xlink", name, val);
726
+ if (name === "xmlns" || name.indexOf("xmlns:") === 0) return el.setAttributeNS("http://www.w3.org/2000/xmlns/", name, val);
727
+ }
728
+ el.setAttribute(name, val);
729
+ }
730
+ // Effect key for a mustache that reads no reactive variable ({{2+3}}, {{location.pathname}}): rendered once by
731
+ // renderAll(), never matched by update(k). Without it such a mustache had no effect at all and stayed blank.
732
+ var _CONST_EFFECT = "\u0000const";
633
733
  function _mergedWidgetsVars() {
634
734
  let out = {};
635
- let names = Object.keys(_vt.Widgets).reverse();
636
- for (const wname of names) {
637
- out = { ...out, ..._vt.Widgets[wname].vars };
735
+ let widgets = _vt.Widgets;
736
+ let names = Object.keys(widgets);
737
+ for (let i = names.length - 1; i >= 0; i--) {
738
+ Object.assign(out, widgets[names[i]].vars);
638
739
  }
639
740
  return out;
640
741
  }
@@ -691,6 +792,7 @@ class _lm {
691
792
  // something momentarily undefined hits it. Fixed by computing `ctx`
692
793
  // first, same effect, no TDZ violation.
693
794
  let ctx = this.concatVarsAtLevel(context, this);
795
+ expr = _numericPathToBrackets(expr);
694
796
  if (kk) {
695
797
  if (!ctx.hasOwnProperty(kk)) return undefined;
696
798
  delete ctx[kk];
@@ -700,11 +802,16 @@ class _lm {
700
802
  // cl(ctx);
701
803
  try {
702
804
  // cl(["LopIsMissing???", context, expr]);
703
- const evaluator = Function.apply(null, [
704
- ...Object.keys(ctx),
705
- "expr",
706
- "return eval(expr)",
707
- ]);
805
+ const ctxKeys = Object.keys(ctx);
806
+ // Compiling a fresh Function for every mustache of every row dominated render time;
807
+ // the compiled function depends only on the parameter names, so reuse it.
808
+ const evalKey = ctxKeys.join("\u0001");
809
+ let evaluator = _scopedEvalFns.get(evalKey);
810
+ if (!evaluator) {
811
+ evaluator = Function.apply(null, [...ctxKeys, "expr", "return eval(expr)"]);
812
+ if (_scopedEvalFns.size >= 500) _scopedEvalFns.clear();
813
+ _scopedEvalFns.set(evalKey, evaluator);
814
+ }
708
815
  // cl(evaluator.apply(null, [...Object.values(context), expr]));
709
816
  // if(expr=="patientProfile['Gender']") alert([evaluator.apply(null, [...Object.values(context), expr]), expr, Object.keys(context), context['patientProfile'], Object.keys(context.patientProfile)]);
710
817
  return evaluator.apply(null, [...Object.values(ctx), expr]);
@@ -747,6 +854,14 @@ class _lm {
747
854
  ]);
748
855
  return evaluator2.apply(null, [...Object.values(strippedCtx), expr]);
749
856
  } catch (e2) {
857
+ // The retry dropped every null/undefined name, so a ReferenceError naming a key
858
+ // that IS in this scope means "declared but currently empty" (`items = undefined`,
859
+ // then `{{items.length}}`): blank like V1, not "exists nowhere" (literal text).
860
+ const m2 = e2 instanceof ReferenceError && /^([\w$]+) is not defined$/.exec(e2.message);
861
+ if (m2 && Object.prototype.hasOwnProperty.call(ctx, m2[1])) {
862
+ reportLumenError({ stage: 'expression', expr: expr, error: e });
863
+ return undefined;
864
+ }
750
865
  if (e2 instanceof ReferenceError) this._lastUnresolved = true;
751
866
  reportLumenError({ stage: 'expression', expr: expr, error: e2 });
752
867
  return undefined;
@@ -762,12 +877,25 @@ class _lm {
762
877
  // A text mustache naming something that exists nowhere (not loading
763
878
  // data — a ReferenceError) stays literal, as V1 left any mustache
764
879
  // outside its bind= list: real V1 prose/code samples rely on that.
880
+ _inForRow() {
881
+ for (let r = this, n = 0; r && n < 50; r = r.view && r.view._pv, n++) {
882
+ if (r._blankUnresolved) return true;
883
+ if (r.vrs && Object.keys(r.vrs).length) return true;
884
+ let v = r.view;
885
+ if (v && v.type === 'section' && v.vars && Object.keys(v.vars).length) return true;
886
+ }
887
+ return false;
888
+ }
889
+
765
890
  _textMustache(content) {
766
891
  this._lastUnresolved = false;
767
892
  let v = this.getVal(content);
768
893
  let unresolved = this._lastUnresolved && (v === undefined || v === null || v === '');
769
894
  this._lastUnresolved = false;
770
895
  if (!unresolved) return v;
896
+ // Inside a :for row V1 always rendered an unresolvable mustache blank (rows only existed inside bind= lists,
897
+ // which evaluate in a try/catch that falls back to ""): an item lacking a field must not show raw `{{field}}`.
898
+ if (this._inForRow()) return v;
771
899
  let raw = String(content);
772
900
  return /^\s*\{\{[\s\S]*\}\}\s*$/.test(raw) ? raw : '{{' + raw + '}}';
773
901
  }
@@ -833,7 +961,7 @@ class _lm {
833
961
  if (effect.name == "value") {
834
962
  effect.nd.value = this.render(effect);
835
963
  } else {
836
- effect.nd.setAttribute(effect.name, this.render(effect));
964
+ _lmSetAttr(effect.nd, effect.name, this.render(effect));
837
965
  if (effect.name == "view") {
838
966
  effect.nd.subPath = this.render(effect);
839
967
  renderView(this.render(effect), true, {});
@@ -917,11 +1045,21 @@ class _lm {
917
1045
  }
918
1046
  }
919
1047
 
1048
+ // V1 rule, kept for V1 sites: a leading '!' negates the WHOLE rest of the condition (`!a == 'x'` is
1049
+ // `!(a == 'x')`, not JS's `(!a) == 'x'`), and a condition that throws counts as false before the
1050
+ // negation, so `!list[0].hasOwnProperty('id')` is true while `list` is still empty.
1051
+ _evalCondition(expr) {
1052
+ if (typeof expr === 'string' && expr.charAt(0) === '!') {
1053
+ return !this.evalExp(expr.substring(1), this.reactiveVariables);
1054
+ }
1055
+ return this.evalExp(expr, this.reactiveVariables);
1056
+ }
1057
+
920
1058
  async updateCXRs(k) {
921
1059
  for (let i = 0; i < this._CXR.length; i++) {
922
1060
  const cx = this._CXR[i];
923
1061
  if (cx.name == "if") {
924
- let isTrue = this.evalExp(cx.content, this.reactiveVariables);
1062
+ let isTrue = this._evalCondition(cx.content);
925
1063
  // cl("IF", isTrue, cx.content, this.reactiveVariables, cx);
926
1064
  if (isTrue) {
927
1065
  await this.showSectionCX(cx, k);
@@ -930,7 +1068,7 @@ class _lm {
930
1068
  }
931
1069
  } else if (cx.name == "else-if") {
932
1070
  if (!this.chainConnected(cx)) {
933
- let isTrue = this.evalExp(cx.content, this.reactiveVariables);
1071
+ let isTrue = this._evalCondition(cx.content);
934
1072
  // cl("ELSE-IF", isTrue, cx.content, this.reactiveVariables, cx);
935
1073
  if (isTrue) {
936
1074
  await this.showSectionCX(cx, k);
@@ -1059,7 +1197,7 @@ class _lm {
1059
1197
  if (effect.name == "value") {
1060
1198
  effect.nd.value = this.render(effect);
1061
1199
  } else {
1062
- effect.nd.setAttribute(effect.name, this.render(effect));
1200
+ _lmSetAttr(effect.nd, effect.name, this.render(effect));
1063
1201
  if (effect.name == "view") {
1064
1202
  effect.nd.subPath = this.render(effect);
1065
1203
  renderView(this.render(effect), true, {});
@@ -1100,13 +1238,42 @@ class _lm {
1100
1238
  }
1101
1239
  }
1102
1240
 
1241
+ // True when this loop's source expression reads the reactive variable `k`: the whole expression
1242
+ // (`rows`), a dotted path (`data.items`, `g.items`) or any expression using it (`rows.filter(...)`).
1243
+ // Matching only the exact text left every non-bare loop stale. Cached per loop and name.
1244
+ _forReads(cx, k) {
1245
+ const js = cx.forX['js'];
1246
+ if (js === k) return true;
1247
+ const cache = cx._reads || (cx._reads = {});
1248
+ if (k in cache) return cache[k];
1249
+ let hit = false;
1250
+ if (typeof k === 'string' && k !== '') {
1251
+ // :for-limit / :for-offset / :for-if can read view vars too (`:for-offset="{{(page-1) * 15}}"`).
1252
+ const src = [js, cx.limit, cx.offset, cx.cond].filter((s) => typeof s === 'string').join('\n');
1253
+ hit = new RegExp('(^|[^\\w$.])' + k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w$])').test(src);
1254
+ }
1255
+ return (cache[k] = hit);
1256
+ }
1257
+
1258
+ // V1 rendered attribute mustaches before reading :for-limit / :for-offset, so `{{(current - 1) * 15}}`
1259
+ // arrived as a number. Resolve them here; a value without mustaches is returned unchanged.
1260
+ _forNum(raw) {
1261
+ if (typeof raw !== 'string' || raw.indexOf('{') === -1) return raw;
1262
+ const self = this;
1263
+ return raw.replace(/\{\s*\{\s*([\s\S]*?)\s*\}\s*\}/g, function (_, expr) {
1264
+ let v;
1265
+ try { v = self.getVal(expr, ""); } catch (e) { v = ""; }
1266
+ return v === undefined || v === null ? "" : String(v);
1267
+ }).trim();
1268
+ }
1269
+
1103
1270
  async updateLXRs(k) {
1104
1271
  for (let i = 0; i < this._LXR.length; i++) {
1105
1272
  var cx = this._LXR[i];
1106
1273
 
1107
1274
  var forX = cx.forX;
1108
1275
 
1109
- if (k && k != forX['js']) continue;
1276
+ if (k && !this._forReads(cx, k)) continue;
1110
1277
 
1111
1278
  // 2026-09-21: real bug found and fixed — updateLXRs is async
1112
1279
  // and does `await this.createSection(...)` per item inside its
@@ -1162,13 +1329,18 @@ class _lm {
1162
1329
  }
1163
1330
  } else vals = clone(val);
1164
1331
 
1165
- if (this.typeStr(vals) == "array" && vals.length > 0) {
1332
+ // An empty (or non-array) value must still run the diff below so the rows rendered
1333
+ // by the previous pass are removed; it used to be skipped, leaving stale rows forever.
1334
+ if (this.typeStr(vals) != "array") vals = [];
1335
+ {
1166
1336
  // cl("ARRAY", cx.ref, vals);
1167
1337
  let forIf = cx.cond;
1168
1338
  let limit = vals.length;
1169
1339
  let offset = 0;
1170
- if (cx.limit) limit = (isNaN(cx.limit) ? cx.limit : limit) > vals.length ? vals.length : cx.limit * 1;
1171
- if (cx.offset) offset = (isNaN(cx.offset) ? cx.offset : offset) < 0 ? 0 : cx.offset * 1;
1340
+ const cxLimit = this._forNum(cx.limit);
1341
+ const cxOffset = this._forNum(cx.offset);
1342
+ if (cxLimit) limit = (isNaN(cxLimit) ? cxLimit : limit) > vals.length ? vals.length : cxLimit * 1;
1343
+ if (cxOffset) offset = (isNaN(cxOffset) ? cxOffset : offset) < 0 ? 0 : cxOffset * 1;
1172
1344
 
1173
1345
 
1174
1346
  let marray = [];
@@ -1203,6 +1375,10 @@ class _lm {
1203
1375
  vx['value'] = marray[index]['value'];
1204
1376
  } else {
1205
1377
  if (forX['as']['k']) vx[forX['as']['k']] = marray[index];
1378
+ // 2026-10-02: V1's createClone() spread an object item's own keys into the row scope
1379
+ // ALWAYS — with or without `as alias`, after the alias — so `:for="sectors as sector"`
1380
+ // with `{{Text}}` / `{{Category}}` in the template rendered the item's fields (dv2). V2
1381
+ // only spread for the bare form; `{{Text}}` then fell through to the DOM's Text constructor.
1206
1382
  // 2026-09-17, real bug found and fixed: a bare
1207
1383
  // `:for="items"` (no `as item` alias) is
1208
1384
  // documented — and was V1's real, working
@@ -1218,7 +1394,7 @@ class _lm {
1218
1394
  // a primitive (string/number) array item has no
1219
1395
  // keys to spread and is read via the untouched
1220
1396
  // alias path instead.
1221
- else if (marray[index] && typeof marray[index] === 'object') {
1397
+ if (marray[index] && typeof marray[index] === 'object' && !Array.isArray(marray[index])) {
1222
1398
  for (const k2 in marray[index]) {
1223
1399
  if (Object.prototype.hasOwnProperty.call(marray[index], k2)) {
1224
1400
  vx[k2] = marray[index][k2];
@@ -1390,7 +1566,7 @@ class _lm {
1390
1566
  if (tx) {
1391
1567
  tx.remove();
1392
1568
  tx.node.remove();
1393
- delete cx.tx?.nodes[keyed];
1569
+ delete cx.ref.nodes[keyed];
1394
1570
  // if(ref.isConnected){
1395
1571
  // } else if(ref.node.isConnected){
1396
1572
 
@@ -1415,6 +1591,12 @@ class _lm {
1415
1591
  // tx._re.reactiveVariables = [...tx._re.reactiveVariables, ...Object.keys(vx)];
1416
1592
  // cl("UPDATE", [tx], vx, tx._re);
1417
1593
  tx._re.vrs = vx;
1594
+ // view.vars is the creation-time vx and outranks vrs in getVal(); refresh it in place or it shadows the new item forever.
1595
+ let _rowVars = tx._re.view && tx._re.view.vars;
1596
+ if (_rowVars && _rowVars !== vx) {
1597
+ for (const _rk in _rowVars) if (!(_rk in vx)) delete _rowVars[_rk];
1598
+ Object.assign(_rowVars, vx);
1599
+ }
1418
1600
  if (tx.isObj) {
1419
1601
  if (tx.forX.as['k'] != "") tx._re.update(tx.forX.as['k']);
1420
1602
  else tx._re.update(tx.forX.js);
@@ -1426,16 +1608,12 @@ class _lm {
1426
1608
  }
1427
1609
  } else {
1428
1610
  if (tx.forX.as['k'] != "") tx._re.update(tx.forX.as['k']);
1429
- else {
1430
- tx._re.update(tx.forX.js);
1431
- // Bare :for="items" spreads each item's own
1432
- // keys into the row's scope, so the row's
1433
- // mustaches are keyed by those names — a key
1434
- // added or changed later ({{dateLeft}}) needs
1435
- // its own refresh.
1436
- for (const ik in vx) {
1437
- if (Object.prototype.hasOwnProperty.call(vx, ik) && ik !== tx.forX.js) tx._re.update(ik);
1438
- }
1611
+ else tx._re.update(tx.forX.js);
1612
+ // Each item's own keys are spread into the row's scope (bare and aliased loops alike,
1613
+ // as V1 did), so the row's mustaches can be keyed by those names: a key added or
1614
+ // changed later ({{dateLeft}}) needs its own refresh.
1615
+ for (const ik in vx) {
1616
+ if (Object.prototype.hasOwnProperty.call(vx, ik) && ik !== tx.forX.js && ik !== tx.forX.as['k']) tx._re.update(ik);
1439
1617
  }
1440
1618
  // cl("Updating", tx.forX);
1441
1619
  }
@@ -1454,9 +1632,6 @@ class _lm {
1454
1632
 
1455
1633
  if (actions.length) await fireRenderHook(cx, 'after-render', cx.ref.parentElement, { items: arrayToRender, actions });
1456
1634
 
1457
- } else {
1458
- // cl("NO ARRAY", cx.ref);
1459
- cx.nodes = [];
1460
1635
  }
1461
1636
  // if (cx.name == "if") {
1462
1637
  // let isTrue = this.evalExp(cx.value, this.reactiveVariables);
@@ -1898,7 +2073,8 @@ class _lm {
1898
2073
  }
1899
2074
 
1900
2075
  createEl(tag, attrs, children, events, doc) {
1901
- const _el = document.createElement(tag);
2076
+ // doc.svg: marked by the compiler for <svg> and its descendants (not <foreignObject> content).
2077
+ const _el = (doc && doc.svg) ? document.createElementNS(_SVG_NS, tag) : document.createElement(tag);
1902
2078
 
1903
2079
  // 2026-09-17: every element knows which _lm instance rendered it —
1904
2080
  // needed so a click on it can resolve its @click handler against
@@ -1979,7 +2155,10 @@ class _lm {
1979
2155
  // function, not defined inside the loop), so without
1980
2156
  // this there'd be no way for it to know which
1981
2157
  // iteration it's being called for at all.
1982
- let _initResult = evalEvAttr(_initAttr, { cType: 'init' }, $(_el), 'init', this.vrs);
2158
+ // A :for row keeps its alias/index on its section view's vars (vrs is still empty while the
2159
+ // row's own elements are being created), so hand over both.
2160
+ let _rowScope = Object.assign({}, (this.view && this.view.type === 'section' && this.view.vars) || {}, this.vrs || {});
2161
+ let _initResult = evalEvAttr(_initAttr, { cType: 'init' }, $(_el), 'init', _rowScope);
1983
2162
  if (_initResult && typeof _initResult === 'object' && typeof _initResult.then !== 'function') {
1984
2163
  Object.assign(_el.vars, _initResult);
1985
2164
  }
@@ -1994,9 +2173,9 @@ class _lm {
1994
2173
  try {
1995
2174
  // cl("DD", doc);
1996
2175
  let val = (doc && doc.ax.hasOwnProperty(prop)) ? "" : attrs[prop];
1997
- if (prop == "value") {
2176
+ if (prop == "value" && !(doc && doc.svg)) {
1998
2177
  _el.value = val;
1999
- } else _el.setAttribute(prop, val);
2178
+ } else _lmSetAttr(_el, prop, val);
2000
2179
  } catch (e) {
2001
2180
  cl(e);
2002
2181
  }
@@ -2213,8 +2392,9 @@ class _lm {
2213
2392
  (tx ?? (tx = [])).push(txnd);
2214
2393
  } else {
2215
2394
  let txnd = document.createTextNode("");
2216
- for (let ri = 0; ri < split.rvs.length; ri++) {
2217
- const element = split.rvs[ri];
2395
+ const _keys = split.rvs.length ? split.rvs : [_CONST_EFFECT];
2396
+ for (let ri = 0; ri < _keys.length; ri++) {
2397
+ const element = _keys[ri];
2218
2398
  (this._effects[element] ?? (this._effects[element] = [])).push({
2219
2399
  "type": "text",
2220
2400
  "content": split.content,
@@ -2232,11 +2412,12 @@ class _lm {
2232
2412
  return tx;
2233
2413
  } else {
2234
2414
  tx = document.createTextNode("");
2415
+ const _anyRv = doc.mss.some((m) => m.rvs.length);
2235
2416
  for (let mui = 0; mui < doc.mss.length; mui++) {
2236
2417
  const mus = doc.mss[mui];
2237
-
2238
- for (let ri = 0; ri < mus.rvs.length; ri++) {
2239
- const element = mus.rvs[ri];
2418
+ const _keys = mus.rvs.length ? mus.rvs : (!_anyRv && mui === 0 ? [_CONST_EFFECT] : []);
2419
+ for (let ri = 0; ri < _keys.length; ri++) {
2420
+ const element = _keys[ri];
2240
2421
  (this._effects[element] ?? (this._effects[element] = [])).push({
2241
2422
  "type": "text",
2242
2423
  "content": doc.content,
@@ -2369,7 +2550,7 @@ class _lm {
2369
2550
  }
2370
2551
  }
2371
2552
  } else if (doc.name.toLowerCase() == "script" || doc.name.toLowerCase() == "js") {
2372
- let child = doc.children[0];
2553
+ let child = doc.children[0] || {};
2373
2554
  let js = child.content;
2374
2555
  let jst = child.jst;
2375
2556
  let isScoped = false;
@@ -2543,11 +2724,13 @@ class _lm {
2543
2724
  for (const attrName in doc.ax) {
2544
2725
  if (Object.hasOwnProperty.call(doc.ax, attrName)) {
2545
2726
  const attrMustaches = doc.ax[attrName];
2727
+ const _anyRv = attrMustaches.some((m) => m.rvs.length);
2546
2728
  for (let i = 0; i < attrMustaches.length; i++) {
2547
2729
  const mus = attrMustaches[i];
2548
- for (let ri = 0; ri < mus.rvs.length; ri++) {
2549
- const element = mus.rvs[ri];
2550
- rvs.push(element);
2730
+ const _keys = mus.rvs.length ? mus.rvs : (!_anyRv && i === 0 ? [_CONST_EFFECT] : []);
2731
+ for (let ri = 0; ri < _keys.length; ri++) {
2732
+ const element = _keys[ri];
2733
+ if (element !== _CONST_EFFECT) rvs.push(element);
2551
2734
  (this._effects[element] ?? (this._effects[element] = [])).push({
2552
2735
  "type": "attr",
2553
2736
  "name": attrName,
@@ -2604,7 +2787,17 @@ class _lm {
2604
2787
 
2605
2788
  // cl("CREATE", cx.doc.name, cx.doc.attrs, [], cx.doc.evs, cx.doc);
2606
2789
 
2607
- let el = this.createEl(cx.doc.name, cx.doc.attrs, [], cx.doc.evs, cx.doc);
2790
+ // The row element itself is created by the loop's owner, before the row has its own engine: expose this
2791
+ // row's scope (alias, index) for the duration of the synchronous createEl(), so `@init` on a
2792
+ // `view=` row receives it like any other row-level code.
2793
+ let _ownerVrs = this.vrs;
2794
+ this.vrs = Object.assign({}, _ownerVrs || {}, vx || {});
2795
+ let el;
2796
+ try {
2797
+ el = this.createEl(cx.doc.name, cx.doc.attrs, [], cx.doc.evs, cx.doc);
2798
+ } finally {
2799
+ this.vrs = _ownerVrs;
2800
+ }
2608
2801
  tx.node = el;
2609
2802
  tx.key = cx.key;
2610
2803
  tx.keyed = keyed;
@@ -2626,6 +2819,9 @@ class _lm {
2626
2819
 
2627
2820
 
2628
2821
  let scsc = await renderSection(tx, cx.doc, this, cx.key);
2822
+ // The row element was created by the loop's owner (above); its @-handlers must resolve against THIS row's
2823
+ // engine (row alias, index) and fall back to the enclosing view through the engine chain.
2824
+ if (el && scsc) Object.defineProperty(el, '_ownerRe', { value: scsc, enumerable: false, configurable: true, writable: true });
2629
2825
  // cl(23);
2630
2826
  // cl(scsc);
2631
2827
  scsc._re = scsc;
@@ -2793,8 +2989,9 @@ async function renderHST(hst, n, type = 'main', tx, _pv = null, scopePath = ["Vi
2793
2989
  const jses = _re._jj[ky];
2794
2990
  for (let inde = 0; inde < jses.length; inde++) {
2795
2991
  const nd = jses[inde].nd;
2992
+ if (nd._jst === undefined) continue;
2796
2993
  let code = getWatcher(nd._jst, _re.view, reactiveVariables, scopePath).code;
2797
- code = `try { ` + code + ` } catch (e) { reportLumenError({ stage: 'script', error: e }); }`;
2994
+ code = `try { _lmSetViewVar(document.currentScript); ` + code + ` } catch (e) { reportLumenError({ stage: 'script', error: e }); }`;
2798
2995
  // sourceURL: DevTools shows this <script>'s errors against
2799
2996
  // "<viewname>.view" instead of an anonymous VM context.
2800
2997
  // 2026-09-14, real bug found testing a real project
@@ -3147,6 +3344,28 @@ async function renderSection(tx, doc, par, k, sectionsData) {
3147
3344
  // subview's own file content changed" caller (ws.js's hot-reload) bypass
3148
3345
  // the new already-mounted skip-gate; every routine caller (updateVXRs())
3149
3346
  // leaves it off and gets the gate.
3347
+ // `modal="some/view"` (lstnrs.js) builds its popup as raw HTML at click time, so no parse-time createEl() ever
3348
+ // registered the `<div view>` inside it and nothing would render it. Register it the way createEl() registers a
3349
+ // `view=` element (scope slots + an entry in the main view's `views`), then render it.
3350
+ // V1 gave every view-mounted (`view="..."`) view's <script> a global `view`: the jQuery-wrapped host element
3351
+ // (`view.scope(fn)`, `view.set()`, `view.props()`). A route's own script never had one, so only a subview host counts.
3352
+ function _lmSetViewVar(script) {
3353
+ for (let n = script && script.parentNode; n; n = n.parentNode) {
3354
+ if (n.isSub === true) { window.view = $(n); return; }
3355
+ }
3356
+ }
3357
+
3358
+ function mountModalView(el, name) {
3359
+ if (!el || !name) return Promise.resolve();
3360
+ el.isSub = true;
3361
+ el.subPath = prepareNode(name).split("?")[0];
3362
+ el.vars = {};
3363
+ el.views = [];
3364
+ el.fns = {};
3365
+ _vt.View.views.push(el);
3366
+ return renderView(name, true, {});
3367
+ }
3368
+
3150
3369
  async function renderView(n, isSub, d, type = 'views', viewsArr, scopeBase = ["View"], force = false) {
3151
3370
  let filePath = "src/views/" + n + ".view"
3152
3371
  if (type == 'layouts') filePath = "src/layouts/" + n + ".layout";