nomad-common 0.1.0

Shared types and protocol for Nomad web extraction engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use std::fmt::Write;

use serde::{Deserialize, Serialize};

fn feq(a: f32, b: f32) -> bool { (a - b).abs() < 0.01 }

use crate::types::{StateTag, Style, Viewport};

/// A complete renderable frame for one tab.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EcsFrame {
    pub tab_id: u64,
    pub viewport: Viewport,
    pub scroll_offset: (f32, f32),
    pub total_extent: (f32, f32),
    pub entities: EntityArray,
    pub content_flags: u16,
    pub form_entries: Vec<FormEntry>,
}

/// Form field attributes extracted during HTML parsing.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct FormEntry {
    pub entity_id: u64,
    pub name: String,
    pub input_type: String,
    pub value: String,
    pub placeholder: String,
    pub required: bool,
}

/// Structure-of-arrays layout — cache-contiguous, SIMD-friendly.
///
/// Each entity carries a `state_tag` for delta compression:
///   STATIC(0)  — unchanged since client's last ack
///   MOVED(1)   — position/viewport only
///   CHANGED(2) — content or style changed
///   REMOVED(3) — no longer present
///
/// `content_hashes[i]` = XXH3-64 of the content blob for dedup.
/// Clients cache blobs by hash and only fetch new ones on CHANGED entities.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EntityArray {
    pub ids: Vec<u64>,
    pub xs: Vec<f32>,
    pub ys: Vec<f32>,
    pub widths: Vec<f32>,
    pub heights: Vec<f32>,
    pub z_indices: Vec<u16>,
    pub styles: Vec<Style>,
    pub state_tags: Vec<u8>,
    pub content_hashes: Vec<u64>,
    pub content_offsets: Vec<u32>,
    pub contents: Vec<u8>,
}

impl EntityArray {
    pub fn len(&self) -> usize {
        self.ids.len()
    }

