@wcstack/router 3.5.4 → 4.0.0-rc.2
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 +8 -5
- package/README.md +8 -5
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.esm.js +26 -38
- package/dist/index.esm.js.map +1 -1
- package/package.json +1 -1
package/README.ja.md
CHANGED
|
@@ -117,7 +117,7 @@
|
|
|
117
117
|
|
|
118
118
|
1.32 以降は 2 つの形がどちらも動きますが、交換可能ではありません。プロジェクト単位でなく、ページごとに選びます。
|
|
119
119
|
|
|
120
|
-
**既定: 本文を `<wcs-route>` の中に置く。** router が入場時にスタンプし、退場時に取り除きます。中の `data-wcs` バインディングはスタンプ時に束ねられる(binder プロトコル)ので、state が描画するマークアップ —— `for:`・`if:`・テキスト —— も他の場所と同じように動きます。router が提供するものはすべてルート本文を基準にしています: ルートごとの `<wcs-head>`、`focus="heading"` / `announce=` ポリシー(*スタンプされた内容の中の*見出しを探す)、ルート切替ごとのビュートランジション。router が state に渡すのはルート本文の要素だけなので、`<wcs-route>` の直下の(要素に包まれていない)テキストの `{{ }}` が束ねられるのは、着地のルートで state
|
|
120
|
+
**既定: 本文を `<wcs-route>` の中に置く。** router が入場時にスタンプし、退場時に取り除きます。中の `data-wcs` バインディングはスタンプ時に束ねられる(binder プロトコル)ので、state が描画するマークアップ —— `for:`・`if:`・テキスト —— も他の場所と同じように動きます。router が提供するものはすべてルート本文を基準にしています: ルートごとの `<wcs-head>`、`focus="heading"` / `announce=` ポリシー(*スタンプされた内容の中の*見出しを探す)、ルート切替ごとのビュートランジション。router が state に渡すのはルート本文の要素だけなので、`<wcs-route>` の直下の(要素に包まれていない)テキストの `{{ }}` が束ねられるのは、着地のルートで state の最初の走査が見つけたときだけで、ナビゲーションで入ったときは束ねられません(@wcstack/state 3.x・4.0 とも)。そうしたテキストは要素で包みます(`<p>{{ title }}</p>`)。
|
|
121
121
|
|
|
122
122
|
```html
|
|
123
123
|
<wcs-route path="/products/:productId(int)">
|
|
@@ -129,9 +129,12 @@
|
|
|
129
129
|
</wcs-route>
|
|
130
130
|
```
|
|
131
131
|
|
|
132
|
-
構造のテンプレート(`for:` / `if:`)は、上の `<ul>`
|
|
132
|
+
構造のテンプレート(`for:` / `if:`)は、上の `<ul>` のようにルート本文の要素の中に置きます。これは @wcstack/state のどの版でも動きます。`<wcs-route>` の直下に置いたものは、版によって扱いが変わります。
|
|
133
133
|
|
|
134
|
-
router
|
|
134
|
+
- **@wcstack/state 4.0** は、着地のルートでも、ナビゲーションで入ったルートでも描き、描いた行や枝(`elseif:` / `else:` を含む)はルートと一緒に出入りします。router は state の binder に「ルートの範囲を持ち運ぶ」と宣言して内容を渡し(binder プロトコルの `bind(subtree, { range: true })`)、4.0 はその宣言があるときだけ、内容の直下で渡された構造のテンプレートを描きます。宣言なしで渡されたもの(古い router)は `[wcs/template-syntax]` #204 として報告します。
|
|
135
|
+
- **@wcstack/state 3.x** が描くのは、state のページの最初の走査のときだけです(着地のルートで、router がスタンプした後に state が読み込みを終えたとき)。ナビゲーションで入ったルートは内容を state に渡し、3.x は、渡された構造のテンプレートそのものは描かず、束縛の適用の失敗として報告します。3.5.0 までは、`data-wcs` を自分に持つ直下の要素を、テンプレートを含む要素より前に置くこともできません(`<wcs-route>` の直下の `<h2 data-wcs="…">` の後ろに `<ul>` が続く形)。3.5.0 までの 3.x はそうした要素を親から走査して束ねるので、まだ準備のできていない後ろのテンプレートに届き、ナビゲーションのときに同じ失敗を報告します。3.5.1 からは、渡された要素だけを束ねます。上の `<article>` のように本文を 1 つの要素で包めば、どちらも避けられます。
|
|
136
|
+
|
|
137
|
+
router は、スタンプしたルート本文の終わりにコメントの印 `<!--@@wcs-route-end:<path>-->`(SSR と同じ印)を置き、退場のときにルートの placeholder からこの印までをまとめて持ち出し、次の入場で戻します。ルート自身のノードのほか、その間に後から描かれたもの(直下のテンプレートが描いた行や枝など)も含みます。作者のコードがこの 2 つのコメントの間に差し込んだノードはルートと一緒に出入りします。ルート本文から外へ移したノード(`<body>` へ移したダイアログなど)は、これまでどおり退場のときにルート本文へ戻して持ちます。戻すのは持ち出したものなので、作者のコードがルート本文から取り除いた直下のノード(閉じたお知らせなど)は、次の入場でも戻りません。印はコメントなので、`wcs-outlet:empty` には影響しません。
|
|
135
138
|
|
|
136
139
|
**例外: ナビゲーションをまたいで DOM を文書に置いたままにしたいときは state で切り替える(`<template data-wcs="if: …">`)。** ルートを離れると本文は文書から外され、入場のときに同じノードが戻されます。ノードが持つもの(入力途中のフォームの値)は残りますが、文書につながっていることが要るものは残りません。再生中の `<video>` は止まり、スクロール済みのリストはスクロール位置を失い(Chromium と WebKit)、`disconnectedCallback` で後始末する部品は初めからやり直します。そうした内容は router の外に置き、router の `routeName` / `typedParams` 出力が立てる state のフラグにバインドし、ルート要素は空(または `<wcs-head>` だけ)にします。
|
|
137
140
|
|
|
@@ -363,7 +366,7 @@ console.log(router.typedParams.userId); // 123 (number)
|
|
|
363
366
|
|
|
364
367
|
テンプレートを読み込み、子要素を`<slot>`へ挿入して`<wcs-layout-outlet>`へ書き出す。Light DOM対応。外部ファイル対応。
|
|
365
368
|
|
|
366
|
-
@wcstack/state と組むと、outlet は置いた要素を、ページに入った後で(テンプレートの読み込みは非同期)state の binder へ渡す。レイアウトのテンプレートと、スロットに入るルートの内容の、要素の中の `data-wcs` / `{{ }}` は、着地のルートだけでなく、ナビゲーションで初めてレイアウトに入ったときから束ねられる。渡すのは要素だけなので、レイアウトのテンプレートの直下の(要素に包まれていない)テキストの `{{ }}` は、ナビゲーションでは束ねられない。ルート本文と同じく要素で包むこと(「ルートの本文はどこに置くか」の節)。`enable-shadow-root` では、テンプレートは outlet の shadow root の中にあり、ページの state は束ねない(light DOM のルートの内容は束ねる)。
|
|
369
|
+
@wcstack/state と組むと、outlet は置いた要素を、ページに入った後で(テンプレートの読み込みは非同期)state の binder へ渡す。レイアウトのテンプレートと、スロットに入るルートの内容の、要素の中の `data-wcs` / `{{ }}` は、着地のルートだけでなく、ナビゲーションで初めてレイアウトに入ったときから束ねられる。渡すのは要素だけなので、レイアウトのテンプレートの直下の(要素に包まれていない)テキストの `{{ }}` は、ナビゲーションでは束ねられない。ルート本文と同じく要素で包むこと(「ルートの本文はどこに置くか」の節)。`enable-shadow-root` では、テンプレートは outlet の shadow root の中にあり、ページの state は束ねない(light DOM のルートの内容は束ねる)。outlet は、router がルートの本文を渡すのと同じく範囲を宣言して内容を渡す(`bind(subtree, { range: true })`)ので、**@wcstack/state 4.0** と組むと、レイアウトのテンプレートの先頭に置いた `for:` / `if:` のテンプレートも、着地のルートでもナビゲーションでも描かれ、行や枝はルートと一緒に出入りする。@wcstack/state 3.x はナビゲーションではそれを描かない(3.x ではルート本文と同じく要素で包むこと)。
|
|
367
370
|
|
|
368
371
|
| 属性 | 説明 |
|
|
369
372
|
|------|------|
|
|
@@ -504,7 +507,7 @@ bootstrapRouter({
|
|
|
504
507
|
});
|
|
505
508
|
```
|
|
506
509
|
|
|
507
|
-
|
|
510
|
+
`bootstrapRouter()` は、持っていないオプション、既定値と型の違う値(`null` や、オブジェクトの所の配列を含む)、定義していない `tagNames` のキー、文字列でないタグ名で例外を投げます。当てる前にすべてのオプションを確かめるので、投げたときは何も当てません。値が `undefined` のオプションは飛ばします。
|
|
508
511
|
|
|
509
512
|
## ルート遷移アニメーション
|
|
510
513
|
|
package/README.md
CHANGED
|
@@ -117,7 +117,7 @@ That's what `<wcs-router>`, `<wcs-route>`, and friends explore. One CDN import,
|
|
|
117
117
|
|
|
118
118
|
Two shapes work since 1.32, and they are not interchangeable. Pick per page, not per project.
|
|
119
119
|
|
|
120
|
-
**Default: put the content inside `<wcs-route>`.** The router stamps it on entry and removes it on exit. `data-wcs` bindings inside it are bound when it is stamped (the binder protocol), so state-rendered markup — `for:`, `if:`, text — works there like anywhere else. Everything the router offers is keyed to the route body: `<wcs-head>` per route, the `focus="heading"` / `announce=` policies (they look for the heading *in the stamped content*), and a view transition per route swap. The router hands state only the route body's elements, so a `{{ }}` in text directly under `<wcs-route>` (not inside an element) is bound only on the landing route, by state's first scan — not when the route is entered by navigation. Wrap such text in an element (`<p>{{ title }}</p>`).
|
|
120
|
+
**Default: put the content inside `<wcs-route>`.** The router stamps it on entry and removes it on exit. `data-wcs` bindings inside it are bound when it is stamped (the binder protocol), so state-rendered markup — `for:`, `if:`, text — works there like anywhere else. Everything the router offers is keyed to the route body: `<wcs-head>` per route, the `focus="heading"` / `announce=` policies (they look for the heading *in the stamped content*), and a view transition per route swap. The router hands state only the route body's elements, so a `{{ }}` in text directly under `<wcs-route>` (not inside an element) is bound only on the landing route, by state's first scan — not when the route is entered by navigation (@wcstack/state 3.x and 4.0 alike). Wrap such text in an element (`<p>{{ title }}</p>`).
|
|
121
121
|
|
|
122
122
|
```html
|
|
123
123
|
<wcs-route path="/products/:productId(int)">
|
|
@@ -129,9 +129,12 @@ Two shapes work since 1.32, and they are not interchangeable. Pick per page, not
|
|
|
129
129
|
</wcs-route>
|
|
130
130
|
```
|
|
131
131
|
|
|
132
|
-
Put a structural template (`for:` / `if:`) inside an element of the route body, as the `<ul>` above does
|
|
132
|
+
Put a structural template (`for:` / `if:`) inside an element of the route body, as the `<ul>` above does: that works with every version of @wcstack/state. One directly under `<wcs-route>` depends on the version:
|
|
133
133
|
|
|
134
|
-
|
|
134
|
+
- **@wcstack/state 4.0** renders it whether the route is the landing one or entered by navigation, and its rows or branch (with its `elseif:` / `else:`) leave and come back with the route. The router tells state's binder that it carries the route's range (`bind(subtree, { range: true })`, the binder protocol), and only then does 4.0 render a template handed over at the top of the content; handed over without it (an older router) it reports `[wcs/template-syntax]` #204.
|
|
135
|
+
- **@wcstack/state 3.x** renders it only in state's first scan of the page — the landing route, when state finishes loading after the router stamped it. A route entered by navigation hands its content to state, and 3.x does not render a structural template handed over itself: it reports that the binding failed to apply. Up to 3.5.0, a top-level element that carries `data-wcs` itself must not come before the element that holds the template either (an `<h2 data-wcs="…">` directly under `<wcs-route>`, followed by the `<ul>`): 3.5.0 and earlier bind such an element by walking from its parent, which reaches the later template before it is set up, and report the same failure on navigation; 3.5.1 and later bind only the element handed over. Wrapping the body in one element, as the `<article>` above does, avoids both.
|
|
136
|
+
|
|
137
|
+
The router marks where a stamped route body ends with a comment, `<!--@@wcs-route-end:<path>-->` (the same marker SSR uses), and on exit takes everything from the route's placeholder up to it along — the route's own nodes and whatever was rendered among them since, such as the rows or branch a top-level template rendered — and puts it all back on the next entry. A node your own code inserts between those two comments goes and comes back with the route; one you moved out of the route body (a dialog moved to `<body>`) is taken back into it on exit, as before. What comes back is what was taken out: a top-level node your code removed from the route body (a dismissed notice) stays removed on the next entry. The marker is a comment, so `wcs-outlet:empty` is unaffected.
|
|
135
138
|
|
|
136
139
|
**Exception: switch it with state (`<template data-wcs="if: …">`) when the DOM must stay in the document across the navigation.** Leaving a route removes its body from the document, and entering puts the same nodes back. What the nodes hold survives (a half-filled form keeps its input), but what needs them to stay connected does not: a `<video>` stops playing, a scrolled list loses its scroll position (in Chromium and WebKit), and a component that tears down in `disconnectedCallback` starts over. Keep such content outside the router, bound to a state flag that the router's `routeName` / `typedParams` outputs set, and leave the route element empty (or holding only `<wcs-head>`).
|
|
137
140
|
|
|
@@ -363,7 +366,7 @@ console.log(router.typedParams.userId); // 123 (number)
|
|
|
363
366
|
|
|
364
367
|
Loads a template, inserts children into `<slot>`, and writes to `<wcs-layout-outlet>`. Light DOM supported. External file supported.
|
|
365
368
|
|
|
366
|
-
With @wcstack/state, the outlet hands the elements it places — and with them the `data-wcs` / `{{ }}` inside elements of the layout template and of the route content in its slots — to state's binder once they are in the page (the template loads asynchronously), so both are bound on the very first navigation into the layout, not only on the landing route. Only elements are handed over: a `{{ }}` in text directly under the layout template (not inside an element) is not bound on a navigation — wrap it in an element, as for a route body (see "Where route content lives"). With `enable-shadow-root`, the template lives in the outlet's shadow root, which the page's state does not bind (the route content in the light DOM is bound).
|
|
369
|
+
With @wcstack/state, the outlet hands the elements it places — and with them the `data-wcs` / `{{ }}` inside elements of the layout template and of the route content in its slots — to state's binder once they are in the page (the template loads asynchronously), so both are bound on the very first navigation into the layout, not only on the landing route. Only elements are handed over: a `{{ }}` in text directly under the layout template (not inside an element) is not bound on a navigation — wrap it in an element, as for a route body (see "Where route content lives"). With `enable-shadow-root`, the template lives in the outlet's shadow root, which the page's state does not bind (the route content in the light DOM is bound). The outlet hands its content over the way the router hands over a route body, declaring the range (`bind(subtree, { range: true })`), so with **@wcstack/state 4.0** a `for:` / `if:` template at the top of the layout template renders as well — on the landing route and on navigation — and its rows or branch leave and come back with the route; @wcstack/state 3.x does not render it on a navigation (wrap it in an element there, as for a route body).
|
|
367
370
|
|
|
368
371
|
| Attribute | Description |
|
|
369
372
|
|------|------|
|
|
@@ -504,7 +507,7 @@ bootstrapRouter({
|
|
|
504
507
|
});
|
|
505
508
|
```
|
|
506
509
|
|
|
507
|
-
|
|
510
|
+
`bootstrapRouter()` throws on an option it does not have, on a value whose type differs from the option's default (`null`, or an array where an object is expected, included), and on a `tagNames` key it does not define or a tag name that is not a string. It checks every option before applying any, so nothing is applied when it throws. An option whose value is `undefined` is skipped.
|
|
508
511
|
|
|
509
512
|
## Route transition animations
|
|
510
513
|
|
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"]},e=t;function a(){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 n(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class s 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:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function r(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}function o(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}const l={static:2,param:1,"catch-all":0};class c 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(t,a){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&n(`${e.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&n(`${e.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(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+=l[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("^(.*)$")});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(`^${n}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",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||n(`${e.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:r(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof n&&""!==n)throw new s("Navigation cancelled by guard.",n);if(!n)throw new s("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof n?n:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new s("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}}const h="data-wcs-ssr",u="data-wcs-ssr-link",d="@@wcs-route-ph:",m="@@wcs-route-start:",p="@@wcs-route-end:";class g extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=a();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new c(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||n(`${e.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(`${p}${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()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,a){if(this._initialized)return;let s;this._initialized=!0;let i=!1,r=!1;this.hasAttribute("path")?s=this.getAttribute("path")||"":this.hasAttribute("index")?(s="",i=!0):this.hasAttribute("fallback")?(s="",r=!0):n(`${e.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=a;const o=a||t;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,r&&(a&&n(`${e.tagNames.route} with fallback attribute must be a direct child of ${e.tagNames.router}.`),t.fallbackRoute&&n(`${e.tagNames.router} can have only one fallback route.`),t.fallbackRoute=this),a&&(this._core.parentCore=a._core),this._core.parsePath(s,{isIndex:i,isFallback:r,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}}const f=Symbol.for("wcstack.trustedTypes.policy"),_=Symbol.for("wcstack.trustedTypes.internal"),b="wcstack";function y(){const t=globalThis[f];return null===t||"object"!=typeof t?null:t}let w=!1;function N(t){const e=function(){const t=globalThis,e=t[_];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy(b,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof y()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${b}". Allow it in the CSP (\`trusted-types ${b};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[_]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=y(),s=n?.createHTML;return"function"==typeof s?(w||(w=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${b}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${b};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const v=new Map;class C extends HTMLElement{_uuid=a();constructor(){super()}async _loadTemplateFromSource(t){try{const a=await fetch(t);a.ok||n(`${e.tagNames.layout} failed to fetch layout from source: ${t}, status: ${a.status}`);const s=await a.text();return v.set(t,s),s}catch(a){n(`${e.tagNames.layout} failed to load layout from source: ${t}, error: ${a}`,{cause:a})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),a=this.getAttribute("layout");t&&a&&console.warn(`${e.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)v.has(t)?n.innerHTML=N(v.get(t)||""):n.innerHTML=N(await this._loadTemplateFromSource(t)||"");else if(a){const t=this._loadTemplateFromDocument(a);t?n.innerHTML=N(t):console.warn(`${e.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")&&e.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class P extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||n(`${e.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")&&e.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const k=new Set(["props","states","attr",""]);function E(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 A(t,e){t.hasAttribute("data-bind")||n(`${t.tagName} has no 'data-bind' attribute.`);const a=t.getAttribute("data-bind")||"";k.has(a)||n(`${t.tagName} has invalid 'data-bind' attribute: ${a}`);const s=a,i=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const a=t.getAttribute("is");return a&&a.includes("-")?a:null}(t);i&&void 0===customElements.get(i)?customElements.whenDefined(i).then(()=>{t.isConnected&&E(t,e,s)}).catch(()=>{n(`Failed to define custom element: ${i}`)}):E(t,e,s)}const S=Symbol.for("wcstack.binder");function $(){const t=globalThis[S];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const x=Symbol.for("wcstack.binder.pending"),R=Symbol.for("wcstack.binder.taken");function T(){const t=globalThis;let e=t[R];return void 0===e&&(e=new WeakSet,t[R]=e),e}function L(t,e){const a=$();return null===a?(function(){const t=globalThis;let e=t[x];return void 0===e&&(e=[],t[x]=e),e}().push(t),!1):(T().add(t),a.bind(t,e),!0)}const H={range:!0};function z(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),z(a,e);return e}function I(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:z(t,new Set),i=[];let r=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)i.push(o),(n||t.childNodeArray.includes(o))&&(r=i.length);return i.length=r,i}class M extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||n(`${e.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 t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const a=t.content.cloneNode(!0),n=new Map;a.querySelectorAll("slot").forEach(t=>{const a=t.getAttribute("name")||"";n.has(a)?console.warn(`${e.tagNames.layoutOutlet} duplicate slot name "${a}" in layout template.`):n.set(a,t)});const s=new Map,i=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}}i.appendChild(t)}for(const[t,e]of n){const a=s.get(t);a&&e.replaceWith(a)}const r=n.get("");r&&r.replaceWith(i),this.appendChild(a)}!function(t){if(null!==$())for(const e of t)1===e.nodeType&&L(e,H)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){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=>{A(e,t)}),e.hasAttribute("data-bind")&&A(e,t))}}function O(){return document.createElement(e.tagNames.layoutOutlet)}const F="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function U(t,e){let a=null,s=null;const i=e.uuid||"",r=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=t.text+r;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){s=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)),n(function(t,e,a){return a?`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 ${F}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${F}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",c)}return a&&"function"==typeof a.default?a.default:null}function W(t,e){U(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function j(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 D(t,a,n,s){const i=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a;const c=l.tagName.toLowerCase();if(c===e.tagNames.route){const e=document.createDocumentFragment();for(const t of Array.from(l.childNodes))e.appendChild(t);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(e);const r=a;r.initialize(t,i),j(s,r),n.push(r),o=r.placeHolder,l=r}else{if(c===e.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=l.querySelector('script[type="module"]');e&&W(e,t)}continue}if("template"===c){r.appendChild(l);continue}if(c===e.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=O();n.layout=a,o=n,l=e}}const h=await D(t,l,n,s);l.replaceChildren(),l.appendChild(h),r.appendChild(o)}else r.appendChild(a);return r}async function G(t){const e=new Map;return await D(t,t.template.content,[],e)}function q(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(B(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(B(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 B(t){return!1!==t.checkVisibility?.()}function K(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)K(s,e,a,n)}function V(t,e){const a=t.routeChildNodes,n=[],s=e.split("/"),i=s.filter((t,e)=>(0!==e||""!==t)&&!(e===s.length-1&&""===t&&s.length>1));for(const t of a)K(t,e,i,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 i=a.absoluteWeight-n.absoluteWeight;if(0!==i)return-i;return a.childIndex-n.childIndex}),n.length>0?n[0]:null}let Y=null,J=null;function Q(){const t=e.basenameFileExtensions;return 0===t.length?null:(Y===t&&J||(Y=t,J=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),J)}function X(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=Q();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Z(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function tt(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=Q();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function et(t){if(null!==t.held)return;const e=I(t),a=new Set(e),n=[...e,...t.childNodeArray];let s=null;for(const i of t.childNodeArray)a.has(i)?s=i:null===i.parentNode||n.some(t=>t!==i&&t.contains(i))||(e.splice(null===s?0:e.indexOf(s)+1,0,i),a.add(i),s=i);const i=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])}(i,e),i.appendChild(t.endMarker),t.held=i}function at(t){t.clearParams(),et(t)}function nt(t,a){const n={},s={};for(const e of t.paramNames)n[e]=a.params[e],s[e]=a.typedParams[e];t.setParams(n,s);for(const a of t.childNodeArray)if(a.nodeType===Node.ELEMENT_NODE){const n=a;n.querySelectorAll("[data-bind]").forEach(e=>{A(e,t.typedParams)}),n.hasAttribute("data-bind")&&A(n,t.typedParams),n.querySelectorAll(e.tagNames.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===e.tagNames.layoutOutlet&&n.assignParams(t.typedParams)}}const st=new WeakSet;function it(t){const e=t.placeHolder;null!==e.parentNode&&(st.has(t)||null!==t.endMarker.parentNode?(et(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),st.add(t))}const rt=Symbol.for("wcstack.transition-runner");function ot(t,e,a){const n=function(t){const e=globalThis[rt];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 lt=new WeakSet,ct="data-wcs";function ht(t,e,a){!lt.has(t)&&function(t){return t.hasAttribute(ct)||null!==t.querySelector(`[${ct}]`)}(t)&&(lt.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==$()||(n=t,T().has(n))||console.warn(`[@wcstack/router] ${e} contains ${ct} 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 ut(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(L(e,H))continue}else if(null!==$())continue;ht(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 dt(t,e){try{let t=null;for(const a of e.routes){const n=await a.guardCheck(e);n&&(t=null===t?n:Object.assign({},t,n))}e.data=t}catch(e){if(e instanceof s)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function mt(t,a,s,i,r=""){const o=Z(s,t.basename);if(t.isSameMatch(o))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:r,path:o}),!0;let l=V(t,o);l||(t.fallbackRoute?l={routes:[t.fallbackRoute],params:{},typedParams:{},path:o,lastPath:i}:n(`${e.tagNames.router} No route matched for path: ${o}`)),l.lastPath=i,l.search=r;const c=a.lastRoutes,h=await async function(t,e,a){if(!await dt(t,e))return!1;const n=new Set(e.routes),s=new Set(a),i=()=>{for(const t of a)n.has(t)||at(t);const t=[];for(const a of e.routes)(t.length>0||!s.has(a)||a.shouldChange(e.params))&&(t.push(a),nt(a,e));let i=!1;for(const e of t){const t=s.has(e);t&&i||it(e),i||=t,a.length>0&&!t&&ut(e)}};let r;return 0===a.length?i():r=ot("router",i),void 0!==r&&await r,!0}(t,l,c);return!!h&&(t.commitNavigation({params:l.params,typedParams:l.typedParams,routeName:l.routes[l.routes.length-1]?.name??"",data:l.data??null,search:r,path:o}),a.lastRoutes=l.routes,c.length>0&&q(t,l),!0)}function pt(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function gt(t){let e=t,a="";const n=e.indexOf("#");n>=0&&(a=e.slice(n),e=e.slice(0,n));let s="";const i=e.indexOf("?");return i>=0&&(s=e.slice(i),e=e.slice(0,i)),{pathname:e,search:s,hash:a}}function ft(t){return"?"===t?"":t}function _t(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}function bt(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const yt=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"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=yt;_typedParams=yt;_searchParams=yt;_routeName="";_data=null;_hasCommitted=!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 X(t)}_normalizeBasename(t){return tt(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}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(e.tagNames.outlet))return t;const a=document.createElement(e.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||n(`${e.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||n(`${e.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){const e=Object.freeze({...t.params}),a=Object.freeze({...t.typedParams}),n=r(t.search),s=t.data??null,i=this._data!==s,l=!o(this._params,e),c=this._routeName!==t.routeName,h=!o(this._searchParams,n),u=this._path!==t.path;i&&(this._data=s),l&&(this._params=e,this._typedParams=a),c&&(this._routeName=t.routeName),h&&(this._searchParams=n),this._path=t.path,this._hasCommitted=!0,i&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),l&&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})),h&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${e.tagNames.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${e.tagNames.router} replace failed:`,t)}).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=gt(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+ft(a.search)+a.hash,i=pt();if(i?.navigate){const t=e?i.navigate(s,{history:"replace"}):i.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(n),i=this.isSameMatch(Z(t,this._basename));await mt(this,this.outlet,t,this._path,ft(a.search))&&!i&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const a=new URL(t.destination.url),n=this._normalizePathname(a.pathname);if(!this._isOwnPath(n))return;const s=this.isSameMatch(Z(n,this._basename)),i=s&&("push"===t.navigationType||"replace"===t.navigationType),r=a.search,o=this;t.intercept({handler:async()=>{try{await mt(o,o.outlet,n,o.path,r)}catch(t){throw console.error(`${e.tagNames.router} applyRoute failed:`,t),t}},scroll:i?"manual":"after-transition",focusReset:s||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await mt(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=bt();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const a=null!==document.querySelector("base[href]"),s=new URL(window.location.href);""!==this._basename||a||"/"===s.pathname||n(`${e.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||n(`${e.tagNames.router} should have a <template> child element.`);const i=t?this._template.content.cloneNode(!0):null,r=await G(this),o=!t&&this._outlet.hasAttribute(h);if(o||this._outlet.rootNode.appendChild(r),null!==i){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(i)}0===this.routeChildNodes.length&&n(`${e.tagNames.router} has no route definitions.`),t||this._ensureA11yRegion();const l=this._normalizePathname(window.location.pathname);if(t)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(h);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}await mt(this,this.outlet,l,this._path,window.location.search||""),(o||null!==$())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){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(e.tagNames.layoutOutlet))return!1;const i=new Map,r=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(d)){const a=e.slice(15);if(i.has(a)||!n.has(a))return!1;i.set(a,t)}else if(e.startsWith(m)){const a=e.slice(18);if(r.has(a)||!n.has(a))return!1;r.set(a,{comment:t,index:c})}else if(e.startsWith(p)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:c})}}if(r.size!==o.size)return!1;const u=[];for(const[t,e]of r){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;u.push({start:e.index,end:a.index})}for(const t of u)for(const e of u)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const g=Z(t,this._basename);let f=V(this,g);if(!f){if(null===this._fallbackRoute)return!1;f={routes:[this._fallbackRoute],params:{},typedParams:{},path:g,lastPath:this._path}}if(f.lastPath=this._path,f.routes.length!==r.size)return!1;for(const t of f.routes)if(!r.has(t.absolutePath))return!1;const _=new Set;for(const t of this.routeChildNodes)_.add(t.absolutePath);for(const t of f.routes)for(const e of t.routeChildNodes)_.add(e.absolutePath);if(i.size!==_.size)return!1;for(const t of _)if(!i.has(t))return!1;for(const[t,e]of i){const a=n.get(t);e.parentNode.replaceChild(a.placeHolder,e)}for(const t of f.routes){const a=r.get(t.absolutePath).comment,n=o.get(t.absolutePath).comment,s=[],i=new Set;let l=a.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const t=l.data;if(t.startsWith(m)){const e=t.slice(18);l=o.get(e).comment.nextSibling;continue}}if(i.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===e.tagNames.link){const t=l.anchorElement;null!==t&&i.add(t)}s.push(l),l=l.nextSibling}}t.adoptChildNodes(s,n)}for(const{comment:t}of r.values())t.remove();this.outlet.removeAttribute(h);for(const t of f.routes)nt(t,f);return this.outlet.lastRoutes=f.routes,!await dt(this,f)||(this.commitNavigation({params:f.params,typedParams:f.typedParams,routeName:f.routes[f.routes.length-1].name,data:f.data??null,search:window.location.search||"",path:g}),!0)}async _renderForSsr(t){const a=Z(t,this._basename),s=V(this,a),i=s?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===i.length&&n(`${e.tagNames.router} No route matched for path: ${a}`),!i.some(t=>t.hasGuard)){await mt(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${d}${t.absolutePath}`}),this.outlet.setAttribute(h,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${m}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&L(e,H)}_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)for(const e of a){const a=e.name;if(!Object.prototype.hasOwnProperty.call(t,a))continue;if(!_t(t,a))continue;const n=t,s=n[a];delete n[a],n[a]=s}}(this),bt()){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=pt();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(pt()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Nt=["title","rel","target","download","hreflang","lang","dir"];class vt extends HTMLElement{static get observedAttributes(){return["to",...Nt]}_childNodeArray=[];_uuid=a();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(e.tagNames.router);if(t)return this._router=t;const a=this.getRootNode(),s=a.querySelector?.(e.tagNames.router);if(s)return this._router=s;n(`${e.tagNames.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return X(t)}_joinInternalPath(t,e){const a=tt(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(t,a){if(this._isInternalTarget(a)){const{pathname:e,search:n,hash:s}=gt(a),i=""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e);t.href=i+ft(n)+s}else try{t.href=new URL(a).toString()}catch{n(`[${e.tagNames.link}] Invalid URL in 'to' attribute: ${a}`)}}connectedCallback(){bt()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(u)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let a;if(null!==e)a=e,a.removeAttribute(u),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-")||Nt.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,bt())return this._updateActiveState(),void a.setAttribute(u,"");pt()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!pt()?.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._updateActiveState()))},a.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){pt()?.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("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Nt.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=gt(this._path),a=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===a?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Ct=[],Pt=new Map;let kt=!1;const Et=new WeakMap;class At extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),kt||(this._captureInitialHead(),kt=!0),Ct.push(this),this._reapplyHead()}disconnectedCallback(){const t=Ct.indexOf(this);-1!==t&&Ct.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||n("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Et.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return Et.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);Pt.has(t)||Pt.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of Ct)for(const a of e._childElementArray)t.add(this._getKey(a));for(const e of Pt.keys())t.add(e);const a=this._buildHeadElementMap();for(const e of a.keys())t.add(e);for(const n of t){let t=null;for(let e=Ct.length-1;e>=0;e--){const a=Ct[e];for(const e of a._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}if(!t&&Pt.has(n)){t=Pt.get(n).cloneNode(!0)}const s=a.get(n)??null;t?(s?s.replaceWith(t):document.head.appendChild(t),a.set(n,t),L(t)||ht(t,`<${t.tagName.toLowerCase()}> inside <${e.tagNames.head}>`,`<${e.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))}}}function St(t=customElements){t.get(e.tagNames.layout)||t.define(e.tagNames.layout,C),t.get(e.tagNames.layoutOutlet)||t.define(e.tagNames.layoutOutlet,M),t.get(e.tagNames.outlet)||t.define(e.tagNames.outlet,P),t.get(e.tagNames.route)||t.define(e.tagNames.route,g),t.get(e.tagNames.router)||t.define(e.tagNames.router,wt),t.get(e.tagNames.link)||t.define(e.tagNames.link,vt),t.get(e.tagNames.head)||t.define(e.tagNames.head,At)}var $t;await void St($t);
|
|
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"]};function e(){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 a(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class n extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}}const s={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:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function i(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}function r(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}const o={static:2,param:1,"catch-all":0};class l 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,n){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&a(`${t.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&a(`${t.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):n()}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+=o[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("^(.*)$")});break}if(n.startsWith(":")){const t=n.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,a="any";t?(e=t[1],t[3]&&Object.keys(s).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(`^${n}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",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||a(`${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,s=await this._guardHandler(e,a,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:i(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof s&&""!==s)throw new n("Navigation cancelled by guard.",s);if(!s)throw new n("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof s?s:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new n("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}}const c="data-wcs-ssr",h="data-wcs-ssr-link",u="@@wcs-route-ph:",d="@@wcs-route-start:",m="@@wcs-route-end:";class p extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=e();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new l(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||a(`${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(`${m}${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()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(e,n){if(this._initialized)return;let s;this._initialized=!0;let i=!1,r=!1;this.hasAttribute("path")?s=this.getAttribute("path")||"":this.hasAttribute("index")?(s="",i=!0):this.hasAttribute("fallback")?(s="",r=!0):a(`${t.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=n;const o=n||e;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,r&&(n&&a(`${t.tagNames.route} with fallback attribute must be a direct child of ${t.tagNames.router}.`),e.fallbackRoute&&a(`${t.tagNames.router} can have only one fallback route.`),e.fallbackRoute=this),n&&(this._core.parentCore=n._core),this._core.parsePath(s,{isIndex:i,isFallback:r,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}}const g=Symbol.for("wcstack.trustedTypes.policy"),f=Symbol.for("wcstack.trustedTypes.internal"),_="wcstack";function b(){const t=globalThis[g];return null===t||"object"!=typeof t?null:t}let y=!1;function w(t){const e=function(){const t=globalThis,e=t[f];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 b()?.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[f]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=b(),s=n?.createHTML;return"function"==typeof s?(y||(y=!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 N=new Map;class v extends HTMLElement{_uuid=e();constructor(){super()}async _loadTemplateFromSource(e){try{const n=await fetch(e);n.ok||a(`${t.tagNames.layout} failed to fetch layout from source: ${e}, status: ${n.status}`);const s=await n.text();return N.set(e,s),s}catch(n){a(`${t.tagNames.layout} failed to load layout from source: ${e}, error: ${n}`,{cause:n})}}_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)N.has(e)?n.innerHTML=w(N.get(e)||""):n.innerHTML=w(await this._loadTemplateFromSource(e)||"");else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=w(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 C extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||a(`${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 P=new Set(["props","states","attr",""]);function k(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 E(t,e){t.hasAttribute("data-bind")||a(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";P.has(n)||a(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const s=n,i=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const a=t.getAttribute("is");return a&&a.includes("-")?a:null}(t);i&&void 0===customElements.get(i)?customElements.whenDefined(i).then(()=>{t.isConnected&&k(t,e,s)}).catch(()=>{a(`Failed to define custom element: ${i}`)}):k(t,e,s)}const A=Symbol.for("wcstack.binder");function S(){const t=globalThis[A];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const $=Symbol.for("wcstack.binder.pending"),x=Symbol.for("wcstack.binder.taken");function R(){const t=globalThis;let e=t[x];return void 0===e&&(e=new WeakSet,t[x]=e),e}function T(t,e){const a=S();return null===a?(function(){const t=globalThis;let e=t[$];return void 0===e&&(e=[],t[$]=e),e}().push(t),!1):(R().add(t),a.bind(t,e),!0)}const L={range:!0};function H(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),H(a,e);return e}function z(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:H(t,new Set),i=[];let r=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)i.push(o),(n||t.childNodeArray.includes(o))&&(r=i.length);return i.length=r,i}class I extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||a(`${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));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}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,i=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}}i.appendChild(t)}for(const[t,e]of n){const a=s.get(t);a&&e.replaceWith(a)}const r=n.get("");r&&r.replaceWith(i),this.appendChild(a)}!function(t){if(null!==S())for(const e of t)1===e.nodeType&&T(e,L)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){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=>{E(e,t)}),e.hasAttribute("data-bind")&&E(e,t))}}function M(){return document.createElement(t.tagNames.layoutOutlet)}const O="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function F(t,e){let n=null,s=null;const i=e.uuid||"",r=`\n//# sourceURL=${i?`wcs-guard-handler:${i}`:"wcs-guard-handler"}\n`,o=t.text+r;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{n=await import(e)}catch(t){s=t}finally{URL.revokeObjectURL(e)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await import(`data:application/javascript;base64,${t}`)}catch(t){await new Promise(t=>setTimeout(t)),a(function(t,e,a){return a?`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 ${O}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${O}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",c)}return n&&"function"==typeof n.default?n.default:null}function U(t,e){F(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function W(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 j(e,a,n,s){const i=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a;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,i),W(s,r),n.push(r),o=r.placeHolder,l=r}else{if(c===t.tagNames.guardHandler){if(n.length>0){const t=n[n.length-1],e=l.querySelector('script[type="module"]');e&&U(e,t)}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=M();n.layout=a,o=n,l=e}}const h=await j(e,l,n,s);l.replaceChildren(),l.appendChild(h),r.appendChild(o)}else r.appendChild(a);return r}async function D(t){const e=new Map;return await j(t,t.template.content,[],e)}function G(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(q(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(q(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 q(t){return!1!==t.checkVisibility?.()}function B(t,e,a,n){const i=function(t,e,a){const n={},i={};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=s[t].parse(h);void 0!==a&&(e.paramName&&(n[e.paramName]=h,i[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,i["*"]=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:i,lastPath:""}:null}(t,e,a);i&&n.push(i);for(const s of t.routeChildNodes)B(s,e,a,n)}function K(t,e){const a=t.routeChildNodes,n=[],s=e.split("/"),i=s.filter((t,e)=>(0!==e||""!==t)&&!(e===s.length-1&&""===t&&s.length>1));for(const t of a)B(t,e,i,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 i=a.absoluteWeight-n.absoluteWeight;if(0!==i)return-i;return a.childIndex-n.childIndex}),n.length>0?n[0]:null}let V=null,Y=null;function J(){const e=t.basenameFileExtensions;return 0===e.length?null:(V===e&&Y||(V=e,Y=new RegExp(`\\/[^/]+(?:${e.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Y)}function Q(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=J();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function X(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function Z(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=J();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function tt(t){if(null!==t.held)return;const e=z(t),a=new Set(e),n=[...e,...t.childNodeArray];let s=null;for(const i of t.childNodeArray)a.has(i)?s=i:null===i.parentNode||n.some(t=>t!==i&&t.contains(i))||(e.splice(null===s?0:e.indexOf(s)+1,0,i),a.add(i),s=i);const i=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])}(i,e),i.appendChild(t.endMarker),t.held=i}function et(t){t.clearParams(),tt(t)}function at(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=>{E(t,e.typedParams)}),n.hasAttribute("data-bind")&&E(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 nt=new WeakSet;function st(t){const e=t.placeHolder;null!==e.parentNode&&(nt.has(t)||null!==t.endMarker.parentNode?(tt(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),nt.add(t))}const it=Symbol.for("wcstack.transition-runner");function rt(t,e,a){const n=function(t){const e=globalThis[it];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 ot=new WeakSet,lt="data-wcs";function ct(t,e,a){!ot.has(t)&&function(t){return t.hasAttribute(lt)||null!==t.querySelector(`[${lt}]`)}(t)&&(ot.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==S()||(n=t,R().has(n))||console.warn(`[@wcstack/router] ${e} contains ${lt} 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 ht(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(T(e,L))continue}else if(null!==S())continue;ct(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 ut(t,e){try{let t=null;for(const a of e.routes){const n=await a.guardCheck(e);n&&(t=null===t?n:Object.assign({},t,n))}e.data=t}catch(e){if(e instanceof n)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function dt(e,n,s,i,r=""){const o=X(s,e.basename);if(e.isSameMatch(o))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:r,path:o}),!0;let l=K(e,o);l||(e.fallbackRoute?l={routes:[e.fallbackRoute],params:{},typedParams:{},path:o,lastPath:i}:a(`${t.tagNames.router} No route matched for path: ${o}`)),l.lastPath=i,l.search=r;const c=n.lastRoutes,h=await async function(t,e,a){if(!await ut(t,e))return!1;const n=new Set(e.routes),s=new Set(a),i=()=>{for(const t of a)n.has(t)||et(t);const t=[];for(const a of e.routes)(t.length>0||!s.has(a)||a.shouldChange(e.params))&&(t.push(a),at(a,e));let i=!1;for(const e of t){const t=s.has(e);t&&i||st(e),i||=t,a.length>0&&!t&&ht(e)}};let r;return 0===a.length?i():r=rt("router",i),void 0!==r&&await r,!0}(e,l,c);return!!h&&(e.commitNavigation({params:l.params,typedParams:l.typedParams,routeName:l.routes[l.routes.length-1]?.name??"",data:l.data??null,search:r,path:o}),n.lastRoutes=l.routes,c.length>0&&G(e,l),!0)}function mt(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function pt(t){let e=t,a="";const n=e.indexOf("#");n>=0&&(a=e.slice(n),e=e.slice(0,n));let s="";const i=e.indexOf("?");return i>=0&&(s=e.slice(i),e=e.slice(0,i)),{pathname:e,search:s,hash:a}}function gt(t){return"?"===t?"":t}function ft(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}function _t(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const bt=Object.freeze({});class yt 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"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=bt;_typedParams=bt;_searchParams=bt;_routeName="";_data=null;_hasCommitted=!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 Q(t)}_normalizeBasename(t){return Z(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}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;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||a(`${t.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||a(`${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){const e=Object.freeze({...t.params}),a=Object.freeze({...t.typedParams}),n=i(t.search),s=t.data??null,o=this._data!==s,l=!r(this._params,e),c=this._routeName!==t.routeName,h=!r(this._searchParams,n),u=this._path!==t.path;o&&(this._data=s),l&&(this._params=e,this._typedParams=a),c&&(this._routeName=t.routeName),h&&(this._searchParams=n),this._path=t.path,this._hasCommitted=!0,o&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),l&&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})),h&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.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=>{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=>{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=pt(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+gt(a.search)+a.hash,i=mt();if(i?.navigate){const t=e?i.navigate(s,{history:"replace"}):i.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(n),i=this.isSameMatch(X(t,this._basename));await dt(this,this.outlet,t,this._path,gt(a.search))&&!i&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_onNavigateFunc(e){if(!e.canIntercept||e.hashChange||null!==e.downloadRequest)return;const a=new URL(e.destination.url),n=this._normalizePathname(a.pathname);if(!this._isOwnPath(n))return;const s=this.isSameMatch(X(n,this._basename)),i=s&&("push"===e.navigationType||"replace"===e.navigationType),r=a.search,o=this;e.intercept({handler:async()=>{try{await dt(o,o.outlet,n,o.path,r)}catch(e){throw console.error(`${t.tagNames.router} applyRoute failed:`,e),e}},scroll:i?"manual":"after-transition",focusReset:s||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await dt(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=_t();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const n=null!==document.querySelector("base[href]"),s=new URL(window.location.href);""!==this._basename||n||"/"===s.pathname||a(`${t.tagNames.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||a(`${t.tagNames.router} should have a <template> child element.`);const i=e?this._template.content.cloneNode(!0):null,r=await D(this),o=!e&&this._outlet.hasAttribute(c);if(o||this._outlet.rootNode.appendChild(r),null!==i){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(i)}0===this.routeChildNodes.length&&a(`${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(c);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}await dt(this,this.outlet,l,this._path,window.location.search||""),(o||null!==S())&&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 i=new Map,r=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(u)){const a=e.slice(15);if(i.has(a)||!n.has(a))return!1;i.set(a,t)}else if(e.startsWith(d)){const a=e.slice(18);if(r.has(a)||!n.has(a))return!1;r.set(a,{comment:t,index:h})}else if(e.startsWith(m)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:h})}}if(r.size!==o.size)return!1;const p=[];for(const[t,e]of r){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;p.push({start:e.index,end:a.index})}for(const t of p)for(const e of p)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const g=X(e,this._basename);let f=K(this,g);if(!f){if(null===this._fallbackRoute)return!1;f={routes:[this._fallbackRoute],params:{},typedParams:{},path:g,lastPath:this._path}}if(f.lastPath=this._path,f.routes.length!==r.size)return!1;for(const t of f.routes)if(!r.has(t.absolutePath))return!1;const _=new Set;for(const t of this.routeChildNodes)_.add(t.absolutePath);for(const t of f.routes)for(const e of t.routeChildNodes)_.add(e.absolutePath);if(i.size!==_.size)return!1;for(const t of _)if(!i.has(t))return!1;for(const[t,e]of i){const a=n.get(t);e.parentNode.replaceChild(a.placeHolder,e)}for(const e of f.routes){const a=r.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,s=[],i=new Set;let l=a.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const t=l.data;if(t.startsWith(d)){const e=t.slice(18);l=o.get(e).comment.nextSibling;continue}}if(i.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===t.tagNames.link){const t=l.anchorElement;null!==t&&i.add(t)}s.push(l),l=l.nextSibling}}e.adoptChildNodes(s,n)}for(const{comment:t}of r.values())t.remove();this.outlet.removeAttribute(c);for(const t of f.routes)at(t,f);return this.outlet.lastRoutes=f.routes,!await ut(this,f)||(this.commitNavigation({params:f.params,typedParams:f.typedParams,routeName:f.routes[f.routes.length-1].name,data:f.data??null,search:window.location.search||"",path:g}),!0)}async _renderForSsr(e){const n=X(e,this._basename),s=K(this,n),i=s?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===i.length&&a(`${t.tagNames.router} No route matched for path: ${n}`),!i.some(t=>t.hasGuard)){await dt(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${u}${t.absolutePath}`}),this.outlet.setAttribute(c,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${d}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&T(e,L)}_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)for(const e of a){const a=e.name;if(!Object.prototype.hasOwnProperty.call(t,a))continue;if(!ft(t,a))continue;const n=t,s=n[a];delete n[a],n[a]=s}}(this),_t()){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=mt();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(mt()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const wt=["title","rel","target","download","hreflang","lang","dir"];class Nt extends HTMLElement{static get observedAttributes(){return["to",...wt]}_childNodeArray=[];_uuid=e();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const e=this.closest(t.tagNames.router);if(e)return this._router=e;const n=this.getRootNode(),s=n.querySelector?.(t.tagNames.router);if(s)return this._router=s;a(`${t.tagNames.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return Q(t)}_joinInternalPath(t,e){const a=Z(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,n){if(this._isInternalTarget(n)){const{pathname:t,search:a,hash:s}=pt(n),i=""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t);e.href=i+gt(a)+s}else try{e.href=new URL(n).toString()}catch{a(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${n}`)}}connectedCallback(){_t()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(h)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let a;if(null!==e)a=e,a.removeAttribute(h),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-")||wt.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,_t())return this._updateActiveState(),void a.setAttribute(h,"");mt()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!mt()?.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._updateActiveState()))},a.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){mt()?.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("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(wt.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=pt(this._path),a=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===a?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const vt=[],Ct=new Map;let Pt=!1;const kt=new WeakMap;class Et extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Pt||(this._captureInitialHead(),Pt=!0),vt.push(this),this._reapplyHead()}disconnectedCallback(){const t=vt.indexOf(this);-1!==t&&vt.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||a("Head component is not initialized yet."),this._childElementArray}_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);Ct.has(t)||Ct.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of vt)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of Ct.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=vt.length-1;t>=0;t--){const a=vt[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=t.cloneNode(!0);break}if(e)break}if(!e&&Ct.has(n)){e=Ct.get(n).cloneNode(!0)}const s=a.get(n)??null;e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),T(e)||ct(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))}}}function At(e=customElements){e.get(t.tagNames.layout)||e.define(t.tagNames.layout,v),e.get(t.tagNames.layoutOutlet)||e.define(t.tagNames.layoutOutlet,I),e.get(t.tagNames.outlet)||e.define(t.tagNames.outlet,C),e.get(t.tagNames.route)||e.define(t.tagNames.route,p),e.get(t.tagNames.router)||e.define(t.tagNames.router,yt),e.get(t.tagNames.link)||e.define(t.tagNames.link,Nt),e.get(t.tagNames.head)||e.define(t.tagNames.head,Et)}var St;await void At(St);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|