gyosjs 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gyos.csp.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.3.1
2
+ * GyosJS v0.4.0
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -8851,59 +8851,59 @@
8851
8851
  return;
8852
8852
  const style = document.createElement('style');
8853
8853
  style.id = styleId;
8854
- style.textContent = `
8855
- /* Opacity utilities */
8854
+ style.textContent = `
8855
+ /* Opacity utilities */
8856
8856
  .gyos-t-opacity-0 { opacity: 0; }
8857
8857
  .gyos-t-opacity-100 { opacity: 1; }
8858
-
8859
- /* Transform - Translate Y */
8858
+
8859
+ /* Transform - Translate Y */
8860
8860
  .gyos-t-translate-y-0 { transform: translateY(0); }
8861
8861
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
8862
8862
  .gyos-t-translate-y-100 { transform: translateY(100%); }
8863
-
8864
- /* Transform - Translate X */
8863
+
8864
+ /* Transform - Translate X */
8865
8865
  .gyos-t-translate-x-0 { transform: translateX(0); }
8866
8866
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
8867
8867
  .gyos-t-translate-x-100 { transform: translateX(100%); }
8868
-
8869
- /* Transform - Scale */
8868
+
8869
+ /* Transform - Scale */
8870
8870
  .gyos-t-scale-0 { transform: scale(0); }
8871
8871
  .gyos-t-scale-50 { transform: scale(0.5); }
8872
8872
  .gyos-t-scale-100 { transform: scale(1); }
8873
-
8874
- /* Animation Keyframes */
8875
- @keyframes gyos-fade-in {
8876
- from { opacity: 0; }
8877
- to { opacity: 1; }
8878
- }
8879
-
8880
- @keyframes gyos-fade-out {
8881
- from { opacity: 1; }
8882
- to { opacity: 0; }
8883
- }
8884
-
8885
- @keyframes gyos-slide-down {
8886
- from { transform: translateY(-100%); opacity: 0; }
8887
- to { transform: translateY(0); opacity: 1; }
8888
- }
8889
-
8890
- @keyframes gyos-slide-up {
8891
- from { transform: translateY(100%); opacity: 0; }
8892
- to { transform: translateY(0); opacity: 1; }
8893
- }
8894
-
8895
- @keyframes gyos-scale-in {
8896
- from { transform: scale(0); opacity: 0; }
8897
- to { transform: scale(1); opacity: 1; }
8898
- }
8899
-
8900
- @keyframes gyos-scale-out {
8901
- from { transform: scale(1); opacity: 1; }
8902
- to { transform: scale(0); opacity: 0; }
8903
- }
8904
-
8905
- [g-cloak] {
8906
- display: none !important;
8873
+
8874
+ /* Animation Keyframes */
8875
+ @keyframes gyos-fade-in {
8876
+ from { opacity: 0; }
8877
+ to { opacity: 1; }
8878
+ }
8879
+
8880
+ @keyframes gyos-fade-out {
8881
+ from { opacity: 1; }
8882
+ to { opacity: 0; }
8883
+ }
8884
+
8885
+ @keyframes gyos-slide-down {
8886
+ from { transform: translateY(-100%); opacity: 0; }
8887
+ to { transform: translateY(0); opacity: 1; }
8888
+ }
8889
+
8890
+ @keyframes gyos-slide-up {
8891
+ from { transform: translateY(100%); opacity: 0; }
8892
+ to { transform: translateY(0); opacity: 1; }
8893
+ }
8894
+
8895
+ @keyframes gyos-scale-in {
8896
+ from { transform: scale(0); opacity: 0; }
8897
+ to { transform: scale(1); opacity: 1; }
8898
+ }
8899
+
8900
+ @keyframes gyos-scale-out {
8901
+ from { transform: scale(1); opacity: 1; }
8902
+ to { transform: scale(0); opacity: 0; }
8903
+ }
8904
+
8905
+ [g-cloak] {
8906
+ display: none !important;
8907
8907
  }`;
8908
8908
  document.head.appendChild(style);
8909
8909
  }
@@ -11838,6 +11838,10 @@
11838
11838
  const structuralElements = [];
11839
11839
  const root = elements[0];
11840
11840
  elements.forEach(el => {
11841
+ // Await branches are detached and parsed only after their alias scope exists.
11842
+ // Do not evaluate nested structural expressions during the parent scan.
11843
+ if (isAwaitBranchDescendant(el))
11844
+ return;
11841
11845
  const hasIf = el.hasAttribute('*if');
11842
11846
  const hasFor = el.hasAttribute('*for');
11843
11847
  const hasSwitch = el.hasAttribute('*switch');
@@ -11882,6 +11886,20 @@
11882
11886
  }
11883
11887
  });
11884
11888
  }
11889
+ function isAwaitBranchDescendant(element) {
11890
+ let child = element;
11891
+ let parent = element.parentElement;
11892
+ while (parent && parent !== document.body) {
11893
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
11894
+ child.hasAttribute('*then') ||
11895
+ child.hasAttribute('*catch'))) {
11896
+ return true;
11897
+ }
11898
+ child = parent;
11899
+ parent = parent.parentElement;
11900
+ }
11901
+ return false;
11902
+ }
11885
11903
  const elementBelongsToAnotherScope = (el, scope) => {
11886
11904
  const owner = getScopeFromElement(el);
11887
11905
  return Boolean(owner && owner !== scope);
@@ -13242,33 +13260,44 @@
13242
13260
  getCurrentProgress() {
13243
13261
  return this.currentProgress;
13244
13262
  }
13263
+ reconnect() {
13264
+ if (!this.element || !this.progressBarEnabled || !document.body)
13265
+ return;
13266
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
13267
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
13268
+ if (node !== this.element)
13269
+ node.remove();
13270
+ });
13271
+ if (!this.element.isConnected)
13272
+ document.body.appendChild(this.element);
13273
+ }
13245
13274
  createBar() {
13246
13275
  if (typeof document === 'undefined')
13247
13276
  return;
13248
13277
  // Create progress bar element
13249
13278
  this.element = document.createElement('div');
13250
13279
  this.element.id = 'gyos-progress-bar';
13251
- this.element.style.cssText = `
13252
- position: fixed;
13253
- top: 0;
13254
- left: 0;
13255
- width: 0%;
13256
- height: 6px;
13257
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
13258
- z-index: 999999;
13259
- transition: width 0.3s linear, opacity 0.3s linear;
13260
- opacity: 0;
13261
- pointer-events: none;
13262
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
13280
+ this.element.style.cssText = `
13281
+ position: fixed;
13282
+ top: 0;
13283
+ left: 0;
13284
+ width: 0%;
13285
+ height: 6px;
13286
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
13287
+ z-index: 999999;
13288
+ transition: width 0.3s linear, opacity 0.3s linear;
13289
+ opacity: 0;
13290
+ pointer-events: none;
13291
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
13263
13292
  `;
13264
13293
  // Insert into DOM when ready
13265
13294
  if (document.readyState === 'loading') {
13266
13295
  document.addEventListener('DOMContentLoaded', () => {
13267
- document.body.insertAdjacentElement('beforeend', this.element);
13268
- });
13296
+ this.reconnect();
13297
+ }, { once: true });
13269
13298
  }
