Skip to main content

atmos/os_lib/web_apis/builtins/
web_forms.rs

1// 分割: builtins.rs より機械的に移動(2026-07-16 リファクタ フェーズ2)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5// ===== Storage API(localStorage / sessionStorage)=====
6// localStorage: SylFS に "__localStorage__" として永続化。sessionStorage: in-memory のみ。
7pub(crate) static LOCAL_STORAGE: spin::Mutex<alloc::collections::BTreeMap<String, String>> =
8    spin::Mutex::new(alloc::collections::BTreeMap::new());
9pub(crate) static SESSION_STORAGE: spin::Mutex<alloc::collections::BTreeMap<String, String>> =
10    spin::Mutex::new(alloc::collections::BTreeMap::new());
11pub(crate) static LS_LOADED: core::sync::atomic::AtomicBool =
12    core::sync::atomic::AtomicBool::new(false);
13// `document.cookie`(丸ごと未対応だった)。実ブラウザのような per-origin の
14// 永続 cookie jar・`expires`/`max-age`/`path`/`domain`/`secure`/`samesite`
15// 属性は非対応の簡略実装(in-memory のみ、OS 再起動で消える)。読み書きされる
16// 属性部分は無視し、`name=value` の1件のみを反映する。
17pub(crate) static COOKIES: spin::Mutex<crate::os_lib::cookie::CookieJar> =
18    spin::Mutex::new(crate::os_lib::cookie::CookieJar::new());
19
20pub(crate) const LS_FILENAME: &str = "__localStorage__";
21
22pub(crate) use crate::os_lib::web_storage::{ls_deserialize, ls_serialize};
23
24/// 起動後初回アクセス時に SylFS から localStorage を読み込む(FS 未マウントなら skip)。
25pub(crate) fn ls_ensure_loaded() {
26    if LS_LOADED.load(core::sync::atomic::Ordering::Relaxed) {
27        return;
28    }
29    LS_LOADED.store(true, core::sync::atomic::Ordering::Relaxed);
30    if !crate::os_lib::platform::fs_is_mounted() {
31        return;
32    }
33    match crate::os_lib::platform::fs_read_file_checked(LS_FILENAME) {
34        Ok(Some(data)) => {
35            *LOCAL_STORAGE.lock() = ls_deserialize(&data);
36        }
37        Ok(None) => {}
38        Err(e) => {
39            crate::warn!("[SYS] localStorage read_file failed: {}", e);
40        }
41    }
42}
43
44/// localStorage の変更を SylFS に書き出す(FS 未マウントなら skip)。
45pub(crate) fn ls_flush() {
46    if !crate::os_lib::platform::fs_is_mounted() {
47        return;
48    }
49    let data = ls_serialize(&LOCAL_STORAGE.lock());
50    // 【2026-08-25 バグ修正】ここは FS_LOCK を取らずに **書いて** いた。
51    //
52    // この関数は JS の setter 経路(ブラウザ本体スレッド)から呼ばれるが、
53    // 画像・フォントのワーカースレッドは同時に `FS_LOCK` を取って
54    // ディスクキャッシュを書いている。番人なしで割り込むと
55    // 空きセクタビットマップが二重確保され、**関係ないファイルが壊れる**。
56    //
57    // 削除と保存はひと続きの書き換えなので、両方を同じ番人の下で行う
58    // (途中で手放すと、消えたまま保存されない瞬間が他スレッドから見える)。
59    let _fs_guard = crate::os_lib::platform::fs_lock();
60    let fs = crate::os_lib::platform::fs_get();
61    // 【2026-07-28】ここで書き込み失敗を捨てると localStorage が**黙って
62    // 永続化されない**(次回起動で消えるのに、その場では成功して見える)。
63    // この関数は `()` を返す JS 側の setter 経路から呼ばれるため例外にはできないが、
64    // 失敗した事実は必ずログへ残す。
65    // 【2026-11-11】以前は「消してから保存」だったので、その間で電源が切れると localStorage が丸ごと消えた。
66    // SylFS の上書き保存は新しい版を書いてから 1 回で切り替えるので、消さずに上書きする。空のときだけ消す。
67    if data.is_empty() {
68        if let Err(e) = fs.delete_file(LS_FILENAME) {
69            // 未作成なら "file not found" は正常。
70            if !e.contains("not found") {
71                crate::warn!("[JS] localStorage: failed to remove empty store: {}", e);
72            }
73        }
74    } else if let Err(e) = fs.save_file(LS_FILENAME, &data, "system") {
75        crate::error!("[JS] localStorage: failed to persist ({} bytes): {}", data.len(), e);
76    }
77}
78
79/// `document.cookie` の getter: `"name=value; name2=value2"` 形式で結合する。
80pub fn cookie_string() -> String {
81    COOKIES.lock().cookie_string()
82}
83
84/// `document.cookie = "..."` または `Set-Cookie` の setter。
85pub fn cookie_set(s: &str) {
86    COOKIES.lock().apply_cookie(s);
87}
88
89/// `cookieStore.get(name)`(Cookie Store API。丸ごと未対応だった)。
90/// `document.cookie` と同じ `COOKIES` を参照する。見つからなければ仕様どおり
91/// `null`。
92pub(crate) fn cookie_store_get(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
93    let name = arg(a, 0).to_js_string();
94    let value = COOKIES.lock().get(&name).map(|c| c.value.clone());
95    let result = match value {
96        Some(v) => {
97            let o = Obj::plain();
98            o.borrow_mut().props.insert("name".into(), Value::str(&name));
99            o.borrow_mut().props.insert("value".into(), Value::str(v));
100            Value::Object(o)
101        }
102        None => Value::Null,
103    };
104    Ok(resolved_promise(it, result))
105}
106/// `cookieStore.getAll(name?)`(対応する複数形。`name` 省略時は全 Cookie)。
107pub(crate) fn cookie_store_get_all(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
108    let filter = if a.is_empty() { None } else { Some(arg(a, 0).to_js_string()) };
109    let items: Vec<Value> = COOKIES
110        .lock()
111        .all()
112        .filter(|c| filter.as_ref().is_none_or(|f| *f == c.name))
113        .map(|c| {
114            let o = Obj::plain();
115            o.borrow_mut().props.insert("name".into(), Value::str(&c.name));
116            o.borrow_mut().props.insert("value".into(), Value::str(&c.value));
117            Value::Object(o)
118        })
119        .collect();
120    Ok(resolved_promise(it, Value::Object(Obj::array(items))))
121}
122/// `cookieStore.set(name, value)`(`cookieStore.set({name, value})` 形式も
123/// 対応)。既存の `cookie_set` と同じ `COOKIES` へ書き込む。
124pub(crate) fn cookie_store_set(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
125    let first = arg(a, 0);
126    let (name, value) = if let Value::Object(_) = &first {
127        (
128            obj_prop(&first, "name").map(|v| v.to_js_string()).unwrap_or_default(),
129            obj_prop(&first, "value").map(|v| v.to_js_string()).unwrap_or_default(),
130        )
131    } else {
132        (first.to_js_string(), arg(a, 1).to_js_string())
133    };
134    if !name.is_empty() {
135        COOKIES.lock().insert(&name, &value);
136    }
137    Ok(resolved_promise(it, Value::Undefined))
138}
139/// `cookieStore.delete(name)`。
140pub(crate) fn cookie_store_delete(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
141    let name = arg(a, 0).to_js_string();
142    COOKIES.lock().delete(&name);
143    Ok(resolved_promise(it, Value::Undefined))
144}
145
146pub(crate) fn storage_map(tag: &str) -> &'static spin::Mutex<alloc::collections::BTreeMap<String, String>> {
147    if tag == "storage:session" {
148        &SESSION_STORAGE
149    } else {
150        &LOCAL_STORAGE
151    }
152}
153/// `HOST_STORAGE` の `id`(`localStorage` = 0・`sessionStorage` = 1)に対応するタグ。保存の表(`storage_map`)はこのタグで引く。
154pub(crate) fn storage_tag_for(id: usize) -> &'static str {
155    if id == STORAGE_SESSION {
156        "storage:session"
157    } else {
158        "storage:local"
159    }
160}
161/// `localStorage`/`sessionStorage`(`tag`)の実データ(キー, 値)の一覧。実データは `.props` ではなく別マップにあるため、
162/// `Object.keys(localStorage)`/`for...in localStorage` 用にここから返す(以前は常に空を返していた)。
163pub(crate) fn storage_entries(tag: &str) -> Vec<(String, String)> {
164    if tag != "storage:session" {
165        ls_ensure_loaded();
166    }
167    storage_map(tag).lock().iter().map(|(k, v)| (k.clone(), v.clone())).collect()
168}
169/// `element.dataset`(ノード `idx`)の `data-*` 属性を camelCase のキーへ変換した (キー, 値) の一覧。
170/// `Object.keys(el.dataset)`/`for...in el.dataset` が実データ(`data-*` 属性、
171/// `.props` ではなく DOM 要素側の属性ストアにある)を素通しして常に空を
172/// 返していたバグの修正用(`storage_entries`(localStorage/sessionStorage)で修正済みの同型バグ)。
173pub(crate) fn dataset_entries(dom: &super::super::dom_bridge::DomBridge, idx: usize) -> Vec<(String, String)> {
174    dom.attr_names(idx)
175        .into_iter()
176        .filter_map(|n| {
177            crate::os_lib::dom_dataset::data_attr_to_camel(&n).map(|camel| {
178                let val = dom.get_attr(idx, &n).unwrap_or_default();
179                (camel, val)
180            })
181        })
182        .collect()
183}
184/// `data-user-id` → `userId`(W3C HTML5 §3.2.6.2 準拠の変換)。
185pub(crate) fn data_attr_to_camel(name: &str) -> String {
186    let full = if name.starts_with("data-") {
187        name.to_string()
188    } else {
189        alloc::format!("data-{}", name)
190    };
191    crate::os_lib::dom_dataset::data_attr_to_camel(&full).unwrap_or_else(|| name.to_string())
192}
193pub(crate) fn this_storage_tag(this: &Value) -> Option<&'static str> {
194    if let Value::Object(o) = this {
195        if let ObjKind::HostRef(h) = &o.borrow().kind {
196            if h.class == HOST_STORAGE {
197                return Some(storage_tag_for(h.id));
198            }
199        }
200    }
201    None
202}
203pub(crate) fn storage_get_item(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
204    if let Some(tag) = this_storage_tag(&this) {
205        if tag != "storage:session" {
206            ls_ensure_loaded();
207        }
208        let k = arg(a, 0).to_js_string();
209        return Ok(match storage_map(tag).lock().get(&k) {
210            Some(v) => Value::str(v.clone()),
211            None => Value::Null,
212        });
213    }
214    Ok(Value::Null)
215}
216pub(crate) fn storage_set_item(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
217    if let Some(tag) = this_storage_tag(&this) {
218        if tag != "storage:session" {
219            ls_ensure_loaded();
220        }
221        storage_map(tag)
222            .lock()
223            .insert(arg(a, 0).to_js_string(), arg(a, 1).to_js_string());
224        if tag != "storage:session" {
225            ls_flush();
226        }
227    }
228    Ok(Value::Undefined)
229}
230pub(crate) fn storage_remove_item(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
231    if let Some(tag) = this_storage_tag(&this) {
232        if tag != "storage:session" {
233            ls_ensure_loaded();
234        }
235        storage_map(tag).lock().remove(&arg(a, 0).to_js_string());
236        if tag != "storage:session" {
237            ls_flush();
238        }
239    }
240    Ok(Value::Undefined)
241}
242pub(crate) fn storage_clear(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
243    if let Some(tag) = this_storage_tag(&this) {
244        storage_map(tag).lock().clear();
245        if tag != "storage:session" {
246            ls_flush();
247        }
248    }
249    Ok(Value::Undefined)
250}
251pub(crate) fn storage_key(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
252    if let Some(tag) = this_storage_tag(&this) {
253        if tag != "storage:session" {
254            ls_ensure_loaded();
255        }
256        let i = arg(a, 0).to_number() as usize;
257        return Ok(match storage_map(tag).lock().keys().nth(i) {
258            Some(k) => Value::str(k.clone()),
259            None => Value::Null,
260        });
261    }
262    Ok(Value::Null)
263}
264
265pub fn storage_method_fn(key: &str) -> Option<(&'static str, NativeFn)> {
266    match key {
267        "getItem" => Some(("getItem", storage_get_item)),
268        "setItem" => Some(("setItem", storage_set_item)),
269        "removeItem" => Some(("removeItem", storage_remove_item)),
270        "clear" => Some(("clear", storage_clear)),
271        "key" => Some(("key", storage_key)),
272        _ => None,
273    }
274}
275
276/// `storage:` host のプロパティ取得(メソッド / length / データキー)。
277pub fn storage_get_prop(tag: &str, key: &str) -> Value {
278    if tag != "storage:session" {
279        ls_ensure_loaded();
280    }
281    if let Some((n, f)) = storage_method_fn(key) {
282        return nv(n, f);
283    }
284    match key {
285        "length" => Value::Number(storage_map(tag).lock().len() as f64),
286        _ => match storage_map(tag).lock().get(key) {
287            Some(v) => Value::str(v.clone()),
288            None => Value::Undefined,
289        },
290    }
291}
292/// `storage:` host へのプロパティ代入(length 以外は setItem 相当)。
293/// `delete localStorage.foo`/`delete sessionStorage.foo`(プロパティ直接削除。`removeItem`
294/// と同義だが、こちらの経路は Host プロキシが `.props` を持たないため以前は黙って
295/// 何も起きなかった)。
296pub fn storage_remove_prop(tag: &str, key: &str) {
297    if tag != "storage:session" {
298        ls_ensure_loaded();
299    }
300    storage_map(tag).lock().remove(key);
301    if tag != "storage:session" {
302        ls_flush();
303    }
304}
305pub fn storage_set_prop(tag: &str, key: &str, val: &Value) {
306    if key != "length" {
307        if tag != "storage:session" {
308            ls_ensure_loaded();
309        }
310        storage_map(tag)
311            .lock()
312            .insert(String::from(key), val.to_js_string());
313        if tag != "storage:session" {
314            ls_flush();
315        }
316    }
317}
318
319// ===== URLSearchParams =====
320// 内部状態は正規化済みクエリ文字列 `_query`("k=v&k=v"、常にエンコード済みの形で保持)。
321// get/set 等の外部インターフェースでは form-urlencoded(+ = 空白, %XX)でデコード/エンコードする。
322pub(crate) fn parse_query(q: &str) -> Vec<(String, String)> {
323    let q = q.strip_prefix('?').unwrap_or(q);
324    q.split('&')
325        .filter(|s| !s.is_empty())
326        .map(|pair| match pair.split_once('=') {
327            Some((k, v)) => (percent_decode(k, true), percent_decode(v, true)),
328            None => (percent_decode(pair, true), String::new()),
329        })
330        .collect()
331}
332/// form-urlencoded(RFC1738 系)でエンコード。空白は `+`、それ以外の非英数字は `%XX`。
333pub(crate) fn form_url_encode(s: &str) -> String {
334    let mut out = String::new();
335    for b in s.as_bytes() {
336        match *b {
337            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
338                out.push(*b as char);
339            }
340            b' ' => out.push('+'),
341            _ => out.push_str(&alloc::format!("%{:02X}", b)),
342        }
343    }
344    out
345}
346pub(crate) fn build_query(pairs: &[(String, String)]) -> String {
347    let parts: Vec<String> = pairs
348        .iter()
349        .map(|(k, v)| format!("{}={}", form_url_encode(k), form_url_encode(v)))
350        .collect();
351    parts.join("&")
352}
353/// `URLSearchParams.prototype.size`(ES2023)の実体。`interp.rs` のプロパティ
354/// getter から呼ばれる(USP は専用 ObjKind を持たない plain object 実装のため、
355/// Map/Set の `size` のように直接カウントを持たず、その都度クエリ文字列をパース
356/// して数える)。
357pub fn usp_entry_count(this: &Value) -> usize {
358    parse_query(&usp_query(this)).len()
359}
360pub(crate) fn usp_size_getter(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
361    Ok(Value::Number(usp_entry_count(&this) as f64))
362}
363pub(crate) fn usp_query(this: &Value) -> String {
364    if let Value::Object(o) = this {
365        return o
366            .borrow()
367            .props
368            .get("_query")
369            .map(|v| v.to_js_string())
370            .unwrap_or_default();
371    }
372    String::new()
373}
374pub(crate) fn usp_set_query(this: &Value, q: &str) {
375    if let Value::Object(o) = this {
376        let parent = {
377            let mut b = o.borrow_mut();
378            b.props.insert(String::from("_query").into(), Value::str(q));
379            b.props.get("_parent_url").cloned()
380        };
381        if let Some(Value::Object(po)) = parent {
382            let search_val = if q.is_empty() {
383                String::new()
384            } else {
385                alloc::format!("?{}", q)
386            };
387            let href = po.borrow().props.get("_href").map(|v| v.to_js_string());
388            let mut b = po.borrow_mut();
389            // クエリが空になったら URL の query は null(href から `?` も消える)。
390            if let Some(mut u) = href.and_then(|h| super::url_parser::parse(&h, None)) {
391                u.query = if q.is_empty() { None } else { Some(String::from(q)) };
392                b.props.insert(String::from("_href").into(), Value::str(super::url_parser::serialize(&u, false)));
393            }
394            b.props.insert(String::from("search").into(), Value::str(search_val));
395        }
396    }
397}
398pub(crate) fn usp_get(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
399    let k = arg(a, 0).to_js_string();
400    let pairs = parse_query(&usp_query(&this));
401    Ok(pairs
402        .iter()
403        .find(|(pk, _)| *pk == k)
404        .map(|(_, v)| Value::str(v.clone()))
405        .unwrap_or(Value::Null))
406}
407pub(crate) fn usp_get_all(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
408    let k = arg(a, 0).to_js_string();
409    let items: Vec<Value> = parse_query(&usp_query(&this))
410        .into_iter()
411        .filter(|(pk, _)| *pk == k)
412        .map(|(_, v)| Value::str(v))
413        .collect();
414    Ok(Value::Object(Obj::array(items)))
415}
416/// `has(name, value)`(ES2023 で追加された第2引数 `value`。省略時は名前だけで判定する
417/// 従来どおりの挙動だが、指定時は名前と値の両方が一致するエントリの有無を返す。
418/// 以前は第2引数を完全に無視しており、`has('a', 'wrong-value')` が誤って `true` に
419/// なるバグだった)。
420pub(crate) fn usp_has(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
421    let k = arg(a, 0).to_js_string();
422    let entries = parse_query(&usp_query(&this));
423    let found = if matches!(arg(a, 1), Value::Undefined) {
424        entries.iter().any(|(pk, _)| *pk == k)
425    } else {
426        let v = arg(a, 1).to_js_string();
427        entries.iter().any(|(pk, pv)| *pk == k && *pv == v)
428    };
429    Ok(Value::Bool(found))
430}
431pub(crate) fn usp_append(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
432    let mut pairs = parse_query(&usp_query(&this));
433    pairs.push((arg(a, 0).to_js_string(), arg(a, 1).to_js_string()));
434    usp_set_query(&this, &build_query(&pairs));
435    Ok(Value::Undefined)
436}
437pub(crate) fn usp_set(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
438    let k = arg(a, 0).to_js_string();
439    let mut pairs: Vec<(String, String)> = parse_query(&usp_query(&this))
440        .into_iter()
441        .filter(|(pk, _)| *pk != k)
442        .collect();
443    pairs.push((k, arg(a, 1).to_js_string()));
444    usp_set_query(&this, &build_query(&pairs));
445    Ok(Value::Undefined)
446}
447/// `delete(name, value)`(ES2023 で追加された第2引数。`has` と同じく省略時は名前だけ
448/// で全削除、指定時は名前と値の両方が一致するエントリのみ削除する。以前は第2引数を
449/// 完全に無視しており、値を問わず同名のエントリを全て消してしまうバグだった)。
450pub(crate) fn usp_delete(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
451    let k = arg(a, 0).to_js_string();
452    let value_filter = if matches!(arg(a, 1), Value::Undefined) {
453        None
454    } else {
455        Some(arg(a, 1).to_js_string())
456    };
457    let pairs: Vec<(String, String)> = parse_query(&usp_query(&this))
458        .into_iter()
459        .filter(|(pk, pv)| match &value_filter {
460            Some(v) => !(*pk == k && pv == v),
461            None => *pk != k,
462        })
463        .collect();
464    usp_set_query(&this, &build_query(&pairs));
465    Ok(Value::Undefined)
466}
467pub(crate) fn usp_to_string(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
468    Ok(Value::str(usp_query(&this)))
469}
470/// `URLSearchParams.prototype.sort()`(ES2020)が丸ごと未対応だった。全エントリを
471/// キー名でソートする(仕様どおり安定ソート。同名キー同士の相対順序は保持する)。
472pub(crate) fn usp_sort(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
473    let mut pairs = parse_query(&usp_query(&this));
474    pairs.sort_by(|a, b| a.0.cmp(&b.0));
475    usp_set_query(&this, &build_query(&pairs));
476    Ok(Value::Undefined)
477}
478/// `URLSearchParams` の既定イテレーション(`entries()` と同義)。`make_iterator()` で
479/// 本物のイテレータ形状(`.next()`)にして返す。
480pub(crate) fn usp_iterator(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
481    let items: Vec<Value> = parse_query(&usp_query(&this))
482        .into_iter()
483        .map(|(k, v)| Value::Object(Obj::array(alloc::vec![Value::str(k), Value::str(v)])))
484        .collect();
485    Ok(Value::Object(make_iterator(items)))
486}
487// `new URLSearchParams(init)` の `init` がオブジェクトの場合、以前は
488// `Value::to_js_string()`(`it: &mut Interp` を持たないため JS 側の
489// カスタム `toString`/イテレータを呼べない、純粋な既定変換)に丸投げしており、
490// 素の `Obj::plain()` はどれも `"[object Object]"` に落ちるため、仕様上有効な
491// 3つの `init` 形式が軒並み壊れていた:`sequence<sequence<USVString>>`
492// (配列のペア列。`to_js_string` は要素をカンマ結合するだけで `=`/`&` に
493// ならない)・`record<USVString, USVString>`(プレーンオブジェクト)・
494// 既存の `URLSearchParams`/`FormData` インスタンス(実ブラウザでは USVString
495// 変換が `toString()` を呼ぶため動く)。
496pub(crate) fn url_search_params_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
497    let init = arg(a, 0);
498    let q = match &init {
499        Value::Undefined | Value::Null => String::new(),
500        Value::Object(o) => {
501            let is_array = matches!(&o.borrow().kind, ObjKind::Array(_));
502            if is_array {
503                let pairs: alloc::vec::Vec<(String, String)> = this_items(&init)
504                    .iter()
505                    .filter_map(|item| {
506                        let inner = this_items(item);
507                        if inner.len() >= 2 {
508                            Some((inner[0].to_js_string(), inner[1].to_js_string()))
509                        } else {
510                            None
511                        }
512                    })
513                    .collect();
514                build_query(&pairs)
515            } else if let Some(existing) = o.borrow().props.get("_query") {
516                // 既存の URLSearchParams/FormData インスタンス由来。
517                existing.to_js_string()
518            } else {
519                let pairs: alloc::vec::Vec<(String, String)> = o
520                    .borrow()
521                    .props
522                    .iter()
523                    .map(|(k, v)| (k.to_string(), v.to_js_string()))
524                    .collect();
525                build_query(&pairs)
526            }
527        }
528        other => other.to_js_string(),
529    };
530    let o = Obj::plain();
531    {
532        let mut b = o.borrow_mut();
533        b.props
534            .insert("_query".into(), Value::str(build_query(&parse_query(&q))));
535        // `.size`(ES2023)はアクセサゲッタとして登録する(ECMAScript 核に _is_usp を持たせない)。
536        b.props.insert("_is_usp".into(), Value::Bool(true));
537        b.insert_accessor(
538            String::from("size"),
539            crate::os_lib::ecma::value::Accessor {
540                get: Some(nv("get size", usp_size_getter)),
541                set: None,
542            },
543        );
544        // `.sort()`(ES2020)は USP 固有の仕様(`FormData` には無い)。
545        b.props.insert("sort".into(), nv("sort", usp_sort));
546        b.props.insert("get".into(), nv("get", usp_get));
547        b.props.insert("getAll".into(), nv("getAll", usp_get_all));
548        b.props.insert("has".into(), nv("has", usp_has));
549        b.props.insert("append".into(), nv("append", usp_append));
550        b.props.insert("set".into(), nv("set", usp_set));
551        b.props.insert("delete".into(), nv("delete", usp_delete));
552        // `entries`/`keys`/`values`/`forEach`(`FormData` は既にあったが、実は同じ
553        // `_query` 内部表現を使うため丸ごと欠落していた `URLSearchParams` 側にも
554        // そのまま流用できる)。
555        b.props.insert("entries".into(), nv("entries", fd_entries));
556        b.props.insert("keys".into(), nv("keys", fd_keys));
557        b.props.insert("values".into(), nv("values", fd_values));
558        b.props.insert("forEach".into(), nv("forEach", fd_for_each));
559        // `Symbol.iterator` が未登録で `for (const [k,v] of params)`(`entries()` と
560        // 同義の既定イテレーション)が丸ごと非対応だったバグ。`entries()` 自体は
561        // 単純な配列を返す簡略実装だが、`for...of` の汎用カスタムイテレータ駆動
562        // 経路は `.next()` を持つ本物のイテレータ形状を要求するため、`make_iterator()`
563        // で包んだ別実装を用意する。
564        b.props.insert(
565            "Symbol(Symbol.iterator)".into(),
566            nv("[Symbol.iterator]", usp_iterator),
567        );
568        b.props
569            .insert("toString".into(), nv("toString", usp_to_string));
570    }
571    Ok(Value::Object(o))
572}
573
574// ===== FormData =====
575// URLSearchParams と同じ `_query` 内部表現を流用しつつ、entries/keys/values/forEach と
576// form 要素からの初期収集に対応する。値は文字列のみ(File は未対応)。
577pub(crate) fn fd_entries(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
578    let items: Vec<Value> = parse_query(&usp_query(&this))
579        .into_iter()
580        .map(|(k, v)| Value::Object(Obj::array(alloc::vec![Value::str(k), Value::str(v)])))
581        .collect();
582    Ok(Value::Object(Obj::array(items)))
583}
584pub(crate) fn fd_keys(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
585    let items: Vec<Value> = parse_query(&usp_query(&this))
586        .into_iter()
587        .map(|(k, _)| Value::str(k))
588        .collect();
589    Ok(Value::Object(Obj::array(items)))
590}
591pub(crate) fn fd_values(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
592    let items: Vec<Value> = parse_query(&usp_query(&this))
593        .into_iter()
594        .map(|(_, v)| Value::str(v))
595        .collect();
596    Ok(Value::Object(Obj::array(items)))
597}
598pub(crate) fn fd_for_each(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
599    let cb = arg(a, 0);
600    if matches!(cb, Value::Object(_)) {
601        for (k, v) in parse_query(&usp_query(&this)) {
602            it.call_value(
603                &cb,
604                Value::Undefined,
605                &[Value::str(v), Value::str(k), this.clone()],
606            )?;
607        }
608    }
609    Ok(Value::Undefined)
610}
611
612/// <form> 要素配下の送信対象コントロールから (name, value) を収集する。
613/// - name 属性が無いコントロールは無視(HTML 仕様)。
614/// - checkbox/radio は checked のときのみ、value(無ければ "on")を採用。
615/// - select は selected option(無ければ最初の option)の value。
616/// - disabled は除外。
617pub(crate) fn collect_form_data(it: &Interp, form_idx: usize) -> Vec<(String, String)> {
618    let dom = it.dom().borrow();
619    let mut out: Vec<(String, String)> = Vec::new();
620    // ドキュメント全体をルート(node[0])からドキュメント順で走査し、その中から
621    // このフォームに実際に属する(`associated_form`が`form_idx`を指す)
622    // コントロールだけを拾う。以前は`form_idx`を起点にした子孫走査のみだった
623    // ため、`<form>`の外に置かれた`<input form="...">`(HTML5仕様の「form
624    // owner」。`element.form`/`checkValidity()`側は既に対応済み)が送信データ
625    // から漏れていた。`associated_form`は`form`属性優先・無ければ祖先探索という
626    // 正しい優先順位を既に実装しているため、それをそのまま判定に使う。
627    let mut stack: Vec<usize> = alloc::vec![0usize];
628    let mut order: Vec<usize> = Vec::new();
629    while let Some(i) = stack.pop() {
630        order.push(i);
631        if let Some(n) = dom.nodes.get(i) {
632            // 子はドキュメント順を保つため逆順 push。
633            for &c in n.children.iter().rev() {
634                stack.push(c);
635            }
636        }
637    }
638    for &i in order.iter() {
639        let n = match dom.nodes.get(i) {
640            Some(n) => n,
641            None => continue,
642        };
643        if n.is_text || i == form_idx {
644            continue;
645        }
646        let tag = n.tag.as_str();
647        if tag != "input" && tag != "select" && tag != "textarea" {
648            continue;
649        }
650        if dom.associated_form(i) != Some(form_idx) {
651            continue;
652        }
653        // `<fieldset disabled>`祖先による暗黙の無効化も含めて判定する
654        // (詳細は`is_disabled`のコメント参照。以前は要素自身の`disabled`
655        // 属性しか見ておらず、無効化されたフィールドの値が送信データに
656        // 混入していた)。
657        if dom.is_disabled(i) {
658            continue;
659        }
660        let name = dom.get_attr(i, "name").unwrap_or_default();
661        if name.is_empty() {
662            continue;
663        }
664        match tag {
665            "input" => {
666                let ty = dom.get_attr(i, "type").unwrap_or_default().to_lowercase();
667                match ty.as_str() {
668                    "submit" | "button" | "reset" | "image" | "file" => { /* 送信対象外 */ }
669                    "checkbox" | "radio" => {
670                        if dom.has_attr(i, "checked") {
671                            let v = dom
672                                .get_attr(i, "value")
673                                .filter(|s| !s.is_empty())
674                                .unwrap_or_else(|| String::from("on"));
675                            out.push((name, v));
676                        }
677                    }
678                    _ => {
679                        out.push((name, dom.get_attr(i, "value").unwrap_or_default()));
680                    }
681                }
682            }
683            "textarea" => {
684                let v = dom
685                    .get_attr(i, "value")
686                    .unwrap_or_else(|| n.initial_text.clone());
687                out.push((name, v));
688            }
689            "select" => {
690                // `<select multiple>`(仕様上は選択された option 1つにつき1エントリを
691                // 送信する)が丸ごと未対応で、常に単一値しか収集しないバグだった
692                // (複数選択リストボックスという定番 UI パターンで送信データが欠落する)。
693                // `<optgroup>`配下の`<option>`が丸ごと見えなくなっていたバグ
694                // (`select_options`側で2026-07-17に修正済み。以前はここで
695                // 直接の子だけを`n.children.iter()`で見ており、`<select
696                // multiple>`の複数選択送信・フォールバック単一選択のどちらも
697                // カテゴリ分けされた`<optgroup>`内のoptionを見落としていた)。
698                // 既に`<optgroup>`対応済みの`select_options`を再利用する。
699                if dom.has_attr(i, "multiple") {
700                    for c in dom.select_options(i) {
701                        if dom.has_attr(c, "selected") {
702                            let v = dom.get_attr(c, "value").unwrap_or_else(|| {
703                                dom.nodes.get(c).map(|cn| cn.initial_text.clone()).unwrap_or_default()
704                            });
705                            out.push((name.clone(), v));
706                        }
707                    }
708                }
709                // select 自身の value 属性(レンダラが選択値を反映)を優先。
710                else if let Some(v) = dom.get_attr(i, "value").filter(|s| !s.is_empty()) {
711                    out.push((name, v));
712                } else {
713                    // フォールバック: HTML属性`selected`が付いたoptionがあれば
714                    // それを、無ければ仕様どおり構造上最初のoption(HTML標準の
715                    // 「selected未指定なら最初のoptionが暗黙に選択される」規則)
716                    // を使う。以前は`selected`属性を一切見ず常に構造上最初の
717                    // optionを使っていたため、`<option selected>`をHTMLの
718                    // マークアップだけで(JS側の`.value=`代入を経由せず)
719                    // 指定した場合、`FormData`送信値が実際の選択と食い違う
720                    // バグだった(`.value`ゲッターは正しく`selected`を見て
721                    // いたのに、こちらのフォールバックだけ非対称だった。
722                    // `<optgroup>`監査中に自己テストで発見。2026-07-17
723                    // 発見・実装)。
724                    let opts = dom.select_options(i);
725                    let chosen = opts
726                        .iter()
727                        .find(|&&o| dom.has_attr(o, "selected"))
728                        .or_else(|| opts.first());
729                    if let Some(&oi) = chosen {
730                        let v = dom.get_attr(oi, "value").unwrap_or_else(|| {
731                            dom.nodes
732                                .get(oi)
733                                .map(|cn| cn.initial_text.clone())
734                                .unwrap_or_default()
735                        });
736                        out.push((name, v));
737                    }
738                }
739            }
740            _ => {}
741        }
742    }
743    out
744}
745
746pub(crate) fn form_data_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
747    // 引数が form 要素なら、その送信対象コントロールから初期化。
748    let pairs = match this_dom_idx(&arg(a, 0)) {
749        Some(form_idx) => collect_form_data(it, form_idx),
750        None => Vec::new(),
751    };
752    let o = Obj::plain();
753    {
754        let mut b = o.borrow_mut();
755        b.props
756            .insert("_query".into(), Value::str(build_query(&pairs)));
757        b.props.insert("get".into(), nv("get", usp_get));
758        b.props.insert("getAll".into(), nv("getAll", usp_get_all));
759        b.props.insert("has".into(), nv("has", usp_has));
760        b.props.insert("append".into(), nv("append", usp_append));
761        b.props.insert("set".into(), nv("set", usp_set));
762        b.props.insert("delete".into(), nv("delete", usp_delete));
763        b.props.insert("entries".into(), nv("entries", fd_entries));
764        b.props.insert("keys".into(), nv("keys", fd_keys));
765        b.props.insert("values".into(), nv("values", fd_values));
766        b.props.insert("forEach".into(), nv("forEach", fd_for_each));
767        // `URLSearchParams` と同じ理由で `Symbol.iterator` が未登録だった
768        // (`for (const [k,v] of formData)` が丸ごと非対応)。
769        b.props.insert(
770            "Symbol(Symbol.iterator)".into(),
771            nv("[Symbol.iterator]", usp_iterator),
772        );
773        b.props
774            .insert("toString".into(), nv("toString", usp_to_string));
775    }
776    Ok(Value::Object(o))
777}
778
779// ===== URL(WHATWG URL Standard。構文解析は url_parser.rs)=====
780use super::url_parser::{self, Url};
781
782/// `URL.canParse`/`URL.parse`/`new URL` の `url` 引数。`URL` インスタンスはその href を使う。
783fn url_arg_string(v: &Value) -> String {
784    if let Value::Object(o) = v {
785        if let Some(h) = o.borrow().props.get("_href") {
786            return h.to_js_string();
787        }
788    }
789    v.to_js_string()
790}
791fn url_parse_args(a: &[Value]) -> Option<Url> {
792    let raw = url_arg_string(&arg(a, 0));
793    let base = match arg(a, 1) {
794        Value::Undefined => None,
795        v => Some(url_arg_string(&v)),
796    };
797    url_parser::parse(&raw, base.as_deref())
798}
799/// `URL.canParse(url, base?)`。
800pub(crate) fn url_can_parse(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
801    Ok(Value::Bool(url_parse_args(a).is_some()))
802}
803/// `URL.parse(url, base?)`: 失敗時は例外でなく `null`。
804pub(crate) fn url_parse(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
805    match url_parse_args(a) {
806        Some(u) => url_build(it, &u),
807        None => Ok(Value::Null),
808    }
809}
810pub(crate) fn has_url_scheme(s: &str) -> bool {
811    if !s.contains(':') {
812        return false;
813    }
814    let mut chars = s.chars().take_while(|&c| c != ':');
815    match chars.next() {
816        Some(c) if c.is_ascii_alphabetic() => {}
817        _ => return false,
818    }
819    chars.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
820}
821pub(crate) fn url_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
822    if a.is_empty() {
823        return Err(it.type_error("Failed to construct 'URL': 1 argument required, but only 0 present."));
824    }
825    match url_parse_args(a) {
826        Some(u) => url_build(it, &u),
827        None => Err(it.type_error("Failed to construct 'URL': Invalid URL")),
828    }
829}
830
831/// 現在の URL 状態(`_href` を解析し、`searchParams` 経由で変わった `search` を反映する)。
832fn url_current(this: &Value) -> Option<Url> {
833    if let Value::Object(o) = this {
834        let href = o.borrow().props.get("_href").map(|v| v.to_js_string())?;
835        let u = url_parser::parse(&href, None)?;
836        return Some(u);
837    }
838    None
839}
840fn url_store(this: &Value, u: &Url) {
841    if let Value::Object(o) = this {
842        let host = u.host.clone().unwrap_or_default();
843        let hostport = match u.port {
844            Some(p) => alloc::format!("{}:{}", host, p),
845            None => host.clone(),
846        };
847        let mut b = o.borrow_mut();
848        let mut put = |k: &str, v: String| {
849            b.props.insert(String::from(k).into(), Value::str(v));
850        };
851        put("_href", url_parser::serialize(u, false));
852        put("protocol", alloc::format!("{}:", u.scheme));
853        put("username", u.username.clone());
854        put("password", u.password.clone());
855        put("host", hostport);
856        put("hostname", host);
857        put("port", u.port.map(|p| alloc::format!("{}", p)).unwrap_or_default());
858        put("pathname", url_parser::path_string(u));
859        put("search", match &u.query {
860            Some(q) if !q.is_empty() => alloc::format!("?{}", q),
861            _ => String::new(),
862        });
863        put("hash", match &u.fragment {
864            Some(f) if !f.is_empty() => alloc::format!("#{}", f),
865            _ => String::new(),
866        });
867        put("origin", url_parser::origin(u));
868    }
869}
870/// `search` が変わったとき、既存の `searchParams` の中身を新しいクエリへ差し替える(オブジェクトは保つ)。
871fn url_sync_search_params(it: &mut Interp, this: &Value, u: &Url) -> Result<(), Value> {
872    let fresh = url_search_params_ctor(it, Value::Undefined, &[Value::str(u.query.clone().unwrap_or_default())])?;
873    let q = usp_query(&fresh);
874    if let Value::Object(o) = this {
875        let sp = o.borrow().props.get("searchParams").cloned();
876        if let Some(Value::Object(spo)) = sp {
877            spo.borrow_mut().props.insert(String::from("_query").into(), Value::str(q));
878        }
879    }
880    Ok(())
881}
882fn url_set_named(it: &mut Interp, this: &Value, name: &str, v: &str) -> Result<Value, Value> {
883    if let Some(mut u) = url_current(this) {
884        url_parser::apply_setter(&mut u, name, v);
885        url_store(this, &u);
886        if name == "search" {
887            url_sync_search_params(it, this, &u)?;
888        }
889    }
890    Ok(Value::Undefined)
891}
892macro_rules! url_accessors {
893    ($(($get:ident, $set:ident, $name:expr)),*) => {$(
894        pub(crate) fn $get(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
895            Ok(url_prop_or_empty(&this, $name))
896        }
897        pub(crate) fn $set(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
898            url_set_named(it, &this, $name, &arg(a, 0).to_js_string())
899        }
900    )*};
901}
902url_accessors!(
903    (url_get_protocol, url_set_protocol, "protocol"),
904    (url_get_username, url_set_username, "username"),
905    (url_get_password, url_set_password, "password"),
906    (url_get_host, url_set_host, "host"),
907    (url_get_hostname, url_set_hostname, "hostname"),
908    (url_get_port, url_set_port, "port"),
909    (url_get_pathname, url_set_pathname, "pathname"),
910    (url_get_search, url_set_search, "search"),
911    (url_get_hash, url_set_hash, "hash")
912);
913pub(crate) fn url_get_origin(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
914    Ok(url_prop_or_empty(&this, "origin"))
915}
916fn url_prop_or_empty(this: &Value, key: &str) -> Value {
917    if let Value::Object(o) = this {
918        if let Some(v) = o.borrow().props.get(key) {
919            return v.clone();
920        }
921    }
922    Value::str("")
923}
924/// `url.href = v`: 解析に失敗したら TypeError。
925pub(crate) fn url_set_href(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
926    match url_parser::parse(&arg(a, 0).to_js_string(), None) {
927        Some(u) => {
928            url_store(&this, &u);
929            url_sync_search_params(it, &this, &u)?;
930            Ok(Value::Undefined)
931        }
932        None => Err(it.type_error("Invalid URL")),
933    }
934}
935/// `URL.prototype.toString()` / `href` / `toJSON()`。
936pub(crate) fn url_to_string(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
937    Ok(Value::str(match url_current(&this) {
938        Some(u) => url_parser::serialize(&u, false),
939        None => String::new(),
940    }))
941}
942fn url_build(it: &mut Interp, u: &Url) -> Result<Value, Value> {
943    let sp = url_search_params_ctor(it, Value::Undefined, &[Value::str(u.query.clone().unwrap_or_default())])?;
944    let o = Obj::plain();
945    if let Value::Object(sp_obj) = &sp {
946        sp_obj.borrow_mut().props.insert(String::from("_parent_url").into(), Value::Object(o.clone()));
947    }
948    {
949        let mut b = o.borrow_mut();
950        b.props.insert("searchParams".into(), sp);
951        b.props.insert("toString".into(), nv("toString", url_to_string));
952        b.props.insert("toJSON".into(), nv("toJSON", url_to_string));
953        let acc = |g: Value, s: Option<Value>| crate::os_lib::ecma::value::Accessor { get: Some(g), set: s };
954        b.insert_accessor(String::from("href"), acc(nv("href", url_to_string), Some(nv("href", url_set_href))));
955        b.insert_accessor(String::from("origin"), acc(nv("origin", url_get_origin), None));
956        for (key, g, s) in [
957            ("protocol", url_get_protocol as NativeFn, url_set_protocol as NativeFn),
958            ("username", url_get_username, url_set_username),
959            ("password", url_get_password, url_set_password),
960            ("host", url_get_host, url_set_host),
961            ("hostname", url_get_hostname, url_set_hostname),
962            ("port", url_get_port, url_set_port),
963            ("pathname", url_get_pathname, url_set_pathname),
964            ("search", url_get_search, url_set_search),
965            ("hash", url_get_hash, url_set_hash),
966        ] {
967            b.insert_accessor(String::from(key), acc(nv(key, g), Some(nv(key, s))));
968        }
969    }
970    let v = Value::Object(o);
971    url_store(&v, u);
972    Ok(v)
973}
974
975// ===== URLPattern API (HTML Standard) =====
976/// `new URLPattern(pattern, baseURL?)` または `new URLPattern({ pathname, hostname, ... })`
977pub(crate) fn url_pattern_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
978    let arg0 = arg(a, 0);
979    let mut pattern_pathname = String::from("*");
980    let mut pattern_hostname = String::from("*");
981    let mut pattern_protocol = String::from("*");
982
983    match &arg0 {
984        Value::Object(o) => {
985            let b = o.borrow();
986            if let Some(p) = b.props.get("pathname") {
987                pattern_pathname = p.to_js_string();
988            }
989            if let Some(h) = b.props.get("hostname") {
990                pattern_hostname = h.to_js_string();
991            }
992            if let Some(pr) = b.props.get("protocol") {
993                pattern_protocol = pr.to_js_string();
994            }
995        }
996        _ => {
997            let pat_str = arg0.to_js_string();
998            if !pat_str.is_empty() {
999                if pat_str.contains("://") {
1000                    let href = pat_str;
1001                    if let Some((proto, rest)) = href.split_once("://") {
1002                        pattern_protocol = proto.to_string();
1003                        match rest.split_once('/') {
1004                            Some((host, path)) => {
1005                                pattern_hostname = host.to_string();
1006                                pattern_pathname = alloc::format!("/{}", path);
1007                            }
1008                            None => {
1009                                pattern_hostname = rest.to_string();
1010                                pattern_pathname = String::from("/");
1011                            }
1012                        }
1013                    }
1014                } else {
1015                    pattern_pathname = pat_str;
1016                }
1017            }
1018        }
1019    }
1020
1021    let o = Obj::plain();
1022    {
1023        let mut b = o.borrow_mut();
1024        b.props.insert("pathname".into(), Value::str(pattern_pathname));
1025        b.props.insert("hostname".into(), Value::str(pattern_hostname));
1026        b.props.insert("protocol".into(), Value::str(pattern_protocol));
1027        b.props.insert("test".into(), nv("test", url_pattern_test));
1028        b.props.insert("exec".into(), nv("exec", url_pattern_exec));
1029    }
1030    Ok(Value::Object(o))
1031}
1032
1033/// パスパターン(`/users/:id`のような`:name`名前付きセグメントを含む)を
1034/// ターゲットパスとスラッシュ区切りのセグメント単位で照合する。
1035/// 以前は`match_pattern_part`がパターン全体を1個の文字列として扱い、
1036/// `pattern.starts_with(':')`(パターン全体の先頭が`:`の場合のみ)しか
1037/// 見ていなかったため、`/users/:id`のように名前付きセグメントが途中に
1038/// ある一般的なパターンが常にマッチ失敗し、かつ`groups`(`URLPattern`の
1039/// 名前付きキャプチャ結果、`res.pathname.groups.id`等でアクセスされる)
1040/// も一切生成されないバグだった。一致した場合は`(名前, 値)`のキャプチャ
1041/// 一覧を返す。
1042fn match_pathname_pattern(pattern: &str, target: &str) -> Option<Vec<(String, String)>> {
1043    if pattern == "*" || pattern.is_empty() {
1044        return Some(Vec::new());
1045    }
1046    if pattern == target {
1047        return Some(Vec::new());
1048    }
1049    if pattern.contains('*') && !pattern.contains(':') {
1050        let parts: Vec<&str> = pattern.split('*').collect();
1051        if parts.len() == 2 && target.starts_with(parts[0]) && target.ends_with(parts[1]) {
1052            return Some(Vec::new());
1053        }
1054        return None;
1055    }
1056    let pat_segs: Vec<&str> = pattern.split('/').collect();
1057    let tgt_segs: Vec<&str> = target.split('/').collect();
1058    if pat_segs.len() != tgt_segs.len() {
1059        return None;
1060    }
1061    let mut groups = Vec::new();
1062    for (p, t) in pat_segs.iter().zip(tgt_segs.iter()) {
1063        if let Some(name) = p.strip_prefix(':') {
1064            groups.push((name.to_string(), t.to_string()));
1065        } else if *p == "*" {
1066            // ワイルドカードセグメント: 何にでもマッチ
1067        } else if p != t {
1068            return None;
1069        }
1070    }
1071    Some(groups)
1072}
1073
1074fn match_pattern_part(pattern: &str, target: &str) -> bool {
1075    if pattern == "*" || pattern.is_empty() {
1076        return true;
1077    }
1078    if pattern == target {
1079        return true;
1080    }
1081    if pattern.starts_with(':') || pattern == "*" {
1082        return true;
1083    }
1084    if pattern.contains('*') {
1085        let parts: Vec<&str> = pattern.split('*').collect();
1086        if parts.len() == 2 {
1087            return target.starts_with(parts[0]) && target.ends_with(parts[1]);
1088        }
1089    }
1090    false
1091}
1092
1093pub(crate) fn url_pattern_test(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1094    let res = url_pattern_exec(it, this, a)?;
1095    Ok(Value::Bool(!matches!(res, Value::Null)))
1096}
1097
1098pub(crate) fn url_pattern_exec(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1099    let input = arg(a, 0);
1100    let (pat_pathname, pat_hostname, pat_protocol) = match &this {
1101        Value::Object(o) => {
1102            let b = o.borrow();
1103            (
1104                b.props.get("pathname").map(|v| v.to_js_string()).unwrap_or_else(|| "*".into()),
1105                b.props.get("hostname").map(|v| v.to_js_string()).unwrap_or_else(|| "*".into()),
1106                b.props.get("protocol").map(|v| v.to_js_string()).unwrap_or_else(|| "*".into()),
1107            )
1108        }
1109        _ => return Ok(Value::Null),
1110    };
1111
1112    let mut target_pathname = String::new();
1113    let mut target_hostname = String::new();
1114    let mut target_protocol = String::new();
1115
1116    match &input {
1117        Value::Object(o) => {
1118            let b = o.borrow();
1119            target_pathname = b.props.get("pathname").map(|v| v.to_js_string()).unwrap_or_default();
1120            target_hostname = b.props.get("hostname").map(|v| v.to_js_string()).unwrap_or_default();
1121            target_protocol = b.props.get("protocol").map(|v| v.to_js_string()).unwrap_or_default();
1122        }
1123        _ => {
1124            let url_str = input.to_js_string();
1125            if url_str.contains("://") {
1126                if let Some((proto, rest)) = url_str.split_once("://") {
1127                    target_protocol = proto.to_string();
1128                    match rest.split_once('/') {
1129                        Some((host, path)) => {
1130                            target_hostname = host.to_string();
1131                            target_pathname = alloc::format!("/{}", path);
1132                        }
1133                        None => {
1134                            target_hostname = rest.to_string();
1135                            target_pathname = String::from("/");
1136                        }
1137                    }
1138                }
1139            } else {
1140                target_pathname = url_str;
1141            }
1142        }
1143    }
1144
1145    let path_match = match_pathname_pattern(&pat_pathname, &target_pathname);
1146    let match_host = match_pattern_part(&pat_hostname, &target_hostname);
1147    let match_proto = match_pattern_part(&pat_protocol, &target_protocol);
1148
1149    if let (Some(groups), true, true) = (path_match, match_host, match_proto) {
1150        let result_obj = Obj::plain();
1151        {
1152            let mut b = result_obj.borrow_mut();
1153            let pathname_obj = Obj::plain();
1154            {
1155                let mut pb = pathname_obj.borrow_mut();
1156                pb.props.insert("input".into(), Value::str(target_pathname));
1157                let groups_obj = Obj::plain();
1158                {
1159                    let mut gb = groups_obj.borrow_mut();
1160                    for (name, value) in &groups {
1161                        gb.props.insert(name.clone().into(), Value::str(value.clone()));
1162                    }
1163                }
1164                pb.props.insert("groups".into(), Value::Object(groups_obj));
1165            }
1166            b.props.insert("pathname".into(), Value::Object(pathname_obj));
1167        }
1168        Ok(Value::Object(result_obj))
1169    } else {
1170        Ok(Value::Null)
1171    }
1172}
1173