gyosjs 0.3.2 → 0.4.1

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/dist/gyos.auto.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.3.2
2
+ * GyosJS v0.4.1
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -189,10 +189,35 @@
189
189
  * count.value++; // Triggers effect
190
190
  * ```
191
191
  */
192
- /**
193
- * Current effect being tracked
194
- */
195
192
  let currentEffect = null;
193
+ function track(source) {
194
+ if (!currentEffect)
195
+ return;
196
+ source.subscribers.add(currentEffect);
197
+ currentEffect.__dependencies?.add(source.subscribers);
198
+ currentEffect.__versions?.set(source, source.version);
199
+ }
200
+ function dependenciesChanged(versions) {
201
+ return untrack(() => {
202
+ for (const [source, version] of versions) {
203
+ source.refresh?.();
204
+ if (source.version !== version)
205
+ return true;
206
+ }
207
+ return false;
208
+ });
209
+ }
210
+ // Invalidate derived caches synchronously; only user effects are deferred.
211
+ function notifySubscribers(subscribers) {
212
+ for (const sub of Array.from(subscribers)) {
213
+ if (sub.__invalidate)
214
+ sub();
215
+ else if (isBatching)
216
+ batchedEffects.add(sub);
217
+ else
218
+ queueEffect(sub);
219
+ }
220
+ }
196
221
  // Simple counter for debug-friendly IDs
197
222
  let signalIdCounter = 0;
198
223
  const WARN_SUBSCRIBERS = () => typeof window !== 'undefined' && window.GYOS_DEBUG_WARN_SUBSCRIBERS;
@@ -230,6 +255,9 @@
230
255
  }
231
256
  });
232
257
  isFlushingQueue = false;
258
+ // A plain subscribe callback can enqueue more work without entering effect().
259
+ if (effectQueue.size > 0)
260
+ queueMicrotask(flushEffectQueue);
233
261
  }
234
262
  /**
235
263
  * Queue an effect for execution in next microtask
@@ -288,17 +316,14 @@
288
316
  const debugId = ++signalIdCounter;
289
317
  let value = initialValue;
290
318
  const subscribers = new Set();
319
+ const source = { subscribers, version: 0 };
291
320
  let warnedSubscribers = false;
292
321
  const read = () => {
293
322
  // Track dependency
294
323
  if (currentEffect) {
295
- // IMPORTANT: Only add if not already subscribed (prevent duplicates)
296
- if (!subscribers.has(currentEffect)) {
297
- subscribers.add(currentEffect);
298
- // Store the subscribers Set in the effect's dependencies for cleanup
299
- if (currentEffect.__dependencies) {
300
- currentEffect.__dependencies.add(subscribers);
301
- }
324
+ const wasSubscribed = subscribers.has(currentEffect);
325
+ track(source);
326
+ if (!wasSubscribed) {
302
327
  if (DEBUG_VERBOSE()) {
303
328
  console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Added subscriber, total:', subscribers.size);
304
329
  }
@@ -317,18 +342,13 @@
317
342
  // For objects/arrays, check if it's actually the same reference
318
343
  // Deep equality is expensive, let user handle it
319
344
  value = newValue;
345
+ source.version++;
320
346
  DEBUG_VERBOSE() && console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Value changed to:', newValue);
321
347
  notify();
322
348
  };
323
349
  const notify = () => {
324
350
  DEBUG_VERBOSE() && console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Notifying', subscribers.size, 'subscribers');
325
- if (isBatching) {
326
- subscribers.forEach(sub => batchedEffects.add(sub));
327
- }
328
- else {
329
- // Always queue effects to prevent cascading updates
330
- subscribers.forEach(sub => queueEffect(sub));
331
- }
351
+ notifySubscribers(subscribers);
332
352
  };
333
353
  // Create callable signal (like Angular/SolidJS)
334
354
  // Call without args = read, call with arg = write
@@ -363,8 +383,16 @@
363
383
  },
364
384
  subscribe: {
365
385
  value: function (fn) {
366
- subscribers.add(fn);
367
- return () => subscribers.delete(fn);
386
+ let active = true;
387
+ const callback = () => { if (active)
388
+ untrack(fn); };
389
+ subscribers.add(callback);
390
+ return () => {
391
+ active = false;
392
+ subscribers.delete(callback);
393
+ effectQueue.delete(callback);
394
+ batchedEffects.delete(callback);
395
+ };
368
396
  },
369
397
  enumerable: true,
370
398
  configurable: true
@@ -424,49 +452,60 @@
424
452
  let value;
425
453
  let isDirty = true;
426
454
  let isFirstRun = true;
455
+ let computing = false;
427
456
  const subscribers = new Set();
428
- let cleanup;
457
+ const dependencies = new Set();
458
+ const versions = new Map();
459
+ const source = { subscribers, version: 0, refresh: () => compute() };
460
+ const invalidate = () => {
461
+ // A later batched write must also move already queued consumers into
462
+ // the batch, even when an earlier ordinary write dirtied this cache.
463
+ if (isDirty && !isBatching)
464
+ return;
465
+ isDirty = true;
466
+ notifySubscribers(subscribers);
467
+ };
468
+ invalidate.__invalidate = true;
469
+ invalidate.__dependencies = dependencies;
470
+ invalidate.__versions = versions;
429
471
  const compute = () => {
430
472
  if (!isDirty && !isFirstRun)
431
473
  return;
432
- // Cleanup previous dependencies
433
- if (cleanup)
434
- cleanup();
435
- // Track dependencies in an effect
436
- cleanup = effect(() => {
437
- try {
438
- const newValue = fn();
439
- // Only update if changed
440
- if (isFirstRun || value !== newValue) {
441
- value = newValue;
442
- isFirstRun = false;
443
- isDirty = false;
444
- // Notify subscribers
445
- if (!isBatching) {
446
- subscribers.forEach(sub => queueEffect(sub));
447
- }
448
- else {
449
- subscribers.forEach(sub => batchedEffects.add(sub));
450
- }
451
- }
474
+ if (computing)
475
+ throw new Error('[Computed] Circular dependency');
476
+ computing = true;
477
+ const previousEffect = currentEffect;
478
+ try {
479
+ // A dirty upstream computed may still resolve to its previous value.
480
+ if (!isFirstRun && !dependenciesChanged(versions)) {
481
+ isDirty = false;
482
+ return;
452
483
  }
453
- catch (error) {
454
- console.error('[Computed] Error in computation:', error);
455
- throw error;
484
+ dependencies.forEach(dependency => dependency.delete(invalidate));
485
+ dependencies.clear();
486
+ versions.clear();
487
+ currentEffect = invalidate;
488
+ const nextValue = fn();
489
+ if (isFirstRun || !Object.is(value, nextValue)) {
490
+ value = nextValue;
491
+ source.version++;
456
492
  }
457
- });
458
- isDirty = false;
493
+ isFirstRun = false;
494
+ isDirty = false;
495
+ }
496
+ catch (error) {
497
+ // Preserve error isolation and the last successful value.
498
+ console.error('[Computed] Error in computation:', error);
499
+ isDirty = false;
500
+ }
501
+ finally {
502
+ currentEffect = previousEffect;
503
+ computing = false;
504
+ }
459
505
  };
460
506
  const read = () => {
461
- if (isDirty || isFirstRun)
462
- compute();
463
- // Track dependency
464
- if (currentEffect && !subscribers.has(currentEffect)) {
465
- subscribers.add(currentEffect);
466
- if (currentEffect.__dependencies) {
467
- currentEffect.__dependencies.add(subscribers);
468
- }
469
- }
507
+ compute();
508
+ track(source);
470
509
  return value;
471
510
  };
472
511
  // Create callable computed (read-only)
@@ -491,8 +530,14 @@
491
530
  },
492
531
  subscribe: {
493
532
  value: function (fn) {
494
- subscribers.add(fn);
495
- return () => subscribers.delete(fn);
533
+ // Establish dependencies even if subscribe() is the first access.
534
+ let first = true;
535
+ return effect(() => {
536
+ read();
537
+ if (!first)
538
+ untrack(fn);
539
+ first = false;
540
+ });
496
541
  },
497
542
  enumerable: true,
498
543
  configurable: true
@@ -543,11 +588,15 @@
543
588
  */
544
589
  function effect(fn) {
545
590
  let cleanup;
546
- let dependencies = new Set();
591
+ const dependencies = new Set();
592
+ const versions = new Map();
547
593
  let active = true;
594
+ let initialized = false;
548
595
  const execute = () => {
549
596
  if (!active)
550
597
  return;
598
+ if (initialized && !dependenciesChanged(versions))
599
+ return;
551
600
  // Prevent recursive execution - if already running, skip
552
601
  if (runningEffects.has(execute)) {
553
602
  DEBUG() && console.warn('[Effect] Skipped recursive execution');
@@ -562,10 +611,13 @@
562
611
  });
563
612
  DEBUG() && console.log('[Effect] Cleaned up dependencies, count:', dependencies.size);
564
613
  dependencies.clear();
614
+ versions.clear();
565
615
  // Clean up previous run
566
616
  if (cleanup) {
617
+ const previousCleanup = cleanup;
618
+ cleanup = undefined;
567
619
  try {
568
- cleanup();
620
+ untrack(previousCleanup);
569
621
  }
570
622
  catch (error) {
571
623
  console.error('[Effect] Error in cleanup:', error);
@@ -576,6 +628,7 @@
576
628
  currentEffect = execute;
577
629
  // Store dependencies for cleanup
578
630
  execute.__dependencies = dependencies;
631
+ execute.__versions = versions;
579
632
  try {
580
633
  const nextCleanup = fn();
581
634
  cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
@@ -585,6 +638,7 @@
585
638
  // Don't throw - allow other effects to continue
586
639
  }
587
640
  finally {
641
+ initialized = true;
588
642
  currentEffect = prevEffect;
589
643
  effectDepth--;
590
644
  runningEffects.delete(execute);
@@ -601,14 +655,17 @@
601
655
  if (!active)
602
656
  return;
603
657
  active = false;
658
+ effectQueue.delete(execute);
659
+ batchedEffects.delete(execute);
604
660
  // Remove from all dependencies
605
661
  dependencies.forEach(depSet => {
606
662
  depSet.delete(execute);
607
663
  });
608
664
  dependencies.clear();
665
+ versions.clear();
609
666
  if (cleanup) {
610
667
  try {
611
- cleanup();
668
+ untrack(cleanup);
612
669
  }
613
670
  catch (error) {
614
671
  console.error('[Effect] Error in final cleanup:', error);
@@ -668,6 +725,8 @@
668
725
  const effects = Array.from(batchedEffects);
669
726
  batchedEffects.clear();
670
727
  effects.forEach(effect => {
728
+ // This batch also settles any earlier queued write to this observer.
729
+ effectQueue.delete(effect);
671
730
  try {
672
731
  effect();
673
732
  }
@@ -2202,59 +2261,59 @@
2202
2261
  return;
2203
2262
  const style = document.createElement('style');
2204
2263
  style.id = styleId;
2205
- style.textContent = `
2206
- /* Opacity utilities */
2264
+ style.textContent = `
2265
+ /* Opacity utilities */
2207
2266
  .gyos-t-opacity-0 { opacity: 0; }
2208
2267
  .gyos-t-opacity-100 { opacity: 1; }
2209
-
2210
- /* Transform - Translate Y */
2268
+
2269
+ /* Transform - Translate Y */
2211
2270
  .gyos-t-translate-y-0 { transform: translateY(0); }
2212
2271
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2213
2272
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2214
-
2215
- /* Transform - Translate X */
2273
+
2274
+ /* Transform - Translate X */
2216
2275
  .gyos-t-translate-x-0 { transform: translateX(0); }
2217
2276
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2218
2277
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2219
-
2220
- /* Transform - Scale */
2278
+
2279
+ /* Transform - Scale */
2221
2280
  .gyos-t-scale-0 { transform: scale(0); }
2222
2281
  .gyos-t-scale-50 { transform: scale(0.5); }
2223
2282
  .gyos-t-scale-100 { transform: scale(1); }
2224
-
2225
- /* Animation Keyframes */
2226
- @keyframes gyos-fade-in {
2227
- from { opacity: 0; }
2228
- to { opacity: 1; }
2229
- }
2230
-
2231
- @keyframes gyos-fade-out {
2232
- from { opacity: 1; }
2233
- to { opacity: 0; }
2234
- }
2235
-
2236
- @keyframes gyos-slide-down {
2237
- from { transform: translateY(-100%); opacity: 0; }
2238
- to { transform: translateY(0); opacity: 1; }
2239
- }
2240
-
2241
- @keyframes gyos-slide-up {
2242
- from { transform: translateY(100%); opacity: 0; }
2243
- to { transform: translateY(0); opacity: 1; }
2244
- }
2245
-
2246
- @keyframes gyos-scale-in {
2247
- from { transform: scale(0); opacity: 0; }
2248
- to { transform: scale(1); opacity: 1; }
2249
- }
2250
-
2251
- @keyframes gyos-scale-out {
2252
- from { transform: scale(1); opacity: 1; }
2253
- to { transform: scale(0); opacity: 0; }
2254
- }
2255
-
2256
- [g-cloak] {
2257
- display: none !important;
2283
+
2284
+ /* Animation Keyframes */
2285
+ @keyframes gyos-fade-in {
2286
+ from { opacity: 0; }
2287
+ to { opacity: 1; }
2288
+ }
2289
+
2290
+ @keyframes gyos-fade-out {
2291
+ from { opacity: 1; }
2292
+ to { opacity: 0; }
2293
+ }
2294
+
2295
+ @keyframes gyos-slide-down {
2296
+ from { transform: translateY(-100%); opacity: 0; }
2297
+ to { transform: translateY(0); opacity: 1; }
2298
+ }
2299
+
2300
+ @keyframes gyos-slide-up {
2301
+ from { transform: translateY(100%); opacity: 0; }
2302
+ to { transform: translateY(0); opacity: 1; }
2303
+ }
2304
+
2305
+ @keyframes gyos-scale-in {
2306
+ from { transform: scale(0); opacity: 0; }
2307
+ to { transform: scale(1); opacity: 1; }
2308
+ }
2309
+
2310
+ @keyframes gyos-scale-out {
2311
+ from { transform: scale(1); opacity: 1; }
2312
+ to { transform: scale(0); opacity: 0; }
2313
+ }
2314
+
2315
+ [g-cloak] {
2316
+ display: none !important;
2258
2317
  }`;
