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.
@@ -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
  */
@@ -183,10 +183,35 @@ function hasStructuralParent(el) {
183
183
  * count.value++; // Triggers effect
184
184
  * ```
185
185
  */
186
- /**
187
- * Current effect being tracked
188
- */
189
186
  let currentEffect = null;
187
+ function track(source) {
188
+ if (!currentEffect)
189
+ return;
190
+ source.subscribers.add(currentEffect);
191
+ currentEffect.__dependencies?.add(source.subscribers);
192
+ currentEffect.__versions?.set(source, source.version);
193
+ }
194
+ function dependenciesChanged(versions) {
195
+ return untrack(() => {
196
+ for (const [source, version] of versions) {
197
+ source.refresh?.();
198
+ if (source.version !== version)
199
+ return true;
200
+ }
201
+ return false;
202
+ });
203
+ }
204
+ // Invalidate derived caches synchronously; only user effects are deferred.
205
+ function notifySubscribers(subscribers) {
206
+ for (const sub of Array.from(subscribers)) {
207
+ if (sub.__invalidate)
208
+ sub();
209
+ else if (isBatching)
210
+ batchedEffects.add(sub);
211
+ else
212
+ queueEffect(sub);
213
+ }
214
+ }
190
215
  // Simple counter for debug-friendly IDs
191
216
  let signalIdCounter = 0;
192
217
  const WARN_SUBSCRIBERS = () => typeof window !== 'undefined' && window.GYOS_DEBUG_WARN_SUBSCRIBERS;
@@ -224,6 +249,9 @@ function flushEffectQueue() {
224
249
  }
225
250
  });
226
251
  isFlushingQueue = false;
252
+ // A plain subscribe callback can enqueue more work without entering effect().
253
+ if (effectQueue.size > 0)
254
+ queueMicrotask(flushEffectQueue);
227
255
  }
228
256
  /**
229
257
  * Queue an effect for execution in next microtask
@@ -282,17 +310,14 @@ function signal(initialValue, debugOrOptions) {
282
310
  const debugId = ++signalIdCounter;
283
311
  let value = initialValue;
284
312
  const subscribers = new Set();
313
+ const source = { subscribers, version: 0 };
285
314
  let warnedSubscribers = false;
286
315
  const read = () => {
287
316
  // Track dependency
288
317
  if (currentEffect) {
289
- // IMPORTANT: Only add if not already subscribed (prevent duplicates)
290
- if (!subscribers.has(currentEffect)) {
291
- subscribers.add(currentEffect);
292
- // Store the subscribers Set in the effect's dependencies for cleanup
293
- if (currentEffect.__dependencies) {
294
- currentEffect.__dependencies.add(subscribers);
295
- }
318
+ const wasSubscribed = subscribers.has(currentEffect);
319
+ track(source);
320
+ if (!wasSubscribed) {
296
321
  if (DEBUG_VERBOSE()) {
297
322
  console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Added subscriber, total:', subscribers.size);
298
323
  }
@@ -311,18 +336,13 @@ function signal(initialValue, debugOrOptions) {
311
336
  // For objects/arrays, check if it's actually the same reference
312
337
  // Deep equality is expensive, let user handle it
313
338
  value = newValue;
339
+ source.version++;
314
340
  DEBUG_VERBOSE() && console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Value changed to:', newValue);
315
341
  notify();
316
342
  };
317
343
  const notify = () => {
318
344
  DEBUG_VERBOSE() && console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Notifying', subscribers.size, 'subscribers');
319
- if (isBatching) {
320
- subscribers.forEach(sub => batchedEffects.add(sub));
321
- }
322
- else {
323
- // Always queue effects to prevent cascading updates
324
- subscribers.forEach(sub => queueEffect(sub));
325
- }
345
+ notifySubscribers(subscribers);
326
346
  };
327
347
  // Create callable signal (like Angular/SolidJS)
328
348
  // Call without args = read, call with arg = write
@@ -357,8 +377,16 @@ function signal(initialValue, debugOrOptions) {
357
377
  },
358
378
  subscribe: {
359
379
  value: function (fn) {
360
- subscribers.add(fn);
361
- return () => subscribers.delete(fn);
380
+ let active = true;
381
+ const callback = () => { if (active)
382
+ untrack(fn); };
383
+ subscribers.add(callback);
384
+ return () => {
385
+ active = false;
386
+ subscribers.delete(callback);
387
+ effectQueue.delete(callback);
388
+ batchedEffects.delete(callback);
389
+ };
362
390
  },
363
391
  enumerable: true,
364
392
  configurable: true
@@ -418,49 +446,60 @@ function computed(fn) {
418
446
  let value;
419
447
  let isDirty = true;
420
448
  let isFirstRun = true;
449
+ let computing = false;
421
450
  const subscribers = new Set();
422
- let cleanup;
451
+ const dependencies = new Set();
452
+ const versions = new Map();
453
+ const source = { subscribers, version: 0, refresh: () => compute() };
454
+ const invalidate = () => {
455
+ // A later batched write must also move already queued consumers into
456
+ // the batch, even when an earlier ordinary write dirtied this cache.
457
+ if (isDirty && !isBatching)
458
+ return;
459
+ isDirty = true;
460
+ notifySubscribers(subscribers);
461
+ };
462
+ invalidate.__invalidate = true;
463
+ invalidate.__dependencies = dependencies;
464
+ invalidate.__versions = versions;
423
465
  const compute = () => {
424
466
  if (!isDirty && !isFirstRun)
425
467
  return;
426
- // Cleanup previous dependencies
427
- if (cleanup)
428
- cleanup();
429
- // Track dependencies in an effect
430
- cleanup = effect(() => {
431
- try {
432
- const newValue = fn();
433
- // Only update if changed
434
- if (isFirstRun || value !== newValue) {
435
- value = newValue;
436
- isFirstRun = false;
437
- isDirty = false;
438
- // Notify subscribers
439
- if (!isBatching) {
440
- subscribers.forEach(sub => queueEffect(sub));
441
- }
442
- else {
443
- subscribers.forEach(sub => batchedEffects.add(sub));
444
- }
445
- }
468
+ if (computing)
469
+ throw new Error('[Computed] Circular dependency');
470
+ computing = true;
471
+ const previousEffect = currentEffect;
472
+ try {
473
+ // A dirty upstream computed may still resolve to its previous value.
474
+ if (!isFirstRun && !dependenciesChanged(versions)) {
475
+ isDirty = false;
476
+ return;
446
477
  }
447
- catch (error) {
448
- console.error('[Computed] Error in computation:', error);
449
- throw error;
478
+ dependencies.forEach(dependency => dependency.delete(invalidate));
479
+ dependencies.clear();
480
+ versions.clear();
481
+ currentEffect = invalidate;
482
+ const nextValue = fn();
483
+ if (isFirstRun || !Object.is(value, nextValue)) {
484
+ value = nextValue;
485
+ source.version++;
450
486
  }
451
- });
452
- isDirty = false;
487
+ isFirstRun = false;
488
+ isDirty = false;
489
+ }
490
+ catch (error) {
491
+ // Preserve error isolation and the last successful value.
492
+ console.error('[Computed] Error in computation:', error);
493
+ isDirty = false;
494
+ }
495
+ finally {
496
+ currentEffect = previousEffect;
497
+ computing = false;
498
+ }
453
499
  };
454
500
  const read = () => {
455
- if (isDirty || isFirstRun)
456
- compute();
457
- // Track dependency
458
- if (currentEffect && !subscribers.has(currentEffect)) {
459
- subscribers.add(currentEffect);
460
- if (currentEffect.__dependencies) {
461
- currentEffect.__dependencies.add(subscribers);
462
- }
463
- }
501
+ compute();
502
+ track(source);
464
503
  return value;
465
504
  };
466
505
  // Create callable computed (read-only)
@@ -485,8 +524,14 @@ function computed(fn) {
485
524
  },
486
525
  subscribe: {
487
526
  value: function (fn) {
488
- subscribers.add(fn);
489
- return () => subscribers.delete(fn);
527
+ // Establish dependencies even if subscribe() is the first access.
528
+ let first = true;
529
+ return effect(() => {
530
+ read();
531
+ if (!first)
532
+ untrack(fn);
533
+ first = false;
534
+ });
490
535
  },
491
536
  enumerable: true,
492
537
  configurable: true
@@ -537,11 +582,15 @@ function computed(fn) {
537
582
  */
538
583
  function effect(fn) {
539
584
  let cleanup;
540
- let dependencies = new Set();
585
+ const dependencies = new Set();
586
+ const versions = new Map();
541
587
  let active = true;
588
+ let initialized = false;
542
589
  const execute = () => {
543
590
  if (!active)
544
591
  return;
592
+ if (initialized && !dependenciesChanged(versions))
593
+ return;
545
594
  // Prevent recursive execution - if already running, skip
546
595
  if (runningEffects.has(execute)) {
547
596
  DEBUG() && console.warn('[Effect] Skipped recursive execution');
@@ -556,10 +605,13 @@ function effect(fn) {
556
605
  });
557
606
  DEBUG() && console.log('[Effect] Cleaned up dependencies, count:', dependencies.size);
558
607
  dependencies.clear();
608
+ versions.clear();
559
609
  // Clean up previous run
560
610
  if (cleanup) {
611
+ const previousCleanup = cleanup;
612
+ cleanup = undefined;
561
613
  try {
562
- cleanup();
614
+ untrack(previousCleanup);
563
615
  }
564
616
  catch (error) {
565
617
  console.error('[Effect] Error in cleanup:', error);
@@ -570,6 +622,7 @@ function effect(fn) {
570
622
  currentEffect = execute;
571
623
  // Store dependencies for cleanup
572
624
  execute.__dependencies = dependencies;
625
+ execute.__versions = versions;
573
626
  try {
574
627
  const nextCleanup = fn();
575
628
  cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
@@ -579,6 +632,7 @@ function effect(fn) {
579
632
  // Don't throw - allow other effects to continue
580
633
  }
581
634
  finally {
635
+ initialized = true;
582
636
  currentEffect = prevEffect;
583
637
  effectDepth--;
584
638
  runningEffects.delete(execute);
@@ -595,14 +649,17 @@ function effect(fn) {
595
649
  if (!active)
596
650
  return;
597
651
  active = false;
652
+ effectQueue.delete(execute);
653
+ batchedEffects.delete(execute);
598
654
  // Remove from all dependencies
599
655
  dependencies.forEach(depSet => {
600
656
  depSet.delete(execute);
601
657
  });
602
658
  dependencies.clear();
659
+ versions.clear();
603
660
  if (cleanup) {
604
661
  try {
605
- cleanup();
662
+ untrack(cleanup);
606
663
  }
607
664
  catch (error) {
608
665
  console.error('[Effect] Error in final cleanup:', error);
@@ -662,6 +719,8 @@ function batch(fn) {
662
719
  const effects = Array.from(batchedEffects);
663
720
  batchedEffects.clear();
664
721
  effects.forEach(effect => {
722
+ // This batch also settles any earlier queued write to this observer.
723
+ effectQueue.delete(effect);
665
724
  try {
666
725
  effect();
667
726
  }
@@ -2196,59 +2255,59 @@ function applyTransitionStyles() {
2196
2255
  return;
2197
2256
  const style = document.createElement('style');
2198
2257
  style.id = styleId;
2199
- style.textContent = `
2200
- /* Opacity utilities */
2258
+ style.textContent = `
2259
+ /* Opacity utilities */
2201
2260
  .gyos-t-opacity-0 { opacity: 0; }
2202
2261
  .gyos-t-opacity-100 { opacity: 1; }
2203
-
2204
- /* Transform - Translate Y */
2262
+
2263
+ /* Transform - Translate Y */
2205
2264
  .gyos-t-translate-y-0 { transform: translateY(0); }
2206
2265
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2207
2266
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2208
-
2209
- /* Transform - Translate X */
2267
+
2268
+ /* Transform - Translate X */
2210
2269
  .gyos-t-translate-x-0 { transform: translateX(0); }
2211
2270
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2212
2271
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2213
-
2214
- /* Transform - Scale */
2272
+
2273
+ /* Transform - Scale */
2215
2274
  .gyos-t-scale-0 { transform: scale(0); }
2216
2275
  .gyos-t-scale-50 { transform: scale(0.5); }
2217
2276
  .gyos-t-scale-100 { transform: scale(1); }
2218
-
2219
- /* Animation Keyframes */
2220
- @keyframes gyos-fade-in {
2221
- from { opacity: 0; }
2222
- to { opacity: 1; }
2223
- }
2224
-
2225
- @keyframes gyos-fade-out {
2226
- from { opacity: 1; }
2227
- to { opacity: 0; }
2228
- }
2229
-
2230
- @keyframes gyos-slide-down {
2231
- from { transform: translateY(-100%); opacity: 0; }
2232
- to { transform: translateY(0); opacity: 1; }
2233
- }
2234
-
2235
- @keyframes gyos-slide-up {
2236
- from { transform: translateY(100%); opacity: 0; }
2237
- to { transform: translateY(0); opacity: 1; }
2238
- }
2239
-
2240
- @keyframes gyos-scale-in {
2241
- from { transform: scale(0); opacity: 0; }
2242
- to { transform: scale(1); opacity: 1; }
2243
- }
2244
-
2245
- @keyframes gyos-scale-out {
2246
- from { transform: scale(1); opacity: 1; }
2247
- to { transform: scale(0); opacity: 0; }
2248
- }
2249
-
2250
- [g-cloak] {
2251
- display: none !important;
2277
+
2278
+ /* Animation Keyframes */
2279
+ @keyframes gyos-fade-in {
2280
+ from { opacity: 0; }
2281
+ to { opacity: 1; }
2282
+ }
2283
+
2284
+ @keyframes gyos-fade-out {
2285
+ from { opacity: 1; }
2286
+ to { opacity: 0; }
2287
+ }
2288
+
2289
+ @keyframes gyos-slide-down {
2290
+ from { transform: translateY(-100%); opacity: 0; }
2291
+ to { transform: translateY(0); opacity: 1; }
2292
+ }
2293
+
2294
+ @keyframes gyos-slide-up {
2295
+ from { transform: translateY(100%); opacity: 0; }
2296
+ to { transform: translateY(0); opacity: 1; }
2297
+ }
2298
+
2299
+ @keyframes gyos-scale-in {
2300
+ from { transform: scale(0); opacity: 0; }
2301
+ to { transform: scale(1); opacity: 1; }
2302
+ }
2303
+
2304
+ @keyframes gyos-scale-out {
2305
+ from { transform: scale(1); opacity: 1; }
2306
+ to { transform: scale(0); opacity: 0; }
2307
+ }
2308
+
2309
+ [g-cloak] {
2310
+ display: none !important;
2252
2311
  }`;
2253
2312
  document.head.appendChild(style);
2254
2313
  }