    pub fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }

    pub fn clear(&mut self) {
        self.ids.clear();
        self.xs.clear();
        self.ys.clear();
        self.widths.clear();
        self.heights.clear();
        self.z_indices.clear();
        self.styles.clear();
        self.state_tags.clear();
        self.content_hashes.clear();
        self.content_offsets.clear();
        self.contents.clear();
    }

    pub fn shrink_to_fit(&mut self) {
        self.ids.shrink_to_fit();
        self.xs.shrink_to_fit();
        self.ys.shrink_to_fit();
        self.widths.shrink_to_fit();
        self.heights.shrink_to_fit();
        self.z_indices.shrink_to_fit();
        self.styles.shrink_to_fit();
        self.state_tags.shrink_to_fit();
        self.content_hashes.shrink_to_fit();
        self.content_offsets.shrink_to_fit();
        self.contents.shrink_to_fit();
    }

    pub fn push(
        &mut self,
        id: u64,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
        z: u16,
        style: Style,
        content: &[u8],
    ) {
        let hash = xxhash_rust::xxh3::xxh3_64(content);
        self.ids.push(id);
        self.xs.push(x);
        self.ys.push(y);
        self.widths.push(w);
        self.heights.push(h);
        self.z_indices.push(z);
        self.styles.push(style);
        self.state_tags.push(StateTag::CHANGED.0);
        self.content_hashes.push(hash);
        self.content_offsets.push(self.contents.len() as u32);
        self.contents.extend_from_slice(content);
    }

    /// Produce delta between self and an older frame.
    /// Returns only entities that differ: STATIC entries are omitted entirely.
    pub fn diff_since(&self, prev: &EntityArray) -> ChangedEntities {
        let n = self.ids.len();
        // O(1) early-exit for large arrays: all slices identical → everything STATIC.
        if n > 100 && n == prev.ids.len()
            && self.ids.as_slice() == prev.ids.as_slice()
            && self.xs.as_slice() == prev.xs.as_slice()
            && self.ys.as_slice() == prev.ys.as_slice()
            && self.widths.as_slice() == prev.widths.as_slice()
            && self.heights.as_slice() == prev.heights.as_slice()
            && self.z_indices.as_slice() == prev.z_indices.as_slice()
            && self.styles.as_slice() == prev.styles.as_slice()
            && self.content_hashes.as_slice() == prev.content_hashes.as_slice()
        {
            return ChangedEntities::default();
        }
        let mut out = ChangedEntities::default();

        let mut prev_idx: std::collections::HashMap<u64, usize> =
            std::collections::HashMap::with_capacity(prev.ids.len());
        for (i, &id) in prev.ids.iter().enumerate() {
            prev_idx.insert(id, i);
        }

        for i in 0..n {
            let id = self.ids[i];
            let hash = self.content_hashes[i];
            let prev_i = prev_idx.get(&id).copied();
            let state = match prev_i {
                None => StateTag::CHANGED,
                Some(pi) => {
                    if hash == prev.content_hashes[pi]
                        && feq(self.xs[i], prev.xs[pi])
                        && feq(self.ys[i], prev.ys[pi])
                        && feq(self.widths[i], prev.widths[pi])
                        && feq(self.heights[i], prev.heights[pi])
                        && self.z_indices[i] == prev.z_indices[pi]
                        && self.styles[i] == prev.styles[pi]
                    {
                        continue; // STATIC — skip entirely
                    }
                    if hash == prev.content_hashes[pi] {
                        StateTag::MOVED
                    } else {
                        StateTag::CHANGED
                    }
                }
            };

            out.ids.push(id);
            out.state_tags.push(state.0);
            out.xs.push(self.xs[i]);
            out.ys.push(self.ys[i]);
            out.widths.push(self.widths[i]);
            out.heights.push(self.heights[i]);
            out.z_indices.push(self.z_indices[i]);
            out.styles.push(self.styles[i]);
            out.content_hashes.push(hash);
            if state == StateTag::CHANGED {
                let slice = self.content_slice(i);
                out.new_content.push(slice.to_vec());
            } else {
                out.new_content.push(Vec::new());
            }
        }

        // Detect removed entities (also when counts equal but IDs differ)
        let current_ids: std::collections::HashSet<u64> = self.ids.iter().copied().collect();
        for &id in &prev.ids {
            if !current_ids.contains(&id) {
                out.ids.push(id);
                out.state_tags.push(StateTag::REMOVED.0);
                out.xs.push(0.0); out.ys.push(0.0);
                out.widths.push(0.0); out.heights.push(0.0);
                out.z_indices.push(0); out.styles.push(Style(0));
                out.content_hashes.push(0);
                out.new_content.push(Vec::new());
            }
        }
        out
    }

    pub fn content_slice(&self, idx: usize) -> &[u8] {
        if idx >= self.ids.len() { return &[]; }
        let start = self.content_offsets[idx] as usize;
        let end = if idx + 1 < self.ids.len() {
            self.content_offsets[idx + 1] as usize
        } else {
            self.contents.len()
        };
        &self.contents[start..end]
    }

    /// Unpack a single entity's content from packed format.
    /// Returns (tag, classes, id, href, role, text) — all slices borrowing from self.contents.
    /// Packed format: \0tag\0[classes]\0[id]\0[href]\0[role]\0text
    pub fn unpack_entity(&self, idx: usize) -> (&[u8], &[u8], &[u8], &[u8], &[u8], &[u8]) {
        let slice = self.content_slice(idx);
        if slice.is_empty() { return (b"", b"", b"", b"", b"", slice); }
        if slice[0] != 0 { return (b"", b"", b"", b"", b"", slice); }
        let tag_end = slice.iter().skip(1).position(|&b| b == 0).map(|p| p + 1).unwrap_or(1);
        let tag = &slice[1..tag_end];
        let mut rest = &slice[tag_end + 1..];

        // classes
        let classes: &[u8];
        if rest.first() == Some(&0) { classes = b""; rest = &rest[1..]; }
        else {
            let e = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
            classes = &rest[..e];
            rest = &rest[(e + 1).min(rest.len())..];
        }
        // id
        let id: &[u8];
        if rest.first() == Some(&0) { id = b""; rest = &rest[1..]; }
        else {
            let e = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
            id = &rest[..e];
            rest = &rest[(e + 1).min(rest.len())..];
        }
        // href
        let href: &[u8];
        if rest.first() == Some(&0) { href = b""; rest = &rest[1..]; }
        else {
            let e = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
            href = &rest[..e];
            rest = &rest[(e + 1).min(rest.len())..];
        }
        // role
        let role: &[u8];
        if rest.first() == Some(&0) { role = b""; rest = &rest[1..]; }
        else {
            let e = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
            role = &rest[..e];
            rest = &rest[(e + 1).min(rest.len())..];
        }
        (tag, classes, id, href, role, rest)
    }
}

impl Default for EntityArray {
    fn default() -> Self {
        Self::with_capacity(512)
    }
}

impl EntityArray {
    pub fn with_capacity(n: usize) -> Self {
        let cap = n.max(16);
        Self {
            ids: Vec::with_capacity(cap),
            xs: Vec::with_capacity(cap),
            ys: Vec::with_capacity(cap),
            widths: Vec::with_capacity(cap),
            heights: Vec::with_capacity(cap),
            z_indices: Vec::with_capacity(cap),
            styles: Vec::with_capacity(cap),
            state_tags: Vec::with_capacity(cap),
            content_hashes: Vec::with_capacity(cap),
            content_offsets: Vec::with_capacity(cap),
            contents: Vec::with_capacity(cap * 16),
        }
    }