2259
2318
  document.head.appendChild(style);
2260
2319
  }
@@ -6611,33 +6670,44 @@
6611
6670
  getCurrentProgress() {
6612
6671
  return this.currentProgress;
6613
6672
  }
6673
+ reconnect() {
6674
+ if (!this.element || !this.progressBarEnabled || !document.body)
6675
+ return;
6676
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6677
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6678
+ if (node !== this.element)
6679
+ node.remove();
6680
+ });
6681
+ if (!this.element.isConnected)
6682
+ document.body.appendChild(this.element);
6683
+ }
6614
6684
  createBar() {
6615
6685
  if (typeof document === 'undefined')
6616
6686
  return;
6617
6687
  // Create progress bar element
6618
6688
  this.element = document.createElement('div');
6619
6689
  this.element.id = 'gyos-progress-bar';
6620
- this.element.style.cssText = `
6621
- position: fixed;
6622
- top: 0;
6623
- left: 0;
6624
- width: 0%;
6625
- height: 6px;
6626
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6627
- z-index: 999999;
6628
- transition: width 0.3s linear, opacity 0.3s linear;
6629
- opacity: 0;
6630
- pointer-events: none;
6631
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6690
+ this.element.style.cssText = `
6691
+ position: fixed;
6692
+ top: 0;
6693
+ left: 0;
6694
+ width: 0%;
6695
+ height: 6px;
6696
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6697
+ z-index: 999999;
6698
+ transition: width 0.3s linear, opacity 0.3s linear;
6699
+ opacity: 0;
6700
+ pointer-events: none;
6701
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6632
6702
  `;
6633
6703
  // Insert into DOM when ready
6634
6704
  if (document.readyState === 'loading') {
6635
6705
  document.addEventListener('DOMContentLoaded', () => {
6636
- document.body.insertAdjacentElement('beforeend', this.element);
6637
- });
6706
+ this.reconnect();
6707
+ }, { once: true });
6638
6708
  }
6639
6709
  else {
6640
- document.body.insertAdjacentElement('beforeend', this.element);
6710
+ this.reconnect();
6641
6711
  }
6642
6712
  }
6643
6713
  start() {
@@ -6661,6 +6731,7 @@
6661
6731
  setProgress(percent) {
6662
6732
  if (!this.element || !this.progressBarEnabled)
6663
6733
  return;
6734
+ this.reconnect();
6664
6735
  // Clamp between 0-100
6665
6736
  percent = Math.min(100, Math.max(0, percent));
6666
6737
  this.currentProgress = percent;
@@ -6709,41 +6780,41 @@
6709
6780
  function createTargetSpinner() {
6710
6781
  const spinner = document.createElement('div');
6711
6782
  spinner.className = 'gyos-target-spinner';
6712
- spinner.innerHTML = `
6713
- <div class="gyos-spinner-content">
6714
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6715
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6716
- </svg>
6717
- </div>
6783
+ spinner.innerHTML = `
6784
+ <div class="gyos-spinner-content">
6785
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6786
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6787
+ </svg>
6788
+ </div>
6718
6789
  `;
6719
6790
  // Inject styles if not already present
6720
6791
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6721
6792
  const style = document.createElement('style');
6722
6793
  style.id = 'gyos-target-spinner-styles';
6723
- style.textContent = `
6724
- .gyos-target-spinner {
6725
- display: flex;
6726
- align-items: center;
6727
- justify-content: center;
6728
- padding: 20px;
6729
- min-height: 60px;
6730
- }
6731
- .gyos-spinner-content {
6732
- display: flex;
6733
- align-items: center;
6734
- gap: 10px;
6735
- color: var(--gyos-spinner-color, #667eea);
6736
- font-size: 14px;
6737
- }
6738
- .gyos-spinner-icon {
6739
- width: 24px;
6740
- height: 24px;
6741
- animation: gyos-spin 1s linear infinite;
6742
- }
6743
- @keyframes gyos-spin {
6744
- 0% { transform: rotate(0deg); }
6745
- 100% { transform: rotate(360deg); }
6746
- }
6794
+ style.textContent = `
6795
+ .gyos-target-spinner {
6796
+ display: flex;
6797
+ align-items: center;
6798
+ justify-content: center;
6799
+ padding: 20px;
6800
+ min-height: 60px;
6801
+ }
6802
+ .gyos-spinner-content {
6803
+ display: flex;
6804
+ align-items: center;
6805
+ gap: 10px;
6806
+ color: var(--gyos-spinner-color, #667eea);
6807
+ font-size: 14px;
6808
+ }
6809
+ .gyos-spinner-icon {
6810
+ width: 24px;
6811
+ height: 24px;
6812
+ animation: gyos-spin 1s linear infinite;
6813
+ }
6814
+ @keyframes gyos-spin {
6815
+ 0% { transform: rotate(0deg); }
6816
+ 100% { transform: rotate(360deg); }
6817
+ }
6747
6818
  `;
6748
6819
  document.head.appendChild(style);
6749
6820
  }
@@ -7103,8 +7174,8 @@
7103
7174
  }
7104
7175
  result = target;
7105
7176
  }
7106
- await options.beforeScripts?.();
7107
7177
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7178
+ await options.beforeScripts?.();
7108
7179
  // Additive swaps must not re-run scripts that already existed in the target.
7109
7180
  if (normalized === 'append' || normalized === 'prepend') {
7110
7181
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7344,6 +7415,21 @@
7344
7415
  window.scrollTo({ top: 0, behavior: 'smooth' });
7345
7416
  }
7346
7417
 
7418
+ // A retained relative URL still identifies the resource loaded on its original
7419
+ // page, even after pushState changes document.baseURI.
7420
+ const resourceUrls = new WeakMap();
7421
+ function rememberResourceUrls(root, baseUrl) {
7422
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7423
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7424
+ const source = node.getAttribute(attribute);
7425
+ if (resourceUrls.get(node)?.source === source)
7426
+ return;
7427
+ try {
7428
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7429
+ }
7430
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7431
+ });
7432
+ }
7347
7433
  function isNonceMeta(el) {
7348
7434
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7349
7435
  }
@@ -7361,7 +7447,20 @@
7361
7447
  return;
7362
7448
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7363
7449
  return;
7364
- attributes.set(attr.name, attr.value);
7450
+ let value = attr.value;
7451
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7452
+ const cached = resourceUrls.get(el);
7453
+ if (cached?.source === value)
7454
+ value = cached.url;
7455
+ else {
7456
+ try {
7457
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7458
+ resourceUrls.set(el, { source: attr.value, url: value });
7459
+ }
7460
+ catch { /* Keep invalid URLs distinct. */ }
7461
+ }
7462
+ }
7463
+ attributes.set(attr.name, value);
7365
7464
  });
7366
7465
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7367
7466
  attributes.set('nonce', context.activeNonce);
@@ -7428,19 +7527,21 @@
7428
7527
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7429
7528
  }
7430
7529
  }
7431
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7530
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7432
7531
  const csp = expressionRuntimeMode() === 'csp';
7433
7532
  const context = {
7434
7533
  csp,
7435
7534
  activeNonce: csp ? resolveCspNonce() : undefined
7436
7535
  };
7437
- const current = keyedNodes(currentNodes, context);
7536
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7438
7537
  const next = keyedNodes(nextNodes, context);
7538
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7539
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7439
7540
  const currentKeys = new Set(current.map(item => item.key));
7440
7541
  const nextKeys = new Set(next.map(item => item.key));
7441
7542
  // Remove nodes that are not in the new head
7442
7543
  current.forEach(({ key, node }) => {
7443
- if (!nextKeys.has(key)) {
7544
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7444
7545
  node.remove();
7445
7546
  }
7446
7547
  });
@@ -7448,6 +7549,8 @@
7448
7549
  for (const { key, node } of next) {
7449
7550
  if (signal?.aborted)
7450
7551
  return;
7552
+ if (persistent.has(persistentKey(node)))
7553
+ continue;
7451
7554
  if (!currentKeys.has(key)) {
7452
7555
  if (!canInsertNode(node, context)) {
7453
7556
  warnSkippedNode(node);
@@ -7650,6 +7753,7 @@
7650
7753
  * MPA boost navigation inspired by Turbo Drive.
7651
7754
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7652
7755
  */
7756
+ const submittingForms = new WeakSet();
7653
7757
  const snapshots = new Map();
7654
7758
  const preloadCache = new Map();
7655
7759
  const preloadControllers = new Map();
@@ -7666,12 +7770,30 @@
7666
7770
  let progressBar = null;
7667
7771
  const beforeNavigate = [];
7668
7772
  const afterNavigate = [];
7773
+ const beforeSwap = [];
7774
+ const navigationEnd = [];
7775
+ function registerNavigationHook(hooks, callback) {
7776
+ // A wrapper gives each registration its own unsubscribe identity.
7777
+ const entry = (url, context) => callback(url, context);
7778
+ hooks.push(entry);
7779
+ return () => {
7780
+ const index = hooks.indexOf(entry);
7781
+ if (index !== -1)
7782
+ hooks.splice(index, 1);
7783
+ };
7784
+ }
7669
7785
  // Expose hooks to register before/after navigation callbacks
7670
7786
  function onBeforeNavigate(callback) {
7671
- beforeNavigate.push(callback);
7787
+ return registerNavigationHook(beforeNavigate, callback);
7672
7788
  }
7673
7789
  function onAfterNavigate(callback) {
7674
- afterNavigate.push(callback);
7790
+ return registerNavigationHook(afterNavigate, callback);
7791
+ }
7792
+ function onBeforeSwap(callback) {
7793
+ return registerNavigationHook(beforeSwap, callback);
7794
+ }
7795
+ function onNavigationEnd(callback) {
7796
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7675
7797
  }
7676
7798
  function startRouter(options) {
7677
7799
  // If not has g-boost attribute, do not start router
@@ -7695,6 +7817,7 @@
7695
7817
  }
7696
7818
  // Cache scripts from initial page to prevent re-execution on first navigation back
7697
7819
  cacheInitialPageScripts();
7820
+ rememberResourceUrls(document, document.baseURI);
7698
7821
  routerStarted = true;
7699
7822
  log('[GyosRouter] started');
7700
7823
  }
@@ -7751,9 +7874,13 @@
7751
7874
  const outlet = findGlobalOutlet();
7752
7875
  return outlet instanceof HTMLElement ? outlet : null;
7753
7876
  }
7877
+ function isFullDocument(html) {
7878
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7879
+ }
7754
7880
  function saveSnapshot(url, html) {
7755
7881
  // create HTMLElement by html string to remove scripts and get clean snapshot
7756
7882
  const doc = parseNavigationDocument(html);
7883
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7757
7884
  // Ignore hash for snapshot keys
7758
7885
  if (url.includes('#'))
7759
7886
  url = url.split('#')[0];
@@ -7762,7 +7889,7 @@
7762
7889
  if (s.hasAttribute('g-script-once'))
7763
7890
  s.textContent = '';
7764
7891
  });
7765
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7892
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7766
7893
  log('[GyosRouter] snapshot saved for', url);
7767
7894
  }
7768
7895
  function getOutletIndex(root, target) {
@@ -7874,10 +8001,10 @@
7874
8001
  // update callback remains the navigation source of truth and is awaited below.
7875
8002
  void promise?.catch(() => undefined);
7876
8003
  }
7877
- function runNavigationHooks(callbacks, url) {
7878
- callbacks.forEach(callback => {
8004
+ function runNavigationHooks(callbacks, url, context) {
8005
+ [...callbacks].forEach(callback => {
7879
8006
  try {
7880
- callback(url);
8007
+ callback(url, { ...context });
7881
8008
  }
7882
8009
  catch (error) {
7883
8010
  console.error('[GyosRouter] navigation hook error', error);
@@ -7915,7 +8042,13 @@
7915
8042
  url = mergeFormDataIntoUrl(url, opts.formData);
7916
8043
  }
7917
8044
  else {
7918
- init.body = opts.formData;
8045
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
8046
+ const encoded = new URLSearchParams();
8047
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
8048
+ init.body = encoded;
8049
+ }
8050
+ else
8051
+ init.body = opts.formData;
7919
8052
  }
7920
8053
  }
7921
8054
  else if (opts.jsonData) {
@@ -7958,25 +8091,26 @@
7958
8091
  preloadControllers.delete(cacheKey);
7959
8092
  });
7960
8093
  }
7961
- async function updateHead(fromDoc, signal) {
8094
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7962
8095
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7963
8096
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7964
8097
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7965
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8098
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7966
8099
  }
7967
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8100
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7968
8101
  // scripts in current document and it not in target outlet
7969
8102
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7970
8103
  // scripts in fromDoc and it not in source outlet
7971
8104
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7972
8105
  // Diff and update scripts not in outlet/target
7973
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8106
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7974
8107
  }
7975
8108
  function resolveIncomingScriptUrls(root, baseUrl) {
7976
- root.querySelectorAll('script[src]').forEach(script => {
7977
- const source = script.getAttribute('src');
8109
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8110
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8111
+ const source = node.getAttribute(attribute);
7978
8112
  if (source)
7979
- script.src = new URL(source, baseUrl).href;
8113
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7980
8114
  });
7981
8115
  }
7982
8116
  function isNavigableHtmlResponse(response) {
@@ -8030,6 +8164,22 @@
8030
8164
  resolveDone
8031
8165
  };
8032
8166
  activeNavigation = transaction;
8167
+ const currentBaseUrl = document.baseURI;
8168
+ rememberResourceUrls(document, currentBaseUrl);
8169
+ const context = {
8170
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8171
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8172
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8173
+ status: null, committed: false, fallback: false, outcome: null
8174
+ };
8175
+ const formEvent = opts.form
8176
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8177
+ : null;
8178
+ const fallback = (url, requestSent) => {
8179
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8180
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8181
+ fallbackFromBoost(opts, url, requestSent);
8182
+ };
8033
8183
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8034
8184
  const setRand = () => {
8035
8185
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8037,7 +8187,10 @@
8037
8187
  }
8038
8188
  };
8039
8189
  try {
8040
- runNavigationHooks(beforeNavigate, opts.url);
8190
+ if (formEvent)
8191
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8192
+ runNavigationHooks(beforeNavigate, opts.url, context);
8193
+ assertActiveNavigation(transaction);
8041
8194
  progressBar?.start();
8042
8195
  // popstate already points history at the destination entry. Keep the visible
8043
8196
  // page's position under currentUrl without overwriting that destination state.
@@ -8046,9 +8199,10 @@
8046
8199
  saveScrollPosition();
8047
8200
  // Pick target element to swap
8048
8201
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8202
+ context.target = target;
8049
8203
  if (!target) {
8050
8204
  if (isActiveNavigation(transaction))
8051
- fallbackFromBoost(opts, opts.url, false);
8205
+ fallback(opts.url, false);
8052
8206
  return;
8053
8207
  }
8054
8208
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8073,6 +8227,7 @@
8073
8227
  if (hasTargetSpinner)
8074
8228
  transaction.spinner = showTargetSpinner(target, swapMode);
8075
8229
  const { finalUrl, init } = buildRequest(opts);
8230
+ context.url = finalUrl;
8076
8231
  // Add abort signal to request
8077
8232
  init.signal = transaction.controller.signal;
8078
8233
  let html;
@@ -8100,7 +8255,8 @@
8100
8255
  if (error.name === 'AbortError')
8101
8256
  throw error;
8102
8257
  assertActiveNavigation(transaction);
8103
- window.location.href = finalUrl;
8258
+ context.outcome = 'network-error';
8259
+ fallback(finalUrl, true);
8104
8260
  return;
8105
8261
  }
8106
8262
  preloadCache.delete(preloadKey); // consume cache
@@ -8125,28 +8281,46 @@
8125
8281
  log('[GyosRouter] Navigation cancelled');
8126
8282
  return;
8127
8283
  }
8284
+ context.outcome = 'network-error';
8128
8285
  if (isActiveNavigation(transaction))
8129
- fallbackFromBoost(opts, finalUrl, true);
8286
+ fallback(finalUrl, true);
8130
8287
  return;
8131
8288
  }
8132
8289
  }
8133
8290
  assertActiveNavigation(transaction);
8134
- // If response not ok, fallback to full navigation
8135
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8291
+ context.status = response?.status ?? null;
8292
+ context.url = response?.url || finalUrl;
8293
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8294
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8295
+ && acceptedErrors.includes(String(response.status));
8296
+ if (response && !response.ok)
8297
+ context.outcome = 'http-error';
8298
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8299
+ context.outcome ?? (context.outcome = 'invalid-response');
8136
8300
  if (isActiveNavigation(transaction))
8137
- fallbackFromBoost(opts, finalUrl, true);
8301
+ fallback(finalUrl, true);
8138
8302
  return;
8139
8303
  }
8140
8304
  html = await response.text();
8141
8305
  assertActiveNavigation(transaction);
8142
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8143
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8144
- }
8145
8306
  }
8146
8307
  // Parse HTML
8147
8308
  const doc = html
8148
8309
  ? parseNavigationDocument(html)
8149
8310
  : document.implementation.createHTMLDocument();
8311
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8312
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8313
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8314
+ context.outcome = 'invalid-response';
8315
+ fallback(response?.url || finalUrl, true);
8316
+ return;
8317
+ }
8318
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8319
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8320
+ }
8321
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8322
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8323
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8150
8324
  // Pick source fragment
8151
8325
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8152
8326
  stripInertFallbackContent(src);
@@ -8158,15 +8332,18 @@
8158
8332
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8159
8333
  }
8160
8334
  resolveIncomingScriptUrls(doc, targetUrl);
8335
+ context.url = targetUrl;
8161
8336
  if (opts.historyFragment)
8162
8337
  resolveIncomingScriptUrls(src, targetUrl);
8163
8338
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8164
8339
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8165
8340
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8166
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8341
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8167
8342
  const performUpdate = async () => {
8168
8343
  assertActiveNavigation(transaction);
8169
8344
  transaction.committing = true;
8345
+ runNavigationHooks(beforeSwap, targetUrl, context);
8346
+ assertActiveNavigation(transaction);
8170
8347
  // Update progress to rand 80 - 90% before swap
8171
8348
  progressBar?.setProgress(Math.random() * 10 + 80);
8172
8349
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8237,21 +8414,34 @@
8237
8414
  beforeScripts: async () => {
8238
8415
  if (!isFullOutletNavigation || currentHead)
8239
8416
  return;
8417
+ if (syncDocumentAttributes) {
8418
+ for (const name of ['lang', 'dir']) {
8419
+ const value = doc.documentElement.getAttribute(name);
8420
+ if (value === null)
8421
+ document.documentElement.removeAttribute(name);
8422
+ else
8423
+ document.documentElement.setAttribute(name, value);
8424
+ }
8425
+ }
8240
8426
  const incomingTitle = doc.querySelector('title');
8241
8427
  if (incomingTitle) {
8242
8428
  document.title = incomingTitle.textContent || document.title;
8243
8429
  }
8244
- await updateHead(doc, transaction.controller.signal);
8430
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8245
8431
  assertActiveNavigation(transaction);
8246
8432
  },
8247
8433
  onCommitted: (committedTarget, roots) => {
8248
8434
  target = committedTarget;
8435
+ context.target = committedTarget;
8436
+ context.committed = true;
8437
+ progressBar?.reconnect();
8249
8438
  committedRoots = roots;
8250
8439
  }
8251
8440
  });
8441
+ context.committed = true;
8252
8442
  assertActiveNavigation(transaction);
8253
8443
  if (isFullOutletNavigation) {
8254
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8444
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8255
8445
  assertActiveNavigation(transaction);
8256
8446
  }
8257
8447
  }
@@ -8285,14 +8475,15 @@
8285
8475
  await performUpdate();
8286
8476
  }
8287
8477
  assertActiveNavigation(transaction);
8288
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8478
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8289
8479
  disposeEffects(opts.trigger);
8290
8480
  opts.trigger.remove();
8291
8481
  }
8292
8482
  if (hasTargetSpinner)
8293
8483
  hideTargetSpinner(transaction.spinner);
8294
8484
  transaction.spinner = null;
8295
- runNavigationHooks(afterNavigate, targetUrl);
8485
+ context.outcome ?? (context.outcome = 'success');
8486
+ runNavigationHooks(afterNavigate, targetUrl, context);
8296
8487
  log('[GyosRouter] navigated to', targetUrl);
8297
8488
  currentUrl = changesState
8298
8489
  ? canonicalUrl(targetUrl, true)
@@ -8308,11 +8499,15 @@
8308
8499
  return;
8309
8500
  }
8310
8501
  if (isActiveNavigation(transaction)) {
8502
+ context.outcome ?? (context.outcome = 'error');
8311
8503
  console.error('[GyosRouter] navigation error', error);
8312
- fallbackFromBoost(opts, opts.url, true);
8504
+ fallback(opts.url, true);
8313
8505
  }
8314
8506
  }
8315
8507
  finally {
8508
+ if (transaction.controller.signal.aborted)
8509
+ context.outcome = 'aborted';
8510
+ context.outcome ?? (context.outcome = 'aborted');
8316
8511
  if (transaction.interval)
8317
8512
  clearInterval(transaction.interval);
8318
8513
  if (transaction.spinner)
@@ -8322,6 +8517,15 @@
8322
8517
  progressBar?.complete();
8323
8518
  }
8324
8519
  transaction.resolveDone();
8520
+ if (formEvent)
8521
+ submittingForms.delete(formEvent.form);
8522
+ runNavigationHooks(navigationEnd, context.url, context);
8523
+ if (formEvent) {
8524
+ const { url, status, outcome, committed, fallback } = context;
8525
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8526
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8527
+ }));
8528
+ }
8325
8529
  }
8326
8530
  }
8327
8531
  function shouldBoost(el) {
@@ -8430,16 +8634,34 @@
8430
8634
  return;
8431
8635
  if (shouldDeferToFormValidation(form))
8432
8636
  return;
8433
- event.preventDefault();
8434
- const action = form.action || window.location.href;
8435
- const method = (form.method || 'GET').toUpperCase();
8436
- const url = new URL(action, window.location.href);
8437
- if (url.origin !== window.location.origin) {
8438
- window.location.href = url.toString();
8637
+ const submitter = event.submitter;
8638
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8639
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8640
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8641
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8642
+ const formEncoding = override('enctype')?.toLowerCase();
8643
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8644
+ return;
8645
+ if (!resolveTarget(form))
8646
+ return;
8647
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8648
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8439
8649
  return;
8650
+ let url;
8651
+ try {
8652
+ url = new URL(override('action') || window.location.href, document.baseURI);
8440
8653
  }
8441
- const formData = new FormData(form);
8442
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8654
+ catch {
8655
+ return;
8656
+ }
8657
+ if (url.origin !== window.location.origin)
8658
+ return;
8659
+ event.preventDefault();
8660
+ if (submittingForms.has(form))
8661
+ return;
8662
+ const formData = new FormData(form, submitter);
8663
+ submittingForms.add(form);
8664
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8443
8665
  }
8444
8666
  function onPopState(event) {
8445
8667
  const url = window.location.href;
@@ -8544,10 +8766,12 @@
8544
8766
  startRouter,
8545
8767
  onBeforeNavigate,
8546
8768
  onAfterNavigate,
8769
+ onBeforeSwap,
8770
+ onNavigationEnd,
8547
8771
  portalCreate,
8548
8772
  portalDestroy,
8549
8773
  setCspNonce,
8550
- version: '0.3.2'
8774
+ version: '0.4.1'
8551
8775
  };
8552
8776
 
8553
8777
  const standardExpressionRuntime = {