gyosjs 0.5.2 → 0.5.4

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.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/dist/core/composables.d.ts +3 -1
  3. package/dist/core/composables.d.ts.map +1 -1
  4. package/dist/core/portal.d.ts.map +1 -1
  5. package/dist/core/reactive.d.ts.map +1 -1
  6. package/dist/core/router/router.d.ts.map +1 -1
  7. package/dist/core/router/scroll.d.ts.map +1 -1
  8. package/dist/core/router/swap.d.ts.map +1 -1
  9. package/dist/core/scope-registry.d.ts.map +1 -1
  10. package/dist/form/form-validation.d.ts.map +1 -1
  11. package/dist/gyos.auto.esm.js +418 -215
  12. package/dist/gyos.auto.esm.js.map +1 -1
  13. package/dist/gyos.auto.js +418 -215
  14. package/dist/gyos.auto.js.map +1 -1
  15. package/dist/gyos.auto.min.js +2 -2
  16. package/dist/gyos.csp.auto.esm.js +434 -231
  17. package/dist/gyos.csp.auto.esm.js.map +1 -1
  18. package/dist/gyos.csp.auto.js +434 -231
  19. package/dist/gyos.csp.auto.js.map +1 -1
  20. package/dist/gyos.csp.auto.min.js +2 -2
  21. package/dist/gyos.csp.esm.js +434 -231
  22. package/dist/gyos.csp.esm.js.map +1 -1
  23. package/dist/gyos.csp.js +434 -231
  24. package/dist/gyos.csp.js.map +1 -1
  25. package/dist/gyos.csp.min.js +2 -2
  26. package/dist/gyos.esm.js +418 -215
  27. package/dist/gyos.esm.js.map +1 -1
  28. package/dist/gyos.js +418 -215
  29. package/dist/gyos.js.map +1 -1
  30. package/dist/gyos.min.js +2 -2
  31. package/dist/reactivity/signal.d.ts.map +1 -1
  32. package/dist/runtime/csp-evaluator.d.ts.map +1 -1
  33. package/dist/template/bindings.d.ts.map +1 -1
  34. package/dist/template/cleanup.d.ts +1 -0
  35. package/dist/template/cleanup.d.ts.map +1 -1
  36. package/dist/template/directives.d.ts.map +1 -1
  37. package/dist/template/effect-queue.d.ts +1 -1
  38. package/dist/template/effect-queue.d.ts.map +1 -1
  39. package/dist/template/events.d.ts.map +1 -1
  40. package/dist/template/process.d.ts.map +1 -1
  41. package/dist/template/structurals/structural.d.ts.map +1 -1
  42. package/dist/utils/helpers.d.ts.map +1 -1
  43. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.5.2
2
+ * GyosJS v0.5.4
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -6414,30 +6414,30 @@ function resolveReference(node, context, expression) {
6414
6414
  throw cspError('Invalid assignment target', expression, node);
6415
6415
  }
6416
6416
  function evaluateCall(node, context, expression) {
6417
- const args = node.arguments.map((argument) => {
6418
- if (argument.type === 'SpreadElement')
6419
- throw cspError('Spread arguments are not supported', expression, argument);
6420
- return evaluateNode(argument, context, expression);
6421
- });
6417
+ let receiver = context.scope;
6418
+ let callable;
6422
6419
  if (node.callee.type === 'MemberExpression') {
6423
6420
  const [object, property] = memberParts(node.callee, context, expression);
6424
6421
  if (object === optionalChainMiss)
6425
6422
  return optionalChainMiss;
6426
- const method = object[property];
6427
- if (method == null && node.optional)
6428
- return optionalChainMiss;
6429
- if (typeof method !== 'function')
6430
- throw cspError('Called value is not a function', expression, node.callee);
6431
- return method.apply(object, args);
6423
+ receiver = object;
6424
+ callable = object[property];
6425
+ }
6426
+ else {
6427
+ callable = evaluateNode(node.callee, context, expression);
6432
6428
  }
6433
- const callable = evaluateNode(node.callee, context, expression);
6434
6429
  if (callable === optionalChainMiss)
6435
6430
  return optionalChainMiss;
6436
6431
  if (callable == null && node.optional)
6437
6432
  return optionalChainMiss;
6433
+ const args = node.arguments.map((argument) => {
6434
+ if (argument.type === 'SpreadElement')
6435
+ throw cspError('Spread arguments are not supported', expression, argument);
6436
+ return evaluateNode(argument, context, expression);
6437
+ });
6438
6438
  if (typeof callable !== 'function')
6439
6439
  throw cspError('Called value is not a function', expression, node.callee);
6440
- return callable.apply(context.scope, args);
6440
+ return callable.apply(receiver, args);
6441
6441
  }
