@wcstack/router 4.31.0 → 4.33.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/README.ja.md CHANGED
@@ -215,9 +215,11 @@ export default {
215
215
  | `navigateUrl` | 書き込み面(null-idle transient) | ターゲットを書くと push 遷移。null は待機、文字列の書き込みで `navigate()` が起動し、完了後に自分で null へ戻る。null / `""` の書き込みは no-op。書くのは**ルートのパス** — basename は router が付ける: リンクの `href` ではなく `/products/3` を書く(basename `/ja` の下で `/ja/products/3` を書くと `/ja/ja/products/3` へ行く) |
216
216
  | `replaceUrl` | 書き込み面(null-idle transient) | `navigateUrl` と完全同型の契約。ただし現在の履歴エントリを**置き換える** |
217
217
  | `leaveConfirm` | input(属性 `leave-confirm`) | 空でない文字列の間、**別のルート**へのナビゲーション(リンク・戻る / 進む・`navigate()`)の前に `confirm(leaveConfirm)` を出し、断られたら留まる。**ページを離れる**ナビゲーションのうちページが取り消せるもの(router の `basename` の外へのリンク — 言語を basename に持つページの言語の切り替え — や別のサイトへのリンク、フォームの送信)も、Navigation API があれば同じく聞く(無ければブラウザの確認)。受け入れたらブラウザは聞き直さない。ページを閉じる・読み直すときはブラウザ自身の確認(`beforeunload`)。1 つの切り替えで両方を扱います。読み直しでは失われるがルートの移動では残るもの(ページ直下の要素で進行中のアップロード)だけを守るには、それには `leaveConfirm` を使わず、`$connectedCallback` で自分の `beforeunload` リスナーを足してください。未保存の変更に束ねる: `data-wcs="leaveConfirm: discardPrompt"` と `get discardPrompt() { return this.dirty ? "変更を破棄しますか?" : null; }`。クエリだけの遷移と、確認済みの遷移のリダイレクトでは聞かない。保存のハンドラが同じ更新でこれを外して `navigateUrl` を書いてもよい — router はその更新の後で確かめる。ブラウザがページに取り消させない戻る / 進むでは聞けない。`null` は属性を外す。4.9 から真偽値も受ける: `true` は英語の既定の文言(`Leave this page? Changes you made may not be saved.`。ページの言語で聞くなら文字列を束ねる)で聞き、`false` は聞かない — 以前は値を文言にしていたので、`leaveConfirm: dirty` は遷移のたびに `confirm("false")` を出していた |
218
+ | `leaveHold` | input(属性 `leave-hold`) | 4.32 から。`true` の間、**別のルート**へのナビゲーション(リンク・戻る / 進む・`navigate()` / `replace()`・`navigateUrl` / `replaceUrl`)を**止める**: 行わずに、行き先を `leaving` に出す。ページは自分のダイアログで尋ね、`proceed()` か `stay()` で答える(React の `useBlocker`)。未保存の変更に束ねる: `leaveHold: dirty`。これらのナビゲーションでは `leaveConfirm` より先。**ページを離れる**ナビゲーション(basename の外・読み直し・タブを閉じる)はページのダイアログを待てないので、`leaveConfirm` / ブラウザの確認のまま —— 両方を書く。止めないもの: クエリだけのナビゲーション、URL がすでに指すパスへのナビゲーション、最初のルート、`proceed()` が行うナビゲーションとその guard のリダイレクト。保存のハンドラは、同じ更新でこれを外して `navigateUrl` を書いてよい。ブラウザがページに取り消させない戻る / 進むは、ページがいた項目へ戻す(URL は一瞬変わる。画面は変わらない)。Navigation API の無いブラウザでは、戻る / 進むは止めない。[ページ自身の「離れますか」](#ページ自身の離れますかleavehold)。 |
219
+ | `leaving` | output only | 4.32 から。`leaveHold` が止めているナビゲーションの行き先。`navigate()` が受ける形(basename の下のパスとクエリとフラグメント)。止めていなければ `null`。次に止めたナビゲーションが置き換え、別のルートへ通ったナビゲーション(`leaveHold` を外した後のもの、Navigation API の無いブラウザの戻る / 進む)が捨てる。`wcs-router:leaving-changed` を発火。 |
218
220
  | `basename` | input | `basename` 属性に書く。Router はこの属性を初期化のときに一度だけ読むので、それより前に書く(後から書いてもルーティングの基準は変わらない。属性を書き換えたときと同じ)。読むと使われている basename を返す(初期化前は `""`)。`null` は属性を外し、`undefined` は最初の属性へ戻す |
219
221
 
220
- コマンド `navigate(path)` / `replace(path)`(いずれも async)も宣言され、command-token プロトコルから起動できる。
222
+ コマンド `navigate(path)` / `replace(path)`(いずれも async)も宣言され、command-token プロトコルから起動できる。4.32 から、`leaving` への答えの `proceed()`(async)と `stay()` も: `proceed()` は止めたナビゲーションをそのまま行い(push・replace、または履歴のその項目へ辿る)、`stay()` は捨てる。止めていなければ、どちらも何もしない。
221
223
 
222
224
  output-only メンバーはバインド attach 時に**読まれ**、以後は変更イベントで流れる — 値は「読むもの」であり「待つもの」ではないので、router が最初のルートを解決した後に attach したバインドでも取りこぼしはない。
223
225
 
@@ -237,6 +239,39 @@ output-only メンバーはバインド attach 時に**読まれ**、以後は
237
239
 
238
240
  **マルチ Router**: `params` / `routeName` は各 Router 自身のマッチを反映するが、ページの URL にクエリは 1 つしかない — どの Router 経由で書いてもページ全体のクエリが置き換わる。一方**読み取り面は per-Router**: Router は自分の `basename` 配下のナビゲーションを処理したときだけ `searchParams` を commit するので、その値は「その Router が最後に処理したナビゲーション時点のクエリ」である。
239
241
 
242
+ #### ページ自身の「離れますか」(`leaveHold`)
243
+
244
+ 4.32 から。`leaveConfirm` はブラウザの `confirm()` で尋ねる。`leaveHold` なら、ページ自身のダイアログで尋ねられる:
245
+
246
+ ```html
247
+ <wcs-router data-wcs="leaveHold: dirty; leaving: leaving; leaveConfirm: dirty;
248
+ command.proceed: $command.leave; command.stay: $command.stay">…</wcs-router>
249
+
250
+ <template data-wcs="if: asking">
251
+ <div role="dialog" aria-label="未保存の変更">
252
+ <p><output data-wcs="textContent: leaving"></output> へ移りますか? 変更は失われます。</p>
253
+ <button data-wcs="onclick: keepEditing">編集に戻る</button>
254
+ <button data-wcs="onclick: discard">破棄して移動</button>
255
+ </div>
256
+ </template>
257
+ ```
258
+
259
+ ```javascript
260
+ export default {
261
+ $commandTokens: ["leave", "stay"],
262
+ draft: "", saved: "", leaving: null,
263
+ get dirty() { return this.draft !== this.saved; },
264
+ get asking() { return this.leaving !== null; },
265
+ keepEditing() { this.$command.stay.emit(); },
266
+ discard() { this.draft = this.saved; this.$command.leave.emit(); },
267
+ };
268
+ ```
269
+
270
+ - 横の `leaveConfirm: dirty` が、どのページも止められないもの —— 読み直し、タブを閉じる、アプリの外へのリンク —— を受け持つ。
271
+ - `proceed()` は `leaveHold` が `true` のままでも行く —— ハンドラは先に下書きを片付けなくてよい。
272
+ - `navigateUrl` で終わる保存は、同じ更新で `dirty` が外れれば止めない: router はその更新の後で確かめる。
273
+ - 4.31 までは、ページはルートを guard で止めるしかなかった —— ほかのすべてのルートに同じ guard、ナビのリンクは手作り、戻るは `history.go(1)` で取り消す(docs/seam-apps.ja.md、street-reports)。
274
+
240
275
  #### ナビゲーションターゲットのクエリ文字列
241
276
 
242
277
  `navigate()` / `replace()` / `navigateUrl` / `replaceUrl` / `<wcs-link to>` は次を受理する:
package/README.md CHANGED
@@ -215,9 +215,11 @@ Define routes and layout slots inside a child template tag. A direct child templ
215
215
  | `navigateUrl` | write surface (null-idle transient) | Write a target to push-navigate. `null` means idle; writing a string starts `navigate()`, and the property resets itself to `null` when the navigation finishes. `null` / `""` writes are no-ops. The target is a **route path** — the basename is added for you: write `/products/3`, not the `href` of a link (`/ja/products/3` under the basename `/ja` lands on `/ja/ja/products/3`). |
216
216
  | `replaceUrl` | write surface (null-idle transient) | Identical contract to `navigateUrl`, but the navigation **replaces** the current history entry. |
217
217
  | `leaveConfirm` | input (attribute `leave-confirm`) | While it is a non-empty string, a navigation to **another route** — a link, Back / Forward, `navigate()` — first asks `confirm(leaveConfirm)` and stays when it is declined. So does a navigation that **leaves the page** and the page may cancel — a link outside the router's `basename` (a language switch, with the locale in the basename) or to another site, a form submission — where the Navigation API is (elsewhere it gets the browser's prompt); when it is accepted, the browser does not ask again. Closing or reloading the page gets the browser's own prompt (`beforeunload`). The one switch covers both: to guard only what a reload loses but a route change keeps (uploads still running in a page-level element), leave `leaveConfirm` unset for them and add your own `beforeunload` listener in `$connectedCallback`. Bind it to unsaved changes: `data-wcs="leaveConfirm: discardPrompt"` with `get discardPrompt() { return this.dirty ? "Discard your changes?" : null; }`. A query-only navigation does not ask, nor does the redirect of a navigation already confirmed. A save handler may clear it and write `navigateUrl` in the same update: the router checks after that update. A Back / Forward the browser does not let a page cancel is not asked. `null` removes the attribute. Since 4.9, a boolean works too: `true` asks with a default message in English (`Leave this page? Changes you made may not be saved.`; bind a string to ask in the page's language) and `false` asks nothing — before, the router turned it into the text, and `leaveConfirm: dirty` asked `confirm("false")` on every navigation. |