13270
13299
  else {
13271
- document.body.insertAdjacentElement('beforeend', this.element);
13300
+ this.reconnect();
13272
13301
  }
13273
13302
  }
13274
13303
  start() {
@@ -13292,6 +13321,7 @@
13292
13321
  setProgress(percent) {
13293
13322
  if (!this.element || !this.progressBarEnabled)
13294
13323
  return;
13324
+ this.reconnect();
13295
13325
  // Clamp between 0-100
13296
13326
  percent = Math.min(100, Math.max(0, percent));
13297
13327
  this.currentProgress = percent;
@@ -13340,41 +13370,41 @@
13340
13370
  function createTargetSpinner() {
13341
13371
  const spinner = document.createElement('div');
13342
13372
  spinner.className = 'gyos-target-spinner';
13343
- spinner.innerHTML = `
13344
- <div class="gyos-spinner-content">
13345
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
13346
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
13347
- </svg>
13348
- </div>
13373
+ spinner.innerHTML = `
13374
+ <div class="gyos-spinner-content">
13375
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
13376
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
13377
+ </svg>
13378
+ </div>
13349
13379
  `;
13350
13380
  // Inject styles if not already present
13351
13381
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
13352
13382
  const style = document.createElement('style');
13353
13383
  style.id = 'gyos-target-spinner-styles';
13354
- style.textContent = `
13355
- .gyos-target-spinner {
13356
- display: flex;
13357
- align-items: center;
13358
- justify-content: center;
13359
- padding: 20px;
13360
- min-height: 60px;
13361
- }
13362
- .gyos-spinner-content {
13363
- display: flex;
13364
- align-items: center;
13365
- gap: 10px;
13366
- color: var(--gyos-spinner-color, #667eea);
13367
- font-size: 14px;
13368
- }
13369
- .gyos-spinner-icon {
13370
- width: 24px;
13371
- height: 24px;
13372
- animation: gyos-spin 1s linear infinite;
13373
- }
13374
- @keyframes gyos-spin {
13375
- 0% { transform: rotate(0deg); }
13376
- 100% { transform: rotate(360deg); }
13377
- }
13384
+ style.textContent = `
13385
+ .gyos-target-spinner {
13386
+ display: flex;
13387
+ align-items: center;
13388
+ justify-content: center;
13389
+ padding: 20px;
13390
+ min-height: 60px;
13391
+ }
13392
+ .gyos-spinner-content {
13393
+ display: flex;
13394
+ align-items: center;
13395
+ gap: 10px;
13396
+ color: var(--gyos-spinner-color, #667eea);
13397
+ font-size: 14px;
13398
+ }
13399
+ .gyos-spinner-icon {
13400
+ width: 24px;
13401
+ height: 24px;
13402
+ animation: gyos-spin 1s linear infinite;
13403
+ }
13404
+ @keyframes gyos-spin {
13405
+ 0% { transform: rotate(0deg); }
13406
+ 100% { transform: rotate(360deg); }
13407
+ }
13378
13408
  `;
13379
13409
  document.head.appendChild(style);
13380
13410
  }
@@ -13734,8 +13764,8 @@
13734
13764
  }
13735
13765
  result = target;
13736
13766
  }
13737
- await options.beforeScripts?.();
13738
13767
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
13768
+ await options.beforeScripts?.();
13739
13769
  // Additive swaps must not re-run scripts that already existed in the target.
13740
13770
  if (normalized === 'append' || normalized === 'prepend') {
13741
13771
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -13975,6 +14005,21 @@
13975
14005
  window.scrollTo({ top: 0, behavior: 'smooth' });
13976
14006
  }
13977
14007
 
14008
+ // A retained relative URL still identifies the resource loaded on its original
14009
+ // page, even after pushState changes document.baseURI.
14010
+ const resourceUrls = new WeakMap();
14011
+ function rememberResourceUrls(root, baseUrl) {
14012
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
14013
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
14014
+ const source = node.getAttribute(attribute);
14015
+ if (resourceUrls.get(node)?.source === source)
14016
+ return;
14017
+ try {
14018
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
14019
+ }
14020
+ catch { /* Invalid resource URLs retain their literal identity. */ }
14021
+ });
14022
+ }
13978
14023
  function isNonceMeta(el) {
13979
14024
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
13980
14025
  }
