Skip to main content

atmos/os_lib/web_apis/builtins/
fetch_body.rs

1// 分離: builtins/promise.rs より Web API(Response/navigator/location/history)を分離(2026-11-19 手順 8)。
2use super::*;
3
4/// `navigator.userAgentData.getHighEntropyValues(hints)`(丸ごと未対応
5/// だった。低エントロピー値(`brands`/`mobile`/`platform`)は常に含み、
6/// 要求されたヒントに応じて残りの固定値を追加で返す誠実な簡略実装。
7/// 実データを収集する仕組みが無いため全て固定値だが、既存の
8/// `navigator.userAgent`/`.platform`と整合する値を返す)。
9pub(crate) fn navigator_get_high_entropy_values(
10    it: &mut Interp,
11    this: Value,
12    a: &[Value],
13) -> Result<Value, Value> {
14    let hints: alloc::vec::Vec<String> = this_items(&arg(a, 0)).iter().map(|v| v.to_js_string()).collect();
15    let result = Obj::plain();
16    {
17        let mut r = result.borrow_mut();
18        if let Value::Object(ua) = &this {
19            for key in ["brands", "mobile", "platform"] {
20                if let Some(v) = ua.borrow().props.get(key).cloned() {
21                    r.props.insert(key.into(), v);
22                }
23            }
24        }
25        for hint in &hints {
26            match hint.as_str() {
27                "architecture" => {
28                    r.props.insert("architecture".into(), Value::str("arm"));
29                }
30                "bitness" => {
31                    r.props.insert("bitness".into(), Value::str("64"));
32                }
33                "model" => {
34                    r.props.insert("model".into(), Value::str(""));
35                }
36                "platformVersion" => {
37                    r.props.insert("platformVersion".into(), Value::str("1.0"));
38                }
39                "uaFullVersion" | "fullVersionList" => {
40                    if let Value::Object(ua) = &this {
41                        if let Some(v) = ua.borrow().props.get("brands").cloned() {
42                            r.props.insert(hint.clone().into(), v);
43                        }
44                    }
45                }
46                _ => {}
47            }
48        }
49    }
50    Ok(resolved_promise(it, Value::Object(result)))
51}
52/// `navigator.storage.estimate()`(StorageManager API。丸ごと未対応
53/// だった)。実際のディスク使用量計測機構が無いため`usage: 0`(誠実な
54/// 未計測値)、`quota`は固定の代表値(1GB)を返す簡略実装。
55pub(crate) fn navigator_storage_estimate(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
56    let result = Obj::plain();
57    {
58        let mut r = result.borrow_mut();
59        r.props.insert("usage".into(), Value::Number(0.0));
60        r.props.insert("quota".into(), Value::Number(1024.0 * 1024.0 * 1024.0));
61    }
62    Ok(resolved_promise(it, Value::Object(result)))
63}
64/// `navigator.storage.persist()`/`.persisted()`(丸ごと未対応だった)。
65/// この処理系はSylFSへの書き込みが常に永続化されるため、両方とも常に
66/// `true`を返す誠実な簡略実装。
67pub(crate) fn navigator_storage_persist(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
68    Ok(resolved_promise(it, Value::Bool(true)))
69}
70
71
72/// URL を (is_https, host, path) に分解。スキーム無しは弾く(絶対のみ)。
73/// `string_slice` lint を避けるため添字スライスは使わず split_once/strip_prefix で処理。
74pub(crate) fn split_http_url(url: &str) -> Option<(bool, String, String)> {
75    let (is_https, rest) = if let Some(r) = url.strip_prefix("https://") {
76        (true, r)
77    } else if let Some(r) = url.strip_prefix("http://") {
78        (false, r)
79    } else {
80        return None;
81    };
82    let (host, path) = match rest.split_once('/') {
83        Some((h, p)) => (h.to_string(), format!("/{}", p)),
84        None => (rest.to_string(), String::from("/")),
85    };
86    if host.is_empty() {
87        return None;
88    }
89    Some((is_https, host, path))
90}
91
92/// `data:[<mime>][;base64],<data>` の本文部分(カンマ以降)を取り出す。base64 は未対応。
93pub(crate) fn data_url_body(url: &str) -> Option<String> {
94    let rest = url.strip_prefix("data:")?;
95    let (meta, body) = rest.split_once(',')?;
96    // `;base64` は復号、それ以外は %xx を戻す(RFC 2397)。
97    // 【2026-10-20】YouTube の改ざん検査(ha3)は base64 の JSON を data: URL で fetch して json() する。
98    let bytes = if meta.to_ascii_lowercase().ends_with(";base64") {
99        super::base64_to_bytes(body)
100    } else {
101        let b = body.as_bytes();
102        let mut out = Vec::with_capacity(b.len());
103        let mut i = 0;
104        while i < b.len() {
105            if b[i] == b'%' && i + 2 < b.len() {
106                let h = core::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok());
107                if let Some(v) = h {
108                    out.push(v);
109                    i += 3;
110                    continue;
111                }
112            }
113            out.push(b[i]);
114            i += 1;
115        }
116        out
117    };
118    Some(String::from_utf8_lossy(&bytes).into_owned())
119}
120
121/// Response オブジェクトを生成(status/ok/_body と text()/json() メソッドを持つ)。
122/// `Response.prototype.statusText`(丸ごと未対応で常に `undefined` だった。`if
123/// (!response.ok) console.log(response.status, response.statusText)` のような
124/// エラーログの定番パターンでよく参照される)。標準的な HTTP ステータス文言の
125/// 主要なもののみのテーブルで近似する(`Reason-Phrase` はサーバ実装依存で仕様上も
126/// クライアント側で正確に再現できるものではない)。
127pub(crate) fn http_status_text(status: u16) -> &'static str {
128    match status {
129        200 => "OK",
130        201 => "Created",
131        202 => "Accepted",
132        204 => "No Content",
133        301 => "Moved Permanently",
134        302 => "Found",
135        304 => "Not Modified",
136        400 => "Bad Request",
137        401 => "Unauthorized",
138        403 => "Forbidden",
139        404 => "Not Found",
140        405 => "Method Not Allowed",
141        408 => "Request Timeout",
142        409 => "Conflict",
143        410 => "Gone",
144        429 => "Too Many Requests",
145        500 => "Internal Server Error",
146        501 => "Not Implemented",
147        502 => "Bad Gateway",
148        503 => "Service Unavailable",
149        504 => "Gateway Timeout",
150        _ => "",
151    }
152}
153pub(crate) fn make_response(status: u16, body: String) -> Value {
154    make_response_with_url(status, body, String::new())
155}
156/// `init.status`(`{status, headers}` 形の `ResponseInit`)を読む共通ヘルパ。
157pub(crate) fn response_init_status(init: &Value, default: u16) -> u16 {
158    match init {
159        Value::Object(o) => o
160            .borrow()
161            .props
162            .get("status")
163            .map(|v| v.to_number() as u16)
164            .unwrap_or(default),
165        _ => default,
166    }
167}
168/// `new Response(body, init)`(Fetch API)。
169pub(crate) fn response_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
170    // 本文が ReadableStream なら、読む時にその中身を使う(`response_stream`)。
171    let stream = match arg(a, 0) {
172        Value::Object(o) if o.borrow().props.contains_key("_chunks") && o.borrow().props.contains_key("getReader") => Some(o),
173        _ => None,
174    };
175    let body = match arg(a, 0) {
176        Value::Undefined => String::new(),
177        _ if stream.is_some() => String::new(),
178        v => v.to_js_string(),
179    };
180    let init = arg(a, 1);
181    let status = response_init_status(&init, 200);
182    let headers_init = match &init {
183        Value::Object(o) => o.borrow().props.get("headers").cloned().unwrap_or(Value::Undefined),
184        _ => Value::Undefined,
185    };
186    let resp = make_response(status, body);
187    if let Value::Object(r) = &resp {
188        let mut r = r.borrow_mut();
189        r.props.insert("headers".into(), make_headers(headers_init));
190        if let Some(s) = stream {
191            r.props.insert("body".into(), Value::Object(s.clone()));
192            r.props.insert("_body_stream".into(), Value::Object(s));
193        }
194    }
195    Ok(resp)
196}
197
198/// `new Response(readableStream)` で作った応答の本文のストリーム。
199fn response_stream(this: &Value) -> Option<crate::os_lib::ecma::value::ObjRef> {
200    match this {
201        Value::Object(o) => match o.borrow().props.get("_body_stream") {
202            Some(Value::Object(s)) => Some(s.clone()),
203            _ => None,
204        },
205        _ => None,
206    }
207}
208/// `Response.json(data, init)`(ES2022 static factory。`JSON.stringify` +
209/// `content-type: application/json` ヘッダ付与を1回で行う)。
210pub(crate) fn response_json_static(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
211    let body = json_stringify(it, Value::Undefined, &[arg(a, 0)])?.to_js_string();
212    let status = response_init_status(&arg(a, 1), 200);
213    let resp = make_response(status, body);
214    if let Value::Object(r) = &resp {
215        let headers = make_headers(Value::Undefined);
216        if let Value::Object(h) = &headers {
217            h.borrow_mut()
218                .props
219                .insert("content-type".into(), Value::str("application/json"));
220        }
221        r.borrow_mut().props.insert("headers".into(), headers);
222    }
223    Ok(resp)
224}
225/// `Response.error()`(ネットワークエラーを表す、`ok:false`/`type:"error"` の
226/// 特殊な不透明 Response)。
227pub(crate) fn response_error_static(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
228    let resp = make_response(0, String::new());
229    if let Value::Object(r) = &resp {
230        let mut b = r.borrow_mut();
231        b.props.insert("type".into(), Value::str("error"));
232        b.props.insert("ok".into(), Value::Bool(false));
233    }
234    Ok(resp)
235}
236/// `Response.redirect(url, status?)`(既定 302。`Location` ヘッダ付きの
237/// リダイレクト応答を表す Response を返す)。
238pub(crate) fn response_redirect_static(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
239    let url = arg(a, 0).to_js_string();
240    let status = match arg(a, 1) {
241        Value::Undefined => 302,
242        v => v.to_number() as u16,
243    };
244    let resp = make_response(status, String::new());
245    if let Value::Object(r) = &resp {
246        let headers = make_headers(Value::Undefined);
247        if let Value::Object(h) = &headers {
248            h.borrow_mut().props.insert("location".into(), Value::str(url));
249        }
250        r.borrow_mut().props.insert("headers".into(), headers);
251    }
252    Ok(resp)
253}
254
255/// `Response.prototype.url`(`fetch()` が実際に取得した絶対 URL。相対 URL 指定時
256/// でも解決済みの絶対形が返る、リダイレクト後の最終 URL 確認等で使われる定番
257/// プロパティ)が丸ごと未対応で常に `undefined` だった。`make_response` の呼び出し元
258/// が URL を知っている場合はこちらを使う。
259pub(crate) fn make_response_with_url(status: u16, body: String, url: String) -> Value {
260    let resp = Obj::plain();
261    {
262        let mut r = resp.borrow_mut();
263        r.props
264            .insert("status".into(), Value::Number(status as f64));
265        r.props
266            .insert("ok".into(), Value::Bool((200..300).contains(&status)));
267        r.props
268            .insert("statusText".into(), Value::str(http_status_text(status)));
269        r.props.insert("url".into(), Value::str(url));
270        // `response.type`/`.redirected` が丸ごと未対応で常に `undefined` だった。
271        // この処理系に CORS モデルは無くリダイレクトも透過的に処理される(追跡は
272        // していない)ため、常に妥当な既定値(`"basic"`/`false`)を返す簡略実装。
273        r.props.insert("type".into(), Value::str("basic"));
274        r.props.insert("redirected".into(), Value::Bool(false));
275        // `response.headers`(`Headers` 未対応だった当時は丸ごと欠落していた)。
276        // この処理系の HTTP クライアントは応答ヘッダを捕捉していないため常に空だが、
277        // `get`/`has` 等のメソッドを持つ本物の `Headers` 形(`undefined` ではない)
278        // を返す点に意味がある。
279        r.props.insert("headers".into(), make_headers(Value::Undefined));
280        r.props.insert("body".into(), make_readable_stream_from_string(&body));
281        r.props.insert("_body".into(), Value::str(body));
282        r.props.insert("text".into(), nv("text", response_text));
283        r.props.insert("json".into(), nv("json", response_json));
284        // `Response.prototype.blob()`(Fetch API。`fetch(...).then(r => r.blob())` という
285        // 定番パターンが `blob is not defined` になっていた)が丸ごと未対応だった。
286        r.props.insert("blob".into(), nv("blob", response_blob));
287        // `Response.prototype.arrayBuffer()` も `blob()` と同種の欠落だった
288        // (バイナリレスポンスを扱う `fetch(...).then(r => r.arrayBuffer())` パターン)。
289        r.props
290            .insert("arrayBuffer".into(), nv("arrayBuffer", response_array_buffer));
291        // `Response.prototype.clone()`(`response.clone().json()` のように本文を
292        // 2回読みたい場合に使う定番パターン)が丸ごと未対応で、`clone is not a
293        // function` になっていた。
294        r.props.insert("clone".into(), nv("clone", response_clone));
295    }
296    Value::Object(resp)
297}
298
299/// `Response.prototype.clone()`。同じ `status`/本文を持つ新しい `Response`
300/// オブジェクトを返す(この処理系は本文を消費済みにする `bodyUsed` 追跡が無く
301/// `.text()`/`.json()` 等を複数回呼べる簡略実装のため、`clone()` は主に
302/// 「呼び出し自体が壊れない」ことを保証する意味合いが強い)。
303pub(crate) fn response_clone(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
304    if let Value::Object(o) = &this {
305        let (status, body, url) = {
306            let b = o.borrow();
307            (
308                b.props.get("status").map(|v| v.to_number() as u16).unwrap_or(200),
309                b.props.get("_body").map(|v| v.to_js_string()).unwrap_or_default(),
310                b.props.get("url").map(|v| v.to_js_string()).unwrap_or_default(),
311            )
312        };
313        let clone = make_response_with_url(status, body, url);
314        // 本文のストリームとヘッダ等も複製する。【2026-11-01】文字列の本文だけを写していたため
315        // `clone().body` のチャンクが Uint8Array でなく、先頭のバイトを見てストリームとして読む
316        // YouTube の `get_watch` が失敗し、オフラインの画面になっていた。
317        let bytes: Vec<u8> = response_body_bytes(&this).iter().map(|&b| b as u8).collect();
318        let stream = super::streams::make_readable_stream_from_bytes(it, &bytes);
319        if let Value::Object(c) = &clone {
320            let src = o.borrow();
321            let mut dst = c.borrow_mut();
322            for key in ["statusText", "ok", "type", "redirected", "headers", "_body_latin1"] {
323                if let Some(v) = src.props.get(key) {
324                    dst.props.insert(key.into(), v.clone());
325                }
326            }
327            dst.props.insert("body".into(), stream);
328        }
329        return Ok(clone);
330    }
331    Ok(this)
332}
333
334/// this._body を取り出す共通処理。
335pub(crate) fn response_body_string(this: &Value) -> String {
336    if let Value::Object(o) = this {
337        if let Some(v) = o.borrow().props.get("_body") {
338            return v.to_js_string();
339        }
340    }
341    String::new()
342}
343
344/// Response.text(): 本文文字列で解決する Promise。
345pub(crate) fn response_text(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
346    if let Some(st) = response_stream(&this) {
347        return Ok(super::streams::read_stream_body(it, &st, "text"));
348    }
349    let body = response_body_string(&this);
350    Ok(resolved_promise(it, Value::str(body)))
351}
352
353/// Response.json(): 本文を JSON.parse して解決する Promise。
354pub(crate) fn response_json(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
355    if let Some(st) = response_stream(&this) {
356        return Ok(super::streams::read_stream_body(it, &st, "json"));
357    }
358    let body = response_body_string(&this);
359    let parsed = json_parse(it, Value::Undefined, &[Value::str(body)])?;
360    Ok(resolved_promise(it, parsed))
361}
362
363/// 応答の生バイト列が UTF-8 文字列(`_body`)と違う(バイナリ)ときだけ、`_body_latin1` に
364/// 1 バイト = 1 文字(U+0000〜U+00FF)で保持する。`arrayBuffer()`/`blob()` はこちらを使う。
365/// 【2026-10-17】従来は本文を常に UTF-8 文字列として持ち、動画セグメント等のバイナリが
366/// 置換文字に化けて壊れていた。
367pub(crate) fn attach_raw_body(resp: &Value, bytes: &[u8]) {
368    let Value::Object(o) = resp else { return };
369    let same = o.borrow().props.get("_body").is_some_and(|v| v.to_js_string().as_bytes() == bytes);
370    if !same {
371        let latin1: String = bytes.iter().map(|&b| b as char).collect();
372        o.borrow_mut().props.insert("_body_latin1".into(), Value::str(latin1));
373    }
374}
375
376/// 応答本文のバイト列(バイナリなら生バイト列、テキストなら UTF-8)。
377fn response_body_bytes(this: &Value) -> alloc::vec::Vec<f64> {
378    if let Value::Object(o) = this {
379        if let Some(v) = o.borrow().props.get("_body_latin1") {
380            return v.to_js_string().chars().map(|c| (c as u32 & 0xff) as f64).collect();
381        }
382    }
383    response_body_string(this).as_bytes().iter().map(|b| *b as f64).collect()
384}
385
386/// Response.blob(): 本文のバイト列の `Blob` で解決する Promise。
387pub(crate) fn response_blob(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
388    if let Some(st) = response_stream(&this) {
389        return Ok(super::streams::read_stream_body(it, &st, "blob"));
390    }
391    let bytes = response_body_bytes(&this);
392    let blob = make_blob(bytes, String::new());
393    Ok(resolved_promise(it, blob))
394}
395
396/// Response.arrayBuffer(): 本文を UTF-8 バイト列化した実バイト列付き `ArrayBuffer`
397/// (`make_arraybuffer_with_bytes()`)で解決する Promise。
398pub(crate) fn response_array_buffer(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
399    if let Some(st) = response_stream(&this) {
400        return Ok(super::streams::read_stream_body(it, &st, "arrayBuffer"));
401    }
402    let bytes = response_body_bytes(&this);
403    let buf = make_arraybuffer_with_bytes(bytes);
404    Ok(resolved_promise(it, buf))
405}
406
407/// location.toString(): href を返す(`String(location)` / 文字列連結用)。
408pub(crate) fn location_to_string(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
409    if let Value::Object(o) = &this {
410        if let Some(v) = o.borrow().props.get("href") {
411            return Ok(v.clone());
412        }
413    }
414    Ok(Value::str(""))
415}
416
417/// location オブジェクトにナビゲーション要求を積む共通ヘルパ。
418/// `mode`: "assign"(履歴あり) / "replace"(履歴置換) / "reload"(再読込)。
419/// ホストが take_pending_location() で回収して実ナビゲーションする。
420pub(crate) fn queue_location_nav(this: &Value, url: &str, mode: &str) {
421    crate::warn!("[JSNAV] location {} {:?}", mode, url.chars().take(120).collect::<String>());
422    if let Value::Object(o) = this {
423        let mut b = o.borrow_mut();
424        b.props
425            .insert(String::from("_pending_location").into(), Value::str(url));
426        b.props
427            .insert(String::from("_pending_location_mode").into(), Value::str(mode));
428    }
429}
430
431/// location.assign(url): 指定URLへ遷移(履歴に新エントリを積む)。
432pub(crate) fn location_assign(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
433    let url = a.first().map(|v| v.to_js_string()).unwrap_or_default();
434    if !url.is_empty() {
435        queue_location_nav(&this, &url, "assign");
436    }
437    Ok(Value::Undefined)
438}
439
440/// location.replace(url): 指定URLへ遷移(現在の履歴エントリを置換)。
441pub(crate) fn location_replace(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
442    let url = a.first().map(|v| v.to_js_string()).unwrap_or_default();
443    if !url.is_empty() {
444        queue_location_nav(&this, &url, "replace");
445    }
446    Ok(Value::Undefined)
447}
448
449/// location.reload(): 現在のページを再読込する。
450pub(crate) fn location_reload(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
451    // 現在の href を再読込要求として積む(ホスト側で現URLを使うため空でも可)。
452    let cur = if let Value::Object(o) = &this {
453        o.borrow()
454            .props
455            .get("href")
456            .map(|v| v.to_js_string())
457            .unwrap_or_default()
458    } else {
459        String::new()
460    };
461    queue_location_nav(&this, &cur, "reload");
462    Ok(Value::Undefined)
463}
464
465/// 絶対URL `scheme://host[:port]/path[?query][#hash]` を location の各成分へ分解。
466/// `string_slice` lint 回避で split_once / strip_prefix のみ使用。
467pub(crate) fn location_components(url: &str) -> Vec<(&'static str, String)> {
468    let (protocol, after) = if let Some(a) = url.strip_prefix("https://") {
469        ("https:", a)
470    } else if let Some(a) = url.strip_prefix("http://") {
471        ("http:", a)
472    } else {
473        ("", url)
474    };
475    // 権限部(host)は最初の '/'・'?'・'#' まで。【2026-10-17】'/' だけで区切っており、
476    // `https://a.com?q=1` のホストが `a.com?q=1` になっていた。パスが空なら "/"。
477    let (hostport, pathpart) = match after.find(['/', '?', '#']) {
478        Some(i) => {
479            let (h, rest) = after.split_at(i);
480            let p = if rest.starts_with('/') { String::from(rest) } else { format!("/{}", rest) };
481            (String::from(h), p)
482        }
483        None => (String::from(after), String::from("/")),
484    };
485    // `user:pass@host` 形式のユーザー情報(userinfo)が丸ごと未対応で、
486    // `hostport`(= `host`/`hostname`/`port`/`origin` の元)にそのまま
487    // 混入していたバグ。`https://user:pass@example.com/` の `hostname` が
488    // 仕様上の `example.com` ではなく `pass@example.com` という壊れた値に
489    // なっていた(`:` での2分割で `user` が誤って `hostname` に化ける)。
490    // userinfo を `host` 系の解析より先に切り離す。
491    let (userinfo, hostport) = match hostport.split_once('@') {
492        Some((ui, hp)) => (String::from(ui), String::from(hp)),
493        None => (String::new(), hostport),
494    };
495    let (username, password) = match userinfo.split_once(':') {
496        Some((u, p)) => (String::from(u), String::from(p)),
497        None => (userinfo.clone(), String::new()),
498    };
499    let (before_hash, hash) = match pathpart.split_once('#') {
500        Some((b, h)) => (String::from(b), format!("#{}", h)),
501        None => (pathpart.clone(), String::new()),
502    };
503    let (pathname, search) = match before_hash.split_once('?') {
504        Some((p, q)) => (String::from(p), format!("?{}", q)),
505        None => (before_hash.clone(), String::new()),
506    };
507    let (hostname, port) = match hostport.split_once(':') {
508        Some((h, p)) => (String::from(h), String::from(p)),
509        None => (hostport.clone(), String::new()),
510    };
511    let origin = if protocol.is_empty() {
512        String::new()
513    } else {
514        format!("{}//{}", protocol, hostport)
515    };
516    // href は正規化した形(`https://a.com` → `https://a.com/`)。スキームの無いものはそのまま。
517    let href = if protocol.is_empty() {
518        String::from(url)
519    } else {
520        let auth = if url.contains('@') && !userinfo.is_empty() { format!("{}@{}", userinfo, hostport) } else { hostport.clone() };
521        format!("{}//{}{}{}{}", protocol, auth, pathname, search, hash)
522    };
523    alloc::vec![
524        ("href", href),
525        ("protocol", String::from(protocol)),
526        ("username", username),
527        ("password", password),
528        ("host", hostport),
529        ("hostname", hostname),
530        ("port", port),
531        ("origin", origin),
532        ("pathname", pathname),
533        ("search", search),
534        ("hash", hash),
535    ]
536}
537
538/// グローバルの location.href を読む(未設定/空なら None)。
539pub fn location_href(global: &Rc<RefCell<Scope>>) -> Option<String> {
540    let loc = match global.borrow().vars.get("location") {
541        Some(Value::Object(o)) => o.clone(),
542        _ => return None,
543    };
544    let href = loc
545        .borrow()
546        .props
547        .get("href")
548        .map(|v| v.to_js_string())
549        .unwrap_or_default();
550    if href.is_empty() {
551        None
552    } else {
553        Some(href)
554    }
555}
556
557/// グローバルの location.hostname を読む(未設定なら空文字列。`document.domain`
558/// の読み取り専用近似が呼ぶ)。
559pub fn location_hostname(global: &Rc<RefCell<Scope>>) -> Option<String> {
560    let loc = match global.borrow().vars.get("location") {
561        Some(Value::Object(o)) => o.clone(),
562        _ => return None,
563    };
564    let hostname = loc.borrow().props.get("hostname").map(|v| v.to_js_string());
565    hostname
566}
567
568/// `document.lastModified` を仕様どおりの `"MM/DD/YYYY HH:MM:SS"` 形式へ整形する。
569/// 実ファイルの mtime を追跡する仕組みが無いため、`epoch_ms_now()`(`Date.now()`
570/// と同じ現在時刻ソース)をそのまま使う簡略実装。
571pub fn format_last_modified() -> String {
572    let (y, mo, d, hh, mm, ss, ..) = decompose_ms(epoch_ms_now());
573    alloc::format!("{mo:02}/{d:02}/{y:04} {hh:02}:{mm:02}:{ss:02}")
574}
575
576/// history.pushState / replaceState 共通: url 指定があれば location を書換え、state を保存。
577/// pushState のみ length をインクリメント。popstate は仕様通り発火しない。
578pub(crate) fn history_change_state(
579    it: &mut Interp,
580    this: &Value,
581    a: &[Value],
582    push: bool,
583) -> Result<Value, Value> {
584    let new_state = arg(a, 0);
585    let url_arg = arg(a, 2);
586
587    if let Value::Object(o) = this {
588        if push {
589            // pushState: 現在の URL・state を _spa_back_stack へ退避してから更新。
590            let cur_url = location_href(&it.global).unwrap_or_default();
591            let cur_state = o.borrow().props.get("state").cloned().unwrap_or(Value::Null);
592            let stack_val = o.borrow().props.get("_spa_back_stack").cloned();
593            let stack = match stack_val {
594                Some(Value::Object(arr)) => arr,
595                _ => Obj::array(alloc::vec![]),
596            };
597            let entry = Obj::plain();
598            {
599                let mut eb = entry.borrow_mut();
600                eb.props.insert("url".into(), Value::str(cur_url));
601                eb.props.insert("state".into(), cur_state);
602            }
603            if let ObjKind::Array(items) = &mut stack.borrow_mut().kind {
604                items.push(Value::Object(entry));
605            }
606            o.borrow_mut().props.insert("_spa_back_stack".into(), Value::Object(stack));
607            // pushState 時は forward スタックをクリア(仕様通り)。
608            o.borrow_mut().props.shift_remove("_spa_fwd_stack");
609        }
610
611        if !matches!(url_arg, Value::Undefined | Value::Null) {
612            let url = url_arg.to_js_string();
613            if !url.is_empty() {
614                let base = location_href(&it.global).unwrap_or_default();
615                let resolved = resolve_url(&base, &url);
616                update_location(&it.global, &resolved);
617                it.base_url = resolved;
618            }
619        }
620
621        let mut b = o.borrow_mut();
622        b.props.insert("state".into(), new_state);
623        if push {
624            let len = match b.props.get("length") {
625                Some(Value::Number(n)) => *n,
626                _ => 1.0,
627            };
628            b.props.insert("length".into(), Value::Number(len + 1.0));
629        }
630    } else {
631        if !matches!(url_arg, Value::Undefined | Value::Null) {
632            let url = url_arg.to_js_string();
633            if !url.is_empty() {
634                let base = location_href(&it.global).unwrap_or_default();
635                let resolved = resolve_url(&base, &url);
636                update_location(&it.global, &resolved);
637                it.base_url = resolved;
638            }
639        }
640    }
641    Ok(Value::Undefined)
642}
643
644pub(crate) fn history_push_state(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
645    history_change_state(it, &this, a, true)
646}
647
648pub(crate) fn history_replace_state(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
649    history_change_state(it, &this, a, false)
650}
651
652/// history のナビゲーション要求を history オブジェクトの隠し props `_pending_nav` に積む。
653/// 値は相対移動量(負=戻る / 正=進む)。エンジンが JS 実行後に take_pending_nav で回収し、
654/// go_back / go_forward を実行してから popstate を発火する。
655/// (SPA だけでなく実ページ遷移にも対応するため、実ナビはホスト側に委譲する)。
656pub(crate) fn set_pending_nav(global: &Rc<RefCell<Scope>>, delta: i64) {
657    if delta == 0 {
658        return;
659    }
660    if let Some(Value::Object(h)) = global.borrow().vars.get("history") {
661        let cur = match h.borrow().props.get("_pending_nav") {
662            Some(Value::Number(n)) => *n as i64,
663            _ => 0,
664        };
665        h.borrow_mut()
666            .props
667            .insert("_pending_nav".into(), Value::Number((cur + delta) as f64));
668    }
669}
670
671pub(crate) fn history_back(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
672    set_pending_nav(&it.global, -1);
673    Ok(Value::Undefined)
674}
675
676pub(crate) fn history_forward(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
677    set_pending_nav(&it.global, 1);
678    Ok(Value::Undefined)
679}
680
681pub(crate) fn history_go(it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
682    // go(0) はリロード相当だが当面は no-op。go(-n)/go(n) を相対移動として扱う。
683    let n = arg(a, 0).to_number();
684    if n.is_finite() {
685        set_pending_nav(&it.global, n as i64);
686    }
687    Ok(Value::Undefined)
688}
689