jacquard 0.12.0-beta.2

Simple and powerful AT Protocol client library for Rust
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
use super::*;

#[test]
fn test_parse_mentions() {
    let text = "Hey @alice.bsky.social check this out";
    let builder = RichText::parse(text);

    assert_eq!(builder.facet_candidates.len(), 1);
    match &builder.facet_candidates[0] {
        FacetCandidate::Mention { range, .. } => {
            // Verify the text in the range includes the @ symbol
            assert_eq!(&builder.text[range.clone()], "@alice.bsky.social");
        }
        _ => panic!("Expected mention facet"),
    }
}

#[test]
fn test_parse_links() {
    let text = "Check out https://example.com for more info";
    let builder = RichText::parse(text);

    assert!(builder.facet_candidates.iter().any(|fc| {
        matches!(fc, FacetCandidate::Link { range } if text[range.clone()].contains("example.com"))
    }));
}

#[test]
fn test_parse_tags() {
    let text = "This is #cool and #awesome";
    let builder = RichText::parse(text);

    let tags: Vec<_> = builder
        .facet_candidates
        .iter()
        .filter_map(|fc| match fc {
            FacetCandidate::Tag { range } => Some(&builder.text[range.clone()]),
            _ => None,
        })
        .collect();

    assert!(tags.contains(&"#cool"));
    assert!(tags.contains(&"#awesome"));
}

#[test]
fn test_markdown_links() {
    let text = "Check out [this link](https://example.com)";
    let builder = RichText::parse(text);

    // Should have stripped markdown syntax
    assert!(builder.text.contains("this link"));
    assert!(!builder.text.contains("["));
    assert!(!builder.text.contains("]"));

    // Should have detected the link facet
    assert!(builder.facet_candidates.iter().any(|fc| matches!(
        fc,
        FacetCandidate::MarkdownLink { url, .. } if url == "https://example.com"
    )));
}

#[test]
#[cfg(feature = "api_bluesky")]
fn test_builder_manual_construction() {
    let did = crate::types::did::Did::new_static("did:plc:z72i7hdynmk6r22z27h6tvur").unwrap();

    let result = RichText::builder()
        .text("Hello @alice check out example.com".to_string())
        .mention(&did, 6..12)
        .link("https://example.com", Some(23..34))
        .build()
        .unwrap();

    assert_eq!(result.text.as_str(), "Hello @alice check out example.com");
    assert!(result.facets.is_some());
    let facets = result.facets.unwrap();
    assert_eq!(facets.len(), 2);
}

#[test]
#[cfg(feature = "api_bluesky")]
fn test_overlapping_facets_error() {
    let did1 = crate::types::did::Did::new_static("did:plc:z72i7hdynmk6r22z27h6tvur").unwrap();
    let did2 = crate::types::did::Did::new_static("did:plc:ewvi7nxzyoun6zhxrhs64oiz").unwrap();

    let result = RichText::builder()
        .text("Hello world".to_string())
        .mention(&did1, 0..5)
        .mention(&did2, 3..8) // Overlaps with previous
        .build();

    assert!(matches!(
        result,
        Err(RichTextError::OverlappingFacets(_, _))
    ));
}

#[test]
fn test_parse_did_mentions() {
    let text = "Hey @did:plc:z72i7hdynmk6r22z27h6tvur check this out";
    let builder = RichText::parse(text);

    assert_eq!(builder.facet_candidates.len(), 1);
    match &builder.facet_candidates[0] {
        FacetCandidate::Mention { range, did } => {
            assert_eq!(&text[range.clone()], "@did:plc:z72i7hdynmk6r22z27h6tvur");
            assert!(did.is_some()); // DID should be pre-resolved
        }
        _ => panic!("Expected mention facet"),
    }
}

#[test]
fn test_bare_domain_link() {
    let text = "Visit example.com for info";
    let builder = RichText::parse(text);

    assert!(builder.facet_candidates.iter().any(|fc| {
        matches!(fc, FacetCandidate::Link { range } if text[range.clone()].contains("example.com"))
    }));
}

#[test]
fn test_trailing_punctuation_stripped() {
    let text = "Check https://example.com, and https://test.org.";
    let builder = RichText::parse(text);

    // Count link facets
    let link_count = builder
        .facet_candidates
        .iter()
        .filter(|fc| matches!(fc, FacetCandidate::Link { .. }))
        .count();

    assert_eq!(link_count, 2);

    // Verify punctuation is not included in ranges
    for fc in &builder.facet_candidates {
        if let FacetCandidate::Link { range } = fc {
            let url = &text[range.clone()];
            assert!(!url.ends_with(','));
            assert!(!url.ends_with('.'));
        }
    }
}