@@ -13992,7 +14037,20 @@
13992
14037
  return;
13993
14038
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
13994
14039
  return;
13995
- attributes.set(attr.name, attr.value);
14040
+ let value = attr.value;
14041
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
14042
+ const cached = resourceUrls.get(el);
14043
+ if (cached?.source === value)
14044
+ value = cached.url;
14045
+ else {
14046
+ try {
14047
+ value = new URL(value, context.baseUrl || el.baseURI).href;
14048
+ resourceUrls.set(el, { source: attr.value, url: value });
14049
+ }
14050
+ catch { /* Keep invalid URLs distinct. */ }
14051
+ }
14052
+ }
14053
+ attributes.set(attr.name, value);
13996
14054
  });
13997
14055
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
13998
14056
  attributes.set('nonce', context.activeNonce);
@@ -14059,19 +14117,21 @@
14059
14117
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
14060
14118
  }
14061
14119
  }
14062
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
14120
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
14063
14121
  const csp = expressionRuntimeMode() === 'csp';
14064
14122
  const context = {
14065
14123
  csp,
14066
14124
  activeNonce: csp ? resolveCspNonce() : undefined
14067
14125
  };
14068
- const current = keyedNodes(currentNodes, context);
14126
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
14069
14127
  const next = keyedNodes(nextNodes, context);
14128
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
14129
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
14070
14130
  const currentKeys = new Set(current.map(item => item.key));
14071
14131
  const nextKeys = new Set(next.map(item => item.key));
14072
14132
  // Remove nodes that are not in the new head