@@ -6605,33 +6664,44 @@ class ProgressBar {
6605
6664
  getCurrentProgress() {
6606
6665
  return this.currentProgress;
6607
6666
  }
6667
+ reconnect() {
6668
+ if (!this.element || !this.progressBarEnabled || !document.body)
6669
+ return;
6670
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6671
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6672
+ if (node !== this.element)
6673
+ node.remove();
6674
+ });
6675
+ if (!this.element.isConnected)
6676
+ document.body.appendChild(this.element);
6677
+ }
6608
6678
  createBar() {
6609
6679
  if (typeof document === 'undefined')
6610
6680
  return;
6611
6681
  // Create progress bar element
6612
6682
  this.element = document.createElement('div');
6613
6683
  this.element.id = 'gyos-progress-bar';
6614
- this.element.style.cssText = `
6615
- position: fixed;
6616
- top: 0;
6617
- left: 0;
6618
- width: 0%;
6619
- height: 6px;
6620
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6621
- z-index: 999999;
6622
- transition: width 0.3s linear, opacity 0.3s linear;
6623
- opacity: 0;
6624
- pointer-events: none;
6625
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6684
+ this.element.style.cssText = `
6685
+ position: fixed;
6686
+ top: 0;
6687
+ left: 0;
6688
+ width: 0%;
6689
+ height: 6px;
6690
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6691
+ z-index: 999999;
6692
+ transition: width 0.3s linear, opacity 0.3s linear;
6693
+ opacity: 0;
6694
+ pointer-events: none;
6695
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6626
6696
  `;
6627
6697
  // Insert into DOM when ready
6628
6698
  if (document.readyState === 'loading') {
6629
6699
  document.addEventListener('DOMContentLoaded', () => {
6630
- document.body.insertAdjacentElement('beforeend', this.element);
6631
- });
6700
+ this.reconnect();
6701
+ }, { once: true });
6632
6702
  }
6633
6703
  else {
6634
- document.body.insertAdjacentElement('beforeend', this.element);
6704
+ this.reconnect();
6635
6705
  }
6636
6706
  }
6637
6707
  start() {
@@ -6655,6 +6725,7 @@ class ProgressBar {
6655
6725
  setProgress(percent) {
6656
6726
  if (!this.element || !this.progressBarEnabled)
6657
6727
  return;
6728
+ this.reconnect();
6658
6729
  // Clamp between 0-100
6659
6730
  percent = Math.min(100, Math.max(0, percent));
6660
6731
  this.currentProgress = percent;
@@ -6703,41 +6774,41 @@ class ProgressBar {
6703
6774
  function createTargetSpinner() {
6704
6775
  const spinner = document.createElement('div');
6705
6776
  spinner.className = 'gyos-target-spinner';
6706
- spinner.innerHTML = `
6707
- <div class="gyos-spinner-content">
6708
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6709
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6710
- </svg>
6711
- </div>
6777
+ spinner.innerHTML = `
6778
+ <div class="gyos-spinner-content">
6779
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6780
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6781
+ </svg>
6782
+ </div>
6712
6783
  `;
6713
6784
  // Inject styles if not already present
6714
6785
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6715
6786
  const style = document.createElement('style');
6716
6787
  style.id = 'gyos-target-spinner-styles';
6717
- style.textContent = `
6718
- .gyos-target-spinner {
6719
- display: flex;
6720
- align-items: center;
6721
- justify-content: center;
6722
- padding: 20px;
6723
- min-height: 60px;
6724
- }
6725
- .gyos-spinner-content {
6726
- display: flex;
6727
- align-items: center;
6728
- gap: 10px;
6729
- color: var(--gyos-spinner-color, #667eea);
6730
- font-size: 14px;
6731
- }
6732
- .gyos-spinner-icon {
6733
- width: 24px;
6734
- height: 24px;
6735
- animation: gyos-spin 1s linear infinite;
6736
- }
6737
- @keyframes gyos-spin {
6738
- 0% { transform: rotate(0deg); }
6739
- 100% { transform: rotate(360deg); }
6740
- }
6788
+ style.textContent = `
6789
+ .gyos-target-spinner {
6790
+ display: flex;
6791
+ align-items: center;
6792
+ justify-content: center;
6793
+ padding: 20px;
6794
+ min-height: 60px;
6795
+ }
6796
+ .gyos-spinner-content {
6797
+ display: flex;
6798
+ align-items: center;
6799
+ gap: 10px;
6800
+ color: var(--gyos-spinner-color, #667eea);
6801
+ font-size: 14px;
6802
+ }
6803
+ .gyos-spinner-icon {
6804
+ width: 24px;
6805
+ height: 24px;
6806
+ animation: gyos-spin 1s linear infinite;
6807
+ }
6808
+ @keyframes gyos-spin {
6809
+ 0% { transform: rotate(0deg); }
6810
+ 100% { transform: rotate(360deg); }
6811
+ }
6741
6812
  `;
6742
6813
  document.head.appendChild(style);
6743
6814
  }
@@ -7097,8 +7168,8 @@ async function performSwap(target, src, mode, options = {}) {
7097
7168
  }
7098
7169
  result = target;
7099
7170
  }
7100
- await options.beforeScripts?.();
7101
7171
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7172
+ await options.beforeScripts?.();
7102
7173
  // Additive swaps must not re-run scripts that already existed in the target.
7103
7174
  if (normalized === 'append' || normalized === 'prepend') {
7104
7175
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7338,6 +7409,21 @@ function handleScroll(url, trigger, savedScroll) {
7338
7409
  window.scrollTo({ top: 0, behavior: 'smooth' });
7339
7410
  }
7340
7411
 
7412
+ // A retained relative URL still identifies the resource loaded on its original
7413
+ // page, even after pushState changes document.baseURI.
7414
+ const resourceUrls = new WeakMap();
7415
+ function rememberResourceUrls(root, baseUrl) {
7416
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7417
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7418
+ const source = node.getAttribute(attribute);
7419
+ if (resourceUrls.get(node)?.source === source)
7420
+ return;
7421
+ try {
7422
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7423
+ }
7424
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7425
+ });
7426
+ }
7341
7427
  function isNonceMeta(el) {
7342
7428
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7343
7429
  }
@@ -7355,7 +7441,20 @@ function serializeAttributes(el, context) {
7355
7441
  return;
7356
7442
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7357
7443
  return;
7358
- attributes.set(attr.name, attr.value);
7444
+ let value = attr.value;
7445
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7446
+ const cached = resourceUrls.get(el);
7447
+ if (cached?.source === value)
7448
+ value = cached.url;
7449
+ else {
7450
+ try {
7451
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7452
+ resourceUrls.set(el, { source: attr.value, url: value });
7453
+ }
7454
+ catch { /* Keep invalid URLs distinct. */ }
7455
+ }
7456
+ }
7457
+ attributes.set(attr.name, value);
7359
7458
  });
7360
7459
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7361
7460
  attributes.set('nonce', context.activeNonce);
@@ -7422,19 +7521,21 @@ function warnSkippedNode(node) {
7422
7521
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7423
7522
  }
7424
7523
  }
7425
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7524
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7426
7525
  const csp = expressionRuntimeMode() === 'csp';
7427
7526
  const context = {
7428
7527
  csp,
7429
7528
  activeNonce: csp ? resolveCspNonce() : undefined
7430
7529
  };
7431
- const current = keyedNodes(currentNodes, context);
7530
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7432
7531
  const next = keyedNodes(nextNodes, context);
7532
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7533
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7433
7534
  const currentKeys = new Set(current.map(item => item.key));
7434
7535
  const nextKeys = new Set(next.map(item => item.key));
7435
7536
  // Remove nodes that are not in the new head
7436
7537
  current.forEach(({ key, node }) => {
7437
- if (!nextKeys.has(key)) {
7538
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7438
7539
  node.remove();
7439
7540
  }
7440
7541
  });
@@ -7442,6 +7543,8 @@ async function diffNodes(currentNodes, nextNodes, container = document.head, sig
7442
7543
  for (const { key, node } of next) {
7443
7544
  if (signal?.aborted)
7444
7545
  return;
7546
+ if (persistent.has(persistentKey(node)))
7547
+ continue;
7445
7548
  if (!currentKeys.has(key)) {
7446
7549
  if (!canInsertNode(node, context)) {
7447
7550
  warnSkippedNode(node);
@@ -7644,6 +7747,7 @@ function prepareNavigationHtml(html) {
7644
7747
  * MPA boost navigation inspired by Turbo Drive.
7645
7748
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7646
7749
  */
7750
+ const submittingForms = new WeakSet();
7647
7751
  const snapshots = new Map();
7648
7752
  const preloadCache = new Map();
7649
7753
  const preloadControllers = new Map();
@@ -7660,12 +7764,30 @@ let activeNavigation = null;
7660
7764
  let progressBar = null;
7661
7765
  const beforeNavigate = [];
7662
7766
  const afterNavigate = [];
7767
+ const beforeSwap = [];
7768
+ const navigationEnd = [];
7769
+ function registerNavigationHook(hooks, callback) {
7770
+ // A wrapper gives each registration its own unsubscribe identity.
7771
+ const entry = (url, context) => callback(url, context);
7772
+ hooks.push(entry);
7773
+ return () => {
7774
+ const index = hooks.indexOf(entry);
7775
+ if (index !== -1)
7776
+ hooks.splice(index, 1);
7777
+ };
7778
+ }
7663
7779
  // Expose hooks to register before/after navigation callbacks
7664
7780
  function onBeforeNavigate(callback) {
7665
- beforeNavigate.push(callback);
7781
+ return registerNavigationHook(beforeNavigate, callback);
7666
7782
  }
7667
7783
  function onAfterNavigate(callback) {
7668
- afterNavigate.push(callback);
7784
+ return registerNavigationHook(afterNavigate, callback);
7785
+ }
7786
+ function onBeforeSwap(callback) {
7787
+ return registerNavigationHook(beforeSwap, callback);
7788
+ }
7789
+ function onNavigationEnd(callback) {
7790
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7669
7791
  }
7670
7792
  function startRouter(options) {
7671
7793
  // If not has g-boost attribute, do not start router
@@ -7689,6 +7811,7 @@ function startRouter(options) {
7689
7811
  }
7690
7812
  // Cache scripts from initial page to prevent re-execution on first navigation back
7691
7813
  cacheInitialPageScripts();
7814
+ rememberResourceUrls(document, document.baseURI);
7692
7815
  routerStarted = true;
7693
7816
  log('[GyosRouter] started');
7694
7817
  }
@@ -7745,9 +7868,13 @@ function resolveTarget(trigger, targetSelector, targetOutletIndex) {
7745
7868
  const outlet = findGlobalOutlet();
7746
7869
  return outlet instanceof HTMLElement ? outlet : null;
7747
7870
  }
7871
+ function isFullDocument(html) {
7872
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7873
+ }
7748
7874
  function saveSnapshot(url, html) {
7749
7875
  // create HTMLElement by html string to remove scripts and get clean snapshot
7750
7876
  const doc = parseNavigationDocument(html);
7877
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7751
7878
  // Ignore hash for snapshot keys
7752
7879
  if (url.includes('#'))
7753
7880
  url = url.split('#')[0];
@@ -7756,7 +7883,7 @@ function saveSnapshot(url, html) {
7756
7883
  if (s.hasAttribute('g-script-once'))
7757
7884
  s.textContent = '';
7758
7885
  });
7759
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7886
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7760
7887
  log('[GyosRouter] snapshot saved for', url);
7761
7888
  }
7762
7889
  function getOutletIndex(root, target) {
@@ -7868,10 +7995,10 @@ function consumeViewTransitionRejection(promise) {
7868
7995
  // update callback remains the navigation source of truth and is awaited below.
7869
7996
  void promise?.catch(() => undefined);
7870
7997
  }
7871
- function runNavigationHooks(callbacks, url) {
7872
- callbacks.forEach(callback => {
7998
+ function runNavigationHooks(callbacks, url, context) {
7999
+ [...callbacks].forEach(callback => {
7873
8000
  try {
7874
- callback(url);
8001
+ callback(url, { ...context });
7875
8002
  }
7876
8003
  catch (error) {
7877
8004
  console.error('[GyosRouter] navigation hook error', error);
@@ -7909,7 +8036,13 @@ function buildRequest(opts) {
7909
8036
  url = mergeFormDataIntoUrl(url, opts.formData);
7910
8037
  }
7911
8038
  else {
7912
- init.body = opts.formData;
8039
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
8040
+ const encoded = new URLSearchParams();
8041
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
8042
+ init.body = encoded;
8043
+ }
8044
+ else
8045
+ init.body = opts.formData;
7913
8046
  }
7914
8047
  }
7915
8048
  else if (opts.jsonData) {
@@ -7952,25 +8085,26 @@ function preload(url) {
7952
8085
  preloadControllers.delete(cacheKey);
7953
8086
  });
7954
8087
  }
7955
- async function updateHead(fromDoc, signal) {
8088
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7956
8089
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7957
8090
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7958
8091
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7959
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8092
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7960
8093
  }
7961
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8094
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7962
8095
  // scripts in current document and it not in target outlet
7963
8096
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7964
8097
  // scripts in fromDoc and it not in source outlet
7965
8098
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7966
8099
  // Diff and update scripts not in outlet/target
7967
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8100
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7968
8101
  }
7969
8102
  function resolveIncomingScriptUrls(root, baseUrl) {
7970
- root.querySelectorAll('script[src]').forEach(script => {
7971
- const source = script.getAttribute('src');
8103
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8104
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8105
+ const source = node.getAttribute(attribute);
7972
8106
  if (source)
7973
- script.src = new URL(source, baseUrl).href;
8107
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7974
8108
  });
7975
8109
  }
7976
8110
  function isNavigableHtmlResponse(response) {
@@ -8024,6 +8158,22 @@ async function navigate(opts) {
8024
8158
  resolveDone
8025
8159
  };
8026
8160
  activeNavigation = transaction;
8161
+ const currentBaseUrl = document.baseURI;
8162
+ rememberResourceUrls(document, currentBaseUrl);
8163
+ const context = {
8164
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8165
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8166
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8167
+ status: null, committed: false, fallback: false, outcome: null
8168
+ };
8169
+ const formEvent = opts.form
8170
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8171
+ : null;
8172
+ const fallback = (url, requestSent) => {
8173
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8174
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8175
+ fallbackFromBoost(opts, url, requestSent);
8176
+ };
8027
8177
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8028
8178
  const setRand = () => {
8029
8179
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8031,7 +8181,10 @@ async function navigate(opts) {
8031
8181
  }
8032
8182
  };
8033
8183
  try {
8034
- runNavigationHooks(beforeNavigate, opts.url);
8184
+ if (formEvent)
8185
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8186
+ runNavigationHooks(beforeNavigate, opts.url, context);
8187
+ assertActiveNavigation(transaction);
8035
8188
  progressBar?.start();
8036
8189
  // popstate already points history at the destination entry. Keep the visible
8037
8190
  // page's position under currentUrl without overwriting that destination state.
@@ -8040,9 +8193,10 @@ async function navigate(opts) {
8040
8193
  saveScrollPosition();
8041
8194
  // Pick target element to swap
8042
8195
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8196
+ context.target = target;
8043
8197
  if (!target) {
8044
8198
  if (isActiveNavigation(transaction))
8045
- fallbackFromBoost(opts, opts.url, false);
8199
+ fallback(opts.url, false);
8046
8200
  return;
8047
8201
  }
8048
8202
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8067,6 +8221,7 @@ async function navigate(opts) {
8067
8221
  if (hasTargetSpinner)
8068
8222
  transaction.spinner = showTargetSpinner(target, swapMode);
8069
8223
  const { finalUrl, init } = buildRequest(opts);
8224
+ context.url = finalUrl;
8070
8225
  // Add abort signal to request
8071
8226
  init.signal = transaction.controller.signal;
8072
8227
  let html;
@@ -8094,7 +8249,8 @@ async function navigate(opts) {
8094
8249
  if (error.name === 'AbortError')
8095
8250
  throw error;
8096
8251
  assertActiveNavigation(transaction);
8097
- window.location.href = finalUrl;
8252
+ context.outcome = 'network-error';
8253
+ fallback(finalUrl, true);
8098
8254
  return;
8099
8255
  }
8100
8256
  preloadCache.delete(preloadKey); // consume cache
@@ -8119,28 +8275,46 @@ async function navigate(opts) {
8119
8275
  log('[GyosRouter] Navigation cancelled');
8120
8276
  return;
8121
8277
  }
8278
+ context.outcome = 'network-error';
8122
8279
  if (isActiveNavigation(transaction))
8123
- fallbackFromBoost(opts, finalUrl, true);
8280
+ fallback(finalUrl, true);
8124
8281
  return;
8125
8282
  }
8126
8283
  }
8127
8284
  assertActiveNavigation(transaction);
8128
- // If response not ok, fallback to full navigation
8129
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8285
+ context.status = response?.status ?? null;
8286
+ context.url = response?.url || finalUrl;
8287
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8288
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8289
+ && acceptedErrors.includes(String(response.status));
8290
+ if (response && !response.ok)
8291
+ context.outcome = 'http-error';
8292
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8293
+ context.outcome ?? (context.outcome = 'invalid-response');
8130
8294
  if (isActiveNavigation(transaction))
8131
- fallbackFromBoost(opts, finalUrl, true);
8295
+ fallback(finalUrl, true);
8132
8296
  return;
8133
8297
  }
8134
8298
  html = await response.text();
8135
8299
  assertActiveNavigation(transaction);
8136
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8137
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8138
- }
8139
8300
  }
8140
8301
  // Parse HTML
8141
8302
  const doc = html
8142
8303
  ? parseNavigationDocument(html)
8143
8304
  : document.implementation.createHTMLDocument();
8305
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8306
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8307
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8308
+ context.outcome = 'invalid-response';
8309
+ fallback(response?.url || finalUrl, true);
8310
+ return;
8311
+ }
8312
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8313
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8314
+ }
8315
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8316
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8317
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8144
8318
  // Pick source fragment
8145
8319
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8146
8320
  stripInertFallbackContent(src);
@@ -8152,15 +8326,18 @@ async function navigate(opts) {
8152
8326
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8153
8327
  }
8154
8328
  resolveIncomingScriptUrls(doc, targetUrl);
8329
+ context.url = targetUrl;
8155
8330
  if (opts.historyFragment)
8156
8331
  resolveIncomingScriptUrls(src, targetUrl);
8157
8332
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8158
8333
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8159
8334
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8160
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8335
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8161
8336
  const performUpdate = async () => {
8162
8337
  assertActiveNavigation(transaction);
8163
8338
  transaction.committing = true;
8339
+ runNavigationHooks(beforeSwap, targetUrl, context);
8340
+ assertActiveNavigation(transaction);
8164
8341
  // Update progress to rand 80 - 90% before swap
8165
8342
  progressBar?.setProgress(Math.random() * 10 + 80);
8166
8343
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8231,21 +8408,34 @@ async function navigate(opts) {
8231
8408
  beforeScripts: async () => {
8232
8409
  if (!isFullOutletNavigation || currentHead)
8233
8410
  return;
8411
+ if (syncDocumentAttributes) {
8412
+ for (const name of ['lang', 'dir']) {
8413
+ const value = doc.documentElement.getAttribute(name);
8414
+ if (value === null)
8415
+ document.documentElement.removeAttribute(name);
8416
+ else
8417
+ document.documentElement.setAttribute(name, value);
8418
+ }
8419
+ }
8234
8420
  const incomingTitle = doc.querySelector('title');
8235
8421
  if (incomingTitle) {
8236
8422
  document.title = incomingTitle.textContent || document.title;
8237
8423
  }
8238
- await updateHead(doc, transaction.controller.signal);
8424
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8239
8425
  assertActiveNavigation(transaction);
8240
8426
  },
8241
8427
  onCommitted: (committedTarget, roots) => {
8242
8428
  target = committedTarget;
8429
+ context.target = committedTarget;
8430
+ context.committed = true;
8431
+ progressBar?.reconnect();
8243
8432
  committedRoots = roots;
8244
8433
  }
8245
8434
  });
8435
+ context.committed = true;
8246
8436
  assertActiveNavigation(transaction);
8247
8437
  if (isFullOutletNavigation) {
8248
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8438
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8249
8439
  assertActiveNavigation(transaction);
8250
8440
  }
8251
8441
  }
@@ -8279,14 +8469,15 @@ async function navigate(opts) {
8279
8469
  await performUpdate();
8280
8470
  }
8281
8471
  assertActiveNavigation(transaction);
8282
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8472
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8283
8473
  disposeEffects(opts.trigger);
8284
8474
  opts.trigger.remove();
8285
8475
  }
8286
8476
  if (hasTargetSpinner)
8287
8477
  hideTargetSpinner(transaction.spinner);
8288
8478
  transaction.spinner = null;
8289
- runNavigationHooks(afterNavigate, targetUrl);
8479
+ context.outcome ?? (context.outcome = 'success');
8480
+ runNavigationHooks(afterNavigate, targetUrl, context);
8290
8481
  log('[GyosRouter] navigated to', targetUrl);
8291
8482
  currentUrl = changesState
8292
8483
  ? canonicalUrl(targetUrl, true)
@@ -8302,11 +8493,15 @@ async function navigate(opts) {
8302
8493
  return;
8303
8494
  }
8304
8495
  if (isActiveNavigation(transaction)) {
8496
+ context.outcome ?? (context.outcome = 'error');
8305
8497
  console.error('[GyosRouter] navigation error', error);
8306
- fallbackFromBoost(opts, opts.url, true);
8498
+ fallback(opts.url, true);
8307
8499
  }
8308
8500
  }
8309
8501
  finally {
8502
+ if (transaction.controller.signal.aborted)
8503
+ context.outcome = 'aborted';
8504
+ context.outcome ?? (context.outcome = 'aborted');
8310
8505
  if (transaction.interval)
8311
8506
  clearInterval(transaction.interval);
8312
8507
  if (transaction.spinner)
@@ -8316,6 +8511,15 @@ async function navigate(opts) {
8316
8511
  progressBar?.complete();
8317
8512
  }
8318
8513
  transaction.resolveDone();
8514
+ if (formEvent)
8515
+ submittingForms.delete(formEvent.form);
8516
+ runNavigationHooks(navigationEnd, context.url, context);
8517
+ if (formEvent) {
8518
+ const { url, status, outcome, committed, fallback } = context;
8519
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8520
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8521
+ }));
8522
+ }
8319
8523
  }
8320
8524
  }
8321
8525
  function shouldBoost(el) {
@@ -8424,16 +8628,34 @@ function onSubmit(event) {
8424
8628
  return;
8425
8629
  if (shouldDeferToFormValidation(form))
8426
8630
  return;
8427
- event.preventDefault();
8428
- const action = form.action || window.location.href;
8429
- const method = (form.method || 'GET').toUpperCase();
8430
- const url = new URL(action, window.location.href);
8431
- if (url.origin !== window.location.origin) {
8432
- window.location.href = url.toString();
8631
+ const submitter = event.submitter;
8632
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8633
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8634
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8635
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8636
+ const formEncoding = override('enctype')?.toLowerCase();
8637
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8638
+ return;
8639
+ if (!resolveTarget(form))
8640
+ return;
8641
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8642
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8433
8643
  return;
8644
+ let url;
8645
+ try {
8646
+ url = new URL(override('action') || window.location.href, document.baseURI);
8434
8647
  }
8435
- const formData = new FormData(form);
8436
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8648
+ catch {
8649
+ return;
8650
+ }
8651
+ if (url.origin !== window.location.origin)
8652
+ return;
8653
+ event.preventDefault();
8654
+ if (submittingForms.has(form))
8655
+ return;
8656
+ const formData = new FormData(form, submitter);
8657
+ submittingForms.add(form);
8658
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8437
8659
  }
8438
8660
  function onPopState(event) {
8439
8661
  const url = window.location.href;
@@ -8538,10 +8760,12 @@ const Gyos = {
8538
8760
  startRouter,
8539
8761
  onBeforeNavigate,
8540
8762
  onAfterNavigate,
8763
+ onBeforeSwap,
8764
+ onNavigationEnd,
8541
8765
  portalCreate,
8542
8766
  portalDestroy,
8543
8767
  setCspNonce,
8544
- version: '0.3.2'
8768
+ version: '0.4.1'
8545
8769
  };
8546
8770
 
8547
8771
  const standardExpressionRuntime = {