#[test]
#[cfg(feature = "api_bluesky")]
fn test_embed_detection_external() {
    let text = "Check out https://external.com/article";
    let builder = RichText::parse(text);

    assert!(builder.embed_candidates.is_some());
    let embeds = builder.embed_candidates.unwrap();
    assert_eq!(embeds.len(), 1);

    match &embeds[0] {
        EmbedCandidate::External { url, metadata } => {
            assert!(url.contains("external.com"));
            assert!(metadata.is_none());
        }
        _ => panic!("Expected external embed"),
    }
}

#[test]
#[cfg(feature = "api_bluesky")]
fn test_embed_detection_bsky_post() {
    let text = "See https://bsky.app/profile/alice.bsky.social/post/abc123";
    let builder = RichText::parse(text);

    assert!(builder.embed_candidates.is_some());
    let embeds = builder.embed_candidates.unwrap();
    assert_eq!(embeds.len(), 1);

    match &embeds[0] {
        EmbedCandidate::Record { at_uri, .. } => {
            assert_eq!(
                at_uri.as_str(),
                "at://alice.bsky.social/app.bsky.feed.post/abc123"
            );
        }
        _ => panic!("Expected record embed"),
    }
}

#[test]
#[cfg(feature = "api_bluesky")]
fn test_markdown_link_with_embed() {
    let text = "Read [my post](https://bsky.app/profile/me.bsky.social/post/xyz)";
    let builder = RichText::parse(text);

    // Should have markdown facet
    assert!(
        builder
            .facet_candidates
            .iter()
            .any(|fc| matches!(fc, FacetCandidate::MarkdownLink { .. }))
    );

    // Should also detect embed
    assert!(builder.embed_candidates.is_some());
    let embeds = builder.embed_candidates.unwrap();
    assert_eq!(embeds.len(), 1);
}

// === Sanitization Tests ===

#[test]
fn test_sanitize_soft_hyphen() {
    // Soft hyphens should be removed
    let text = "Hello\u{00AD}World";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "HelloWorld");
}

#[test]
fn test_sanitize_zero_width_space() {
    // Zero-width spaces should be removed
    let text = "Hello\u{200B}World";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "HelloWorld");
}

#[test]
fn test_sanitize_normalize_newlines() {
    // \r\n should normalize to \n
    let text = "Hello\r\nWorld";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "Hello\nWorld");
}

#[test]
fn test_sanitize_collapse_multiple_newlines() {
    // Multiple newlines should collapse to \n\n
    let text = "Hello\n\n\n\nWorld";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "Hello\n\nWorld");
}

#[test]
fn test_sanitize_mixed_invisible_and_newlines() {
    // Mix of invisible chars and newlines
    let text = "Hello\u{200B}\n\u{200C}\n\u{00AD}World";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "Hello\n\nWorld");
}

#[test]
fn test_sanitize_preserves_facets() {
    // Make sure sanitization doesn't break facet detection
    let text = "Hey @alice.bsky.social\u{200B} check\u{00AD}out https://example.com";
    let builder = RichText::parse(text);

    // Should still detect both mention and link
    assert!(
        builder
            .facet_candidates
            .iter()
            .any(|fc| matches!(fc, FacetCandidate::Mention { .. }))
    );
    assert!(
        builder
            .facet_candidates
            .iter()
            .any(|fc| matches!(fc, FacetCandidate::Link { .. }))
    );
}

#[test]
fn test_sanitize_newlines_with_spaces() {
    // Newlines with spaces between should collapse
    let text = "Hello\n \n \nWorld";
    let builder = RichText::parse(text);

    // 3 newlines with spaces -> collapses to \n\n
    assert_eq!(builder.text, "Hello\n\nWorld");
}

#[test]
fn test_sanitize_preserves_no_excess_newlines() {
    // Text without excessive newlines should be unchanged
    let text = "Hello\nWorld";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "Hello\nWorld");
}

#[test]
fn test_sanitize_empty_input() {
    // Empty string should remain empty
    let text = "";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "");
}

#[test]
fn test_sanitize_only_invisible_chars() {
    // Only invisible chars should be removed entirely
    let text = "\u{200B}\u{200C}\u{200D}\u{00AD}";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "");
}

#[test]
fn test_sanitize_cr_normalization() {
    // Standalone \r should normalize to \n
    let text = "Hello\rWorld";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "Hello\nWorld");
}

#[test]
fn test_sanitize_mixed_line_endings() {
    // Mix of \r\n, \r, \n should all normalize
    let text = "Line1\r\nLine2\rLine3\nLine4";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "Line1\nLine2\nLine3\nLine4");
}

#[test]
fn test_sanitize_preserves_regular_spaces() {
    // Regular spaces without newlines should be preserved
    let text = "Hello    World";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "Hello    World");
}