14073
14133
  current.forEach(({ key, node }) => {
14074
- if (!nextKeys.has(key)) {
14134
+ if (!nextKeys.has(key) && !persistentKey(node)) {
14075
14135
  node.remove();
14076
14136
  }
14077
14137
  });
@@ -14079,6 +14139,8 @@
14079
14139
  for (const { key, node } of next) {
14080
14140
  if (signal?.aborted)
14081
14141
  return;
14142
+ if (persistent.has(persistentKey(node)))
14143
+ continue;
14082
14144
  if (!currentKeys.has(key)) {
14083
14145
  if (!canInsertNode(node, context)) {
14084
14146
  warnSkippedNode(node);
@@ -14281,6 +14343,7 @@
14281
14343
  * MPA boost navigation inspired by Turbo Drive.
14282
14344
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
14283
14345
  */
14346
+ const submittingForms = new WeakSet();
14284
14347
  const snapshots = new Map();
14285
14348
  const preloadCache = new Map();
14286
14349
  const preloadControllers = new Map();
@@ -14297,12 +14360,30 @@
14297
14360
  let progressBar = null;
14298
14361
  const beforeNavigate = [];
14299
14362
  const afterNavigate = [];
14363
+ const beforeSwap = [];
14364
+ const navigationEnd = [];
14365
+ function registerNavigationHook(hooks, callback) {
14366
+ // A wrapper gives each registration its own unsubscribe identity.
14367
+ const entry = (url, context) => callback(url, context);
14368
+ hooks.push(entry);
14369
+ return () => {
14370
+ const index = hooks.indexOf(entry);
14371
+ if (index !== -1)
14372
+ hooks.splice(index, 1);
14373
+ };
14374
+ }
14300
14375
  // Expose hooks to register before/after navigation callbacks
14301
14376
  function onBeforeNavigate(callback) {
14302
- beforeNavigate.push(callback);
14377
+ return registerNavigationHook(beforeNavigate, callback);
14303
14378
  }
14304
14379
  function onAfterNavigate(callback) {
14305
- afterNavigate.push(callback);
14380
+ return registerNavigationHook(afterNavigate, callback);
14381
+ }
14382
+ function onBeforeSwap(callback) {
14383
+ return registerNavigationHook(beforeSwap, callback);
14384
+ }
14385
+ function onNavigationEnd(callback) {
14386
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
14306
14387
  }
14307
14388
  function startRouter(options) {
14308
14389
  // If not has g-boost attribute, do not start router
@@ -14326,6 +14407,7 @@
14326
14407
  }
14327
14408
  // Cache scripts from initial page to prevent re-execution on first navigation back
14328
14409
  cacheInitialPageScripts();
14410
+ rememberResourceUrls(document, document.baseURI);
14329
14411
  routerStarted = true;
14330
14412
  log('[GyosRouter] started');
14331
14413
  }
@@ -14382,9 +14464,13 @@
14382
14464
  const outlet = findGlobalOutlet();
14383
14465
  return outlet instanceof HTMLElement ? outlet : null;
14384
14466
  }
14467
+ function isFullDocument(html) {
14468
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
14469
+ }
14385
14470
  function saveSnapshot(url, html) {
14386
14471
  // create HTMLElement by html string to remove scripts and get clean snapshot
14387
14472
  const doc = parseNavigationDocument(html);
14473
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
14388
14474
  // Ignore hash for snapshot keys
14389
14475
  if (url.includes('#'))
14390
14476
  url = url.split('#')[0];
@@ -14393,7 +14479,7 @@
14393
14479
  if (s.hasAttribute('g-script-once'))
14394
14480
  s.textContent = '';
14395
14481
  });
14396
- snapshots.set(url, { html: doc.documentElement.outerHTML });
14482
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
14397
14483
  log('[GyosRouter] snapshot saved for', url);
14398
14484
  }
14399
14485
  function getOutletIndex(root, target) {
@@ -14505,10 +14591,10 @@
14505
14591
  // update callback remains the navigation source of truth and is awaited below.
14506
14592
  void promise?.catch(() => undefined);
14507
14593
  }
