package chatmarkdown // This test-only projection observes Render/RenderDraft's HTML, not a second // interpretation of Markdown. Changing production output changes the goldens. import ( "bytes" "encoding/json" "fmt" "math/rand/v2" "os" "path/filepath" "regexp" "strconv" "strings" "sync" "testing" "unicode/utf8" xhtml "golang.org/x/net/html" "golang.org/x/net/html/atom" ) type nativeNode struct { Kind string `json:"kind"` Text string `json:"text,omitempty"` Target string `json:"target,omitempty"` Label string `json:"label,omitempty"` Copy string `json:"copy,omitempty"` Copied string `json:"copied,omitempty"` Wrap bool `json:"wrap,omitempty"` CopyEnabled *bool `json:"copyEnabled,omitempty"` Children []nativeNode `json:"children"` } type nativeFixture struct { Name string `json:"name"` Source string `json:"source"` Draft bool `json:"draft"` Tree []nativeNode `json:"tree"` } func nativeLeaf(kind, text string) nativeNode { return nativeNode{Kind: kind, Text: text, Children: []nativeNode{}} } func nativeAttr(n *xhtml.Node, key string) string { for _, a := range n.Attr { if a.Key == key { return a.Val } } return "" } func nativeText(n *xhtml.Node) string { if n.Type == xhtml.TextNode { return n.Data } var b strings.Builder for c := n.FirstChild; c != nil; c = c.NextSibling { b.WriteString(nativeText(c)) } return b.String() } func nativeFind(n *xhtml.Node, tag string) *xhtml.Node { if n.Type == xhtml.ElementNode && n.Data == tag { return n } for c := n.FirstChild; c != nil; c = c.NextSibling { if found := nativeFind(c, tag); found != nil { return found } } return nil } func nativeChildren(n *xhtml.Node) []nativeNode { out := []nativeNode{} for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type == xhtml.TextNode && c.Data == "\n" && (n.Data == "div" || n.Data == "ul" || n.Data == "ol" || n.Data == "li" || c.PrevSibling != nil && c.PrevSibling.Data == "br") { continue } if c.Type == xhtml.TextNode && c.PrevSibling != nil && (c.PrevSibling.Data == "br" || n.Data == "div" && c.PrevSibling.Type == xhtml.ElementNode) { c.Data = strings.TrimPrefix(c.Data, "\n") } for _, next := range nativeWalk(c) { if next.Kind == "text" && next.Text == "" { continue } if next.Kind == "text" && len(out) > 0 && out[len(out)-1].Kind == "text" { out[len(out)-1].Text += next.Text } else { out = append(out, next) } } } return out } func nativeWalk(n *xhtml.Node) []nativeNode { if n.Type == xhtml.TextNode { return []nativeNode{nativeLeaf("text", n.Data)} } if n.Type != xhtml.ElementNode { return nil } if kind := nativeAttr(n, "equipo-paste"); kind != "" { box := nativeLeaf("paste", nativeText(nativeFind(n, "pre"))) box.Wrap = kind == "prose" bar := n.FirstChild if span := nativeFind(bar, "span"); span != nil && nativeAttr(span, "equipo-paste-lang") == "" { // Attribute presence matters: its HTML value is empty. for _, a := range span.Attr { if a.Key == "equipo-paste-lang" { box.Label = nativeText(span) } } } button := nativeFind(bar, "button") enabled := nativeAttr(button, "aria-disabled") != "true" box.CopyEnabled = &enabled box.Copied = nativeAttr(button, "data-copied") for c := button.FirstChild; c != nil; c = c.NextSibling { if nativeAttr(c, "equipo-paste-word") == "" { for _, a := range c.Attr { if a.Key == "equipo-paste-word" { box.Copy = nativeText(c) } } } } return []nativeNode{box} } kinds := map[string]string{"p": "paragraph", "em": "emphasis", "strong": "strong", "code": "code", "ul": "unordered", "ol": "ordered", "li": "item", "a": "link", "br": "break"} if n.Data == "pre" { return []nativeNode{nativeLeaf("codeBlock", nativeText(n))} } if kind := kinds[n.Data]; kind != "" { node := nativeLeaf(kind, "") if kind == "code" { node.Text = nativeText(n) } else { node.Children = nativeChildren(n) } if kind == "link" { node.Target = nativeAttr(n, "href") } return []nativeNode{node} } return nativeChildren(n) } var nativeWords Labels var nativeWordsOnce sync.Once func nativeLabels(t *testing.T) Labels { nativeWordsOnce.Do(func() { nativeWords = readNativeLabels(t) }) return nativeWords } func readNativeLabels(t *testing.T) Labels { t.Helper() source, err := os.ReadFile(filepath.Join("..", "equipo", "copy.go")) if err != nil { t.Fatal(err) } words := map[string]string{} for _, match := range regexp.MustCompile(`"chat\.paste\.(\w+)":\s*("(?:[^"\\]|\\.)*")`).FindAllSubmatch(source, -1) { value, err := strconv.Unquote(string(match[2])) if err != nil { t.Fatal(err) } words[string(match[1])] = value } if len(words) != 6 { t.Fatalf("expected all six paste-box labels, got %d", len(words)) } return Labels{Copy: words["copy"], Copied: words["copied"], Selected: words["selected"], Prompt: words["prompt"], Text: words["text"], Command: words["command"]} } func nativeTree(t *testing.T, source string, draft bool) []nativeNode { t.Helper() words := nativeLabels(t) rendered := words.Render(source) if draft { rendered = words.RenderDraft(source) } context := &xhtml.Node{Type: xhtml.ElementNode, Data: "div", DataAtom: atom.Div} nodes, err := xhtml.ParseFragment(strings.NewReader(string(rendered)), context) if err != nil { t.Fatal(err) } for _, n := range nodes { context.AppendChild(n) } return nativeChildren(context) } const phoneReply = "I found the cause and logged it as [Operator confirm page on oficina.works looks plainer than on id.oficina.works](/tasks/tkwkpraqeeer). Engineering is working on it now.\n\n**Why they look different:** the id.oficina.works page is shown in estilo's sign-in card on the sky. The oficina.works page never got that treatment, so it shows as a plain page. The fix moves it into the same card. The page's content stays the same.\n\nI've also put a hold on the merge, so it won't merge until you've seen it. I asked Engineering to include before and after screenshots so you can compare the two pages side by side." // Regenerate intentionally: EQUIPO_UPDATE_MARKDOWN=1 go test // ./internal/chatmarkdown -run '^TestNativeMarkdownFixtures$' -count=1. func TestNativeMarkdownFixtures(t *testing.T) { inputs := append(append([]string{phoneReply}, corpus...), reviewInputs...) inputs = append(inputs, "[query](https://example.test/?q=%zz) [opaque](mailto:a%zz@example.test) [opaque](https:bad%zz) [fragment](https://example.test/#%zz)", "[host](https://%41.example.test) [host](https://example.test:bad) [host](https://[::1]/) [bad](https://[127.0.0.1]/) [bad](https://[:::]/) [query](https://example.test/?q=%zz#valid)", "[x](HTTPS://example.test) [x](mailto:a@example.test?subject=Hi) [bad](https://[broken) [bad](https://example.test/%zz)", "[x](https://example.test/a\\_b) [x](https://example.test/a%20b) [x](https://example.test/a\\(b\\))", "~~no strike~~ | no | table |\n| --- | --- |\n| a | b |\n\n- [x] no task control", "***three*** ____four____ __outer _inner_ outer__ a***b***c \\*literal \\_literal \\`literal", "` a b ` and `` a`b `` and `a\nb` and ``\n``", "- fenced\n\n ```prompt\n nested prose\n ```\n\n> ~~~~sh\n> ls\n> ~~~~\n", "
\nraw **text** &\n
\n\n\n\n\r\n```\r\n", "[nested **strong** and *em*](/tasks/tk1) ![image *alt*](https://example.test/a)", "[x](/tasks/tk"+strings.Repeat("a", 33)+") [x](/projects/p_"+strings.Repeat("a", 41)+")", "# Heading\n## Smaller\n\nsetext\n===\n\n---\n\n***\n\nend", "***nested*** **outer *inner* end** *outer **inner** end* a_b_c & 🙂 \\*escaped\\*", "\n\nraw \n\n![alt **words**](https://evil.test/x)", "[task](/tasks/tk1) [project](/projects/p_abc123) [web](https://example.test/a?q=1&b=2) [mail](mailto:a@example.test)", "[no](javascript:alert%281%29) [no](data:text/html,evil) [no](//evil.test) [no](/settings) [no](/tasks/tk1?a=b) [no](/tasks/tk1/../../logout)", "[no](javascript:evil) [no](/tasks/TK1) [no](tasks/tk1) [no](/\\\\evil.test) [yes](http://example.test)", " [reference][id]\n\n[id]: /tasks/tk1", "7. seven\n8. eight\n\n- loose\n\n paragraph\n\n - nested\n\n> quote\n>\n> second", " indented\n &\n\n```go\nif a < b {\n\tprint(\"&\") \n}\n```", "``````text\n``` inside\n`````\n``````\n\n~~~prompt\nwrap me\n~~~", "CRLF\r\n\r\n**strong**\r\n\r\n```sh\r\nls\r\n```\r\n", "Para **open\n\nNext", "2 * 3", "it*", "a**b", "`one``two", "See [partial](/tasks/tk1", "Code `a[b`", "- **Guest:** a\n- **", "1. owner\n2", "Text\n--", "## Pl", "## **open\n", "soft\nbreak \nhard\\\nbreak", ) for _, lang := range []string{"", "prompt", "PROMPT", "text", "Text", "bash", "sh", "zsh", "shell", "console", "Bash", "go", "Python", "c++", "c#", ".env", "objective-c", "