// === Adversarial / Edge Case Tests ===

#[test]
fn test_tag_too_long() {
    // Tags must be 64 chars or less
    let long_tag = "a".repeat(65);
    let text = format!("#{}", long_tag);
    let builder = RichText::parse(text);

    // Should NOT detect the tag
    assert!(
        builder
            .facet_candidates
            .iter()
            .all(|fc| !matches!(fc, FacetCandidate::Tag { .. }))
    );
}

#[test]
fn test_tag_with_zero_width_chars() {
    // Zero-width joiners and other invisible unicode
    let text = "This is #cool\u{200B}tag";
    let builder = RichText::parse(text);

    // Tag should stop at zero-width char
    let tags: Vec<_> = builder
        .facet_candidates
        .iter()
        .filter_map(|fc| match fc {
            FacetCandidate::Tag { range } => Some(&builder.text[range.clone()]),
            _ => None,
        })
        .collect();

    // Should only capture up to the zero-width char
    assert!(tags.iter().any(|t| t.starts_with("#cool")));
}

#[test]
fn test_url_with_parens() {
    // URLs like wikipedia with (parens) in them
    let text = "See https://en.wikipedia.org/wiki/Rust_(programming_language)";
    let builder = RichText::parse(text);

    // Should capture the full URL including parens
    assert!(builder.facet_candidates.iter().any(|fc| {
        matches!(fc, FacetCandidate::Link { range } if text[range.clone()].contains("programming_language"))
    }));
}

#[test]
fn test_markdown_link_unclosed() {
    // Malformed markdown should not be processed
    let text = "This is [unclosed link";
    let builder = RichText::parse(text);

    // Should not detect markdown link, text unchanged
    assert_eq!(builder.text, text);
    assert!(
        builder
            .facet_candidates
            .iter()
            .all(|fc| !matches!(fc, FacetCandidate::MarkdownLink { .. }))
    );
}

#[test]
fn test_nested_markdown_attempts() {
    // Try to nest markdown links
    let text = "[[nested](https://inner.com)](https://outer.com)";
    let builder = RichText::parse(text);

    // Should only match the innermost valid pattern
    let markdown_count = builder
        .facet_candidates
        .iter()
        .filter(|fc| matches!(fc, FacetCandidate::MarkdownLink { .. }))
        .count();

    // Regex should match leftmost, should get one
    assert!(markdown_count > 0);
}

#[test]
fn test_mention_with_emoji() {
    // Handles can't have emoji but let's make sure it doesn't crash
    let text = "Hey @alice😎.bsky.social wassup";
    let builder = RichText::parse(text);

    // Should not match or should stop at emoji
    let mentions: Vec<_> = builder
        .facet_candidates
        .iter()
        .filter_map(|fc| match fc {
            FacetCandidate::Mention { range, .. } => Some(&text[range.clone()]),
            _ => None,
        })
        .collect();

    // Either no mentions or mention stops before emoji
    for mention in mentions {
        assert!(!mention.contains('😎'));
    }
}

#[test]
fn test_handle_with_trailing_dots() {
    // Handles like @alice... should not include trailing dots
    let text = "Hey @alice.bsky.social... how are you";
    let builder = RichText::parse(text);

    if let Some(FacetCandidate::Mention { range, .. }) = builder.facet_candidates.first() {
        let mention = &text[range.clone()];
        assert!(!mention.ends_with('.'));
    }
}

#[test]
fn test_url_javascript_protocol() {
    // Should not detect javascript: or data: URLs
    let text = "Click javascript:alert(1) or data:text/html,<script>alert(1)</script>";
    let builder = RichText::parse(text);

    // Should not match non-http(s) URLs
    for fc in &builder.facet_candidates {
        if let FacetCandidate::Link { range } = fc {
            let url = &text[range.clone()];
            assert!(!url.starts_with("javascript:"));
            assert!(!url.starts_with("data:"));
        }
    }
}

#[test]
fn test_extremely_long_url() {
    // Very long URL should still work (no panic)
    let long_path = "a/".repeat(1000);
    let text = format!("Visit https://example.com/{}", long_path);
    let builder = RichText::parse(text);

    // Should detect the URL without panicking
    assert!(
        builder
            .facet_candidates
            .iter()
            .any(|fc| matches!(fc, FacetCandidate::Link { .. }))
    );
}

#[test]
fn test_empty_string() {
    let text = "";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "");
    assert!(builder.facet_candidates.is_empty());
}

#[test]
fn test_only_whitespace() {
    let text = "   \t\n  ";
    let builder = RichText::parse(text);

    assert!(builder.facet_candidates.is_empty());
}