14508
- function runNavigationHooks(callbacks, url) {
14509
- callbacks.forEach(callback => {
14594
+ function runNavigationHooks(callbacks, url, context) {
14595
+ [...callbacks].forEach(callback => {
14510
14596
  try {
14511
- callback(url);
14597
+ callback(url, { ...context });
14512
14598
  }
14513
14599
  catch (error) {
14514
14600
  console.error('[GyosRouter] navigation hook error', error);
@@ -14546,7 +14632,13 @@
14546
14632
  url = mergeFormDataIntoUrl(url, opts.formData);
14547
14633
  }
14548
14634
  else {
14549
- init.body = opts.formData;
14635
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
14636
+ const encoded = new URLSearchParams();
14637
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
14638
+ init.body = encoded;
14639
+ }
14640
+ else
14641
+ init.body = opts.formData;
14550
14642
  }
14551
14643
  }
14552
14644
  else if (opts.jsonData) {
@@ -14589,25 +14681,26 @@
14589
14681
  preloadControllers.delete(cacheKey);
14590
14682
  });
14591
14683
  }
14592
- async function updateHead(fromDoc, signal) {
14684
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
14593
14685
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
14594
14686
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
14595
14687
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
14596
- await diffNodes(currentNodes, nextNodes, document.head, signal);
14688
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
14597
14689
  }
14598
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
14690
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
14599
14691
  // scripts in current document and it not in target outlet
14600
14692
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
14601
14693
  // scripts in fromDoc and it not in source outlet
14602
14694
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
14603
14695
  // Diff and update scripts not in outlet/target
14604
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
14696
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
14605
14697
  }
14606
14698
  function resolveIncomingScriptUrls(root, baseUrl) {
14607
- root.querySelectorAll('script[src]').forEach(script => {
14608
- const source = script.getAttribute('src');
14699
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
14700
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
14701
+ const source = node.getAttribute(attribute);
14609
14702
  if (source)
14610
- script.src = new URL(source, baseUrl).href;
14703
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
14611
14704
  });
14612
14705
  }
14613
14706
  function isNavigableHtmlResponse(response) {
@@ -14661,6 +14754,22 @@
14661
14754
  resolveDone
14662
14755
  };
14663
14756
  activeNavigation = transaction;
14757
+ const currentBaseUrl = document.baseURI;
14758
+ rememberResourceUrls(document, currentBaseUrl);
14759
+ const context = {
14760
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
14761
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
14762
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
14763
+ status: null, committed: false, fallback: false, outcome: null
14764
+ };
14765
+ const formEvent = opts.form
14766
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
14767
+ : null;
14768
+ const fallback = (url, requestSent) => {
14769
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
14770
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
14771
+ fallbackFromBoost(opts, url, requestSent);
14772
+ };
14664
14773
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
14665
14774
  const setRand = () => {
14666
14775
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -14668,7 +14777,10 @@
14668
14777
  }
14669
14778
  };
14670
14779
  try {
14671
- runNavigationHooks(beforeNavigate, opts.url);
14780
+ if (formEvent)
14781
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
14782
+ runNavigationHooks(beforeNavigate, opts.url, context);
14783
+ assertActiveNavigation(transaction);
14672
14784
  progressBar?.start();
14673
14785
  // popstate already points history at the destination entry. Keep the visible
14674
14786
  // page's position under currentUrl without overwriting that destination state.
@@ -14677,9 +14789,10 @@
14677
14789
  saveScrollPosition();
14678
14790
  // Pick target element to swap
14679
14791
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
14792
+ context.target = target;
14680
14793
  if (!target) {
14681
14794
  if (isActiveNavigation(transaction))
14682
- fallbackFromBoost(opts, opts.url, false);
14795
+ fallback(opts.url, false);
14683
14796
  return;
14684
14797
  }
14685
14798
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -14704,6 +14817,7 @@
14704
14817
  if (hasTargetSpinner)
14705
14818
  transaction.spinner = showTargetSpinner(target, swapMode);
14706
14819
  const { finalUrl, init } = buildRequest(opts);
14820
+ context.url = finalUrl;
14707
14821
  // Add abort signal to request
14708
14822
  init.signal = transaction.controller.signal;
14709
14823
  let html;
@@ -14731,7 +14845,8 @@
14731
14845
  if (error.name === 'AbortError')
14732
14846
  throw error;
14733
14847
  assertActiveNavigation(transaction);
14734
- window.location.href = finalUrl;
14848
+ context.outcome = 'network-error';
14849
+ fallback(finalUrl, true);
14735
14850
  return;
14736
14851
  }
14737
14852
  preloadCache.delete(preloadKey); // consume cache