6442
6442
  function applyAssignment(operator, current, value, expression, node) {
6443
6443
  switch (operator) {
@@ -6560,10 +6560,10 @@ function evaluateNode(node, context, expression) {
6560
6560
  }
6561
6561
  case 'UpdateExpression': {
6562
6562
  const reference = resolveReference(node.argument, context, expression);
6563
- const current = reference.get();
6564
- const next = node.operator === '++' ? current + 1 : current - 1;
6563
+ let next = reference.get();
6564
+ const previous = node.operator === '++' ? next++ : next--;
6565
6565
  reference.set(next);
6566
- return node.prefix ? next : current;
6566
+ return node.prefix ? next : previous;
6567
6567
  }
6568
6568
  case 'SequenceExpression': {
6569
6569
  let value;
@@ -6733,25 +6733,30 @@ function clone(obj) {
6733
6733
  }
6734
6734
  const cloned = {};
6735
6735
  for (const key in obj) {
6736
- if (obj.hasOwnProperty(key)) {
6736
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
6737
6737
  cloned[key] = clone(obj[key]);
6738
6738
  }
6739
6739
  }
6740
6740
  return cloned;
6741
6741
  }
6742
6742
  function deepEqual(a, b) {
6743
- if (a === b)
6743
+ if (Object.is(a, b))
6744
6744
  return true;
6745
6745
  if (typeof a !== 'object' || typeof b !== 'object' || a == null || b == null) {
6746
6746
  return false;
6747
6747
  }
6748
+ if (a instanceof Date || b instanceof Date) {
6749
+ return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime());
6750
+ }
6751
+ if (Array.isArray(a) !== Array.isArray(b))
6752
+ return false;
6748
6753
  const keysA = Object.keys(a);
6749
6754
  const keysB = Object.keys(b);
6750
6755
  if (keysA.length !== keysB.length) {
6751
6756
  return false;
6752
6757
  }
6753
6758
  for (const key of keysA) {
6754
- if (!deepEqual(a[key], b[key])) {
6759
+ if (!Object.prototype.hasOwnProperty.call(b, key) || !deepEqual(a[key], b[key])) {
6755
6760
  return false;
6756
6761
  }
6757
6762
  }
@@ -7287,8 +7292,11 @@ function effect(fn) {
7287
7292
  execute.__dependencies = dependencies;
7288
7293
  execute.__versions = versions;
7289
7294
  try {
7290
- const nextCleanup = fn();
7291
- cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
7295
+ // The previous cleanup can dispose this effect before the next run.
7296
+ if (active) {
7297
+ const nextCleanup = fn();
7298
+ cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
7299
+ }
7292
7300
  }
7293
7301
  catch (error) {
7294
7302
  console.error('[Effect] Error in effect:', error);
@@ -7297,6 +7305,25 @@ function effect(fn) {
7297
7305
  finally {
7298
7306
  initialized = true;
7299
7307
  currentEffect = prevEffect;
7308
+ // stop() may have been called inside fn, before its cleanup was returned
7309
+ // or before later reads registered more dependencies.
7310
+ if (!active) {
7311
+ dependencies.forEach(dependency => dependency.delete(execute));
7312
+ dependencies.clear();
7313
+ versions.clear();
7314
+ effectQueue.delete(execute);
7315
+ batchedEffects.delete(execute);
7316
+ const finalCleanup = cleanup;
7317
+ cleanup = undefined;
7318
+ if (finalCleanup) {
7319
+ try {
7320
+ untrack(finalCleanup);
7321
+ }
7322
+ catch (error) {
7323
+ console.error('[Effect] Error in final cleanup:', error);
7324
+ }
7325
+ }
7326
+ }
7300
7327
  effectDepth--;
7301
7328
  runningEffects.delete(execute);
7302
7329
  // Flush queue when we're back to top level
@@ -7321,8 +7348,10 @@ function effect(fn) {
7321
7348
  dependencies.clear();
7322
7349
  versions.clear();
7323
7350
  if (cleanup) {
7351
+ const finalCleanup = cleanup;
7352
+ cleanup = undefined;
7324
7353
  try {
7325
- untrack(cleanup);
7354
+ untrack(finalCleanup);
7326
7355
  }
7327
7356
  catch (error) {
7328
7357
  console.error('[Effect] Error in final cleanup:', error);
@@ -8050,11 +8079,6 @@ function evaluateExpression(expr, scope, allowPipes = true) {
8050
8079
  * @returns Evaluated value
8051
8080
  */
8052
8081
  function evaluateSimpleExpression(expr, scope) {
8053
- // Handle string literals
8054
- if ((expr.startsWith("'") && expr.endsWith("'")) ||
8055
- (expr.startsWith('"') && expr.endsWith('"'))) {
8056
- return expr.slice(1, -1);
8057
- }
8058
8082
  // Handle numbers
8059
8083
  if (!isNaN(Number(expr))) {
8060
8084
  return Number(expr);
@@ -8101,6 +8125,8 @@ function unmountScope(el) {
8101
8125
  let instance = mountedScopes.get(el);
8102
8126
  if (!instance)
8103
8127
  return;
8128
+ // A hook may call cleanup again; each mount is disposed at most once.
8129
+ mountedScopes.delete(el);
8104
8130
  // Cleanup all effects
8105
8131
  if (instance.__gyos_effects__) {
8106
8132
  instance.__gyos_effects__.forEach((cleanup) => {
@@ -8115,7 +8141,12 @@ function unmountScope(el) {
8115
8141
  }
8116
8142
  // Call lifecycle hook
8117
8143
  if (instance.onUnmount) {
8118
- instance.onUnmount.call(instance);
8144
+ try {
8145
+ instance.onUnmount.call(instance);
8146
+ }
8147
+ catch (error) {
8148
+ console.error('[Component] Error in onUnmount:', error);
8149
+ }
8119
8150
  }
8120
8151
  // Clear reference on element
8121
8152
  el.__gyos_scope__ = null;
@@ -8152,6 +8183,9 @@ function currentQueue() {
8152
8183
  return effectQueueStack[effectQueueStack.length - 1];
8153
8184
  }
8154
8185
  function attachDispose(target, runner) {
8186
+ // An earlier queued content binding can replace this subtree during flush.
8187
+ if (!target.isConnected)
8188
+ return;
8155
8189
  const dispose = effect(runner);
8156
8190
  if (!target.__gyos_effects__) {
8157
8191
  target.__gyos_effects__ = [];
@@ -9071,6 +9105,125 @@ function applyLeaveTransition(element, scope, removeElement = true) {
9071
9105
  return transitionManager.leave(element, transitionConfig, removeElement);
9072
9106
  }
9073
9107
 
9108
+ /**
9109
+ * Portal/Teleport System - Render content in different DOM location
9110
+ * Useful for modals, tooltips, notifications that need to break out of parent containers
9111
+ *
9112
+ * @example
9113
+ * // Portal to body (for modals)
9114
+ * <div g-portal="body">
9115
+ * <div class="modal">Modal content</div>
9116
+ * </div>
9117
+ *
9118
+ * @example
9119
+ * // Portal to specific element
9120
+ * <div g-portal="#notifications">
9121
+ * <div class="toast">Toast message</div>
9122
+ * </div>
9123
+ */
9124
+ /**
9125
+ * Create a portal - Move element to target location
9126
+ *
9127
+ * @param sourceEl - Element to teleport
9128
+ * @param targetSelector - CSS selector for destination
9129
+ *
9130
+ * @example
9131
+ * portalCreate(modalEl, 'body');
9132
+ * portalCreate(tooltipEl, '#tooltip-container');
9133
+ */
9134
+ function portalCreate(sourceEl, targetSelector) {
9135
+ if (!sourceEl)
9136
+ return;
9137
+ const target = document.querySelector(targetSelector);
9138
+ if (!target) {
9139
+ console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
9140
+ return;
9141
+ }
9142
+ // Create placeholder comment to mark original position
9143
+ const placeholder = document.createComment('g-portal');
9144
+ sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
9145
+ // Store original parent for restoration
9146
+ sourceEl.__portal_placeholder__ = placeholder;
9147
+ sourceEl.__portal_target__ = target;
9148
+ placeholder.__gyos_portal__ = sourceEl;
9149
+ // Move the entire element to target
9150
+ target.appendChild(sourceEl);
9151
+ DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
9152
+ }
9153
+ /**
9154
+ * Destroy a portal - Restore element to original position
9155
+ *
9156
+ * @param sourceEl - Element to restore
9157
+ *
9158
+ * @example
9159
+ * portalDestroy(modalEl); // Returns modal to original location
9160
+ */
9161
+ function portalDestroy(sourceEl) {
9162
+ if (!sourceEl)
9163
+ return;
9164
+ const placeholder = sourceEl.__portal_placeholder__;
9165
+ if (placeholder && placeholder.parentNode) {
9166
+ delete placeholder.__gyos_portal__;
9167
+ // Move element back to original position
9168
+ placeholder.parentNode.insertBefore(sourceEl, placeholder);
9169
+ placeholder.remove();
9170
+ delete sourceEl.__portal_placeholder__;
9171
+ delete sourceEl.__portal_target__;
9172
+ DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
9173
+ }
9174
+ }
9175
+
9176
+ /**
9177
+ * Cleanup utilities for disposing effects and event listeners
9178
+ */
9179
+ /**
9180
+ * Dispose all effects attached to an element and its descendants
9181
+ * Handles both element effects (__gyos_effects__) and component lifecycle
9182
+ */
9183
+ function disposeEffects(element = document.body, removeElement = false) {
9184
+ if (!element)
9185
+ return;
9186
+ disposeNode(element);
9187
+ if (removeElement)
9188
+ element.remove();
9189
+ }
9190
+ function disposeNode(element, removeElement = false) {
9191
+ untrack(() => disposeNodeInternal(element, removeElement));
9192
+ }
9193
+ function disposeNodeInternal(element, removeElement = false) {
9194
+ const portal = element.__gyos_portal__;
9195
+ if (portal) {
9196
+ delete element.__gyos_portal__;
9197
+ disposeNode(portal, removeElement);
9198
+ }
9199
+ // Include structural comment anchors. Snapshot before hooks mutate the tree.
9200
+ const children = Array.from(element.childNodes);
9201
+ const effects = element.__gyos_effects__;
9202
+ // Release ownership before callbacks to make reentrant cleanup safe.
9203
+ element.__gyos_effects__ = null;
9204
+ // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
9205
+ if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
9206
+ unmountScope(element);
9207
+ }
9208
+ // Dispose effects on this element (template effects like g-show, :class, {text})
9209
+ if (effects) {
9210
+ effects.forEach((dispose) => {
9211
+ try {
9212
+ dispose();
9213
+ }
9214
+ catch (error) {
9215
+ console.error('[GyosJS] Error disposing effect:', error);
9216
+ }
9217
+ });
9218
+ }
9219
+ // Recursively dispose effects on all descendants
9220
+ children.forEach(child => disposeNode(child));
9221
+ // Restore a portal to its placeholder before removing the owning tree.
9222
+ portalDestroy(element);
9223
+ if (removeElement)
9224
+ element.parentNode?.removeChild(element);
9225
+ }
9226
+
9074
9227
  /**
9075
9228
  * Directive Processing
9076
9229
  * Handles built-in directives (g-show, g-html, g-text) and custom directives
@@ -9132,6 +9285,7 @@ function processDirectives(element, scope, root) {
9132
9285
  const expr = element.getAttribute('g-html');
9133
9286
  queueReactiveEffect(element, () => {
9134
9287
  const value = evaluateExpression(expr, scope);
9288
+ Array.from(element.childNodes).forEach(child => disposeNode(child));
9135
9289
  element.innerHTML = value;
9136
9290
  });
9137
9291
  }
@@ -9140,6 +9294,7 @@ function processDirectives(element, scope, root) {
9140
9294
  const expr = element.getAttribute('g-text');
9141
9295
  queueReactiveEffect(element, () => {
9142
9296
  const value = evaluateExpression(expr, scope);
9297
+ Array.from(element.childNodes).forEach(child => disposeNode(child));
9143
9298
  element.textContent = value;
9144
9299
  });
9145
9300
  }
@@ -9217,7 +9372,7 @@ function processDirectives(element, scope, root) {
9217
9372
  * @param scope - Scope object for evaluation
9218
9373
  */
9219
9374
  function processDirectivesStatic(el, scope) {
9220
- const directives = Array.from(el.querySelectorAll('[g-show], [g-html], [g-text]'))
9375
+ const directives = [el, ...el.querySelectorAll('[g-show], [g-html], [g-text]')]
9221
9376
  .filter(element => !isInIgnoredTree(element));
9222
9377
  directives.forEach(elem => {
9223
9378
  const element = elem;
@@ -9294,7 +9449,9 @@ function readStyleValues(style) {
9294
9449
  return values;
9295
9450
  }
9296
9451
  function normalizeStyleProperty(property) {
9297
- if (property.startsWith('--') || property.includes('-'))
9452
+ if (property.startsWith('--'))
9453
+ return property;
9454
+ if (property.includes('-'))
9298
9455
  return property.toLowerCase();
9299
9456
  return property.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
9300
9457
  }
@@ -9473,72 +9630,6 @@ function processBindingsStatic(root, scope) {
9473
9630
  }
9474
9631
  }
9475
9632
 
9476
- /**
9477
- * Portal/Teleport System - Render content in different DOM location
9478
- * Useful for modals, tooltips, notifications that need to break out of parent containers
9479
- *
9480
- * @example
9481
- * // Portal to body (for modals)
9482
- * <div g-portal="body">
9483
- * <div class="modal">Modal content</div>
9484
- * </div>
9485
- *
9486
- * @example
9487
- * // Portal to specific element
9488
- * <div g-portal="#notifications">
9489
- * <div class="toast">Toast message</div>
9490
- * </div>
9491
- */
9492
- /**
9493
- * Create a portal - Move element to target location
9494
- *
9495
- * @param sourceEl - Element to teleport
9496
- * @param targetSelector - CSS selector for destination
9497
- *
9498
- * @example
9499
- * portalCreate(modalEl, 'body');
9500
- * portalCreate(tooltipEl, '#tooltip-container');
9501
- */
9502
- function portalCreate(sourceEl, targetSelector) {
9503
- if (!sourceEl)
9504
- return;
9505
- const target = document.querySelector(targetSelector);
9506
- if (!target) {
9507
- console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
9508
- return;
9509
- }
9510
- // Create placeholder comment to mark original position
9511
- const placeholder = document.createComment('g-portal');
9512
- sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
9513
- // Store original parent for restoration
9514
- sourceEl.__portal_placeholder__ = placeholder;
9515
- sourceEl.__portal_target__ = target;
9516
- // Move the entire element to target
9517
- target.appendChild(sourceEl);
9518
- DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
9519
- }
9520
- /**
9521
- * Destroy a portal - Restore element to original position
9522
- *
9523
- * @param sourceEl - Element to restore
9524
- *
9525
- * @example
9526
- * portalDestroy(modalEl); // Returns modal to original location
9527
- */
9528
- function portalDestroy(sourceEl) {
9529
- if (!sourceEl)
9530
- return;
9531
- const placeholder = sourceEl.__portal_placeholder__;
9532
- if (placeholder && placeholder.parentNode) {
9533
- // Move element back to original position
9534
- placeholder.parentNode.insertBefore(sourceEl, placeholder);
9535
- placeholder.remove();
9536
- delete sourceEl.__portal_placeholder__;
9537
- delete sourceEl.__portal_target__;
9538
- DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
9539
- }
9540
- }
9541
-
9542
9633
  /**
9543
9634
  * Validator registry
9544
9635
  */
@@ -9724,7 +9815,7 @@ validator('maxLength', (value, length) => {
9724
9815
  * @example "min(18)"
9725
9816
  */
9726
9817
  validator('min', (value, min) => {
9727
- if (!value)
9818
+ if (value == null || value === '')
9728
9819
  return true;
9729
9820
  const minVal = parseFloat(min);
9730
9821
  return parseFloat(value) >= minVal || `Minimum value is ${minVal}`;
@@ -9735,7 +9826,7 @@ validator('min', (value, min) => {
9735
9826
  * @example "max(100)"
9736
9827
  */
9737
9828
  validator('max', (value, max) => {
9738
- if (!value)
9829
+ if (value == null || value === '')
9739
9830
  return true;
9740
9831
  const maxVal = parseFloat(max);
9741
9832
  return parseFloat(value) <= maxVal || `Maximum value is ${maxVal}`;
@@ -9756,9 +9847,9 @@ validator('number', (value) => {
9756
9847
  * @example "integer"
9757
9848
  */
9758
9849
  validator('integer', (value) => {
9759
- if (!value)
9850
+ if (value == null || value === '')
9760
9851
  return true;
9761
- return Number.isInteger(parseFloat(value)) || 'Must be an integer';
9852
+ return (String(value).trim() !== '' && Number.isInteger(Number(value))) || 'Must be an integer';
9762
9853
  });
9763
9854
  /**
9764
9855
  * Numeric - Must contain only digits
@@ -9871,7 +9962,7 @@ validator('date', (value) => {
9871
9962
  return 'Invalid date format (use YYYY-MM-DD)';
9872
9963
  }
9873
9964
  const date = new Date(value);
9874
- return !isNaN(date.getTime()) || 'Invalid date';
9965
+ return (!isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value) || 'Invalid date';
9875
9966
  });
9876
9967
  /**
9877
9968
  * Before - Date must be before specified date
@@ -9951,7 +10042,7 @@ validator('notIn', (value, ...forbiddenValues) => {
9951
10042
  * @example "between(18,65)"
9952
10043
  */
9953
10044
  validator('between', (value, min, max) => {
9954
- if (!value)
10045
+ if (value == null || value === '')
9955
10046
  return true;
9956
10047
  const num = parseFloat(value);
9957
10048
  const minVal = parseFloat(min);
@@ -10205,8 +10296,16 @@ function processValidateDirective(el) {
10205
10296
  // Initialize error state - direct mutation
10206
10297
  state.errors.value[modelAttr] = null;
10207
10298
  state.touched.value[modelAttr] = false;
10208
- // Validation function
10209
- const validateField = async () => {
10299
+ let active = true;
10300
+ let generation = 0;
10301
+ let timeout;
10302
+ let latestValidation = Promise.resolve();
10303
+ // Each control publishes only its newest result. validateAll also waits for
10304
+ // a newer validation that superseded the request it originally started.
10305
+ const runValidation = async () => {
10306
+ if (!active)
10307
+ return;
10308
+ const request = ++generation;
10210
10309
  const value = getControlValue(el, form);
10211
10310
  // Get form context for validators that need it (like 'same')
10212
10311
  const formData = {};
@@ -10221,7 +10320,26 @@ function processValidateDirective(el) {
10221
10320
  }
10222
10321
  }
10223
10322
  });
10224
- const error = await validate(value, rules, { form: formData, field: modelAttr });
10323
+ let error;
10324
+ try {
10325
+ error = await validate(value, rules, { form: formData, field: modelAttr });
10326
+ }
10327
+ catch (cause) {
10328
+ console.error('[GyosJS] Field validation failed:', cause);
10329
+ error = 'Validation failed. Please try again.';
10330
+ }
10331
+ if (!active)
10332
+ return;
10333
+ if (request !== generation) {
10334
+ await latestValidation;
10335
+ return;
10336
+ }
10337
+ // Input may have changed while its debounce timer has not fired yet.
10338
+ // A submit must validate the current value before publishing approval.
10339
+ if (value !== getControlValue(el, form)) {
10340
+ await validateField();
10341
+ return;
10342
+ }
10225
10343
  // Update errors - only if changed
10226
10344
  const currentErrors = state.errors.value;
10227
10345
  if (currentErrors[modelAttr] !== error) {
@@ -10231,6 +10349,12 @@ function processValidateDirective(el) {
10231
10349
  updateFormState(state);
10232
10350
  }
10233
10351
  };
10352
+ const validateField = () => {
10353
+ clearTimeout(timeout);
10354
+ timeout = undefined;
10355
+ latestValidation = runValidation();
10356
+ return latestValidation;
10357
+ };
10234
10358
  // Register validator for validateAll
10235
10359
  if (!formValidators.has(form)) {
10236
10360
  formValidators.set(form, []);
@@ -10248,7 +10372,6 @@ function processValidateDirective(el) {
10248
10372
  };
10249
10373
  el.addEventListener('blur', blurListener);
10250
10374
  // Validate on input (with debounce)
10251
- let timeout;
10252
10375
  const inputListener = () => {
10253
10376
  clearTimeout(timeout);
10254
10377
  timeout = setTimeout(() => {
@@ -10260,6 +10383,24 @@ function processValidateDirective(el) {
10260
10383
  el.__gyos_effects__ = [];
10261
10384
  }
10262
10385
  el.__gyos_effects__.push(() => {
10386
+ active = false;
10387
+ generation++;
10388
+ delete el[validationFieldKey];
10389
+ const validators = formValidators.get(form);
10390
+ const index = validators?.indexOf(validateField) ?? -1;
10391
+ if (index !== -1)
10392
+ validators.splice(index, 1);
10393
+ const sharesField = Array.from(form.querySelectorAll('input, textarea, select'))
10394
+ .some(control => control[validationFieldKey] === modelAttr);
10395
+ if (!sharesField) {
10396
+ const errors = { ...state.errors.peek };
10397
+ delete errors[modelAttr];
10398
+ const touched = { ...state.touched.peek };
10399
+ delete touched[modelAttr];
10400
+ state.errors.value = errors;
10401
+ state.touched.value = touched;
10402
+ updateFormState(state);
10403
+ }
10263
10404
  el.removeEventListener('blur', blurListener);
10264
10405
  el.removeEventListener('input', inputListener);
10265
10406
  clearTimeout(timeout);
@@ -10332,7 +10473,9 @@ function processFormValidation(root, scope) {
10332
10473
  processFormDirective(root, scope);
10333
10474
  }
10334
10475
  // Then process g-validate
10335
- root.querySelectorAll('[g-validate]').forEach(el => {
10476
+ [root, ...root.querySelectorAll('[g-validate]')].forEach(el => {
10477
+ if (!el.hasAttribute('g-validate'))
10478
+ return;
10336
10479
  if (isInIgnoredTree(el))
10337
10480
  return;
10338
10481
  if (el instanceof HTMLElement) {
@@ -10340,7 +10483,9 @@ function processFormValidation(root, scope) {
10340
10483
  }
10341
10484
  });
10342
10485
  // Finally process g-errors
10343
- root.querySelectorAll('[g-errors]').forEach(el => {
10486
+ [root, ...root.querySelectorAll('[g-errors]')].forEach(el => {
10487
+ if (!el.hasAttribute('g-errors'))
10488
+ return;
10344
10489
  if (isInIgnoredTree(el))
10345
10490
  return;
10346
10491
  if (el instanceof HTMLElement) {
@@ -10371,12 +10516,13 @@ const RESERVED_MODIFIERS = new Set(['prevent', 'stop', 'once', 'capture', 'passi
10371
10516
  /**
10372
10517
  * Execute handler with modifiers (prevent, stop)
10373
10518
  */
10374
- function executeHandler(handler, scope, e, modifiers) {
10375
- // Handle prevent/stop modifiers
10519
+ function applyEventModifiers(e, modifiers) {
10376
10520
  if (modifiers.includes('prevent'))
10377
10521
  e.preventDefault();
10378
10522
  if (modifiers.includes('stop'))
10379
10523
  e.stopPropagation();
10524
+ }
10525
+ function executeHandler(handler, scope, e) {
10380
10526
  try {
10381
10527
  expressionRuntime().execute(handler, scope, e);
10382
10528
  }
@@ -10466,10 +10612,11 @@ function setupClickOutsideHandler(element, handler, modifiers, scope, attrName)
10466
10612
  if (target instanceof Element && target.closest('[g-ignore-outside-click]'))
10467
10613
  return;
10468
10614
  if (element !== target && !element.contains(target)) {
10615
+ applyEventModifiers(e, modifiers);
10469
10616
  const currentScope = getScopeFromElement(element) || scope;
10470
10617
  if (modifiers.includes('once'))
10471
10618
  cleanup();
10472
- executeHandler(handler, currentScope, e, modifiers);
10619
+ executeHandler(handler, currentScope, e);
10473
10620
  }
10474
10621
  };
10475
10622
  // Cleanup function
@@ -10546,13 +10693,14 @@ function processEvents(el, scope) {
10546
10693
  return; // Key doesn't match, skip
10547
10694
  }
10548
10695
  // Execute handler with optional debounce
10696
+ applyEventModifiers(e, modifiers);
10549
10697
  const execute = () => {
10550
10698
  if (modifiers.includes('once'))
10551
10699
  cleanup();
10552
10700
  // Batch in case handler mutates multiple signals
10553
10701
  batch(() => {
10554
10702
  const currentScope = getScopeFromElement(element) || scope;
10555
- executeHandler(handler, currentScope, e, modifiers);
10703
+ executeHandler(handler, currentScope, e);
10556
10704
  });
10557
10705
  };
10558
10706
  if (debounceMs > 0) {
@@ -10802,60 +10950,6 @@ function processModel(element, scope, root) {
10802
10950
  element.removeAttribute(modelAttr.name);
10803
10951
  }
10804
10952
 
10805
- /**
10806
- * Cleanup utilities for disposing effects and event listeners
10807
- */
10808
- /**
10809
- * Dispose all effects attached to an element and its descendants
10810
- * Handles both element effects (__gyos_effects__) and component lifecycle
10811
- */
10812
- function disposeEffects(element = document.body, removeElement = false) {
10813
- if (!element)
10814
- return;
10815
- // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
10816
- if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
10817
- unmountScope(element);
10818
- }
10819
- // Dispose effects on this element (template effects like g-show, :class, {text})
10820
- if (element.__gyos_effects__) {
10821
- const effects = element.__gyos_effects__;
10822
- effects.forEach((dispose) => {
10823
- try {
10824
- dispose();
10825
- }
10826
- catch (error) {
10827
- console.error('[GyosJS] Error disposing effect:', error);
10828
- }
10829
- });
10830
- element.__gyos_effects__ = null;
10831
- }
10832
- // Recursively dispose effects on all descendants
10833
- const descendants = element.querySelectorAll('*');
10834
- descendants.forEach((child) => {
10835
- // Unmount child scopes
10836
- if (child.hasAttribute?.('g-scope') || child.__gyos_scope__) {
10837
- unmountScope(child);
10838
- }
10839
- // Dispose child template effects
10840
- if (child.__gyos_effects__) {
10841
- const effects = child.__gyos_effects__;
10842
- effects.forEach((dispose) => {
10843
- try {
10844
- dispose();
10845
- }
10846
- catch (error) {
10847
- console.error('[GyosJS] Error disposing child effect:', error);
10848
- }
10849
- });
10850
- child.__gyos_effects__ = null;
10851
- }
10852
- });
10853
- // portal cleanup could be added here if needed
10854
- portalDestroy(element);
10855
- if (removeElement)
10856
- element.remove();
10857
- }
10858
-
10859
10953
  const storeCache = new WeakMap();
10860
10954
  const reactiveProxies = new WeakSet();
10861
10955
  const fieldSignals = new WeakMap();
@@ -10870,7 +10964,7 @@ function bumpScopeVersion(target) {
10870
10964
  if (visited.has(ver))
10871
10965
  return;
10872
10966
  visited.add(ver);
10873
- ver.value = ver.value + 1;
10967
+ ver.update(value => value + 1);
10874
10968
  const parents = versionParents.get(ver);
10875
10969
  if (parents) {
10876
10970
  parents.forEach(parentVer => bumpSignal(parentVer));
@@ -10908,7 +11002,7 @@ function getFieldSignal(target, key, initial) {
10908
11002
  }
10909
11003
  const STORE_MARKER = Symbol.for('gyos.store');
10910
11004
  function markStore(obj) {
10911
- if (obj.hasOwnProperty(STORE_MARKER))
11005
+ if (Object.prototype.hasOwnProperty.call(obj, STORE_MARKER))
10912
11006
  return obj;
10913
11007
  Reflect.defineProperty(obj, STORE_MARKER, {
10914
11008
  value: true,
@@ -10922,7 +11016,7 @@ function isStoreObject(val) {
10922
11016
  // markRaw: đánh dấu object để reactive() bỏ qua, không tạo proxy
10923
11017
  const RAW_MARKER = Symbol.for('gyos.raw');
10924
11018
  function markRaw(obj) {
10925
- if (obj.hasOwnProperty(RAW_MARKER))
11019
+ if (Object.prototype.hasOwnProperty.call(obj, RAW_MARKER))
10926
11020
  return obj;
10927
11021
  Reflect.defineProperty(obj, RAW_MARKER, {
10928
11022
  value: true,
@@ -10936,7 +11030,7 @@ function isRawObject(val) {
10936
11030
  // shallow: chỉ reactive "lớp ngoài", không reactive sâu bên trong
10937
11031
  const SHALLOW_MARKER = Symbol.for('gyos.shallow');
10938
11032
  function shallow(obj) {
10939
- if (obj.hasOwnProperty(SHALLOW_MARKER))
11033
+ if (Object.prototype.hasOwnProperty.call(obj, SHALLOW_MARKER))
10940
11034
  return obj;
10941
11035
  Reflect.defineProperty(obj, SHALLOW_MARKER, {
10942
11036
  value: true,
@@ -10970,6 +11064,25 @@ function linkParentVersion(child, parentVersion) {
10970
11064
  }
10971
11065
  versionParentsSet.add(parentVersion);
10972
11066
  }
11067
+ // Array [[DefineOwnProperty]] can change length or remove indices without
11068
+ // entering their individual Proxy traps. Keep already observed fields current.
11069
+ function syncArrayFields(target, previousLength) {
11070
+ if (previousLength === undefined)
11071
+ return;
11072
+ const array = target;
11073
+ if (array.length === previousLength)
11074
+ return;
11075
+ const signals = fieldSignals.get(target);
11076
+ signals?.get('length')?.update(() => array.length);
11077
+ if (array.length < previousLength) {
11078
+ signals?.forEach((sig, key) => {
11079
+ if (typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key)
11080
+ && Number(key) >= array.length && Number(key) < previousLength) {
11081
+ sig.update(() => Reflect.get(target, key));
11082
+ }
11083
+ });
11084
+ }
11085
+ }
10973
11086
  function reactive(raw) {
10974
11087
  if (!raw || typeof raw !== "object" || isBuiltInObject(raw)) {
10975
11088
  return raw;
@@ -11007,6 +11120,8 @@ function reactive(raw) {
11007
11120
  return value;
11008
11121
  }
11009
11122
  if (isStoreObject(value)) {
11123
+ if (hasCurrentEffect())
11124
+ getFieldSignal(target, key, value).value;
11010
11125
  return value;
11011
11126
  }
11012
11127
  // Check if this is a getter property (computed property)
@@ -11083,10 +11198,6 @@ function reactive(raw) {
11083
11198
  }
11084
11199
  // capture old value BEFORE write to detect real changes
11085
11200
  const oldValue = target[key];
11086
- // VALUE LÀ STORE → set thẳng, KHÔNG tạo signal, KHÔNG trigger
11087
- if (isStoreObject(value)) {
11088
- return Reflect.set(target, key, value, receiver);
11089
- }
11090
11201
  const ok = Reflect.set(target, key, value, receiver);
11091
11202
  if (!ok)
11092
11203
  return false;
@@ -11128,7 +11239,9 @@ function reactive(raw) {
11128
11239
  const oldDesc = Object.getOwnPropertyDescriptor(target, key);
11129
11240
  const oldValue = oldDesc && "value" in oldDesc ? oldDesc.value : undefined;
11130
11241
  const newValue = "value" in descriptor ? descriptor.value : oldValue;
11242
+ const previousLength = Array.isArray(target) ? target.length : undefined;
11131
11243
  const ok = Reflect.defineProperty(target, key, descriptor);
11244
+ syncArrayFields(target, previousLength);
11132
11245
  if (!ok)
11133
11246
  return false;
11134
11247
  if ('value' in descriptor) {
@@ -11154,7 +11267,7 @@ function makeReactive(source) {
11154
11267
  // tạo 1 version signal cho root scope
11155
11268
  const version = ensureVersion(source);
11156
11269
  const proxy = reactive(source);
11157
- if (!proxy.hasOwnProperty(SCOPE_VERSION)) {
11270
+ if (!Object.prototype.hasOwnProperty.call(proxy, SCOPE_VERSION)) {
11158
11271
  Object.defineProperty(proxy, SCOPE_VERSION, {
11159
11272
  value: version,
11160
11273
  enumerable: false,
@@ -11276,6 +11389,20 @@ function getCachedTemplate(template) {
11276
11389
  function setRootScope(element, scope) {
11277
11390
  element.__gyos_scope__ = scope;
11278
11391
  }
11392
+ function inheritScope(child, parent) {
11393
+ attachParentScope(child, parent);
11394
+ for (const key in parent) {
11395
+ if (!(key in child)) {
11396
+ Object.defineProperty(child, key, {
11397
+ get: () => parent[key],
11398
+ set: value => { parent[key] = value; },
11399
+ enumerable: true,
11400
+ configurable: true,
11401
+ });
11402
+ }
11403
+ }
11404
+ return child;
11405
+ }
11279
11406
  /**
11280
11407
  * Create child scope for *for loops
11281
11408
  * Inherits parent scope properties via getters
@@ -11346,13 +11473,15 @@ function processForDirective(element, currentScope) {
11346
11473
  template.removeAttribute('g-key');
11347
11474
  const placeholder = document.createComment('*for');
11348
11475
  element.parentNode?.replaceChild(placeholder, element);
11476
+ const end = document.createComment('/*for');
11477
+ placeholder.parentNode?.insertBefore(end, placeholder.nextSibling);
11349
11478
  // Store previous items for key-based diffing
11350
11479
  // WARNING: Use primitive keys (id, string, number) to avoid memory leaks
11351
11480
  // Object keys will prevent garbage collection
11352
11481
  let prevItemsMap = new Map();
11353
11482
  let prevListRef = null;
11354
11483
  let prevVersionValue = undefined;
11355
- queueReactiveEffect(element, () => {
11484
+ queueReactiveEffect(placeholder, () => {
11356
11485
  // Parse: "item in items" or "item, index in items"
11357
11486
  const match = expr.match(/(.+?)\s+in\s+(.+)/);
11358
11487
  if (!match)
@@ -11379,7 +11508,7 @@ function processForDirective(element, currentScope) {
11379
11508
  }
11380
11509
  else {
11381
11510
  // Simple re-render (no diffing)
11382
- processForSimple(placeholder, template, list, itemVar, currentScope);
11511
+ processForSimple(placeholder, end, template, list, itemVar, currentScope);
11383
11512
  }
11384
11513
  });
11385
11514
  });
@@ -11486,16 +11615,19 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
11486
11615
  /**
11487
11616
  * Process *for without keys (simple re-render)
11488
11617
  */
11489
- function processForSimple(placeholder, template, list, itemVar, currentScope) {
11618
+ function processForSimple(placeholder, end, template, list, itemVar, currentScope) {
11490
11619
  // Remove all existing items
11491
11620
  let next = placeholder.nextSibling;
11492
- while (next && next.nodeType !== Node.COMMENT_NODE) {
11621
+ while (next && next !== end) {
11493
11622
  const toRemove = next;
11494
11623
  next = next.nextSibling;
11495
11624
  if (toRemove instanceof Element) {
11496
11625
  unmountChildScopes(toRemove);
11497
11626
  disposeEffects(toRemove, true);
11498
11627
  }
11628
+ else {
11629
+ disposeNode(toRemove, true);
11630
+ }
11499
11631
  }
11500
11632
  // Render new items
11501
11633
  // Track last inserted node to maintain order
@@ -11588,7 +11720,7 @@ function processIfChain(element, currentScope) {
11588
11720
  element.parentNode?.replaceChild(placeholder, element);
11589
11721
  let currentElement = null;
11590
11722
  let currentIndex = -1;
11591
- queueReactiveEffect(element, () => {
11723
+ queueReactiveEffect(placeholder, () => {
11592
11724
  // Find first truthy condition
11593
11725
  let matchedIndex = -1;
11594
11726
  for (let i = 0; i < templates.length; i++) {
@@ -11714,14 +11846,13 @@ function processSwitchDirective(element, currentScope) {
11714
11846
  const switchValue = evaluateExpression(switchExpr, currentScope, false);
11715
11847
  // Find matching case
11716
11848
  let matchedIndex = -1;
11849
+ let defaultIndex = -1;
11717
11850
  for (let i = 0; i < templates.length; i++) {
11718
11851
  const { value } = templates[i];
11719
11852
  if (value === null) {
11720
- // *default matches (only if no other case matched)
11721
- if (matchedIndex === -1) {
11722
- matchedIndex = i;
11723
- }
11724
- break;
11853
+ if (defaultIndex === -1)
11854
+ defaultIndex = i;
11855
+ continue;
11725
11856
  }
11726
11857
  const caseValue = evaluateExpression(value, currentScope, false);
11727
11858
  if (switchValue === caseValue) {
@@ -11729,6 +11860,8 @@ function processSwitchDirective(element, currentScope) {
11729
11860
  break;
11730
11861
  }
11731
11862
  }
11863
+ if (matchedIndex === -1)
11864
+ matchedIndex = defaultIndex;
11732
11865
  // If same case, do nothing
11733
11866
  if (matchedIndex === currentIndex)
11734
11867
  return;
@@ -11847,6 +11980,7 @@ function processAwaitDirective(element, currentScope) {
11847
11980
  let requestVersion = 0;
11848
11981
  // Helper to render state
11849
11982
  const renderState = (state, data) => {
11983
+ currentState = state;
11850
11984
  // Remove old element
11851
11985
  if (currentElement) {
11852
11986
  const elemToRemove = currentElement;
@@ -11872,20 +12006,19 @@ function processAwaitDirective(element, currentScope) {
11872
12006
  else if (state === 'fulfilled' && thenTemplate) {
11873
12007
  template = thenTemplate.template;
11874
12008
  // Create child scope with data if varName provided
11875
- if (thenTemplate.varName && data !== undefined) {
11876
- scope = { ...currentScope, [thenTemplate.varName]: data };
12009
+ if (thenTemplate.varName) {
12010
+ scope = inheritScope({ [thenTemplate.varName]: data }, currentScope);
11877
12011
  }
11878
12012
  }
11879
12013
  else if (state === 'rejected' && catchTemplate) {
11880
12014
  template = catchTemplate.template;
11881
12015
  // Create child scope with error if varName provided
11882
- if (catchTemplate.varName && data !== undefined) {
11883
- scope = { ...currentScope, [catchTemplate.varName]: data };
12016
+ if (catchTemplate.varName) {
12017
+ scope = inheritScope({ [catchTemplate.varName]: data }, currentScope);
11884
12018
  }
11885
12019
  }
11886
12020
  if (template) {
11887
12021
  currentElement = getCachedTemplate(template);
11888
- currentState = state;
11889
12022
  setRootScope(currentElement, scope);
11890
12023
  // Apply transition initial state
11891
12024
  const elementsWithTransition = findElementsWithTransition(currentElement);
@@ -11913,8 +12046,6 @@ function processAwaitDirective(element, currentScope) {
11913
12046
  }
11914
12047
  }
11915
12048
  };
11916
- // Initial state: pending
11917
- renderState('pending');
11918
12049
  // Track promise expression
11919
12050
  queueReactiveEffect(element, () => {
11920
12051
  const promiseOrValue = evaluateExpression(awaitExpr, currentScope, false);
@@ -11938,6 +12069,8 @@ function processAwaitDirective(element, currentScope) {
11938
12069
  renderState('rejected', error);
11939
12070
  }
11940
12071
  });
12072
+ // Both reruns and disposal invalidate callbacks from this request.
12073
+ return () => { requestVersion++; };
11941
12074
  });
11942
12075
  }
11943
12076
 
@@ -12005,6 +12138,9 @@ function processStructuralDirectives(elements, scope) {
12005
12138
  structuralElements.sort((a, b) => a.depth - b.depth);
12006
12139
  // Process each structural directive
12007
12140
  structuralElements.forEach(({ element, type }) => {
12141
+ // Parent directives parse their clones, not the detached original tree.
12142
+ if (!root.contains(element) || elementBelongsToAnotherScope(element, scope))
12143
+ return;
12008
12144
  if (type === 'for') {
12009
12145
  processForDirective(element, scope);
12010
12146
  }
@@ -12040,6 +12176,10 @@ const elementBelongsToAnotherScope = (el, scope) => {
12040
12176
  function processParse(element, scope, fromStructural = false) {
12041
12177
  if (isInIgnoredTree(element))
12042
12178
  return;
12179
+ if (fromStructural && element.hasAttribute('g-scope') && mountFunction) {
12180
+ mountFunction(element);
12181
+ return;
12182
+ }
12043
12183
  beginEffectCollection();
12044
12184
  const allElements = [
12045
12185
  element,
@@ -12061,7 +12201,7 @@ function processParse(element, scope, fromStructural = false) {
12061
12201
  return;
12062
12202
  if (el.attributes.length === 0)
12063
12203
  return; // Skip if no attributes
12064
- if (elementBelongsToAnotherScope(el, scope) && !fromStructural) {
12204
+ if (elementBelongsToAnotherScope(el, scope)) {
12065
12205
  // (fromStructural allows processing newly created elements inside structurals)
12066
12206
  return; // Skip if inside mounted scope
12067
12207
  }
@@ -12069,8 +12209,9 @@ function processParse(element, scope, fromStructural = false) {
12069
12209
  if (el.hasAttribute('g-static')) {
12070
12210
  // Pre-process g-static elements (mark and render them before reactive processing)
12071
12211
  processStaticElements(el, scope);
12212
+ return;
12072
12213
  }
12073
- if (el.hasAttribute('g-form')) {
12214
+ if (el.hasAttribute('g-form') || el.hasAttribute('g-validate') || el.hasAttribute('g-errors')) {
12074
12215
  // Process form validation (g-form, g-validate, g-errors)
12075
12216
  processFormValidation(el, scope);
12076
12217
  }
@@ -12420,7 +12561,7 @@ function mountAll(root) {
12420
12561
  const allElements = [...elements, ...elementsNotScope].filter(el => !isInIgnoredTree(el));
12421
12562
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
12422
12563
  // Filter out elements inside structural directives - they will be mounted by structural processor
12423
- allElements.forEach(el => !hasStructuralParent(el) && mount(el));
12564
+ allElements.forEach(el => !el.hasAttribute('*if') && !el.hasAttribute('*for') && !hasStructuralParent(el) && mount(el));
12424
12565
  diagnoseUnscopedReveals(document.body);
12425
12566
  }
12426
12567
  function mountTree(el) {
@@ -12431,7 +12572,7 @@ function mountTree(el) {
12431
12572
  .filter(element => element.hasAttribute('g-scope') || hasAutoScope(element));
12432
12573
  // Child scopes own their subtree before an existing parent scope parses the insertion.
12433
12574
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
12434
- candidates.forEach(element => !hasStructuralParent(element) && mount(element));
12575
+ candidates.forEach(element => !element.hasAttribute('*if') && !element.hasAttribute('*for') && !hasStructuralParent(element) && mount(element));
12435
12576
  diagnoseUnscopedReveals(el);
12436
12577
  if (getMountedScope(el))
12437
12578
  return;
@@ -12460,9 +12601,17 @@ function mount(el) {
12460
12601
  /**
12461
12602
  * Parse inline scope definition from HTML attribute
12462
12603
  */
12604
+ function decodeMarkupExpression(value) {
12605
+ try {
12606
+ return decodeURIComponent(value);
12607
+ }
12608
+ catch {
12609
+ return value;
12610
+ } // Plain expressions may contain a literal % or modulo.
12611
+ }
12463
12612
  function parseInlineScope(scopeStr) {
12464
12613
  // If scopeStr is encode urld, decode it first
12465
- scopeStr = decodeURIComponent(scopeStr);
12614
+ scopeStr = decodeMarkupExpression(scopeStr);
12466
12615
  try {
12467
12616
  // Check if it's an inline object definition (starts with '{')
12468
12617
  const trimmed = scopeStr.trim();
@@ -12529,7 +12678,7 @@ function parseAutoScope(el) {
12529
12678
  // gm-method-name:args:arg2="expression"
12530
12679
  if (attr.name.match(/^gm-.+/)) {
12531
12680
  // If expr is encoded url, decode it first
12532
- const expr = decodeURIComponent(attr.value.trim());
12681
+ const expr = decodeMarkupExpression(attr.value.trim());
12533
12682
  if (forbidden.some(f => expr.includes(f))) {
12534
12683
  DEBUG() && console.log("[GyosJS] Scope mount error: Forbidden expression:", expr);
12535
12684
  }
@@ -12640,15 +12789,11 @@ function handleDefinition(el, scopeAttr) {
12640
12789
  * Mount a specific scope
12641
12790
  */
12642
12791
  function mountScope(el, scopeAttr) {
12643
- const definition = handleDefinition(el, scopeAttr);
12644
12792
  // Check if already mounted
12645
12793
  if (getMountedScope(el)) {
12646
12794
  return;
12647
12795
  }
12648
- // Check if element is static (no reactivity)
12649
- if (el.hasAttribute('g-static')) {
12650
- return;
12651
- }
12796
+ const definition = handleDefinition(el, scopeAttr);
12652
12797
  // Check hydration strategy
12653
12798
  const hydrationStrategy = getHydrationStrategy(el);
12654
12799
  if (hydrationStrategy) {
@@ -12671,8 +12816,9 @@ function mountScopeInternal(el, definition) {
12671
12816
  if (typeof definition === 'object') {
12672
12817
  instance = makeReactive(definition);
12673
12818
  }
12674
- // Create component context (needs instance for $watch)
12675
- const context = createContext(el, instance);
12819
+ // Factories receive context before their reactive instance exists. Resolve it
12820
+ // when an observer is registered so captured context also works in onMount.
12821
+ const context = createContext(el, () => instance);
12676
12822
  // If function component, call it now with context
12677
12823
  if (typeof definition === 'function' && !instance) {
12678
12824
  const factoryResult = definition(context);
@@ -12712,13 +12858,21 @@ function mountScopeInternal(el, definition) {
12712
12858
  // Parse and bind template (portals will be processed inside *if)
12713
12859
  // Pass onMount callback to be called after parsing (or after hydration triggers)
12714
12860
  parseTemplate(el, instance, () => {
12861
+ // The hook may inspect or clean up its own mount. Register before calling
12862
+ // user code, and do not register again if the hook disposes the scope.
12863
+ registerMountedScope(el, instance);
12715
12864
  // Call lifecycle hook after template is parsed
12716
12865
  if (instance.onMount) {
12717
- Promise.resolve(instance.onMount.call(instance)).catch(console.error);
12866
+ try {
12867
+ Promise.resolve(instance.onMount.call(instance)).catch(console.error);
12868
+ }
12869
+ catch (error) {
12870
+ console.error('[Component] Error in onMount:', error);
12871
+ }
12718
12872
  }
12719
12873
  });
12720
- // Store instance
12721
- registerMountedScope(el, instance);
12874
+ if (getMountedScope(el) !== instance)
12875
+ return;
12722
12876
  // Cache instance if g-scope-persist is set (with interpolation support)
12723
12877
  getPersistKey$1(el, persistKey => {
12724
12878
  if (!scopeCached.has(persistKey)) {
@@ -12729,12 +12883,12 @@ function mountScopeInternal(el, definition) {
12729
12883
  /**
12730
12884
  * Create component context
12731
12885
  */
12732
- function createContext(el, instance) {
12886
+ function createContext(el, getInstance) {
12733
12887
  const refs = {};
12734
12888
  const events = new Map();
12735
12889
  // Find all refs within this scope only
12736
12890
  el.querySelectorAll('[g-ref]').forEach(refEl => {
12737
- if (isInIgnoredTree(refEl))
12891
+ if (isInIgnoredTree(refEl) || (refEl.closest('[g-scope]') || el) !== el)
12738
12892
  return;
12739
12893
  const refName = refEl.getAttribute('g-ref');
12740
12894
  if (refName && !hasUnsafePropertyPath(refName)) {
@@ -12777,19 +12931,23 @@ function createContext(el, instance) {
12777
12931
  },
12778
12932
  $watch: (key, handler, options = {}) => {
12779
12933
  // Watch a reactive property for changes (supports nested paths like 'xxx.count')
12934
+ const instance = getInstance();
12780
12935
  if (!instance) {
12781
12936
  DEBUG() && console.warn('[Component] $watch called before instance created');
12782
12937
  return () => { };
12783
12938
  }
12784
12939
  const { immediate = false, deep = false, debounce = 0 } = options;
12785
12940
  let timeoutId;
12941
+ let active = true;
12786
12942
  if (debounce > 0) {
12787
12943
  // Wrap handler with debounce
12788
12944
  const originalHandler = handler;
12789
12945
  handler = (...args) => {
12790
12946
  clearTimeout(timeoutId);
12791
12947
  timeoutId = setTimeout(() => {
12792
- originalHandler(...args);
12948
+ timeoutId = undefined;
12949
+ if (active)
12950
+ untrack(() => originalHandler.call(instance, ...args));
12793
12951
  }, debounce);
12794
12952
  };
12795
12953
  }
@@ -12818,31 +12976,38 @@ function createContext(el, instance) {
12818
12976
  initialized = true;
12819
12977
  // Call immediately if requested
12820
12978
  if (immediate) {
12821
- handler.call(instance, clonedValue, undefined);
12979
+ untrack(() => handler.call(instance, clonedValue, undefined));
12822
12980
  }
12823
12981
  return;
12824
12982
  }
12825
12983
  // Check if value actually changed
12826
12984
  const changed = deep
12827
12985
  ? !deepEqual(oldValue, clonedValue)
12828
- : oldValue !== clonedValue;
12986
+ : !Object.is(oldValue, clonedValue);
12829
12987
  if (changed) {
12830
- handler.call(instance, clonedValue, oldValue);
12988
+ untrack(() => handler.call(instance, clonedValue, oldValue));
12831
12989
  oldValue = deep && typeof clonedValue === 'object'
12832
12990
  ? clone(clonedValue)
12833
12991
  : clonedValue;
12834
12992
  }
12835
12993
  });
12994
+ const stopWatching = () => {
12995
+ active = false;
12996
+ clearTimeout(timeoutId);
12997
+ timeoutId = undefined;
12998
+ watchEffect();
12999
+ };
12836
13000
  // Store cleanup for unmount
12837
13001
  if (!instance.__gyos_effects__) {
12838
13002
  instance.__gyos_effects__ = [];
12839
13003
  }
12840
- instance.__gyos_effects__.push(watchEffect);
13004
+ instance.__gyos_effects__.push(stopWatching);
12841
13005
  // Return unwatch function
12842
- return watchEffect;
13006
+ return stopWatching;
12843
13007
  },
12844
13008
  $effect: (fn) => {
12845
13009
  // Shorthand for effect with auto cleanup on unmount
13010
+ const instance = getInstance();
12846
13011
  if (!instance) {
12847
13012
  DEBUG() && console.warn('[Component] $effect called before instance created');
12848
13013
  return () => { };
@@ -13046,8 +13211,8 @@ function off(event, handler) {
13046
13211
  */
13047
13212
  function once(event, handler) {
13048
13213
  const wrapper = (...args) => {
13049
- handler(...args);
13050
13214
  off(event, wrapper);
13215
+ handler(...args);
13051
13216
  };
13052
13217
  return on(event, wrapper);
13053
13218
  }
@@ -13085,23 +13250,34 @@ function useFetch(url) {
13085
13250
  const data = signal(null);
13086
13251
  const loading = signal(true);
13087
13252
  const error = signal(null);
13253
+ let generation = 0;
13254
+ let active = true;
13088
13255
  const fetchData = async () => {
13256
+ if (!active)
13257
+ return;
13258
+ const requestId = ++generation;
13089
13259
  loading.value = true;
13090
13260
  error.value = null;
13091
13261
  data.value = null;
13092
13262
  try {
13093
13263
  const request = typeof url === 'function' ? await url() : url;
13264
+ if (requestId !== generation)
13265
+ return;
13094
13266
  const response = typeof request === 'string' ? await fetch(request) : request;
13095
13267
  if (!response.ok) {
13096
13268
  throw new Error(`HTTP error! status: ${response.status}`);
13097
13269
  }
13098
- data.value = await response.json();
13270
+ const result = await response.json();
13271
+ if (requestId === generation)
13272
+ data.value = result;
13099
13273
  }
13100
13274
  catch (e) {
13101
- error.value = e;
13275
+ if (requestId === generation)
13276
+ error.value = e;
13102
13277
  }
13103
13278
  finally {
13104
- loading.value = false;
13279
+ if (requestId === generation)
13280
+ loading.value = false;
13105
13281
  }
13106
13282
  };
13107
13283
  return {
@@ -13109,7 +13285,8 @@ function useFetch(url) {
13109
13285
  loading,
13110
13286
  error,
13111
13287
  refetch: fetchData,
13112
- onMount: fetchData
13288
+ onMount: () => { active = true; return fetchData(); },
13289
+ onUnmount: () => { active = false; generation++; loading.value = false; }
13113
13290
  };
13114
13291
  }
13115
13292
  /**
@@ -13367,17 +13544,26 @@ function useAsync(asyncFn, immediate = true) {
13367
13544
  const data = signal(null);
13368
13545
  const loading = signal(false);
13369
13546
  const error = signal(null);
13547
+ let generation = 0;
13548
+ let active = true;
13370
13549
  const execute = async () => {
13550
+ if (!active)
13551
+ return;
13552
+ const requestId = ++generation;
13371
13553
  loading.value = true;
13372
13554
  error.value = null;
13373
13555
  try {
13374
- data.value = await asyncFn();
13556
+ const result = await asyncFn();
13557
+ if (requestId === generation)
13558
+ data.value = result;
13375
13559
  }
13376
13560
  catch (e) {
13377
- error.value = e;
13561
+ if (requestId === generation)
13562
+ error.value = e;
13378
13563
  }
13379
13564
  finally {
13380
- loading.value = false;
13565
+ if (requestId === generation)
13566
+ loading.value = false;
13381
13567
  }
13382
13568
  };
13383
13569
  return {
@@ -13386,9 +13572,10 @@ function useAsync(asyncFn, immediate = true) {
13386
13572
  error,
13387
13573
  execute,
13388
13574
  onMount: () => {
13389
- if (immediate)
13390
- execute();
13391
- }
13575
+ active = true;
13576
+ return immediate ? execute() : undefined;
13577
+ },
13578
+ onUnmount: () => { active = false; generation++; loading.value = false; }
13392
13579
  };
13393
13580
  }
13394
13581
 
@@ -13862,7 +14049,10 @@ function syncAttributes(target, source) {
13862
14049
  Array.from(source.attributes).forEach(attribute => {
13863
14050
  sourceAttributes.add(attribute.name);
13864
14051
  if (target.getAttribute(attribute.name) !== attribute.value) {
13865
- target.setAttribute(attribute.name, attribute.value);
14052
+ // HTML permits directive names such as @click and *if, while older
14053
+ // DOM implementations apply XML name validation in setAttribute.
14054
+ // Transfer the already-parsed Attr without validating its name again.
14055
+ target.setAttributeNodeNS(target.ownerDocument.importNode(attribute, true));
13866
14056
  }
13867
14057
  });
13868
14058
  Array.from(target.attributes).forEach(attribute => {
@@ -14146,7 +14336,14 @@ function handleScroll(url, trigger, savedScroll) {
14146
14336
  // Hash scrolling
14147
14337
  const hash = new URL(url).hash;
14148
14338
  if (hash) {
14149
- const el = document.querySelector(hash);
14339
+ // A URL fragment identifies an id, not a CSS selector. Numeric ids,
14340
+ // punctuation and percent-encoded Unicode must work without escaping.
14341
+ let id = hash.slice(1);
14342
+ try {
14343
+ id = decodeURIComponent(id);
14344
+ }
14345
+ catch { /* Keep malformed fragments literal. */ }
14346
+ const el = document.getElementById(id);
14150
14347
  if (el) {
14151
14348
  el.scrollIntoView({ behavior: 'smooth' });
14152
14349
  return;
@@ -14726,6 +14923,12 @@ function getHistoryFragment(entryId, neighbourId) {
14726
14923
  return fragment?.cloneNode(true);
14727
14924
  }
14728
14925
  function cloneHistoryTarget(target) {
14926
+ // Mounted templates have already consumed event/model attributes and text
14927
+ // expressions. A DOM clone cannot recreate their observers. Restore these
14928
+ // targets from response HTML (snapshot or fetch) instead of caching inert UI.
14929
+ if (getScopeFromElement(target) || Array.from(target.querySelectorAll('*'))
14930
+ .some(element => element.__gyos_scope__))
14931
+ return null;
14729
14932
  const clone = target.cloneNode(true);
14730
14933
  clone.querySelectorAll('.gyos-target-spinner').forEach(spinner => spinner.remove());
14731
14934
  return clone;
@@ -15583,7 +15786,7 @@ const Gyos = {
15583
15786
  portalCreate,
15584
15787
  portalDestroy,
15585
15788
  setCspNonce,
15586
- version: '0.5.2'
15789
+ version: '0.5.4'
15587
15790
  };
15588
15791
 
15589
15792
  setExpressionRuntime(cspExpressionRuntime);