218
+ | `leaveHold` | input (attribute `leave-hold`) | Since 4.32. While it is `true`, a navigation to **another route** — a link, Back / Forward, `navigate()` / `replace()`, `navigateUrl` / `replaceUrl` — is **held**: not made, its destination put in `leaving`, so the page can ask in its own dialog and answer with `proceed()` or `stay()` (React's `useBlocker`). Bind it to unsaved changes: `leaveHold: dirty`. It takes precedence over `leaveConfirm` for those navigations; a navigation that **leaves the page** (outside the basename, a reload, closing the tab) cannot wait for a page's dialog, and still gets `leaveConfirm` / the browser's prompt — set both. Not held: a query-only navigation, a navigation to the path already in the URL, the first route, the navigation `proceed()` makes and its guard's redirects. A save handler may clear it and write `navigateUrl` in the same update. Back / Forward the browser does not let a page cancel are taken back to the entry the page was on (the URL changes for a moment; the screen does not); in a browser without the Navigation API they are not held. See [A page's own "leave?" dialog](#a-pages-own-leave-dialog-leavehold). |
219
+ | `leaving` | output only | Since 4.32. The destination of the navigation `leaveHold` holds, in the form `navigate()` takes (the path under the basename, with its query and hash), or `null`. A second held navigation replaces it; a navigation to another route that goes through (one made after `leaveHold` turned `false`, or a Back / Forward in a browser without the Navigation API) drops it. Fires `wcs-router:leaving-changed`. |
218
220
  | `basename` | input | Writes the `basename` attribute, which the router reads once, when it initializes: set it before then (a later write does not move the routing base, as with the attribute). Reading it returns the basename in effect (`""` before initialization). `null` removes the attribute; `undefined` restores the attribute the element started with. |
219
221
 
220
- Commands `navigate(path)` and `replace(path)` (both async) are also declared, so they can be invoked through the command-token protocol.
222
+ Commands `navigate(path)` and `replace(path)` (both async) are also declared, so they can be invoked through the command-token protocol — and, since 4.32, `proceed()` (async) and `stay()`, the answers to `leaving`: `proceed()` makes the held navigation as it was (a push, a replace, or a step through the history to that entry), `stay()` drops it. Neither does anything when nothing is held.
221
223
 
222
224
  Output-only members are **read** when a binding attaches and streamed through their change events afterwards — the value is read, not awaited, so a binding that attaches after the router already resolved its first route misses nothing.
223
225
 
@@ -237,6 +239,39 @@ Two things a search page with its query in the URL gets wrong without a word:
237
239
 
238
240
  **Multiple routers**: `params` / `routeName` reflect each router's own match, but the page URL has a single query string — a query written through *any* router replaces the query for the whole page. Reads, however, are per-router: a router commits `searchParams` only when it processes a navigation under its own `basename`, so its value is "the query as of the last navigation this router processed".
239
241
 
242
+ #### A page's own "leave?" dialog (`leaveHold`)
243
+
244
+ Since 4.32. `leaveConfirm` asks with the browser's `confirm()`; `leaveHold` lets the page ask in its own dialog:
245
+
246
+ ```html
247
+ <wcs-router data-wcs="leaveHold: dirty; leaving: leaving; leaveConfirm: dirty;
248
+ command.proceed: $command.leave; command.stay: $command.stay">…</wcs-router>
249
+
250
+ <template data-wcs="if: asking">
251
+ <div role="dialog" aria-label="Unsaved changes">
252
+ <p>Leave for <output data-wcs="textContent: leaving"></output>? Your changes will be lost.</p>
253
+ <button data-wcs="onclick: keepEditing">Keep editing</button>
254
+ <button data-wcs="onclick: discard">Discard and leave</button>
255
+ </div>
256
+ </template>
257
+ ```
258
+
259
+ ```javascript
260
+ export default {
261
+ $commandTokens: ["leave", "stay"],
262
+ draft: "", saved: "", leaving: null,
263
+ get dirty() { return this.draft !== this.saved; },
264
+ get asking() { return this.leaving !== null; },
265
+ keepEditing() { this.$command.stay.emit(); },
266
+ discard() { this.draft = this.saved; this.$command.leave.emit(); },
267
+ };
268
+ ```
269
+
270
+ - `leaveConfirm: dirty` beside it covers what no page can hold: a reload, closing the tab, a link out of the app.
271
+ - `proceed()` goes even if `leaveHold` is still `true` — the handler need not clear the draft first.
272
+ - A save that ends with `navigateUrl` is not held when the same update clears `dirty`: the router checks after that update.
273
+ - Up to 4.31 the page could only hold a route with its guards — the same guard on every other route, the links of the nav built by hand, Back undone with `history.go(1)` (docs/seam-apps.md, street-reports).
274
+
240
275
  #### Query strings in navigation targets
241
276
 
242
277
  `navigate()` / `replace()` / `navigateUrl` / `replaceUrl` / `<wcs-link to>` accept:
package/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const t={tagNames:{route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},enableShadowRoot:!1,basenameFileExtensions:[".html"]};var e="@wcstack/router",a="4.31.0";function n(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function s(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class r extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}}const i={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,a,n]=t.split("-").map(Number),s=new Date(e,a-1,n);return s.getFullYear()===e&&s.getMonth()===a-1&&s.getDate()===n?s:void 0}},any:{typeName:"any",pattern:/^.+$/s,parse(t){if(this.pattern.test(t))return t}}};function o(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}function l(t,e){const a=Object.keys(t),n=Object.keys(e);if(a.length!==n.length)return!1;for(const n of a){if(!Object.prototype.hasOwnProperty.call(e,n))return!1;if(t[n]!==e[n])return!1}return!0}function c(t,e){const a=new URLSearchParams(e),n=new URLSearchParams(t);for(const t of new Set(a.keys())){const e=a.getAll(t).sort(),s=n.getAll(t).sort();if(e.length!==s.length||e.some((t,e)=>t!==s[e]))return!1}return!0}let h=null,u=null;function d(){const e=t.basenameFileExtensions;return 0===e.length?null:(h===e&&u||(h=e,u=new RegExp(`\\/[^/]+(?:${e.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),u)}const m=/^(?!.*\/\.{1,2}(?:\/|$))[\w\-.~!$&'()*+,;=:@/%[\]|^]*$/;function f(t){return m.test(t)||t.includes("\\")?t:new URL(t.replace(/\?/g,"%3F").replace(/#/g,"%23"),"http://localhost").pathname}function p(t){if(!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}}function g(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=f(e.replace(/\/{2,}/g,"/"));const a=d();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function _(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function b(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=f(e.replace(/\/{2,}/g,"/"));const a=d();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}const y={static:2,param:1,"catch-all":0};class w extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(e,a){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&s(`${t.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&s(`${t.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):a()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=y[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const a=t.split("/");for(let t=0;t<a.length;t++){const n=a[t];if(!(""===n&&t===a.length-1&&t>0)){if("*"===n){this._segmentInfos.push({type:"catch-all",segmentText:n,paramName:"*",pattern:new RegExp("^(.*)$","s")});break}if(n.startsWith(":")){const t=n.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,a="any";t?(e=t[1],t[3]&&Object.keys(i).includes(t[3])&&(a=t[3])):e=n.substring(1),this._segmentInfos.push({type:"param",segmentText:n,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:a})}else""===n&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:n,paramName:null,pattern:new RegExp(`^${p(n).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`)})}}this._hasGuard=!1,e.hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this.enableGuard())}enableGuard(){this._hasGuard||(this._hasGuard=!0,this._guardFallbackPath||="/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const a=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),a||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||s(`${t.tagNames.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,a=t.lastPath,n=await this._guardHandler(e,a,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:o(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof n&&""!==n)throw new r("Navigation cancelled by guard.",n);if(!n)throw new r("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof n?n:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new r("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}}const v="data-wcs-ssr",N="data-wcs-ssr-link",C="@@wcs-route-ph:",P="@@wcs-route-start:",k="@@wcs-route-end:";class A extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=n();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new w(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||s(`${t.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${k}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t,e){for(this._childNodeArray=[...t],e&&(this._endMarker=e);this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}enableGuard(){this._core.enableGuard()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(e,a){if(this._initialized)return;let n;this._initialized=!0;let r=!1,i=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",r=!0):this.hasAttribute("fallback")?(n="",i=!0):s(`${t.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=a;const o=a||e;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,i&&(a&&s(`${t.tagNames.route} with fallback attribute must be a direct child of ${t.tagNames.router}.`),e.fallbackRoute&&s(`${t.tagNames.router} can have only one fallback route.`),e.fallbackRoute=this),a&&(this._core.parentCore=a._core),this._core.parsePath(n,{isIndex:r,isFallback:i,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}}const E=Symbol.for("wcstack.trustedTypes.policy"),S=Symbol.for("wcstack.trustedTypes.internal"),$="wcstack";function R(){const t=globalThis[E];return null===t||"object"!=typeof t?null:t}let L=!1;function T(t){const e=function(){const t=globalThis,e=t[S];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy($,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof R()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${$}". Allow it in the CSP (\`trusted-types ${$};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[S]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=R(),s=n?.createHTML;return"function"==typeof s?(L||(L=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${$}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${$};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const x=new Map;class H extends HTMLElement{_uuid=n();constructor(){super()}async _loadTemplateFromSource(e){try{const a=await fetch(e);a.ok||s(`${t.tagNames.layout} failed to fetch layout from source: ${e}, status: ${a.status}`);const n=await a.text();return x.set(e,n),n}catch(a){s(`${t.tagNames.layout} failed to load layout from source: ${e}, error: ${a}`,{cause:a})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),a=this.getAttribute("layout");e&&a&&console.warn(`${t.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)x.has(e)?n.innerHTML=T(x.get(e)||""):n.innerHTML=T(await this._loadTemplateFromSource(e)||"");else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=T(e):console.warn(`${t.tagNames.layout} could not find template with id "${a}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class z extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||s(`${t.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const I=new Set(["props","states","attr",""]);function M(t,e,a){for(const[n,s]of Object.entries(e))switch(a){case"props":t.props={...t.props,[n]:s};break;case"states":t.states={...t.states,[n]:s};break;case"attr":null==s?t.removeAttribute(n):t.setAttribute(n,String(s));break;case"":t[n]=s}}function U(t,e){t.hasAttribute("data-bind")||s(`${t.tagName} has no 'data-bind' attribute.`);const a=t.getAttribute("data-bind")||"";I.has(a)||s(`${t.tagName} has invalid 'data-bind' attribute: ${a}`);const n=a,r=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const a=t.getAttribute("is");return a&&a.includes("-")?a:null}(t);r&&void 0===customElements.get(r)?customElements.whenDefined(r).then(()=>{t.isConnected&&M(t,e,n)}).catch(()=>{s(`Failed to define custom element: ${r}`)}):M(t,e,n)}const O=Symbol.for("wcstack.binder");function F(){const t=globalThis[O];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const W=Symbol.for("wcstack.binder.pending"),j=Symbol.for("wcstack.binder.taken");function D(){const t=globalThis;let e=t[j];return void 0===e&&(e=new WeakSet,t[j]=e),e}function G(t,e){const a=F();if(null===a){const e=function(){const t=globalThis;let e=t[W];return void 0===e&&(e=[],t[W]=e),e}();for(let t=e.length-1;t>=0;t--)e[t].isConnected||e.splice(t,1);return e.includes(t)||e.push(t),!1}return D().add(t),a.bind(t,e),!0}const B={range:!0};function q(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),q(a,e);return e}function K(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:q(t,new Set),r=[];let i=0;for(let o=e.nextSibling;null!==o&&o!==a&&(null===s||8!==o.nodeType||!/^@@(route:|wcs-route-)/.test(o.data)||s.has(o));o=o.nextSibling)r.push(o),(n||t.childNodeArray.includes(o))&&(i=r.length);return r.length=i,r}const V=new WeakSet;function X(e){const a=t.tagNames.router,n=t.tagNames.outlet;for(const t of e.querySelectorAll(n))V.has(t)||t.previousElementSibling?.matches(a)||(V.add(t),console.warn(`[@wcstack/router] [wcs/router-outlet-misplaced] A <${a}> uses only the element right after it as its outlet, and this page has a <${n}> that no router uses. The router makes an outlet of its own right after itself, so the routes render there and the <${n}> you placed stays empty. Move the <${n}> right after the <${a}>.`,t))}const Y=t=>{for(const e of t)if(e.nodeType===Node.ELEMENT_NODE||e.nodeType===Node.TEXT_NODE&&""!==e.textContent.trim())return!0;return!1};function J(e){console.warn(`[@wcstack/router] [wcs/layout-slot-missing] This layout's template has no default <slot>, so what its <${t.tagNames.layout}> holds outside the named slots — the nested routes and their pages — is not shown. Put a <slot></slot> where the page goes.`,e)}class Q extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||s(`${t.tagNames.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const e=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(e.content.cloneNode(!0));const t=[];for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),e instanceof Element&&e.getAttribute("slot")||t.push(e),this.appendChild(e);!this.shadowRoot.querySelector('slot:not([name]), slot[name=""]')&&Y(t)&&J(this),X(this.shadowRoot)}else{const a=e.content.cloneNode(!0),n=new Map;a.querySelectorAll("slot").forEach(e=>{const a=e.getAttribute("name")||"";n.has(a)?console.warn(`${t.tagNames.layoutOutlet} duplicate slot name "${a}" in layout template.`):n.set(a,e)});const s=new Map,r=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){s.has(e)||s.set(e,document.createDocumentFragment()),s.get(e)?.appendChild(t);continue}}r.appendChild(t)}for(const[t,e]of n){const a=s.get(t);a&&e.replaceWith(a)}const i=n.get("");i?i.replaceWith(r):Y(r.childNodes)&&J(this),this.appendChild(a),X(this)}!function(t){if(null!==F())for(const e of t)1===e.nodeType&&G(e,B)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){null!==this._layout&&(this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected))}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{U(e,t)}),e.hasAttribute("data-bind")&&U(e,t))}}function Z(){return document.createElement(t.tagNames.layoutOutlet)}const tt="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function et(t,e){let a=null,n=null;const r=e.uuid||"",i=`\n//# sourceURL=${r?`wcs-guard-handler:${r}`:"wcs-guard-handler"}\n`,o=t.text+i;let l=!1;const c=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",c);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),e=URL.createObjectURL(t);try{a=await import(e)}catch(t){n=t}finally{URL.revokeObjectURL(e)}}if(!a){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{a=await import(`data:application/javascript;base64,${t}`)}catch(t){await new Promise(t=>setTimeout(t)),s(function(t,e,a){if(a)return`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${tt}`;const n=`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"");return/specifier|does not resolve/i.test(n)?`${n}. A guard <script> is evaluated from a blob: URL, against which a relative or root-relative import ("./x.js", "/js/x.js") does not resolve: import a full URL inside the guard function — await import(new URL("/js/x.js", location.href).href) — or a name the page's import map gives ({ "imports": { "@app/": "/js/" } }).`:`${n}. If this page sets a Content-Security-Policy, see ${tt}`}(t,n,l),{cause:n??t})}}}finally{document.removeEventListener("securitypolicyviolation",c)}return a&&"function"==typeof a.default?a.default:null}function at(e,a){et(e,a).then(e=>{e?a.guardHandler=e:(console.error(`${t.tagNames.guardHandler}: the <script type="module"> has no default-exported function, so the route's guard redirects every navigation.`),a.notifyGuardHandlerLoadFailed())}).catch(t=>{console.error("loadGuardHandler failed:",t),a.notifyGuardHandlerLoadFailed()})}function nt(t,e){let a=t.get(e.absolutePath);a||(a=[]);for(const t of a)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}a.push(e),1===a.length&&t.set(e.absolutePath,a)}async function st(e,a,n,s){const r=document.createDocumentFragment();let i=null;const o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a,c=n;const h=l.tagName.toLowerCase();if(h===t.tagNames.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(t);const r=a;r.initialize(e,n),nt(s,r),o=r.placeHolder,l=r,c=r,i=r}else{if(h===t.tagNames.guardHandler){const e=n??i,a=l.querySelector('script[type="module"]');null===e?console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${t.tagNames.guardHandler}> outside a <${t.tagNames.route}> guards nothing: put it inside the route it guards.`):a?(null===n&&console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${t.tagNames.guardHandler}> outside a <${t.tagNames.route}> guards the route before it, "${e.absolutePath}": put it inside that route.`),e.enableGuard(),at(a,e)):(e.enableGuard(),e.notifyGuardHandlerLoadFailed(),console.error(`[@wcstack/router] [wcs/guard-handler-ignored] The <${t.tagNames.guardHandler}> of route "${e.absolutePath}" has no <script type="module">, so its guard cannot run: every navigation into the route is redirected to "${e.getAttribute("guard")||"/"}".`));continue}if("template"===h){r.appendChild(l);continue}if(h===t.tagNames.layout){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const e=document.importNode(l,!0);customElements.upgrade(e),e.appendChild(t);const a=e,n=Z();n.layout=a,o=n,l=e}}const u=await st(e,l,c,s);l.replaceChildren(),l.appendChild(u),r.appendChild(o)}else r.appendChild(a);return r}async function rt(t){const e=new Map;return await st(t,t.template.content,null,e)}function it(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(ot(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(ot(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}function ot(t){return!1!==t.checkVisibility?.()}function lt(t,e,a,n){const s=function(t,e,a){const n={},s={};let r=!0,o=!1,l=0,c=0;for(;l<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[l];if(e.isIndex){l++;continue}if(0===l&&""===e.segmentText&&"static"===e.type){l++;continue}const h=a[c];if(void 0===h){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=i[t].parse(h);void 0!==a&&(e.paramName&&(n[e.paramName]=h,s[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(h);if(!u){r=!1;break}if("catch-all"===e.type){const t=a.slice(c).join("/");n["*"]=t,s["*"]=t,o=!0;break}l++,c++}let h=!1;return r&&(o||l===t.absoluteSegmentInfos.length&&c===a.length)&&(h=!0),h?{path:e,routes:t.routes,params:n,typedParams:s,lastPath:""}:null}(t,e,a);s&&n.push(s);for(const s of t.routeChildNodes)lt(s,e,a,n)}function ct(t,e){const a=t.routeChildNodes,n=[],s=e.split("/"),r=s.filter((t,e)=>(0!==e||""!==t)&&!(e===s.length-1&&""===t&&s.length>1)).map(p);for(const t of a)lt(t,e,r,n);return n.sort((t,e)=>{const a=t.routes.at(-1),n=e.routes.at(-1),s=a.absoluteSegmentCount-n.absoluteSegmentCount;if(0!==s)return-s;const r=a.absoluteWeight-n.absoluteWeight;if(0!==r)return-r;return a.childIndex-n.childIndex}),n.length>0?n[0]:null}function ht(t){if(null!==t.held)return;const e=K(t),a=new Set(e),n=[...e,...t.childNodeArray];let s=null;for(const r of t.childNodeArray)a.has(r)?s=r:null===r.parentNode||n.some(t=>t!==r&&t.contains(r))||(e.splice(null===s?0:e.indexOf(s)+1,0,r),a.add(r),s=r);const r=document.createDocumentFragment();!function(t,e){const a=e.map(t=>t.parentNode);for(let n=0;n<e.length;n++)e[n].parentNode===a[n]&&t.appendChild(e[n])}(r,e),r.appendChild(t.endMarker),t.held=r}function ut(t){t.clearParams(),ht(t)}function dt(e,a){const n={},s={};for(const t of e.paramNames)n[t]=a.params[t],s[t]=a.typedParams[t];e.setParams(n,s);for(const a of e.childNodeArray)if(a.nodeType===Node.ELEMENT_NODE){const n=a;n.querySelectorAll("[data-bind]").forEach(t=>{U(t,e.typedParams)}),n.hasAttribute("data-bind")&&U(n,e.typedParams),n.querySelectorAll(t.tagNames.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===t.tagNames.layoutOutlet&&n.assignParams(e.typedParams)}}const mt=new WeakSet;function ft(t){const e=t.placeHolder;null!==e.parentNode&&(mt.has(t)||null!==t.endMarker.parentNode?(ht(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),mt.add(t))}const pt=Symbol.for("wcstack.transition-runner");function gt(t,e,a){const n=function(t){const e=globalThis[pt];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==n)return n.run(e,{source:t,types:a});e()}const _t=new WeakSet,bt="data-wcs";function yt(t){return t.hasAttribute(bt)||null!==t.querySelector(`[${bt}]`)}function wt(t,e,a){!_t.has(t)&&yt(t)&&(_t.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==F()||(n=t,D().has(n))||console.warn(`[@wcstack/router] ${e} contains ${bt} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${a}`)}))}function vt(t){return"AbortError"===t?.name}const Nt=new WeakMap;function Ct(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(G(e,B))continue}else if(null!==F())continue;wt(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.')}}async function Pt(e,a,n=()=>!1){try{let t=null;for(const e of a.routes){const n=await e.guardCheck(a);n&&(t=null===t?n:Object.assign({},t,n))}if(n())return!1;a.data=t,Nt.delete(e)}catch(s){if(s instanceof r){if(n())return!1;const r=(Nt.get(e)??0)+1;return r>10?(Nt.delete(e),console.error(`${t.tagNames.router}: guard redirect loop — stopped after 10 redirects in a row (the last: ${a.path} → ${s.fallbackPath}). The guards of these routes send each other back and forth.`),!1):(Nt.set(e,r),e.connectedCallbackPromise.catch(()=>{}).then(()=>e.replace(s.fallbackPath)).catch(t=>{vt(t)||console.error("Fallback navigation failed:",t)}),!1)}throw s}return!0}const kt=new WeakMap;async function At(e,a,n,r,i=""){const o=_(n,e.basename),l=(kt.get(e)??0)+1;kt.set(e,l);const c=()=>kt.get(e)!==l;if(e.isSameMatch(o))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:i,path:o}),!0;let h=ct(e,o);h||(e.fallbackRoute?h={routes:[e.fallbackRoute],params:{},typedParams:{},path:o,lastPath:r}:s(`${t.tagNames.router} No route matched for path: ${o}`)),h.lastPath=r,h.search=i;const u=a.lastRoutes,d=await async function(t,e,a,n,s={lastRoutes:a},r){if(!await Pt(t,e,r))return!1;n?.();const i=new Set(e.routes),o=()=>{const t=s.lastRoutes,a=new Set(t);for(const e of t)i.has(e)||ut(e);const n=[];for(const t of e.routes)(n.length>0||!a.has(t)||t.shouldChange(e.params))&&(n.push(t),dt(t,e));let r=!1;for(const e of n){const n=a.has(e);n&&r||ft(e),r||=n,!n&&(t.length>0||null!==F())&&Ct(e)}s.lastRoutes=e.routes};let l;return 0===a.length?o():l=gt("router",o),void 0!==l&&await l,!0}(e,h,u,()=>{e.commitNavigation({params:h.params,typedParams:h.typedParams,routeName:h.routes[h.routes.length-1]?.name??"",data:h.data??null,search:i,path:o},!0)},a,c);return!!d&&(e.releasePath(),c()||u.length>0&&it(e,h),!0)}function Et(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function St(t){let e=t,a="";const n=e.indexOf("#");n>=0&&(a=e.slice(n),e=e.slice(0,n));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:a}}function $t(t){return"?"===t?"":t}function Rt(t,e){let a=Object.getPrototypeOf(t);for(;null!==a;){const t=Object.getOwnPropertyDescriptor(a,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;a=Object.getPrototypeOf(a)}return!1}const Lt=new WeakSet;function Tt(t,e,a){if(Lt.has(t))return;Lt.add(t);const n=t.localName??"element";console.warn(`[wcs/input-as-attribute] <${n}> has the attribute ${e}="${a}": an object was written as an attribute, so the element did not receive it. A framework does that when the property is set before the element's definition loads (React 19), or when told to (Vue's .attr). Load the definition before rendering, or assign the property through a ref (Vue: .prop). (Said once per element.)`,t)}const xt=new WeakMap;function Ht(t,e,a){const n=function(t,e){let a=xt.get(t);return void 0===a&&(a=new Map,xt.set(t,a)),a.has(e)||a.set(e,t.getAttribute(e)),a.get(e)}(t,e);!function(t,e,a){null===a?t.removeAttribute(e):t.setAttribute(e,a)}(t,e,void 0===a?n:null===a?null:String(a))}function zt(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}function It(t){if(!t||"a"!==t.localName&&"area"!==t.localName)return null;const e=t.getAttribute("href")?.trim();return void 0!==e&&e.startsWith("#")?e:null}function Mt(t){const e=new URL(window.location.href),a=new URL(t);return e.hash="",a.hash="",e.href===a.href}function Ut(t){const e=function(t){if(""===t)return null;const e=t=>document.getElementById(t)??Array.from(document.getElementsByName(t)).find(t=>"a"===t.localName)??null,a=e(t);if(null!==a)return a;let n;try{n=decodeURIComponent(t)}catch{return null}return n===t?null:e(n)}(t);null!==e&&(e.matches("a[href], area[href], button, input, select, textarea, iframe, summary, [contenteditable], audio[controls], video[controls], [tabindex]")||e.setAttribute("tabindex","-1"),e.focus({preventScroll:!0}))}function Ot(t){const e=new URL(t,window.location.href);window.location.assign(e.href),Ut(e.hash.slice(1))}const Ft=Object.freeze({});class Wt extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"},{name:"leaveConfirm",attribute:"leave-confirm"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_listeningClick=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Ft;_typedParams=Ft;_searchParams=Ft;_routeName="";_data=null;_hasCommitted=!1;_pathHeld=!1;_leaveChecked=!1;_leaveConfirmed=!1;_unloadConfirmed=!1;_listeningUnload=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return g(t)}_normalizeBasename(t){return b(t)}_joinInternalPath(t,e){const a=this._normalizeBasename(t);let n=e.startsWith("/")?e:"/"+e;return n=this._normalizePathname(n),a?"/"===n?a+"/":a+n:n}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}set basename(t){Ht(this,"basename",t)}get leaveConfirm(){return this.getAttribute("leave-confirm")||null}set leaveConfirm(t){Ht(this,"leave-confirm",!0===t?"Leave this page? Changes you made may not be saved.":!1===t?null:t),this._syncBeforeUnload()}_onBeforeUnload=t=>{null===this.leaveConfirm||this._unloadConfirmed||t.preventDefault()};_syncBeforeUnload(){const t=this.isConnected&&null!==this.leaveConfirm&&!zt();t!==this._listeningUnload&&(this._listeningUnload=t,t?window.addEventListener("beforeunload",this._onBeforeUnload):window.removeEventListener("beforeunload",this._onBeforeUnload))}_confirmLeave(t){const e=this.leaveConfirm;return!(null!==e&&this._hasCommitted&&!this._leaveConfirmed&&!this.isSameMatch(_(this._normalizePathname(t),this._basename)))||(this._leaveConfirmed=window.confirm(e))}_confirmUnload(t){const e=this.leaveConfirm;null!==e&&!1!==t.cancelable&&this._hasCommitted&&!this._unloadConfirmed&&(window.confirm(e)?(this._unloadConfirmed=!0,setTimeout(()=>{this._unloadConfirmed=!1},0)):t.preventDefault?.())}_ownedByAnotherRouter(e){for(const a of document.querySelectorAll(t.tagNames.router))if(a!==this&&a instanceof Wt&&a._isOwnPath(e))return!0;return!1}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;!function(t){const e=t.getRootNode();e.nodeType!==Node.DOCUMENT_NODE&&e.nodeType!==Node.DOCUMENT_FRAGMENT_NODE||X(e)}(this);const a=document.createElement(t.tagNames.outlet);return this.parentNode?this.parentNode.insertBefore(a,this.nextSibling):document.body.appendChild(a),a}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||s(`${t.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||s(`${t.tagNames.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t,e=!1){const a=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),s=o(t.search),r=t.data??null,i=this._data!==r,c=!l(this._params,a),h=this._routeName!==t.routeName,u=!l(this._searchParams,s),d=this._path!==t.path;i&&(this._data=r),c&&(this._params=a,this._typedParams=n),h&&(this._routeName=t.routeName),u&&(this._searchParams=s),this._path=t.path,this._hasCommitted=!0,this._leaveConfirmed=!1,i&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),h&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),this._pathHeld=d&&e,d&&!e&&this._firePathChanged()}releasePath(){this._pathHeld&&(this._pathHeld=!1,this._firePathChanged())}_firePathChanged(){this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:this._path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{vt(e)||console.error(`${t.tagNames.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{vt(e)||console.error(`${t.tagNames.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const a=St(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+$t(a.search)+a.hash;if(null!==this.leaveConfirm&&(await Promise.resolve(),!this._confirmLeave(n)))return;const r=Et();if(r?.navigate){let t;this._leaveChecked=!0;try{t=e?r.navigate(s,{history:"replace"}):r.navigate(s)}finally{this._leaveChecked=!1}await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(n),r=this.isSameMatch(_(t,this._basename));await At(this,this.outlet,t,this._path,$t(a.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_ownsCurrentPage(){return this._isOwnPath(this._normalizePathname(window.location.pathname))}_onFragmentLinkNavigate(t,e){if(!this._ownsCurrentPage())return;const a=t.destination.url;Mt(a)?Ut(new URL(a).hash.slice(1)):(t.preventDefault?.(),Ot(e))}_onNavigateFunc(e){if(e.defaultPrevented||null!==e.downloadRequest||"reload"===e.navigationType)return;const a=e.sourceElement,n=a?.ownerDocument===document?It(a):null;if(null!==n)return void this._onFragmentLinkNavigate(e,n);if(e.hashChange||e.destination.url.includes("#")&&Mt(e.destination.url))return;const s=new URL(e.destination.url),r=this._normalizePathname(s.pathname);if(!e.canIntercept||!this._isOwnPath(r))return void(e.canIntercept&&this._ownedByAnotherRouter(r)||this._confirmUnload(e));if(!this._leaveChecked&&!1!==e.cancelable&&!this._confirmLeave(r))return void e.preventDefault?.();const i=this.isSameMatch(_(r,this._basename)),o=i&&("push"===e.navigationType||"replace"===e.navigationType),l=s.search,c=this;e.intercept({handler:async()=>{try{await At(c,c.outlet,r,c.path,l)}catch(e){throw console.error(`${t.tagNames.router} applyRoute failed:`,e),e}},scroll:o?"manual":"after-transition",focusReset:i||null!==c.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await At(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};_onClick=t=>{if(t.defaultPrevented||0!==t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;const e=t.composedPath().find(t=>t instanceof Element&&("a"===t.localName||"area"===t.localName)&&t.hasAttribute("href")),a=It(e);null!==a&&!e.hasAttribute("download")&&function(t){const e=t.getAttribute("target")??document.querySelector("base[target]")?.getAttribute("target")??"";return""===e||"_self"===e.toLowerCase()}(e)&&this._ownsCurrentPage()&&(t.preventDefault(),Ot(a))};async _initialize(){this._initializing=!0;try{const e=zt();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const a=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||a||"/"===n.pathname||s(`${t.tagNames.router} basename is empty, but current path is not "/".`),e||""===this._basename||a||this.getAttribute("basename")||console.warn(`[@wcstack/router] [wcs/base-href-missing] The basename "${this._basename}" was taken from this page's URL: the page has no <base href> and <${t.tagNames.router}> no basename, so routes and links resolve under it, and a deep link or a reload away from the app's root shows the wrong route. Add <base href="/"> (or the app's folder) to <head>.`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||s(`${t.tagNames.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await rt(this),o=!e&&this._outlet.hasAttribute(v);if(o||this._outlet.rootNode.appendChild(i),null!==r){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}0===this.routeChildNodes.length&&s(`${t.tagNames.router} has no route definitions.`),e||this._ensureA11yRegion();const l=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(l),void(this._initialized=!0);if(o){if(await this._hydrateFromSsr(l))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(v);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(i)}await At(this,this.outlet,l,this._path,window.location.search||""),(o||null!==F())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const a=this.outlet.rootNode,n=new Map;let s=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?s=!0:n.set(t.absolutePath,t)}),s)return!1;if(null!==a.querySelector(t.tagNames.layoutOutlet))return!1;const r=new Map,i=new Map,o=new Map,l=document.createTreeWalker(a,NodeFilter.SHOW_COMMENT);let c=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(c++,e.startsWith(C)){const a=e.slice(15);if(r.has(a)||!n.has(a))return!1;r.set(a,t)}else if(e.startsWith(P)){const a=e.slice(18);if(i.has(a)||!n.has(a))return!1;i.set(a,{comment:t,index:c})}else if(e.startsWith(k)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:c})}}if(i.size!==o.size)return!1;const h=[];for(const[t,e]of i){const a=o.get(t);if(!a)return!1;if(a.comment.parentNode!==e.comment.parentNode)return!1;if(a.index<=e.index)return!1;h.push({start:e.index,end:a.index})}for(const t of h)for(const e of h)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=_(e,this._basename);let d=ct(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==i.size)return!1;for(const t of d.routes)if(!i.has(t.absolutePath))return!1;const m=new Set;for(const t of this.routeChildNodes)m.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)m.add(e.absolutePath);if(r.size!==m.size)return!1;for(const t of m)if(!r.has(t))return!1;for(const[t,e]of r){const a=n.get(t);e.parentNode.replaceChild(a.placeHolder,e)}for(const e of d.routes){const a=i.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,s=[],r=new Set;let l=a.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const t=l.data;if(t.startsWith(P)){const e=t.slice(18);l=o.get(e).comment.nextSibling;continue}}if(r.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===t.tagNames.link){const t=l.anchorElement;null!==t&&r.add(t)}s.push(l),l=l.nextSibling}}e.adoptChildNodes(s,n)}for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(v);for(const t of d.routes)dt(t,d);return this.outlet.lastRoutes=d.routes,!await Pt(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(e){const a=_(e,this._basename),n=ct(this,a),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&s(`${t.tagNames.router} No route matched for path: ${a}`),!r.some(t=>t.hasGuard)){await At(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${C}${t.absolutePath}`}),this.outlet.setAttribute(v,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${P}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&G(e,B)}_forEachRoute(t,e=this){for(const a of e.routeChildNodes)t(a),this._forEachRoute(t,a)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,a=e?.inputs;if(void 0===a)return;const n=t.getAttribute;for(const e of a){const a=e.name,s="function"==typeof n?n.call(t,a.toLowerCase()):null;if(null!==s&&s.startsWith("[object ")&&Tt(t,a,s),!Object.prototype.hasOwnProperty.call(t,a))continue;if(!Rt(t,a))continue;const r=t,i=r[a];delete r[a],r[a]=i}}(this),this._syncBeforeUnload(),zt()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Et();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),t&&function(){const t=globalThis.NavigateEvent;return"function"==typeof t&&"sourceElement"in t.prototype}()||this._listeningClick||(window.addEventListener("click",this._onClick),this._listeningClick=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Et()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),this._listeningClick&&(window.removeEventListener("click",this._onClick),this._listeningClick=!1),this._syncBeforeUnload(),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const jt=["title","rel","target","download","hreflang","lang","dir"];class Dt extends HTMLElement{static get observedAttributes(){return["to","match","query-keys","current",...jt]}_childNodeArray=[];_uuid=n();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get to(){return this.getAttribute("to")??""}set to(t){Ht(this,"to",t)}get router(){return this._findRouter()??s(`${t.tagNames.link} is not connected to a router.`)}_findRouter(){if(this._router)return this._router;const e=this.closest(t.tagNames.router)??this.getRootNode().querySelector?.(t.tagNames.router)??null;return null===e?null:this._router=e}_initialize(){zt()||(this.style.display="none"),this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return g(t)}_joinInternalPath(t,e){const a=b(t),n=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(n);return a?"/"===s?a+"/":a+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(e,a){if(""!==a)if(this._isInternalTarget(a)){const{pathname:t,search:n,hash:s}=St(a),r=(""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t))+$t(n)+s;e.getAttribute("href")!==r&&(e.href=r)}else try{e.href=new URL(a).toString()}catch{s(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${a}`)}else e.removeAttribute("href")}connectedCallback(){zt()?queueMicrotask(()=>{if(this.isConnected)try{this._connect()}catch(t){console.error(t)}}):(this._adoptOwnTo(),this._initialized||!this._isInternalTarget(this.to)||null!==this._findRouter()?this._connect():queueMicrotask(()=>{this.isConnected&&!this._initialized&&this._connect()}))}_adoptOwnTo(){if(Object.prototype.hasOwnProperty.call(this,"to")){const t=this.to;delete this.to,this.to=t}}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(N)?t:null}_connect(){this._adoptOwnTo(),this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let a;if(null!==e)a=e,a.removeAttribute(N),this._childNodeArray=Array.from(a.childNodes),this._setAnchorHref(a,this._path);else{const e=this.nextSibling;a=document.createElement("a"),this._setAnchorHref(a,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||jt.includes(t.name))&&a.setAttribute(t.name,t.value);for(const t of this._childNodeArray)a.appendChild(t);e?t.insertBefore(a,e):t.appendChild(a)}if(this._anchorElement=a,zt())return this._updateActiveState(),void a.setAttribute(N,"");Et()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),""!==this._path&&!this._isInternalTarget(this._path)||Et()?.navigate||(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this.isConnected&&this._updateActiveState()))},a.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Et()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,a){if("match"!==t&&"query-keys"!==t&&"current"!==t||e===a){if("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(jt.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}else this._anchorElement&&this._updateActiveState()}_updateActiveState=()=>{this._anchorElement&&this._isInternalTarget(this._path)&&this._setAnchorHref(this._anchorElement,this._path);const t=new URL(window.location.href),e=this._normalizePathname(t.pathname),{pathname:a,search:n}=St(this._path),s=$t(n),r=(this.getAttribute("query-keys")??"").split(/[\s,]+/).filter(t=>""!==t),i=c(t.search,s),o=""===n&&0===r.length||c(l=t.search,h=s)&&c(h,l);var l,h;const u=this._normalizePathname(this._isInternalTarget(this._path)?""===a?window.location.pathname:this._joinInternalPath(this.router.basename,a):a),d=e===u,m="prefix"===this.getAttribute("match"),f=m&&e.startsWith(u+"/"),p=""!==this._path&&d&&o,g=!p&&""!==this._path&&(d||f)&&(r.length>0?function(t,e,a){const n=new URLSearchParams(t),s=new URLSearchParams(e);return a.every(t=>{const e=n.getAll(t).sort(),a=s.getAll(t).sort();return e.length===a.length&&e.every((t,e)=>t===a[e])})}(t.search,s,r):m&&i);this._anchorElement&&(p||g?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current",this.getAttribute("current")||(p?"page":"true"))):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Gt=[],Bt=new Map;let qt=!1;const Kt=new WeakMap,Vt=new WeakMap;class Xt extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super()}_initialize(){if(!this._initialized&&(this._initialized=!0,this._childElementArray=Array.from(this.children),!zt())){this.style.display="none";for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),qt||(this._captureInitialHead(),qt=!0),Gt.push(this),this._reapplyHead()}disconnectedCallback(){const t=Gt.indexOf(this);-1!==t&&Gt.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||s("Head component is not initialized yet."),this._childElementArray}_cloneOf(t){if(!yt(t))return t.cloneNode(!0);let e=Vt.get(t);return void 0===e&&(e=t.cloneNode(!0),Vt.set(t,e)),e}_getKey(t){const e=Kt.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return Kt.set(t,a),a}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e){return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`}if("link"===e){return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`}if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",a=t.getAttribute("id")||"",n=t.getAttribute("type")||"";return e||a?`script:${e}:${a}:${n}`:`script::${n}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",a=t.getAttribute("media")||"";return e?`style:${e}:${a}`:`style::${a}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const a=this._getKey(e);t.has(a)||t.set(a,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Bt.has(t)||Bt.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of Gt)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of Bt.keys())e.add(t);const a=this._buildHeadElementMap();for(const t of a.keys())e.add(t);for(const n of e){let e=null;for(let t=Gt.length-1;t>=0;t--){const a=Gt[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=this._cloneOf(t);break}if(e)break}if(!e&&Bt.has(n)){e=Bt.get(n).cloneNode(!0)}const s=a.get(n)??null;null!==e&&s===e||(e&&s?.isEqualNode(e)&&!yt(e)||(e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),G(e)||wt(e,`<${e.tagName.toLowerCase()}> inside <${t.tagNames.head}>`,`<${t.tagNames.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(s?.remove(),a.delete(n))))}}}const Yt=Symbol.for("wcstack.package"),Jt=new WeakSet;function Qt(t,e){Object.defineProperty(t,Yt,{value:e,configurable:!0})}function Zt(t,e,a,n,s){if(void 0!==n&&(a===n||a.prototype instanceof n))return;const r=a[Yt];if(r===s||Jt.has(t))return;Jt.add(t);const i=s.slice(0,s.lastIndexOf("@"));console.warn(`[${i}] [wcs/package-twice] <${e}> is already defined by ${r??`another copy of ${i} that does not name its version`}; this copy, ${s}, does nothing. Load each package once.`)}function te(n=customElements){!function(t,e,a){for(const[n,s]of a){const a=t.get(n);void 0===a?(Qt(s,e),t.define(n,s)):Zt(t,n,a,s,e)}}(n,`${e}@${a}`,[[t.tagNames.layout,H],[t.tagNames.layoutOutlet,Q],[t.tagNames.outlet,z],[t.tagNames.route,A],[t.tagNames.router,Wt],[t.tagNames.link,Dt],[t.tagNames.head,Xt]])}var ee;await void te(ee);
1
+ const t={tagNames:{route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},enableShadowRoot:!1,basenameFileExtensions:[".html"]};var e="@wcstack/router",a="4.33.0";function n(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function s(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class r extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}}const i={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,a,n]=t.split("-").map(Number),s=new Date(e,a-1,n);return s.getFullYear()===e&&s.getMonth()===a-1&&s.getDate()===n?s:void 0}},any:{typeName:"any",pattern:/^.+$/s,parse(t){if(this.pattern.test(t))return t}}};function o(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}function l(t,e){const a=Object.keys(t),n=Object.keys(e);if(a.length!==n.length)return!1;for(const n of a){if(!Object.prototype.hasOwnProperty.call(e,n))return!1;if(t[n]!==e[n])return!1}return!0}function h(t,e){const a=new URLSearchParams(e),n=new URLSearchParams(t);for(const t of new Set(a.keys())){const e=a.getAll(t).sort(),s=n.getAll(t).sort();if(e.length!==s.length||e.some((t,e)=>t!==s[e]))return!1}return!0}let c=null,u=null;function d(){const e=t.basenameFileExtensions;return 0===e.length?null:(c===e&&u||(c=e,u=new RegExp(`\\/[^/]+(?:${e.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),u)}const m=/^(?!.*\/\.{1,2}(?:\/|$))[\w\-.~!$&'()*+,;=:@/%[\]|^]*$/;function p(t){return m.test(t)||t.includes("\\")?t:new URL(t.replace(/\?/g,"%3F").replace(/#/g,"%23"),"http://localhost").pathname}function f(t){if(!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}}function g(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=p(e.replace(/\/{2,}/g,"/"));const a=d();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function _(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function b(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=p(e.replace(/\/{2,}/g,"/"));const a=d();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}const y={static:2,param:1,"catch-all":0};class w extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(e,a){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&s(`${t.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&s(`${t.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):a()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=y[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const a=t.split("/");for(let t=0;t<a.length;t++){const n=a[t];if(!(""===n&&t===a.length-1&&t>0)){if("*"===n){this._segmentInfos.push({type:"catch-all",segmentText:n,paramName:"*",pattern:new RegExp("^(.*)$","s")});break}if(n.startsWith(":")){const t=n.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,a="any";t?(e=t[1],t[3]&&Object.keys(i).includes(t[3])&&(a=t[3])):e=n.substring(1),this._segmentInfos.push({type:"param",segmentText:n,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:a})}else""===n&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:n,paramName:null,pattern:new RegExp(`^${f(n).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`)})}}this._hasGuard=!1,e.hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this.enableGuard())}enableGuard(){this._hasGuard||(this._hasGuard=!0,this._guardFallbackPath||="/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const a=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),a||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||s(`${t.tagNames.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,a=t.lastPath,n=await this._guardHandler(e,a,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:o(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof n&&""!==n)throw new r("Navigation cancelled by guard.",n);if(!n)throw new r("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof n?n:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new r("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}}const v="data-wcs-ssr",N="data-wcs-ssr-link",C="@@wcs-route-ph:",P="@@wcs-route-start:",k="@@wcs-route-end:";class A extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=n();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new w(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||s(`${t.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${k}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t,e){for(this._childNodeArray=[...t],e&&(this._endMarker=e);this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}enableGuard(){this._core.enableGuard()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(e,a){if(this._initialized)return;let n;this._initialized=!0;let r=!1,i=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",r=!0):this.hasAttribute("fallback")?(n="",i=!0):s(`${t.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=a;const o=a||e;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,i&&(a&&s(`${t.tagNames.route} with fallback attribute must be a direct child of ${t.tagNames.router}.`),e.fallbackRoute&&s(`${t.tagNames.router} can have only one fallback route.`),e.fallbackRoute=this),a&&(this._core.parentCore=a._core),this._core.parsePath(n,{isIndex:r,isFallback:i,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}}const E=Symbol.for("wcstack.trustedTypes.policy"),S=Symbol.for("wcstack.trustedTypes.internal"),$="wcstack";function T(){const t=globalThis[E];return null===t||"object"!=typeof t?null:t}let R=!1;function L(t){const e=function(){const t=globalThis,e=t[S];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy($,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof T()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${$}". Allow it in the CSP (\`trusted-types ${$};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[S]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=T(),s=n?.createHTML;return"function"==typeof s?(R||(R=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${$}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${$};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const x=new Map;class H extends HTMLElement{_uuid=n();constructor(){super()}async _loadTemplateFromSource(e){try{const a=await fetch(e);a.ok||s(`${t.tagNames.layout} failed to fetch layout from source: ${e}, status: ${a.status}`);const n=await a.text();return x.set(e,n),n}catch(a){s(`${t.tagNames.layout} failed to load layout from source: ${e}, error: ${a}`,{cause:a})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),a=this.getAttribute("layout");e&&a&&console.warn(`${t.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)x.has(e)?n.innerHTML=L(x.get(e)||""):n.innerHTML=L(await this._loadTemplateFromSource(e)||"");else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=L(e):console.warn(`${t.tagNames.layout} could not find template with id "${a}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class z extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||s(`${t.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const I=new Set(["props","states","attr",""]);function M(t,e,a){for(const[n,s]of Object.entries(e))switch(a){case"props":t.props={...t.props,[n]:s};break;case"states":t.states={...t.states,[n]:s};break;case"attr":null==s?t.removeAttribute(n):t.setAttribute(n,String(s));break;case"":t[n]=s}}function U(t,e){t.hasAttribute("data-bind")||s(`${t.tagName} has no 'data-bind' attribute.`);const a=t.getAttribute("data-bind")||"";I.has(a)||s(`${t.tagName} has invalid 'data-bind' attribute: ${a}`);const n=a,r=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const a=t.getAttribute("is");return a&&a.includes("-")?a:null}(t);r&&void 0===customElements.get(r)?customElements.whenDefined(r).then(()=>{t.isConnected&&M(t,e,n)}).catch(()=>{s(`Failed to define custom element: ${r}`)}):M(t,e,n)}const O=Symbol.for("wcstack.binder");function F(){const t=globalThis[O];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const W=Symbol.for("wcstack.binder.pending"),D=Symbol.for("wcstack.binder.taken");function j(){const t=globalThis;let e=t[D];return void 0===e&&(e=new WeakSet,t[D]=e),e}function G(t,e){const a=F();if(null===a){const e=function(){const t=globalThis;let e=t[W];return void 0===e&&(e=[],t[W]=e),e}();for(let t=e.length-1;t>=0;t--)e[t].isConnected||e.splice(t,1);return e.includes(t)||e.push(t),!1}return j().add(t),a.bind(t,e),!0}const B={range:!0};function q(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),q(a,e);return e}function K(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:q(t,new Set),r=[];let i=0;for(let o=e.nextSibling;null!==o&&o!==a&&(null===s||8!==o.nodeType||!/^@@(route:|wcs-route-)/.test(o.data)||s.has(o));o=o.nextSibling)r.push(o),(n||t.childNodeArray.includes(o))&&(i=r.length);return r.length=i,r}const V=new WeakSet;function X(e){const a=t.tagNames.router,n=t.tagNames.outlet;for(const t of e.querySelectorAll(n))V.has(t)||t.previousElementSibling?.matches(a)||(V.add(t),console.warn(`[@wcstack/router] [wcs/router-outlet-misplaced] A <${a}> uses only the element right after it as its outlet, and this page has a <${n}> that no router uses. The router makes an outlet of its own right after itself, so the routes render there and the <${n}> you placed stays empty. Move the <${n}> right after the <${a}>.`,t))}const Y=t=>{for(const e of t)if(e.nodeType===Node.ELEMENT_NODE||e.nodeType===Node.TEXT_NODE&&""!==e.textContent.trim())return!0;return!1};function J(e){console.warn(`[@wcstack/router] [wcs/layout-slot-missing] This layout's template has no default <slot>, so what its <${t.tagNames.layout}> holds outside the named slots — the nested routes and their pages — is not shown. Put a <slot></slot> where the page goes.`,e)}class Q extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||s(`${t.tagNames.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const e=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(e.content.cloneNode(!0));const t=[];for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),e instanceof Element&&e.getAttribute("slot")||t.push(e),this.appendChild(e);!this.shadowRoot.querySelector('slot:not([name]), slot[name=""]')&&Y(t)&&J(this),X(this.shadowRoot)}else{const a=e.content.cloneNode(!0),n=new Map;a.querySelectorAll("slot").forEach(e=>{const a=e.getAttribute("name")||"";n.has(a)?console.warn(`${t.tagNames.layoutOutlet} duplicate slot name "${a}" in layout template.`):n.set(a,e)});const s=new Map,r=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){s.has(e)||s.set(e,document.createDocumentFragment()),s.get(e)?.appendChild(t);continue}}r.appendChild(t)}for(const[t,e]of n){const a=s.get(t);a&&e.replaceWith(a)}const i=n.get("");i?i.replaceWith(r):Y(r.childNodes)&&J(this),this.appendChild(a),X(this)}!function(t){if(null!==F())for(const e of t)1===e.nodeType&&G(e,B)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){null!==this._layout&&(this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected))}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{U(e,t)}),e.hasAttribute("data-bind")&&U(e,t))}}function Z(){return document.createElement(t.tagNames.layoutOutlet)}const tt="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function et(t,e){let a=null,n=null;const r=e.uuid||"",i=`\n//# sourceURL=${r?`wcs-guard-handler:${r}`:"wcs-guard-handler"}\n`,o=t.text+i;let l=!1;const h=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",h);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),e=URL.createObjectURL(t);try{a=await import(e)}catch(t){n=t}finally{URL.revokeObjectURL(e)}}if(!a){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{a=await import(`data:application/javascript;base64,${t}`)}catch(t){await new Promise(t=>setTimeout(t)),s(function(t,e,a){if(a)return`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${tt}`;const n=`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"");return/specifier|does not resolve/i.test(n)?`${n}. A guard <script> is evaluated from a blob: URL, against which a relative or root-relative import ("./x.js", "/js/x.js") does not resolve: import a full URL inside the guard function — await import(new URL("/js/x.js", location.href).href) — or a name the page's import map gives ({ "imports": { "@app/": "/js/" } }).`:`${n}. If this page sets a Content-Security-Policy, see ${tt}`}(t,n,l),{cause:n??t})}}}finally{document.removeEventListener("securitypolicyviolation",h)}return a&&"function"==typeof a.default?a.default:null}function at(e,a){et(e,a).then(e=>{e?a.guardHandler=e:(console.error(`${t.tagNames.guardHandler}: the <script type="module"> has no default-exported function, so the route's guard redirects every navigation.`),a.notifyGuardHandlerLoadFailed())}).catch(t=>{console.error("loadGuardHandler failed:",t),a.notifyGuardHandlerLoadFailed()})}function nt(t,e){let a=t.get(e.absolutePath);a||(a=[]);for(const t of a)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}a.push(e),1===a.length&&t.set(e.absolutePath,a)}async function st(e,a,n,s){const r=document.createDocumentFragment();let i=null;const o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a,h=n;const c=l.tagName.toLowerCase();if(c===t.tagNames.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(t);const r=a;r.initialize(e,n),nt(s,r),o=r.placeHolder,l=r,h=r,i=r}else{if(c===t.tagNames.guardHandler){const e=n??i,a=l.querySelector('script[type="module"]');null===e?console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${t.tagNames.guardHandler}> outside a <${t.tagNames.route}> guards nothing: put it inside the route it guards.`):a?(null===n&&console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${t.tagNames.guardHandler}> outside a <${t.tagNames.route}> guards the route before it, "${e.absolutePath}": put it inside that route.`),e.enableGuard(),at(a,e)):(e.enableGuard(),e.notifyGuardHandlerLoadFailed(),console.error(`[@wcstack/router] [wcs/guard-handler-ignored] The <${t.tagNames.guardHandler}> of route "${e.absolutePath}" has no <script type="module">, so its guard cannot run: every navigation into the route is redirected to "${e.getAttribute("guard")||"/"}".`));continue}if("template"===c){r.appendChild(l);continue}if(c===t.tagNames.layout){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const e=document.importNode(l,!0);customElements.upgrade(e),e.appendChild(t);const a=e,n=Z();n.layout=a,o=n,l=e}}const u=await st(e,l,h,s);l.replaceChildren(),l.appendChild(u),r.appendChild(o)}else r.appendChild(a);return r}async function rt(t){const e=new Map;return await st(t,t.template.content,null,e)}function it(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(ot(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(ot(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}function ot(t){return!1!==t.checkVisibility?.()}function lt(t,e,a,n){const s=function(t,e,a){const n={},s={};let r=!0,o=!1,l=0,h=0;for(;l<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[l];if(e.isIndex){l++;continue}if(0===l&&""===e.segmentText&&"static"===e.type){l++;continue}const c=a[h];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=i[t].parse(c);void 0!==a&&(e.paramName&&(n[e.paramName]=c,s[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=a.slice(h).join("/");n["*"]=t,s["*"]=t,o=!0;break}l++,h++}let c=!1;return r&&(o||l===t.absoluteSegmentInfos.length&&h===a.length)&&(c=!0),c?{path:e,routes:t.routes,params:n,typedParams:s,lastPath:""}:null}(t,e,a);s&&n.push(s);for(const s of t.routeChildNodes)lt(s,e,a,n)}function ht(t,e){const a=t.routeChildNodes,n=[],s=e.split("/"),r=s.filter((t,e)=>(0!==e||""!==t)&&!(e===s.length-1&&""===t&&s.length>1)).map(f);for(const t of a)lt(t,e,r,n);return n.sort((t,e)=>{const a=t.routes.at(-1),n=e.routes.at(-1),s=a.absoluteSegmentCount-n.absoluteSegmentCount;if(0!==s)return-s;const r=a.absoluteWeight-n.absoluteWeight;if(0!==r)return-r;return a.childIndex-n.childIndex}),n.length>0?n[0]:null}function ct(t){if(null!==t.held)return;const e=K(t),a=new Set(e),n=[...e,...t.childNodeArray];let s=null;for(const r of t.childNodeArray)a.has(r)?s=r:null===r.parentNode||n.some(t=>t!==r&&t.contains(r))||(e.splice(null===s?0:e.indexOf(s)+1,0,r),a.add(r),s=r);const r=document.createDocumentFragment();!function(t,e){const a=e.map(t=>t.parentNode);for(let n=0;n<e.length;n++)e[n].parentNode===a[n]&&t.appendChild(e[n])}(r,e),r.appendChild(t.endMarker),t.held=r}function ut(t){t.clearParams(),ct(t)}function dt(e,a){const n={},s={};for(const t of e.paramNames)n[t]=a.params[t],s[t]=a.typedParams[t];e.setParams(n,s);for(const a of e.childNodeArray)if(a.nodeType===Node.ELEMENT_NODE){const n=a;n.querySelectorAll("[data-bind]").forEach(t=>{U(t,e.typedParams)}),n.hasAttribute("data-bind")&&U(n,e.typedParams),n.querySelectorAll(t.tagNames.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===t.tagNames.layoutOutlet&&n.assignParams(e.typedParams)}}const mt=new WeakSet;function pt(t){const e=t.placeHolder;null!==e.parentNode&&(mt.has(t)||null!==t.endMarker.parentNode?(ct(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),mt.add(t))}const ft=Symbol.for("wcstack.transition-runner");function gt(t,e,a){const n=function(t){const e=globalThis[ft];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==n)return n.run(e,{source:t,types:a});e()}const _t=new WeakSet,bt="data-wcs";function yt(t){return t.hasAttribute(bt)||null!==t.querySelector(`[${bt}]`)}function wt(t,e,a){!_t.has(t)&&yt(t)&&(_t.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==F()||(n=t,j().has(n))||console.warn(`[@wcstack/router] ${e} contains ${bt} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${a}`)}))}function vt(t){return"AbortError"===t?.name}const Nt=new WeakMap;function Ct(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(G(e,B))continue}else if(null!==F())continue;wt(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.')}}async function Pt(e,a,n=()=>!1){try{let t=null;for(const e of a.routes){const n=await e.guardCheck(a);n&&(t=null===t?n:Object.assign({},t,n))}if(n())return!1;a.data=t,Nt.delete(e)}catch(s){if(s instanceof r){if(n())return!1;const r=(Nt.get(e)??0)+1;return r>10?(Nt.delete(e),console.error(`${t.tagNames.router}: guard redirect loop — stopped after 10 redirects in a row (the last: ${a.path} → ${s.fallbackPath}). The guards of these routes send each other back and forth.`),!1):(Nt.set(e,r),e.connectedCallbackPromise.catch(()=>{}).then(()=>e.guardRedirect(s.fallbackPath)).catch(t=>{vt(t)||console.error("Fallback navigation failed:",t)}),!1)}throw s}return!0}const kt=new WeakMap;async function At(e,a,n,r,i=""){const o=_(n,e.basename),l=(kt.get(e)??0)+1;kt.set(e,l);const h=()=>kt.get(e)!==l;if(e.isSameMatch(o))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:i,path:o}),!0;let c=ht(e,o);c||(e.fallbackRoute?c={routes:[e.fallbackRoute],params:{},typedParams:{},path:o,lastPath:r}:s(`${t.tagNames.router} No route matched for path: ${o}`)),c.lastPath=r,c.search=i;const u=a.lastRoutes,d=await async function(t,e,a,n,s={lastRoutes:a},r){if(!await Pt(t,e,r))return!1;n?.();const i=new Set(e.routes),o=()=>{const t=s.lastRoutes,a=new Set(t);for(const e of t)i.has(e)||ut(e);const n=[];for(const t of e.routes)(n.length>0||!a.has(t)||t.shouldChange(e.params))&&(n.push(t),dt(t,e));let r=!1;for(const e of n){const n=a.has(e);n&&r||pt(e),r||=n,!n&&(t.length>0||null!==F())&&Ct(e)}s.lastRoutes=e.routes};let l;return 0===a.length?o():l=gt("router",o),void 0!==l&&await l,!0}(e,c,u,()=>{e.commitNavigation({params:c.params,typedParams:c.typedParams,routeName:c.routes[c.routes.length-1]?.name??"",data:c.data??null,search:i,path:o},!0)},a,h);return!!d&&(e.releasePath(),h()||u.length>0&&it(e,c),!0)}function Et(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function St(t){let e=t,a="";const n=e.indexOf("#");n>=0&&(a=e.slice(n),e=e.slice(0,n));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:a}}function $t(t){return"?"===t?"":t}function Tt(t,e){let a=Object.getPrototypeOf(t);for(;null!==a;){const t=Object.getOwnPropertyDescriptor(a,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;a=Object.getPrototypeOf(a)}return!1}const Rt=new WeakSet;function Lt(t,e,a){if(Rt.has(t))return;Rt.add(t);const n=t.localName??"element";console.warn(`[wcs/input-as-attribute] <${n}> has the attribute ${e}="${a}": an object was written as an attribute, so the element did not receive it. A framework does that when the property is set before the element's definition loads (React 19), or when told to (Vue's .attr). Load the definition before rendering, or assign the property through a ref (Vue: .prop). (Said once per element.)`,t)}const xt=new WeakMap;function Ht(t,e){let a=xt.get(t);return void 0===a&&(a=new Map,xt.set(t,a)),a.has(e)||a.set(e,t.getAttribute(e)),a.get(e)}function zt(t,e,a){null===a?t.removeAttribute(e):t.setAttribute(e,a)}function It(t,e,a){const n=Ht(t,e);zt(t,e,void 0===a?n:null===a?null:String(a))}function Mt(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}function Ut(t){if(!t||"a"!==t.localName&&"area"!==t.localName)return null;const e=t.getAttribute("href")?.trim();return void 0!==e&&e.startsWith("#")?e:null}function Ot(t){const e=new URL(window.location.href),a=new URL(t);return e.hash="",a.hash="",e.href===a.href}function Ft(t){const e=function(t){if(""===t)return null;const e=t=>document.getElementById(t)??Array.from(document.getElementsByName(t)).find(t=>"a"===t.localName)??null,a=e(t);if(null!==a)return a;let n;try{n=decodeURIComponent(t)}catch{return null}return n===t?null:e(n)}(t);null!==e&&(e.matches("a[href], area[href], button, input, select, textarea, iframe, summary, [contenteditable], audio[controls], video[controls], [tabindex]")||e.setAttribute("tabindex","-1"),e.focus({preventScroll:!0}))}function Wt(t){const e=new URL(t,window.location.href);window.location.assign(e.href),Ft(e.hash.slice(1))}const Dt=Object.freeze({});class jt extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"},{name:"leaving",event:"wcs-router:leaving-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"},{name:"leaveConfirm",attribute:"leave-confirm"},{name:"leaveHold",attribute:"leave-hold"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0},{name:"proceed",async:!0},{name:"stay"}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_listeningClick=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Dt;_typedParams=Dt;_searchParams=Dt;_routeName="";_data=null;_hasCommitted=!1;_pathHeld=!1;_leaveChecked=!1;_leaveConfirmed=!1;_unloadConfirmed=!1;_held=null;_proceeding=!1;_revertingTo=null;_redirecting=!1;_listeningUnload=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return g(t)}_normalizeBasename(t){return b(t)}_joinInternalPath(t,e){const a=this._normalizeBasename(t);let n=e.startsWith("/")?e:"/"+e;return n=this._normalizePathname(n),a?"/"===n?a+"/":a+n:n}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}set basename(t){It(this,"basename",t)}get leaveConfirm(){return this.getAttribute("leave-confirm")||null}set leaveConfirm(t){It(this,"leave-confirm",!0===t?"Leave this page? Changes you made may not be saved.":!1===t?null:t),this._syncBeforeUnload()}get leaveHold(){return this.hasAttribute("leave-hold")}set leaveHold(t){!function(t,e,a){const n=Ht(t,e);zt(t,e,void 0===a?n:a?"":null)}(this,"leave-hold",t)}get leaving(){return this._held?.path??null}_setHeld(t){(this._held?.path??null)!==(t?.path??null)||this._held?.traverseKey!==t?.traverseKey?(this._held=t,this.dispatchEvent(new CustomEvent("wcs-router:leaving-changed",{detail:this.leaving,bubbles:!0}))):this._held=t}_shouldHold(t){const e=this._normalizePathname(t);return this.leaveHold&&this._hasCommitted&&!this._proceeding&&e!==this._normalizePathname(window.location.pathname)&&!this.isSameMatch(_(e,this._basename))}_leavingPath(t,e,a){return _(this._normalizePathname(t),this._basename)+e+a}async proceed(){const t=this._held;if(null===t)return;this._setHeld(null),this._proceeding=!0;const e=Et();void 0!==t.traverseKey&&e?.traverseTo?await(e.traverseTo(t.traverseKey)?.finished):await this._performNavigation(t.path,"replace"===t.history)}stay(){this._setHeld(null)}_onBeforeUnload=t=>{null===this.leaveConfirm||this._unloadConfirmed||t.preventDefault()};_syncBeforeUnload(){const t=this.isConnected&&null!==this.leaveConfirm&&!Mt();t!==this._listeningUnload&&(this._listeningUnload=t,t?window.addEventListener("beforeunload",this._onBeforeUnload):window.removeEventListener("beforeunload",this._onBeforeUnload))}_confirmLeave(t){const e=this.leaveConfirm;return!(null!==e&&this._hasCommitted&&!this._leaveConfirmed&&!this.isSameMatch(_(this._normalizePathname(t),this._basename)))||(this._leaveConfirmed=window.confirm(e))}_confirmUnload(t){const e=this.leaveConfirm;null!==e&&!1!==t.cancelable&&this._hasCommitted&&!this._unloadConfirmed&&(window.confirm(e)?(this._unloadConfirmed=!0,setTimeout(()=>{this._unloadConfirmed=!1},0)):t.preventDefault?.())}_ownedByAnotherRouter(e){for(const a of document.querySelectorAll(t.tagNames.router))if(a!==this&&a instanceof jt&&a._isOwnPath(e))return!0;return!1}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;!function(t){const e=t.getRootNode();e.nodeType!==Node.DOCUMENT_NODE&&e.nodeType!==Node.DOCUMENT_FRAGMENT_NODE||X(e)}(this);const a=document.createElement(t.tagNames.outlet);return this.parentNode?this.parentNode.insertBefore(a,this.nextSibling):document.body.appendChild(a),a}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||s(`${t.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||s(`${t.tagNames.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t,e=!1){const a=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),s=o(t.search),r=t.data??null,i=this._data!==r,h=!l(this._params,a),c=this._routeName!==t.routeName,u=!l(this._searchParams,s),d=this._path!==t.path;i&&(this._data=r),h&&(this._params=a,this._typedParams=n),c&&(this._routeName=t.routeName),u&&(this._searchParams=s),this._path=t.path,this._hasCommitted=!0,this._leaveConfirmed=!1,this._proceeding=!1,d&&null!==this._held&&this._setHeld(null),i&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),h&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),this._pathHeld=d&&e,d&&!e&&this._firePathChanged()}releasePath(){this._pathHeld&&(this._pathHeld=!1,this._firePathChanged())}_firePathChanged(){this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:this._path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{vt(e)||console.error(`${t.tagNames.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{vt(e)||console.error(`${t.tagNames.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}guardRedirect(t){this._redirecting=!0;try{return this.replace(t)}finally{this._redirecting=!1}}async _performNavigation(t,e){const a=this._redirecting,n=St(t),s=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,r=s+$t(n.search)+n.hash;if(null!==this.leaveConfirm||this.leaveHold){if(await Promise.resolve(),!a&&this._shouldHold(s))return void this._setHeld({path:this._leavingPath(s,$t(n.search),n.hash),history:e?"replace":"push"});if(!this._confirmLeave(s))return}const i=Et();if(i?.navigate){let t;this._leaveChecked=!0;try{t=e?i.navigate(r,{history:"replace"}):i.navigate(r)}finally{this._leaveChecked=!1}await(t?.finished)}else{e?history.replaceState(null,"",r):history.pushState(null,"",r);const t=this._normalizePathname(s),a=this.isSameMatch(_(t,this._basename));await At(this,this.outlet,t,this._path,$t(n.search))&&!a&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_ownsCurrentPage(){return this._isOwnPath(this._normalizePathname(window.location.pathname))}_onFragmentLinkNavigate(t,e){if(!this._ownsCurrentPage())return;const a=t.destination.url;Ot(a)?Ft(new URL(a).hash.slice(1)):(t.preventDefault?.(),Wt(e))}_onNavigateFunc(e){if(e.defaultPrevented||null!==e.downloadRequest||"reload"===e.navigationType)return;const a=e.sourceElement,n=a?.ownerDocument===document?Ut(a):null;if(null!==n)return void this._onFragmentLinkNavigate(e,n);if(e.hashChange||e.destination.url.includes("#")&&Ot(e.destination.url))return;const s=new URL(e.destination.url),r=this._normalizePathname(s.pathname);if(!e.canIntercept||!this._isOwnPath(r))return void(e.canIntercept&&this._ownedByAnotherRouter(r)||this._confirmUnload(e));if(null!==this._revertingTo&&e.destination.key===this._revertingTo)return this._revertingTo=null,void e.intercept({handler:async()=>{},scroll:"manual",focusReset:"manual"});if(!this._leaveChecked&&this._shouldHold(r)){const t="traverse"===e.navigationType?e.destination.key:void 0,a={path:this._leavingPath(r,s.search,s.hash),history:"replace"===e.navigationType?"replace":"push",...void 0!==t?{traverseKey:t}:{}};if(!1!==e.cancelable)return e.preventDefault?.(),void this._setHeld(a);const n=Et()?.currentEntry?.key;if(void 0!==t&&void 0!==n)return this._setHeld(a),void e.intercept({handler:async()=>{this._revertingTo=n,setTimeout(()=>{Et()?.traverseTo?.(n)?.finished?.catch(()=>{})},0)},scroll:"manual",focusReset:"manual"})}if(!this._leaveChecked&&!1!==e.cancelable&&!this._confirmLeave(r))return void e.preventDefault?.();const i=this.isSameMatch(_(r,this._basename)),o=i&&("push"===e.navigationType||"replace"===e.navigationType),l=s.search,h=this;e.intercept({handler:async()=>{try{await At(h,h.outlet,r,h.path,l)}catch(e){throw console.error(`${t.tagNames.router} applyRoute failed:`,e),e}},scroll:o?"manual":"after-transition",focusReset:i||null!==h.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await At(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};_onClick=t=>{if(t.defaultPrevented||0!==t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;const e=t.composedPath().find(t=>t instanceof Element&&("a"===t.localName||"area"===t.localName)&&t.hasAttribute("href")),a=Ut(e);null!==a&&!e.hasAttribute("download")&&function(t){const e=t.getAttribute("target")??document.querySelector("base[target]")?.getAttribute("target")??"";return""===e||"_self"===e.toLowerCase()}(e)&&this._ownsCurrentPage()&&(t.preventDefault(),Wt(a))};async _initialize(){this._initializing=!0;try{const e=Mt();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const a=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||a||"/"===n.pathname||s(`${t.tagNames.router} basename is empty, but current path is not "/".`),e||""===this._basename||a||this.getAttribute("basename")||console.warn(`[@wcstack/router] [wcs/base-href-missing] The basename "${this._basename}" was taken from this page's URL: the page has no <base href> and <${t.tagNames.router}> no basename, so routes and links resolve under it, and a deep link or a reload away from the app's root shows the wrong route. Add <base href="/"> (or the app's folder) to <head>.`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||s(`${t.tagNames.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await rt(this),o=!e&&this._outlet.hasAttribute(v);if(o||this._outlet.rootNode.appendChild(i),null!==r){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}0===this.routeChildNodes.length&&s(`${t.tagNames.router} has no route definitions.`),e||this._ensureA11yRegion();const l=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(l),void(this._initialized=!0);if(o){if(await this._hydrateFromSsr(l))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(v);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(i)}await At(this,this.outlet,l,this._path,window.location.search||""),(o||null!==F())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const a=this.outlet.rootNode,n=new Map;let s=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?s=!0:n.set(t.absolutePath,t)}),s)return!1;if(null!==a.querySelector(t.tagNames.layoutOutlet))return!1;const r=new Map,i=new Map,o=new Map,l=document.createTreeWalker(a,NodeFilter.SHOW_COMMENT);let h=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(h++,e.startsWith(C)){const a=e.slice(15);if(r.has(a)||!n.has(a))return!1;r.set(a,t)}else if(e.startsWith(P)){const a=e.slice(18);if(i.has(a)||!n.has(a))return!1;i.set(a,{comment:t,index:h})}else if(e.startsWith(k)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:h})}}if(i.size!==o.size)return!1;const c=[];for(const[t,e]of i){const a=o.get(t);if(!a)return!1;if(a.comment.parentNode!==e.comment.parentNode)return!1;if(a.index<=e.index)return!1;c.push({start:e.index,end:a.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=_(e,this._basename);let d=ht(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==i.size)return!1;for(const t of d.routes)if(!i.has(t.absolutePath))return!1;const m=new Set;for(const t of this.routeChildNodes)m.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)m.add(e.absolutePath);if(r.size!==m.size)return!1;for(const t of m)if(!r.has(t))return!1;for(const[t,e]of r){const a=n.get(t);e.parentNode.replaceChild(a.placeHolder,e)}for(const e of d.routes){const a=i.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,s=[],r=new Set;let l=a.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const t=l.data;if(t.startsWith(P)){const e=t.slice(18);l=o.get(e).comment.nextSibling;continue}}if(r.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===t.tagNames.link){const t=l.anchorElement;null!==t&&r.add(t)}s.push(l),l=l.nextSibling}}e.adoptChildNodes(s,n)}for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(v);for(const t of d.routes)dt(t,d);return this.outlet.lastRoutes=d.routes,!await Pt(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(e){const a=_(e,this._basename),n=ht(this,a),r=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&s(`${t.tagNames.router} No route matched for path: ${a}`),!r.some(t=>t.hasGuard)){await At(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${C}${t.absolutePath}`}),this.outlet.setAttribute(v,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${P}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&G(e,B)}_forEachRoute(t,e=this){for(const a of e.routeChildNodes)t(a),this._forEachRoute(t,a)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,a=e?.inputs;if(void 0===a)return;const n=t.getAttribute;for(const e of a){const a=e.name,s="function"==typeof n?n.call(t,a.toLowerCase()):null;if(null!==s&&s.startsWith("[object ")&&Lt(t,a,s),!Object.prototype.hasOwnProperty.call(t,a))continue;if(!Tt(t,a))continue;const r=t,i=r[a];delete r[a],r[a]=i}}(this),this._syncBeforeUnload(),Mt()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Et();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),t&&function(){const t=globalThis.NavigateEvent;return"function"==typeof t&&"sourceElement"in t.prototype}()||this._listeningClick||(window.addEventListener("click",this._onClick),this._listeningClick=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Et()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),this._listeningClick&&(window.removeEventListener("click",this._onClick),this._listeningClick=!1),this._syncBeforeUnload(),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Gt=["title","rel","target","download","hreflang","lang","dir"];class Bt extends HTMLElement{static get observedAttributes(){return["to","match","query-keys","current",...Gt]}_childNodeArray=[];_uuid=n();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get to(){return this.getAttribute("to")??""}set to(t){It(this,"to",t)}get router(){return this._findRouter()??s(`${t.tagNames.link} is not connected to a router.`)}_findRouter(){if(this._router)return this._router;const e=this.closest(t.tagNames.router)??this.getRootNode().querySelector?.(t.tagNames.router)??null;return null===e?null:this._router=e}_initialize(){Mt()||(this.style.display="none"),this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return g(t)}_joinInternalPath(t,e){const a=b(t),n=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(n);return a?"/"===s?a+"/":a+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(e,a){if(""!==a)if(this._isInternalTarget(a)){const{pathname:t,search:n,hash:s}=St(a),r=(""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t))+$t(n)+s;e.getAttribute("href")!==r&&(e.href=r)}else try{e.href=new URL(a).toString()}catch{s(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${a}`)}else e.removeAttribute("href")}connectedCallback(){Mt()?queueMicrotask(()=>{if(this.isConnected)try{this._connect()}catch(t){console.error(t)}}):(this._adoptOwnTo(),this._initialized||!this._isInternalTarget(this.to)||null!==this._findRouter()?this._connect():queueMicrotask(()=>{this.isConnected&&!this._initialized&&this._connect()}))}_adoptOwnTo(){if(Object.prototype.hasOwnProperty.call(this,"to")){const t=this.to;delete this.to,this.to=t}}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(N)?t:null}_connect(){this._adoptOwnTo(),this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let a;if(null!==e)a=e,a.removeAttribute(N),this._childNodeArray=Array.from(a.childNodes),this._setAnchorHref(a,this._path);else{const e=this.nextSibling;a=document.createElement("a"),this._setAnchorHref(a,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||Gt.includes(t.name))&&a.setAttribute(t.name,t.value);for(const t of this._childNodeArray)a.appendChild(t);e?t.insertBefore(a,e):t.appendChild(a)}if(this._anchorElement=a,Mt())return this._updateActiveState(),void a.setAttribute(N,"");Et()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),""!==this._path&&!this._isInternalTarget(this._path)||Et()?.navigate||(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this.isConnected&&this._updateActiveState()))},a.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Et()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,a){if("match"!==t&&"query-keys"!==t&&"current"!==t||e===a){if("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Gt.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}else this._anchorElement&&this._updateActiveState()}_updateActiveState=()=>{this._anchorElement&&this._isInternalTarget(this._path)&&this._setAnchorHref(this._anchorElement,this._path);const t=new URL(window.location.href),e=this._normalizePathname(t.pathname),{pathname:a,search:n}=St(this._path),s=$t(n),r=(this.getAttribute("query-keys")??"").split(/[\s,]+/).filter(t=>""!==t),i=h(t.search,s),o=""===n&&0===r.length||h(l=t.search,c=s)&&h(c,l);var l,c;const u=this._normalizePathname(this._isInternalTarget(this._path)?""===a?window.location.pathname:this._joinInternalPath(this.router.basename,a):a),d=e===u,m="prefix"===this.getAttribute("match"),p=m&&e.startsWith(u+"/"),f=""!==this._path&&d&&o,g=!f&&""!==this._path&&(d||p)&&(r.length>0?function(t,e,a){const n=new URLSearchParams(t),s=new URLSearchParams(e);return a.every(t=>{const e=n.getAll(t).sort(),a=s.getAll(t).sort();return e.length===a.length&&e.every((t,e)=>t===a[e])})}(t.search,s,r):m&&i);this._anchorElement&&(f||g?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current",this.getAttribute("current")||(f?"page":"true"))):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const qt=[],Kt=new Map;let Vt=!1;const Xt=new WeakMap,Yt=new WeakMap;class Jt extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super()}_initialize(){if(!this._initialized&&(this._initialized=!0,this._childElementArray=Array.from(this.children),!Mt())){this.style.display="none";for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Vt||(this._captureInitialHead(),Vt=!0),qt.push(this),this._reapplyHead()}disconnectedCallback(){const t=qt.indexOf(this);-1!==t&&qt.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||s("Head component is not initialized yet."),this._childElementArray}_cloneOf(t){if(!yt(t))return t.cloneNode(!0);let e=Yt.get(t);return void 0===e&&(e=t.cloneNode(!0),Yt.set(t,e)),e}_getKey(t){const e=Xt.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return Xt.set(t,a),a}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e){return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`}if("link"===e){return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`}if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",a=t.getAttribute("id")||"",n=t.getAttribute("type")||"";return e||a?`script:${e}:${a}:${n}`:`script::${n}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",a=t.getAttribute("media")||"";return e?`style:${e}:${a}`:`style::${a}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const a=this._getKey(e);t.has(a)||t.set(a,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Kt.has(t)||Kt.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of qt)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of Kt.keys())e.add(t);const a=this._buildHeadElementMap();for(const t of a.keys())e.add(t);for(const n of e){let e=null;for(let t=qt.length-1;t>=0;t--){const a=qt[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=this._cloneOf(t);break}if(e)break}if(!e&&Kt.has(n)){e=Kt.get(n).cloneNode(!0)}const s=a.get(n)??null;null!==e&&s===e||(e&&s?.isEqualNode(e)&&!yt(e)||(e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),G(e)||wt(e,`<${e.tagName.toLowerCase()}> inside <${t.tagNames.head}>`,`<${t.tagNames.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(s?.remove(),a.delete(n))))}}}const Qt=Symbol.for("wcstack.package"),Zt=new WeakSet;function te(t,e){Object.defineProperty(t,Qt,{value:e,configurable:!0})}function ee(t,e,a,n,s){if(void 0!==n&&(a===n||a.prototype instanceof n))return;const r=a[Qt];if(r===s||Zt.has(t))return;Zt.add(t);const i=s.slice(0,s.lastIndexOf("@"));console.warn(`[${i}] [wcs/package-twice] <${e}> is already defined by ${r??`another copy of ${i} that does not name its version`}; this copy, ${s}, does nothing. Load each package once.`)}function ae(n=customElements){!function(t,e,a){for(const[n,s]of a){const a=t.get(n);void 0===a?(te(s,e),t.define(n,s)):ee(t,n,a,s,e)}}(n,`${e}@${a}`,[[t.tagNames.layout,H],[t.tagNames.layoutOutlet,Q],[t.tagNames.outlet,z],[t.tagNames.route,A],[t.tagNames.router,jt],[t.tagNames.link,Bt],[t.tagNames.head,Jt]])}var ne;await void ae(ne);
2
2
  //# sourceMappingURL=auto.min.js.map