@@ -14756,28 +14871,46 @@
14756
14871
  log('[GyosRouter] Navigation cancelled');
14757
14872
  return;
14758
14873
  }
14874
+ context.outcome = 'network-error';
14759
14875
  if (isActiveNavigation(transaction))
14760
- fallbackFromBoost(opts, finalUrl, true);
14876
+ fallback(finalUrl, true);
14761
14877
  return;
14762
14878
  }
14763
14879
  }
14764
14880
  assertActiveNavigation(transaction);
14765
- // If response not ok, fallback to full navigation
14766
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
14881
+ context.status = response?.status ?? null;
14882
+ context.url = response?.url || finalUrl;
14883
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
14884
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
14885
+ && acceptedErrors.includes(String(response.status));
14886
+ if (response && !response.ok)
14887
+ context.outcome = 'http-error';
14888
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
14889
+ context.outcome ?? (context.outcome = 'invalid-response');
14767
14890
  if (isActiveNavigation(transaction))
14768
- fallbackFromBoost(opts, finalUrl, true);
14891
+ fallback(finalUrl, true);
14769
14892
  return;
14770
14893
  }
14771
14894
  html = await response.text();
14772
14895
  assertActiveNavigation(transaction);
14773
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
14774
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
14775
- }
14776
14896
  }
14777
14897
  // Parse HTML
14778
14898
  const doc = html
14779
14899
  ? parseNavigationDocument(html)
14780
14900
  : document.implementation.createHTMLDocument();
14901
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
14902
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
14903
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
14904
+ context.outcome = 'invalid-response';
14905
+ fallback(response?.url || finalUrl, true);
14906
+ return;
14907
+ }
14908
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
14909
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
14910
+ }
14911
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
14912
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
14913
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
14781
14914
  // Pick source fragment
14782
14915
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
14783
14916
  stripInertFallbackContent(src);
@@ -14789,15 +14922,18 @@
14789
14922
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
14790
14923
  }
14791
14924
  resolveIncomingScriptUrls(doc, targetUrl);
14925
+ context.url = targetUrl;
14792
14926
  if (opts.historyFragment)
14793
14927
  resolveIncomingScriptUrls(src, targetUrl);
14794
14928
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
14795
14929
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
14796
14930
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
14797
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
14931
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
14798
14932
  const performUpdate = async () => {
14799
14933
  assertActiveNavigation(transaction);
14800
14934
  transaction.committing = true;
14935
+ runNavigationHooks(beforeSwap, targetUrl, context);
14936
+ assertActiveNavigation(transaction);
14801
14937
  // Update progress to rand 80 - 90% before swap
14802
14938
  progressBar?.setProgress(Math.random() * 10 + 80);
14803
14939
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -14868,21 +15004,34 @@
14868
15004
  beforeScripts: async () => {
14869
15005
  if (!isFullOutletNavigation || currentHead)
14870
15006
  return;
15007
+ if (syncDocumentAttributes) {
15008
+ for (const name of ['lang', 'dir']) {
15009
+ const value = doc.documentElement.getAttribute(name);
15010
+ if (value === null)
15011
+ document.documentElement.removeAttribute(name);
15012
+ else
15013
+ document.documentElement.setAttribute(name, value);
15014
+ }
15015
+ }
14871
15016
  const incomingTitle = doc.querySelector('title');
14872
15017
  if (incomingTitle) {
14873
15018
  document.title = incomingTitle.textContent || document.title;
14874
15019
  }
14875
- await updateHead(doc, transaction.controller.signal);
15020
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
14876
15021
  assertActiveNavigation(transaction);
14877
15022
  },
14878
15023
  onCommitted: (committedTarget, roots) => {
14879
15024
  target = committedTarget;
15025
+ context.target = committedTarget;
15026
+ context.committed = true;
15027
+ progressBar?.reconnect();
14880
15028
  committedRoots = roots;
14881
15029
  }
14882
15030
  });
15031
+ context.committed = true;
14883
15032
  assertActiveNavigation(transaction);
14884
15033
  if (isFullOutletNavigation) {
14885
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
15034
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
14886
15035
  assertActiveNavigation(transaction);
14887
15036
  }
14888
15037
  }
@@ -14916,14 +15065,15 @@
14916
15065
  await performUpdate();
14917
15066
  }
14918
15067
  assertActiveNavigation(transaction);
14919
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
15068
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
14920
15069
  disposeEffects(opts.trigger);