#[test]
fn test_markdown_with_newlines() {
    // Markdown regex should not match across newlines
    let text = "This is [text\nwith](https://example.com) newline";
    let builder = RichText::parse(text);

    // Current regex won't match \n in the display text part
    // Just make sure it doesn't panic
    let _ = builder.facet_candidates;
}

#[test]
fn test_multiple_at_signs() {
    // @@alice should only match @alice
    let text = "Hey @@alice.bsky.social";
    let builder = RichText::parse(text);

    // Regex requires word boundary before @, so @@ might not match
    // Or might match the second @
    // Just verify it doesn't panic and produces valid ranges
    for fc in &builder.facet_candidates {
        if let FacetCandidate::Mention { range, .. } = fc {
            assert!(range.end <= text.len());
            let _ = &text[range.clone()]; // Shouldn't panic
        }
    }
}

#[test]
fn test_url_with_unicode_domain() {
    // IDN domains
    let text = "Visit https://δΎ‹γˆ.jp for info";
    let builder = RichText::parse(text);

    // Current regex only matches ASCII domains, so this might not detect
    // Just make sure no panic
    let _ = builder.facet_candidates;
}

#[test]
#[cfg(feature = "api_bluesky")]
fn test_build_with_invalid_range() {
    let did = crate::types::did::Did::new_static("did:plc:z72i7hdynmk6r22z27h6tvur").unwrap();

    // Range exceeds text length
    let result = RichText::builder()
        .text("Short".to_string())
        .mention(&did, 0..100)
        .build();

    assert!(matches!(result, Err(RichTextError::InvalidRange { .. })));
}

#[test]
fn test_rtl_override_injection() {
    // Right-to-left override character attempts
    let text = "Hey @alice\u{202E}reversed\u{202C}.bsky.social";
    let builder = RichText::parse(text);

    // Should either not match or handle gracefully
    let _ = builder.facet_candidates;
}

#[test]
fn test_tag_empty_after_hash() {
    // Just # with nothing after
    let text = "This is # a test";
    let builder = RichText::parse(text);

    // Should not detect empty tag
    assert!(
        builder
            .facet_candidates
            .iter()
            .all(|fc| !matches!(fc, FacetCandidate::Tag { .. }))
    );
}

// === Unicode Byte Boundary Tests ===

#[test]
fn test_facet_ranges_valid_utf8_boundaries() {
    // All detected facet ranges must be valid UTF-8 boundaries
    let text = "Hey @alice.bsky.social check δ½ ε₯½ #tagπŸ”₯ and https://example.com/ζ΅‹θ―•";
    let builder = RichText::parse(text);

    for fc in &builder.facet_candidates {
        let range = match fc {
            FacetCandidate::Mention { range, .. } => range,
            FacetCandidate::Link { range } => range,
            FacetCandidate::Tag { range } => range,
            FacetCandidate::MarkdownLink { display_range, .. } => display_range,
        };

        // This will panic if range is not on UTF-8 char boundary
        // Use builder.text (sanitized) not original text
        let slice = &builder.text[range.clone()];
        // Verify it's valid UTF-8
        assert!(std::str::from_utf8(slice.as_bytes()).is_ok());
    }
}

#[test]
fn test_emoji_grapheme_clusters() {
    // Family emoji with ZWJ sequences: "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§" is 25 bytes but 1 grapheme
    let text = "Hello πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘§ @alice.bsky.social";
    let builder = RichText::parse(text);

    // Should still detect the mention after the emoji
    assert!(
        builder
            .facet_candidates
            .iter()
            .any(|fc| matches!(fc, FacetCandidate::Mention { .. }))
    );

    // Verify all ranges are valid against the sanitized text
    for fc in &builder.facet_candidates {
        if let FacetCandidate::Mention { range, .. } = fc {
            let _ = &builder.text[range.clone()]; // Shouldn't panic
        }
    }
}

#[test]
fn test_tag_with_emoji() {
    // Tags can contain emoji
    let text = "This is #coolπŸ”₯";
    let builder = RichText::parse(text);

    let tags: Vec<_> = builder
        .facet_candidates
        .iter()
        .filter_map(|fc| match fc {
            FacetCandidate::Tag { range } => Some(&builder.text[range.clone()]),
            _ => None,
        })
        .collect();

    // Should include emoji in tag
    assert!(tags.iter().any(|t| t.contains("πŸ”₯")));
}

#[test]
fn test_sanitize_newlines_with_emoji() {
    // Newlines with emoji should still collapse correctly
    let text = "Hello πŸŽ‰\n\n\n\nWorld 🌍";
    let builder = RichText::parse(text);

    assert_eq!(builder.text, "Hello πŸŽ‰\n\nWorld 🌍");
}