    fn json_esc_buf(buf: &mut String, s: &[u8]) {
        let s = std::str::from_utf8(s).unwrap_or("");
        for c in s.chars() {
            match c {
                '"' => buf.push_str("\\\""),
                '\\' => buf.push_str("\\\\"),
                '\n' => buf.push_str("\\n"),
                '\r' => buf.push_str("\\r"),
                '\t' => buf.push_str("\\t"),
                '\x08' => buf.push_str("\\b"),
                '\x0C' => buf.push_str("\\f"),
                c if c.is_control() => { let _ = write!(buf, "\\u{:04x}", c as u32); }
                c => buf.push(c),
            }
        }
    }

    /// Build a JSON string for the ECS-to-JS hydration bridge.
    /// Output flat array with parentId for reconstructing the DOM tree in QuickJS.
    pub fn hydration_json(&self) -> String {
        let mut out = String::with_capacity(self.ids.len() * 80);
        out.push('[');
        let mut parents: Vec<Option<usize>> = vec![None; self.ids.len()];
        let mut stack: Vec<usize> = Vec::with_capacity(16);
        let mut last_was_block = false;
        for i in 0..self.ids.len() {
            if let Some(&top) = stack.last() { parents[i] = Some(top); }
            if self.styles[i].display_type() == 0 {
                if last_was_block {
                    stack.pop();
                }
                stack.push(i);
                last_was_block = true;
            } else {
                last_was_block = false;
            }
        }

        let mut first = true;
        for i in 0..self.ids.len() {
            let style = self.styles[i];
            if style.display_type() == 3 { continue; }
            let (tag, _, _, href, role, text) = self.unpack_entity(i);
            let parent_id = parents[i].map(|p| self.ids[p] as i64).unwrap_or(0);

            if !first { out.push(','); } first = false;
            write!(out, "{{\"i\":{}", self.ids[i]).ok();
            out.push_str(",\"t\":\"");
            Self::json_esc_buf(&mut out, tag);
            out.push('"');
            if !text.is_empty() && !text.iter().all(|&b| b == b' ') {
                out.push_str(",\"x\":\"");
                Self::json_esc_buf(&mut out, text);
                out.push('"');
            }
            if !href.is_empty() {
                out.push_str(",\"h\":\"");
                Self::json_esc_buf(&mut out, href);
                out.push('"');
            }
            if !role.is_empty() {
                out.push_str(",\"r\":\"");
                Self::json_esc_buf(&mut out, role);
                out.push('"');
            }
            if parent_id != 0 { write!(out, ",\"p\":{}", parent_id).ok(); }
            out.push('}');
        }
        out.push(']');
        out
    }
}

// ── Frame Delta ──

/// Minimal delta between two frames — sent on scroll, resize, JS state diff.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct ChangedEntities {
    pub ids: Vec<u64>,
    pub state_tags: Vec<u8>,
    pub xs: Vec<f32>,
    pub ys: Vec<f32>,
    pub widths: Vec<f32>,
    pub heights: Vec<f32>,
    pub z_indices: Vec<u16>,
    pub styles: Vec<Style>,
    pub content_hashes: Vec<u64>,
    /// Empty vec for MOVED/REMOVED; content bytes for CHANGED.
    pub new_content: Vec<Vec<u8>>,
}

impl ChangedEntities {
    pub fn len(&self) -> usize {
        self.ids.len()
    }
    pub fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }
}

// ── Page metadata sent alongside the first frame ──

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct PageMetadata {
    pub title: String,
    pub url: String,
    pub description: String,
    pub og_title: String,
    pub og_image: String,
    pub og_description: String,
    pub canonical_url: String,
    pub json_ld: Vec<String>,
}

/// Metadata extraction level — controls how much metadata to extract during parse.
/// Use `Minimal` for maximum throughput (only title, description, canonical).
/// Use `Full` for rich metadata including Open Graph and JSON-LD.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MetadataLevel {
    Minimal,
    Full,
}

impl Default for MetadataLevel {
    fn default() -> Self {
        Self::Minimal
    }
}

impl std::str::FromStr for MetadataLevel {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "full" => Ok(Self::Full),
            _ => Ok(Self::Minimal),
        }
    }
}

// ── Content flags for real-world site detection ──