14921
15070
  opts.trigger.remove();
14922
15071
  }
14923
15072
  if (hasTargetSpinner)
14924
15073
  hideTargetSpinner(transaction.spinner);
14925
15074
  transaction.spinner = null;
14926
- runNavigationHooks(afterNavigate, targetUrl);
15075
+ context.outcome ?? (context.outcome = 'success');
15076
+ runNavigationHooks(afterNavigate, targetUrl, context);
14927
15077
  log('[GyosRouter] navigated to', targetUrl);
14928
15078
  currentUrl = changesState
14929
15079
  ? canonicalUrl(targetUrl, true)
@@ -14939,11 +15089,15 @@
14939
15089
  return;
14940
15090
  }
14941
15091
  if (isActiveNavigation(transaction)) {
15092
+ context.outcome ?? (context.outcome = 'error');
14942
15093
  console.error('[GyosRouter] navigation error', error);
14943
- fallbackFromBoost(opts, opts.url, true);
15094
+ fallback(opts.url, true);
14944
15095
  }
14945
15096
  }
14946
15097
  finally {
15098
+ if (transaction.controller.signal.aborted)
15099
+ context.outcome = 'aborted';
15100
+ context.outcome ?? (context.outcome = 'aborted');
14947
15101
  if (transaction.interval)
14948
15102
  clearInterval(transaction.interval);
14949
15103
  if (transaction.spinner)
@@ -14953,6 +15107,15 @@
14953
15107
  progressBar?.complete();
14954
15108
  }
14955
15109
  transaction.resolveDone();
15110
+ if (formEvent)
15111
+ submittingForms.delete(formEvent.form);
15112
+ runNavigationHooks(navigationEnd, context.url, context);
15113
+ if (formEvent) {
15114
+ const { url, status, outcome, committed, fallback } = context;
15115
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
15116
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
15117
+ }));
15118
+ }
14956
15119
  }
14957
15120
  }
14958
15121
  function shouldBoost(el) {
@@ -15061,16 +15224,34 @@
15061
15224
  return;
15062
15225
  if (shouldDeferToFormValidation(form))
15063
15226
  return;
15064
- event.preventDefault();
15065
- const action = form.action || window.location.href;
15066
- const method = (form.method || 'GET').toUpperCase();
15067
- const url = new URL(action, window.location.href);
15068
- if (url.origin !== window.location.origin) {
15069
- window.location.href = url.toString();
15227
+ const submitter = event.submitter;
15228
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
15229
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
15230
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
15231
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
15232
+ const formEncoding = override('enctype')?.toLowerCase();
15233
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
15234
+ return;
15235
+ if (!resolveTarget(form))
15236
+ return;
15237
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
15238
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
15239
+ return;
15240
+ let url;
15241
+ try {
15242
+ url = new URL(override('action') || window.location.href, document.baseURI);
15243
+ }
15244
+ catch {
15070
15245
  return;
15071
15246
  }
15072
- const formData = new FormData(form);
15073
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
15247
+ if (url.origin !== window.location.origin)
15248
+ return;
15249
+ event.preventDefault();
15250
+ if (submittingForms.has(form))
15251
+ return;
15252
+ const formData = new FormData(form, submitter);
15253
+ submittingForms.add(form);
15254
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
15074
15255
  }
15075
15256
  function onPopState(event) {
15076
15257
  const url = window.location.href;
@@ -15175,10 +15356,12 @@
15175
15356
  startRouter,
15176
15357
  onBeforeNavigate,
15177
15358
  onAfterNavigate,
15359
+ onBeforeSwap,
15360
+ onNavigationEnd,
15178
15361
  portalCreate,
15179
15362
  portalDestroy,
15180
15363
  setCspNonce,
15181
- version: '0.3.1'
15364
+ version: '0.4.0'
15182
15365
  };
15183
15366
 
15184
15367
  setExpressionRuntime(cspExpressionRuntime);
@@ -15214,6 +15397,8 @@
15214
15397
  exports.on = on;
15215
15398
  exports.onAfterNavigate = onAfterNavigate;
15216
15399
  exports.onBeforeNavigate = onBeforeNavigate;
15400
+ exports.onBeforeSwap = onBeforeSwap;
15401
+ exports.onNavigationEnd = onNavigationEnd;
15217
15402
  exports.once = once;
15218
15403
  exports.pipe = pipe;
15219
15404
  exports.portalCreate = portalCreate;