pub const FLAG_HAS_VIDEO: u16 = 1;
pub const FLAG_HAS_CANVAS: u16 = 2;
pub const FLAG_HAS_IFRAME: u16 = 4;
pub const FLAG_HAS_LAZY_IMAGES: u16 = 8;
pub const FLAG_HAS_PAYWALL: u16 = 16;
pub const FLAG_HAS_LOGIN_WALL: u16 = 32;
pub const FLAG_IS_SPA: u16 = 64;
pub const FLAG_HAS_TABLES: u16 = 128;
pub const FLAG_IS_ARTICLE: u16 = 256;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_unpack_entity_roundtrip() {
        let mut arr = EntityArray::with_capacity(4);
        let packed = {
            let mut p = Vec::new();
            p.push(0u8);
            p.extend_from_slice(b"div"); p.push(0u8);
            p.extend_from_slice(b"container main"); p.push(0u8);
            p.extend_from_slice(b"my-id"); p.push(0u8);
            p.extend_from_slice(b"https://example.com"); p.push(0u8);
            p.extend_from_slice(b"navigation"); p.push(0u8);
            p.extend_from_slice(b"Hello world");
            p
        };
        arr.push(1, 0.0, 0.0, 0.0, 0.0, 0, Style(0), &packed);

        let (tag, classes, id, href, role, text) = arr.unpack_entity(0);
        assert_eq!(tag, b"div");
        assert_eq!(classes, b"container main");
        assert_eq!(id, b"my-id");
        assert_eq!(href, b"https://example.com");
        assert_eq!(role, b"navigation");
        assert_eq!(text, b"Hello world");
    }

    #[test]
    fn test_diff_since_static_unchanged() {
        let mut prev = EntityArray::with_capacity(2);
        let p1 = build_packed(b"p", b"", b"", b"", b"", b"hello");
        prev.push(1, 10.0, 20.0, 100.0, 20.0, 0, Style(0), &p1);
        let p2 = build_packed(b"p", b"", b"", b"", b"", b"world");
        prev.push(2, 10.0, 40.0, 100.0, 20.0, 0, Style(0), &p2);

        let curr = prev.clone();
        let delta = curr.diff_since(&prev);
        assert!(delta.is_empty());
    }

    #[test]
    fn test_diff_since_moved() {
        let mut prev = EntityArray::with_capacity(2);
        let p1 = build_packed(b"p", b"", b"", b"", b"", b"hello");
        prev.push(1, 10.0, 20.0, 100.0, 20.0, 0, Style(0), &p1);

        let mut curr = EntityArray::with_capacity(2);
        curr.push(1, 15.0, 25.0, 100.0, 20.0, 0, Style(0), &p1);

        let delta = curr.diff_since(&prev);
        assert_eq!(delta.len(), 1);
        assert_eq!(delta.state_tags[0], StateTag::MOVED.0);
    }

    #[test]
    fn test_diff_since_changed() {
        let mut prev = EntityArray::with_capacity(2);
        let p1 = build_packed(b"p", b"", b"", b"", b"", b"hello");
        prev.push(1, 10.0, 20.0, 100.0, 20.0, 0, Style(0), &p1);

        let mut curr = EntityArray::with_capacity(2);
        let p2 = build_packed(b"p", b"", b"", b"", b"", b"goodbye");
        curr.push(1, 10.0, 20.0, 100.0, 20.0, 0, Style(0), &p2);

        let delta = curr.diff_since(&prev);
        assert_eq!(delta.len(), 1);
        assert_eq!(delta.state_tags[0], StateTag::CHANGED.0);
        assert!(!delta.new_content[0].is_empty());
    }

    #[test]
    fn test_diff_since_removed() {
        let mut prev = EntityArray::with_capacity(2);
        let p1 = build_packed(b"p", b"", b"", b"", b"", b"hello");
        prev.push(1, 10.0, 20.0, 100.0, 20.0, 0, Style(0), &p1);
        let p2 = build_packed(b"p", b"", b"", b"", b"", b"world");
        prev.push(2, 10.0, 40.0, 100.0, 20.0, 0, Style(0), &p2);

        let mut curr = EntityArray::with_capacity(1);
        curr.push(1, 10.0, 20.0, 100.0, 20.0, 0, Style(0), &p1);

        let delta = curr.diff_since(&prev);
        assert_eq!(delta.len(), 1);
        assert_eq!(delta.state_tags[0], StateTag::REMOVED.0);
    }

    fn build_packed(tag: &[u8], classes: &[u8], id: &[u8], href: &[u8], role: &[u8], text: &[u8]) -> Vec<u8> {
        let mut p = Vec::new();
        p.push(0u8);
        p.extend_from_slice(tag); p.push(0u8);
        p.extend_from_slice(classes); p.push(0u8);
        p.extend_from_slice(id); p.push(0u8);
        p.extend_from_slice(href); p.push(0u8);
        p.extend_from_slice(role); p.push(0u8);
        p.extend_from_slice(text);
        p
    }
}