Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

diff.gno

package wiki

import "strings"

// DiffOp is what happened to one line between two revisions.
type DiffOp uint8

const (
	OpEqual DiffOp = iota
	OpInsert
	OpDelete
)

// DiffLine is one line of a rendered diff.
type DiffLine struct {
	Op   DiffOp
	Text string
}

// DiffMaxLines bounds the changed region a diff will compute exactly.
//
// The cost of an LCS over the changed region is O(n*m), and this runs inside
// vm/qrender, which has a gas ceiling a reader cannot raise. 80 lines caps the
// table at 6,400 cells; beyond it, a diff degrades to "this block was replaced"
// rather than making the page unrenderable. Both revisions are still available
// in full through the raw view, so nothing is hidden by the degradation.
const DiffMaxLines = 80

// TODO(#140 Q5): decide whether diffing belongs on chain at all. Both options
// are still open: keep this bounded server-side diff, or drop it and let
// clients diff two /raw responses themselves, which costs the chain nothing
// and removes DiffMaxLines entirely. Keeping it for now because a diff a
// reader can reach from a plain URL is most of what makes a history readable,
// and 691M gas at the body cap leaves room. Revisit if MaxBody ever rises.

// DiffLines compares two bodies line by line.
//
// exact reports whether the result is a real line diff. When it is false the
// changed region was larger than DiffMaxLines and the result is the coarse
// form: every removed line, then every added line.
func DiffLines(older, newer string) (out []DiffLine, exact bool) {
	a := splitLines(older)
	b := splitLines(newer)

	// Trim the common prefix and suffix. Ordinary wiki edits touch a few
	// lines of a long article, so this alone brings almost every real diff
	// under the exact-computation bound.
	head := 0
	for head < len(a) && head < len(b) && a[head] == b[head] {
		head++
	}
	tailA, tailB := len(a), len(b)
	for tailA > head && tailB > head && a[tailA-1] == b[tailB-1] {
		tailA--
		tailB--
	}

	midA := a[head:tailA]
	midB := b[head:tailB]

	out = []DiffLine{}
	for _, l := range a[:head] {
		out = append(out, DiffLine{OpEqual, l})
	}

	exact = len(midA) <= DiffMaxLines && len(midB) <= DiffMaxLines
	if exact {
		out = append(out, lcsDiff(midA, midB)...)
	} else {
		for _, l := range midA {
			out = append(out, DiffLine{OpDelete, l})
		}
		for _, l := range midB {
			out = append(out, DiffLine{OpInsert, l})
		}
	}

	for _, l := range a[tailA:] {
		out = append(out, DiffLine{OpEqual, l})
	}
	return out, exact
}

// DiffStat counts added and removed lines.
func DiffStat(lines []DiffLine) (added, removed int) {
	for _, l := range lines {
		switch l.Op {
		case OpInsert:
			added++
		case OpDelete:
			removed++
		}
	}
	return added, removed
}

// lcsDiff is the textbook longest-common-subsequence diff, bounded by the
// caller to DiffMaxLines on each side.
func lcsDiff(a, b []string) []DiffLine {
	n, m := len(a), len(b)
	if n == 0 && m == 0 {
		return []DiffLine{}
	}
	// table[i][j] is the LCS length of a[i:] and b[j:].
	table := make([][]int, n+1)
	for i := range table {
		table[i] = make([]int, m+1)
	}
	for i := n - 1; i >= 0; i-- {
		for j := m - 1; j >= 0; j-- {
			if a[i] == b[j] {
				table[i][j] = table[i+1][j+1] + 1
			} else if table[i+1][j] >= table[i][j+1] {
				table[i][j] = table[i+1][j]
			} else {
				table[i][j] = table[i][j+1]
			}
		}
	}

	out := []DiffLine{}
	i, j := 0, 0
	for i < n && j < m {
		switch {
		case a[i] == b[j]:
			out = append(out, DiffLine{OpEqual, a[i]})
			i++
			j++
		case table[i+1][j] >= table[i][j+1]:
			out = append(out, DiffLine{OpDelete, a[i]})
			i++
		default:
			out = append(out, DiffLine{OpInsert, b[j]})
			j++
		}
	}
	for ; i < n; i++ {
		out = append(out, DiffLine{OpDelete, a[i]})
	}
	for ; j < m; j++ {
		out = append(out, DiffLine{OpInsert, b[j]})
	}
	return out
}

func splitLines(s string) []string {
	if s == "" {
		return []string{}
	}
	s = strings.TrimSuffix(s, "\n")
	return strings.Split(s, "\n")
}

diff_test.gno

package wiki

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

// render turns a diff into the compact "+a -b =c" form the tests assert on.
func render(lines []DiffLine) string {
	var b strings.Builder
	for _, l := range lines {
		switch l.Op {
		case OpInsert:
			b.WriteString("+")
		case OpDelete:
			b.WriteString("-")
		default:
			b.WriteString("=")
		}
		b.WriteString(l.Text)
		b.WriteString(";")
	}
	return b.String()
}

func TestDiffLines(t *testing.T) {
	cases := []struct {
		name     string
		old, new string
		want     string
	}{
		{"identical", "a\nb\n", "a\nb\n", "=a;=b;"},
		{"append", "a\n", "a\nb\n", "=a;+b;"},
		{"prepend", "b\n", "a\nb\n", "+a;=b;"},
		{"delete", "a\nb\n", "a\n", "=a;-b;"},
		{"replace middle", "a\nb\nc\n", "a\nx\nc\n", "=a;-b;+x;=c;"},
		{"from empty", "", "a\n", "+a;"},
		{"to empty", "a\n", "", "-a;"},
		{"both empty", "", "", ""},
		{"no trailing newline", "a\nb", "a\nc", "=a;-b;+c;"},
	}
	for _, tc := range cases {
		got, exact := DiffLines(tc.old, tc.new)
		uassert.True(t, exact, tc.name+" must be exact")
		uassert.Equal(t, tc.want, render(got), tc.name)
	}
}

func TestDiffStat(t *testing.T) {
	lines, _ := DiffLines("a\nb\nc\n", "a\nx\ny\nc\n")
	added, removed := DiffStat(lines)
	uassert.Equal(t, 2, added)
	uassert.Equal(t, 1, removed)
}

// TestDiffCommonPrefixKeepsLongArticlesExact is the property that makes the
// DiffMaxLines bound usable in practice: a one-line edit to a 500-line article
// still diffs exactly, because only the changed region is fed to the LCS.
func TestDiffCommonPrefixKeepsLongArticlesExact(t *testing.T) {
	var b strings.Builder
	for i := 0; i < 500; i++ {
		b.WriteString("line\n")
	}
	old := b.String()
	updated := old + "added\n"

	lines, exact := DiffLines(old, updated)
	uassert.True(t, exact, "a one-line change to a 500-line article must diff exactly")
	added, removed := DiffStat(lines)
	uassert.Equal(t, 1, added)
	uassert.Equal(t, 0, removed)
}

// TestDiffDegradesInsteadOfBlowingTheGasBudget locks the documented fallback:
// past DiffMaxLines the diff becomes a block replacement rather than an
// unrenderable page.
func TestDiffDegradesInsteadOfBlowingTheGasBudget(t *testing.T) {
	var a, b strings.Builder
	for i := 0; i < DiffMaxLines+1; i++ {
		a.WriteString("old\n")
		b.WriteString("new\n")
	}
	lines, exact := DiffLines(a.String(), b.String())
	uassert.False(t, exact, "past the bound the diff must report itself inexact")
	added, removed := DiffStat(lines)
	uassert.Equal(t, DiffMaxLines+1, added)
	uassert.Equal(t, DiffMaxLines+1, removed)
}

doc.gno

// Package wiki is a Wikipedia-shaped wiki engine for gno.land: namespaced
// titles, an append-only revision chain, wikilinks with backlinks, categories,
// redirects, protection levels, line diffs, and markdown rendering.
//
// It is pure: no realm globals, no chain imports. Every call takes the context
// it needs (author address, wall clock, block height) from the caller, so the
// whole engine is unit-testable off-chain. The live demo realm is
// gno.land/r/nym-moultest123/x/wiki/v0.
//
// # Storage model
//
// A realm write locks a storage deposit proportional to the bytes it adds
// (100ugnot per byte since gnolang/gno#6171), so a wiki that kept every
// revision in full would charge its editors for the whole history forever.
// This engine instead stores a content-addressed spine plus a bounded body
// window:
//
//   - Every revision keeps its metadata permanently: id, parent, author,
//     time, height, summary, byte size, and the SHA-256 of the body. That is
//     roughly 200 bytes, independent of article size.
//   - Only the newest Retention revisions of a page keep their body. Older
//     bodies are evicted (set to ""), which releases their deposit.
//
// An evicted body is not lost: its bytes were an argument of the transaction
// that wrote it, so they remain in the chain's transaction history, and the
// retained hash proves which bytes were the real ones. The realm stops paying
// rent for deep history; the archive lives where archives belong.
//
// # Untrusted markdown
//
// Article bodies are attacker-controlled markdown. Render passes every body
// through gno.land/p/nt/markdown/sanitize/v0 before any wikilink rewriting,
// never after: sanitize escapes "[" to "\\[", so a rewriter that ran first
// would hand its own generated links to the escaper. See links.gno.
package wiki

gnomod.toml

module = "gno.land/p/nym-moultest123/x/wiki/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186410
  max_deposit = "42000000ugnot"

limits_test.gno

package wiki

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

// maxLines is how many typical lines fit in DefaultMaxBody: 32 KiB at 43
// bytes per line.
const maxLines = 758

func buildLines(n int) string {
	var b strings.Builder
	for i := 0; i < n; i++ {
		b.WriteString("some article line of moderate length here.\n")
	}
	return b.String()
}

// TestWorstCaseRendersStayWithinTheQueryBudget exercises the two render paths
// at the largest body MaxBody admits.
//
// vm/qrender runs under a fixed ceiling (maxGasQuery = 3e9 in
// gno.land/pkg/sdk/vm/keeper.go), which a reader cannot raise, so a render
// that exceeds it makes the page permanently unreadable. Measured with
// `gno test -v` on gno master.184 (2026-09-17):
//
//	diff of a 33 KB body against itself plus one line    691M gas   23% of the ceiling
//	article render of a 33 KB body with links            693M gas   23% of the ceiling
//
// gno test reports gas per test function but a test cannot assert on it, so
// this test pins the shape, not the number: it fails if either path starts
// panicking or truncating at the limit. Re-measure with `gno test -v` and
// update the table when either path changes.
func TestWorstCaseRendersStayWithinTheQueryBudget(t *testing.T) {
	w := New(3, DefaultMaxBody)
	body := buildLines(maxLines-2) + "see [[Other page]]\n[[Category:Big]]\n"
	uassert.True(t, len(body) < DefaultMaxBody, "the fixture must fit in MaxBody")

	now, h := at(1)
	_, err := w.Edit(alice, now, h, "Big", body, "", false)
	uassert.NoError(t, err)

	p, err := w.Page("Big")
	uassert.NoError(t, err)

	c := Ctx{Base: "/r/nym-moultest123/x/wiki/v0", Exists: w.Exists}
	uassert.True(t, len(RenderArticle(c, w, p, nil)) > len(body), "the article must render in full")

	now, h = at(2)
	_, err = w.Edit(alice, now, h, "Big", body+"added\n", "", false)
	uassert.NoError(t, err)

	hist := p.History(0, 2)
	out := RenderDiff(c, p, hist[1], hist[0])
	uassert.True(t, strings.Contains(out, "+1 −0 lines"), "a one-line append to a 32 KiB body diffs exactly")
}

links.gno

package wiki

import (
	"strings"

	"gno.land/p/nt/markdown/sanitize/v0"
)

// Link is one wikilink occurrence in a body.
type Link struct {
	Target   string // target text as written, before ParseTitle
	Label    string // display text; "" means render the target
	Explicit bool   // written [[:Category:X]]: link to the category, do not join it
	Start    int    // byte offset of the opening delimiter
	End      int    // byte offset just past the closing delimiter
}

// ScanLinks finds every [[target|label]] occurrence delimited by open and
// close.
//
// The delimiters are parameters because the same syntax has to be found twice
// with different bytes. Indexing reads the raw body, where a link is
// "[[X]]". Rendering reads the body after sanitize.BlockRich, where the very
// same link is "\[\[X\]\]" because the sanitizer escapes every "[". Rendering
// must sanitize first and rewrite second: a rewriter that ran first would
// hand the markdown links it just generated to the escaper, and every link on
// the wiki would render as literal text.
//
// A link whose inner text spans a newline or is empty is not a link. When a
// nearer opener appears inside the inner text, scanning restarts from it, so
// "[[a [[b]]" yields b rather than a mis-parsed a.
func ScanLinks(s, openTok, closeTok string) []Link {
	out := []Link{}
	i := 0
	for i < len(s) {
		a := strings.Index(s[i:], openTok)
		if a < 0 {
			break
		}
		a += i
		rest := a + len(openTok)
		b := strings.Index(s[rest:], closeTok)
		if b < 0 {
			break
		}
		b += rest

		inner := s[rest:b]
		if n := strings.Index(inner, openTok); n >= 0 {
			i = rest + n
			continue
		}
		i = b + len(closeTok)
		if inner == "" || strings.Contains(inner, "\n") {
			continue
		}

		l := Link{Start: a, End: i}
		if p := strings.Index(inner, "|"); p >= 0 {
			l.Target = strings.TrimSpace(inner[:p])
			l.Label = strings.TrimSpace(inner[p+1:])
		} else {
			l.Target = strings.TrimSpace(inner)
		}
		if strings.HasPrefix(l.Target, ":") {
			l.Explicit = true
			l.Target = strings.TrimSpace(l.Target[1:])
		}
		if l.Target == "" {
			continue
		}
		out = append(out, l)
	}
	return out
}

// redirectTarget returns the canonical title a body redirects to, or "".
// The syntax is MediaWiki's: "#REDIRECT [[Target]]" on the first line.
func redirectTarget(body string) string {
	line := body
	if i := strings.Index(line, "\n"); i >= 0 {
		line = line[:i]
	}
	line = strings.TrimSpace(line)
	if len(line) < len("#REDIRECT") || !strings.EqualFold(line[:len("#REDIRECT")], "#REDIRECT") {
		return ""
	}
	links := ScanLinks(line, "[[", "]]")
	if len(links) == 0 {
		return ""
	}
	t, err := ParseTitle(links[0].Target)
	if err != nil {
		return ""
	}
	return t.String()
}

// Ctx carries what rendering needs from the realm: where the realm lives, and
// which titles exist. Its function fields are read during a single Render call
// and never stored, so no closure is ever persisted.
type Ctx struct {
	Base   string            // realm path prefix, e.g. "/r/nym-moultest123/x/wiki/v0"
	Exists func(Title) bool // nil treats every title as existing
}

func (c Ctx) exists(t Title) bool {
	if c.Exists == nil {
		return true
	}
	return c.Exists(t)
}

// URL is the render path of a title under this realm.
func (c Ctx) URL(t Title) string { return c.Sub(t, "") }

// Sub is the render path of a sub-route of a title, e.g. "history".
func (c Ctx) Sub(t Title, route string) string {
	u := c.Base + ":" + t.Slug()
	if route != "" {
		u += "/" + route
	}
	return escapeURL(u)
}

// SpecialURL is the render path of a Special: page.
func (c Ctx) SpecialURL(name, query string) string {
	u := c.Base + ":Special:" + name
	if query != "" {
		u += "?" + query
	}
	return escapeURL(u)
}

// escapeURL percent-encodes the characters a title may contain that would
// otherwise terminate a markdown link destination or split a path. Titles
// admit "(", ")", " ", "'" and "," (see validTitleRune), and an unencoded ")"
// ends the "(...)" of a markdown link at the first occurrence, which turns
// [[Mercury (planet)]] into a broken link plus stray text.
func escapeURL(u string) string {
	r := strings.NewReplacer(
		" ", "%20",
		"(", "%28",
		")", "%29",
		"'", "%27",
		",", "%2C",
	)
	return sanitize.URL(r.Replace(u))
}

// RewriteLinks turns the wikilinks of an already-sanitized body into markdown
// links. Category declarations are removed from the flow: membership is shown
// by the rendered footer, not inline, which is also what MediaWiki does.
//
// s MUST be the output of sanitize.BlockRich or sanitize.Block, and open/close
// MUST be the escaped delimiters. Passing a raw body here would emit links
// built from unsanitized bytes.
func RewriteLinks(c Ctx, s string) string {
	links := ScanLinks(s, `\[\[`, `\]\]`)
	if len(links) == 0 {
		return s
	}
	var out strings.Builder
	prev := 0
	for _, l := range links {
		out.WriteString(s[prev:l.Start])
		prev = l.End

		t, err := ParseTitle(unescapeInline(l.Target))
		if err != nil {
			// Not a usable title: leave the sanitized text in place. It is
			// already escaped, so it renders as the literal brackets the
			// author typed.
			out.WriteString(s[l.Start:l.End])
			continue
		}
		if t.NS == NSCategory && !l.Explicit {
			continue
		}
		label := l.Label
		if label == "" {
			label = t.String()
		}
		if c.exists(t) {
			out.WriteString("[" + label + "](" + c.URL(t) + ")")
		} else {
			// A red link: the page does not exist yet. Point at the same
			// path, which renders the "create this page" stub.
			out.WriteString("[" + label + "](" + c.URL(t) + ") ⁺")
		}
	}
	out.WriteString(s[prev:])
	return out.String()
}

// unescapeInline undoes the backslash escaping the sanitizer applies inside a
// link's inner text, so ParseTitle sees the title the author typed.
func unescapeInline(s string) string {
	if !strings.Contains(s, `\`) {
		return s
	}
	var b strings.Builder
	for i := 0; i < len(s); i++ {
		if s[i] == '\\' && i+1 < len(s) {
			i++
		}
		b.WriteByte(s[i])
	}
	return b.String()
}

links_test.gno

package wiki

import (
	"testing"

	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/uassert/v0"
)

func TestScanLinks(t *testing.T) {
	cases := []struct {
		name      string
		in        string
		targets   []string
		labels    []string
		explicits []bool
	}{
		{"none", "plain text", nil, nil, nil},
		{"one", "see [[Gno land]] here", []string{"Gno land"}, []string{""}, []bool{false}},
		{"labelled", "[[Gno land|the chain]]", []string{"Gno land"}, []string{"the chain"}, []bool{false}},
		{"two", "[[A]] and [[B]]", []string{"A", "B"}, []string{"", ""}, []bool{false, false}},
		{"category", "[[Category:Chains]]", []string{"Category:Chains"}, []string{""}, []bool{false}},
		{"explicit category", "[[:Category:Chains]]", []string{"Category:Chains"}, []string{""}, []bool{true}},
		{"whitespace is trimmed", "[[  A  |  b  ]]", []string{"A"}, []string{"b"}, []bool{false}},
		{"unclosed is not a link", "[[A", nil, nil, nil},
		{"empty is not a link", "[[]]", nil, nil, nil},
		{"newline inside is not a link", "[[A\nB]]", nil, nil, nil},
		{"nested opener wins", "[[a [[b]]", []string{"b"}, []string{""}, []bool{false}},
	}
	for _, tc := range cases {
		got := ScanLinks(tc.in, "[[", "]]")
		if !uassert.Equal(t, len(tc.targets), len(got), tc.name) {
			continue
		}
		for i, l := range got {
			uassert.Equal(t, tc.targets[i], l.Target, tc.name)
			uassert.Equal(t, tc.labels[i], l.Label, tc.name)
			uassert.Equal(t, tc.explicits[i], l.Explicit, tc.name)
		}
	}
}

func TestScanLinksOffsets(t *testing.T) {
	in := "see [[A]] end"
	got := ScanLinks(in, "[[", "]]")
	uassert.Equal(t, 1, len(got))
	uassert.Equal(t, "[[A]]", in[got[0].Start:got[0].End])
}

// TestScanLinksAfterSanitize is the reason ScanLinks takes its delimiters as
// parameters: the sanitizer escapes every "[", so the rendering pass has to
// look for a different byte sequence than the indexing pass.
func TestScanLinksAfterSanitize(t *testing.T) {
	escaped := sanitize.BlockRich("see [[Gno land|the chain]] here\n")
	uassert.Equal(t, 0, len(ScanLinks(escaped, "[[", "]]")),
		"the raw delimiters must find nothing in sanitized text")
	got := ScanLinks(escaped, `\[\[`, `\]\]`)
	uassert.Equal(t, 1, len(got))
	uassert.Equal(t, "Gno land", got[0].Target)
	uassert.Equal(t, "the chain", got[0].Label)
}

func TestRedirectTarget(t *testing.T) {
	cases := []struct{ in, want string }{
		{"#REDIRECT [[Gno land]]\n", "Gno land"},
		{"#redirect [[gno_land]]", "Gno land"},
		{"  #REDIRECT   [[User:Gno land]]  \nrest", "User:Gno land"},
		{"not a redirect [[Gno land]]", ""},
		{"#REDIRECT no link", ""},
		{"#REDIRECT [[bad|title]]", "Bad"},
		{"text\n#REDIRECT [[Gno land]]", ""},
		{"", ""},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, redirectTarget(tc.in), tc.in)
	}
}

func TestRewriteLinks(t *testing.T) {
	c := Ctx{
		Base:   "/r/nym-moultest123/x/wiki/v0",
		Exists: func(tt Title) bool { return tt.Name == "Gno land" },
	}

	body := sanitize.BlockRich("See [[Gno land]], [[Missing page]] and [[Gno land|the chain]].\n" +
		"[[Category:Chains]]\n")
	got := RewriteLinks(c, body)

	uassert.True(t, contains(got, "[Gno land](/r/nym-moultest123/x/wiki/v0:Gno_land)"), "existing page links plainly")
	uassert.True(t, contains(got, "[Missing page](/r/nym-moultest123/x/wiki/v0:Missing_page) ⁺"), "a redlink is marked")
	uassert.True(t, contains(got, "[the chain](/r/nym-moultest123/x/wiki/v0:Gno_land)"), "labels are honored")
	uassert.False(t, contains(got, "Category:Chains"), "category declarations leave the flow")
}

func TestRewriteLinksEscapesURLs(t *testing.T) {
	c := Ctx{Base: "/r/nym-moultest123/x/wiki/v0"}
	got := RewriteLinks(c, sanitize.BlockRich("[[Mercury (planet)]]\n"))
	// An unescaped ")" would terminate the markdown destination early and
	// leave "planet))" as visible text.
	uassert.True(t, contains(got, "(/r/nym-moultest123/x/wiki/v0:Mercury_%28planet%29)"), got)
}

func TestRewriteLinksLeavesNonTitlesAlone(t *testing.T) {
	c := Ctx{Base: "/r/nym-moultest123/x/wiki/v0"}
	// "[[ ]]" has no usable target, and "[[a/b]]" is not a legal title: both
	// must render as the literal text the author typed, never as a link.
	got := RewriteLinks(c, sanitize.BlockRich("[[a/b]]\n"))
	uassert.True(t, contains(got, `\[\[a/b\]\]`), got)
}

func contains(haystack, needle string) bool {
	for i := 0; i+len(needle) <= len(haystack); i++ {
		if haystack[i:i+len(needle)] == needle {
			return true
		}
	}
	return false
}

page.gno

package wiki

import (
	"time"

	"gno.land/p/nym-moultest123/ulist/v0"
)

// Protection is a page's edit gate. The engine stores it and reports it; it
// never enforces it, because authority belongs to the realm that owns the
// wiki, not to a pure library. See Wiki.Edit.
type Protection uint8

const (
	Open          Protection = iota // anyone the realm lets through
	SemiProtected                   // realm-defined trusted editors
	Locked                          // stewards only
)

// String returns the protection level's display name.
func (p Protection) String() string {
	switch p {
	case SemiProtected:
		return "semi-protected"
	case Locked:
		return "locked"
	default:
		return "open"
	}
}

// ParseProtection maps a user-supplied level name onto a Protection.
func ParseProtection(s string) (Protection, error) {
	switch s {
	case "open", "":
		return Open, nil
	case "semi", "semi-protected":
		return SemiProtected, nil
	case "locked":
		return Locked, nil
	}
	return Open, ErrBadProtection
}

// Page is one title's history plus the indexes derived from its current
// revision. Revisions live in a ulist: append is O(1) and does not rewrite the
// existing entries, which matters when a popular page accumulates thousands of
// edits and every write would otherwise re-serialize the whole slice.
type Page struct {
	Title      Title
	Protection Protection
	Created    time.Time
	Blanked    bool // a steward blanked it; history is retained

	revs *ulist.List // *Revision, oldest first
	head *Revision

	redirect string   // target title, "" when this page is not a redirect
	links    []string // outgoing wikilink target keys of head
	cats     []string // category keys head belongs to
}

// Head returns the current revision, or nil for a page with no revisions.
func (p *Page) Head() *Revision { return p.head }

// NumRevisions returns how many revisions the page has.
func (p *Page) NumRevisions() int { return p.revs.Size() }

// Redirect returns the title this page redirects to, or "" if it does not.
func (p *Page) Redirect() string { return p.redirect }

// Body returns the current text and whether it is held on chain.
func (p *Page) Body() (string, bool) {
	if p.head == nil {
		return "", false
	}
	return p.head.Body()
}

// Revision returns the revision with the given id, or nil.
func (p *Page) Revision(id uint64) *Revision {
	var found *Revision
	p.revs.Iterator(0, p.revs.Size()-1, func(_ int, v any) bool {
		r := v.(*Revision)
		if r.ID == id {
			found = r
			return true
		}
		return false
	})
	return found
}

// History returns up to count revisions, newest first, skipping the newest
// offset of them.
func (p *Page) History(offset, count int) []*Revision {
	out := []*Revision{}
	if count <= 0 {
		return out
	}
	size := p.revs.Size()
	// Walk backwards: index size-1 is the newest.
	for i := size - 1 - offset; i >= 0 && len(out) < count; i-- {
		out = append(out, p.revs.MustGet(i).(*Revision))
	}
	return out
}

// Contributors returns the distinct authors of the page, oldest edit first.
func (p *Page) Contributors() []address {
	seen := map[string]bool{}
	out := []address{}
	p.revs.Iterator(0, p.revs.Size()-1, func(_ int, v any) bool {
		r := v.(*Revision)
		if !seen[r.Author.String()] {
			seen[r.Author.String()] = true
			out = append(out, r.Author)
		}
		return false
	})
	return out
}

render.gno

package wiki

import (
	"strings"

	"gno.land/p/nym-moultest123/md/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/ufmt/v0"
)

// DepositPerByte is the storage deposit a realm write locks per byte, in
// ugnot (gnolang/gno#6171). It is used only to show a reader what a page
// costs; the chain, not this package, does the accounting.
const DepositPerByte = 100

// Action builds a transaction link for a realm function. The realm supplies
// it (txlink.Realm("…").Call is the usual value); a nil Action renders a page
// with no edit controls, which is what an archived or read-only mirror wants.
type Action func(fn string, args ...string) string

// RenderArticle renders a page for reading: the sanitized body with its
// wikilinks resolved, a header identifying the current revision, and a footer
// with categories and cost.
func RenderArticle(c Ctx, w *Wiki, p *Page, act Action) string {
	var out strings.Builder
	out.WriteString(md.H1(p.Title.String()))

	if p.head == nil {
		out.WriteString(md.Paragraph("_This page has no revisions._"))
		return out.String()
	}
	out.WriteString(articleMeta(c, w, p, act))

	if p.Blanked {
		out.WriteString(md.Blockquote("This page was blanked. Its history is still on chain: " +
			md.Link("view history", c.Sub(p.Title, "history"))))
		return out.String()
	}

	body, kept := p.Body()
	switch {
	case !kept:
		out.WriteString(md.Blockquote("The current revision's body is no longer held on chain. " +
			"Recover it from the transaction that wrote it and check it against `" + p.head.ShortHash() + "`."))
	case p.redirect != "":
		out.WriteString(md.Paragraph("Redirects to " + md.Link(p.redirect, escapeURL(c.Base+":"+strings.ReplaceAll(p.redirect, " ", "_")))))
	default:
		// sanitize.BlockRich wraps its output in blank lines on both sides,
		// and that padding is load-bearing: a CommonMark HTML block of type
		// 6 or 7 is not escaped in any mode, and without the blank line it
		// would swallow the footer this function appends next. Do not trim
		// it to tidy the output.
		out.WriteString(RewriteLinks(c, sanitize.BlockRich(body)))
	}

	out.WriteString(articleFooter(c, w, p))
	return out.String()
}

func articleMeta(c Ctx, w *Wiki, p *Page, act Action) string {
	h := p.head
	parts := []string{
		ufmt.Sprintf("rev %d", h.ID),
		h.Time.Format("2006-01-02 15:04"),
		"by " + shortAddr(h.Author),
	}
	if p.Protection != Open {
		parts = append(parts, p.Protection.String())
	}
	line := strings.Join(parts, " · ")

	nav := []string{
		md.Link("history", c.Sub(p.Title, "history")),
		md.Link("source", c.Sub(p.Title, "raw")),
		md.Link("what links here", c.SpecialURL("Backlinks", "page="+p.Title.Slug())),
	}
	if act != nil {
		nav = append(nav, md.Link("edit", act("Edit", "title", p.Title.String())))
	}
	// The count sits outside the link text on purpose: md.Link sanitizes its
	// label, so parentheses inside it would render as "\(1\)".
	nav = append(nav, md.Link("discussion", c.Sub(p.Title, "talk"))+
		ufmt.Sprintf(" (%d)", w.NumComments(p.Title)))
	return md.Paragraph(line + "\n\n" + strings.Join(nav, " · "))
}

func articleFooter(c Ctx, w *Wiki, p *Page) string {
	var out strings.Builder
	out.WriteString(md.HorizontalRule())

	if len(p.cats) > 0 {
		cats := []string{}
		for _, key := range p.cats {
			t := Title{NS: NSCategory, Name: key[len(NSCategory.Prefix()):]}
			cats = append(cats, md.Link(t.Name, c.URL(t)))
		}
		out.WriteString(md.Paragraph("**Categories:** " + strings.Join(cats, " · ")))
	}

	held := 0
	p.revs.Iterator(0, p.revs.Size()-1, func(_ int, v any) bool {
		r := v.(*Revision)
		if r.kept {
			held += r.Size
		}
		return false
	})
	out.WriteString(md.Paragraph(ufmt.Sprintf(
		"%s · %d bytes of text held on chain · %s of storage deposit · %s link here",
		plural(p.NumRevisions(), "revision", "revisions"),
		held, formatGNOT(held*DepositPerByte),
		plural(len(w.Backlinks(p.Title)), "page", "pages"))))
	return out.String()
}

// RenderMissing renders the stub shown for a title with no page: the red-link
// destination, listing whoever already points at it.
func RenderMissing(c Ctx, w *Wiki, t Title, act Action) string {
	var out strings.Builder
	out.WriteString(md.H1(t.String()))
	out.WriteString(md.Paragraph("_This page does not exist yet._"))
	if act != nil {
		out.WriteString(md.Paragraph(md.Link("Create it", act("Edit", "title", t.String()))))
	}
	if in := w.Backlinks(t); len(in) > 0 {
		out.WriteString(md.H2("Pages that already link here"))
		out.WriteString(titleList(c, in))
	}
	return out.String()
}

// RenderHistory renders a page's revision list, newest first.
func RenderHistory(c Ctx, p *Page, offset, count int, act Action) string {
	var out strings.Builder
	out.WriteString(md.H1("History of " + p.Title.String()))
	out.WriteString(md.Paragraph(md.Link("← back to the article", c.URL(p.Title))))

	revs := p.History(offset, count)
	if len(revs) == 0 {
		out.WriteString(md.Paragraph("_No revisions in this range._"))
		return out.String()
	}
	items := []string{}
	for _, r := range revs {
		line := ufmt.Sprintf("**rev %d** · %s · %s · %s · %d bytes · `%s`",
			r.ID, r.Time.Format("2006-01-02 15:04"), shortAddr(r.Author), string(r.Kind), r.Size, r.ShortHash())
		if r.Summary != "" {
			line += "\n\n" + sanitize.InlineText(r.Summary)
		}
		extra := []string{}
		if r.Prev != 0 {
			extra = append(extra, md.Link("diff", c.Sub(p.Title, "diff")+"?from="+ufmt.Sprintf("%d", r.Prev)+"&to="+ufmt.Sprintf("%d", r.ID)))
		}
		if r.kept {
			extra = append(extra, md.Link("view", c.Sub(p.Title, "rev")+"/"+ufmt.Sprintf("%d", r.ID)))
			if act != nil {
				extra = append(extra, md.Link("revert to this", act("Revert",
					"title", p.Title.String(), "rev", ufmt.Sprintf("%d", r.ID))))
			}
		} else {
			extra = append(extra, "_body evicted_")
		}
		items = append(items, line+"\n\n"+strings.Join(extra, " · "))
	}
	out.WriteString(md.BulletList(items))

	if offset+len(revs) < p.NumRevisions() {
		out.WriteString(md.Paragraph(md.Link("older →",
			c.Sub(p.Title, "history")+"?offset="+ufmt.Sprintf("%d", offset+count))))
	}
	return out.String()
}

// RenderRevision renders one stored revision verbatim.
func RenderRevision(c Ctx, p *Page, r *Revision) string {
	var out strings.Builder
	out.WriteString(md.H1(ufmt.Sprintf("%s: revision %d", p.Title.String(), r.ID)))
	out.WriteString(md.Paragraph(ufmt.Sprintf("%s · %s · `%s`",
		r.Time.Format("2006-01-02 15:04"), shortAddr(r.Author), r.Hash)))
	body, kept := r.Body()
	if !kept {
		out.WriteString(md.Blockquote("This revision's body is no longer held on chain."))
		return out.String()
	}
	out.WriteString(RewriteLinks(c, sanitize.BlockRich(body)))
	return out.String()
}

// RenderRaw renders a revision's source inside a code block, which is what a
// reader needs before editing and what a verifier needs to re-hash.
func RenderRaw(c Ctx, p *Page, r *Revision) string {
	var out strings.Builder
	out.WriteString(md.H1(ufmt.Sprintf("Source of %s (rev %d)", p.Title.String(), r.ID)))
	out.WriteString(md.Paragraph("sha256 `" + r.Hash + "`"))
	body, kept := r.Body()
	if !kept {
		out.WriteString(md.Blockquote("This revision's body is no longer held on chain."))
		return out.String()
	}
	out.WriteString(sanitize.CodeBlock(body))
	out.WriteString(md.Paragraph(md.Link("← back to the article", c.URL(p.Title))))
	return out.String()
}

// RenderDiff renders the line diff between two revisions of a page.
func RenderDiff(c Ctx, p *Page, from, to *Revision) string {
	var out strings.Builder
	out.WriteString(md.H1(ufmt.Sprintf("%s: rev %d → rev %d", p.Title.String(), from.ID, to.ID)))

	a, okA := from.Body()
	b, okB := to.Body()
	if !okA || !okB {
		out.WriteString(md.Blockquote("One of these revisions' bodies is no longer held on chain, so the diff cannot be computed. " +
			"Their hashes are `" + from.ShortHash() + "` and `" + to.ShortHash() + "`."))
		return out.String()
	}

	lines, exact := DiffLines(a, b)
	added, removed := DiffStat(lines)
	note := ufmt.Sprintf("+%d −%d lines", added, removed)
	if !exact {
		note += " · changed region larger than " + ufmt.Sprintf("%d", DiffMaxLines) + " lines, shown as a block replacement"
	}
	out.WriteString(md.Paragraph(note))

	var d strings.Builder
	for _, l := range lines {
		switch l.Op {
		case OpInsert:
			d.WriteString("+" + l.Text + "\n")
		case OpDelete:
			d.WriteString("-" + l.Text + "\n")
		default:
			d.WriteString(" " + l.Text + "\n")
		}
	}
	out.WriteString(sanitize.LanguageCodeBlock("diff", d.String()))
	out.WriteString(md.Paragraph(md.Link("← back to the article", c.URL(p.Title))))
	return out.String()
}

// RenderIndex renders the wiki's front page: recent changes and a page count.
func RenderIndex(c Ctx, w *Wiki, recent int) string {
	var out strings.Builder
	s := w.Stats()
	out.WriteString(md.H1("Wiki"))
	out.WriteString(md.Paragraph(strings.Join([]string{
		md.Link("all pages", c.SpecialURL("AllPages", "")),
		md.Link("categories", c.SpecialURL("Categories", "")),
		md.Link("recent changes", c.SpecialURL("RecentChanges", "")),
		md.Link("stats", c.SpecialURL("Stats", "")),
	}, " · ")))
	out.WriteString(md.Paragraph(ufmt.Sprintf("%d pages · %d revisions · %d bytes on chain",
		s.Pages, s.Revisions, s.BytesHeld)))
	out.WriteString(md.H2("Recent changes"))
	out.WriteString(changeList(c, w.Recent(recent)))
	return out.String()
}

// RenderRecent renders the recent-changes feed.
func RenderRecent(c Ctx, w *Wiki, n int) string {
	return md.H1("Recent changes") + changeList(c, w.Recent(n))
}

// RenderAllPages renders the page index for a namespace prefix.
func RenderAllPages(c Ctx, w *Wiki, ns Namespace, offset, count int) string {
	var out strings.Builder
	out.WriteString(md.H1("All pages"))

	tabs := []string{}
	for i := range namespaces {
		n := Namespace(i)
		if n == NSSpecial {
			continue
		}
		label := n.String()
		if label == "" {
			label = "Articles"
		}
		if n == ns {
			label = "**" + label + "**"
		}
		tabs = append(tabs, md.Link(label, c.SpecialURL("AllPages", "ns="+ufmt.Sprintf("%d", i))))
	}
	out.WriteString(md.Paragraph(strings.Join(tabs, " · ")))

	titles := w.Titles(ns.Prefix(), offset, count)
	if len(titles) == 0 {
		out.WriteString(md.Paragraph("_No pages in this namespace._"))
		return out.String()
	}
	out.WriteString(titleList(c, titles))
	if len(titles) == count {
		out.WriteString(md.Paragraph(md.Link("next →",
			c.SpecialURL("AllPages", ufmt.Sprintf("ns=%d&offset=%d", uint8(ns), offset+count)))))
	}
	return out.String()
}

// RenderCategory renders a category page: its own text, then its members.
func RenderCategory(c Ctx, w *Wiki, t Title, p *Page, act Action) string {
	var out strings.Builder
	if p != nil {
		out.WriteString(RenderArticle(c, w, p, act))
	} else {
		out.WriteString(md.H1(t.String()))
		out.WriteString(md.Paragraph("_This category has no description page._"))
	}
	members := w.CategoryMembers(t)
	out.WriteString(md.H2(ufmt.Sprintf("Pages in this category (%d)", len(members))))
	if len(members) == 0 {
		out.WriteString(md.Paragraph("_None._"))
		return out.String()
	}
	out.WriteString(titleList(c, members))
	return out.String()
}

// RenderCategories lists every category that has at least one member.
func RenderCategories(c Ctx, w *Wiki) string {
	cats := w.Categories()
	var out strings.Builder
	out.WriteString(md.H1("Categories"))
	if len(cats) == 0 {
		out.WriteString(md.Paragraph("_No categories yet._"))
		return out.String()
	}
	items := []string{}
	for _, t := range cats {
		items = append(items, ufmt.Sprintf("%s (%d)", md.Link(t.Name, c.URL(t)), len(w.CategoryMembers(t))))
	}
	out.WriteString(md.BulletList(items))
	return out.String()
}

// RenderBacklinks renders "what links here" for a title.
func RenderBacklinks(c Ctx, w *Wiki, t Title) string {
	var out strings.Builder
	out.WriteString(md.H1("Pages that link to " + t.String()))
	out.WriteString(md.Paragraph(md.Link("← back to the article", c.URL(t))))
	in := w.Backlinks(t)
	if len(in) == 0 {
		out.WriteString(md.Paragraph("_Nothing links here._"))
		return out.String()
	}
	out.WriteString(titleList(c, in))
	return out.String()
}

// RenderStats renders the wiki's size and what it is paying the chain.
func RenderStats(c Ctx, w *Wiki) string {
	s := w.Stats()
	rows := []string{
		ufmt.Sprintf("pages: %d", s.Pages),
		ufmt.Sprintf("revisions: %d", s.Revisions),
		ufmt.Sprintf("comments: %d", s.Comments),
		ufmt.Sprintf("body bytes on chain: %d", s.BytesHeld),
		ufmt.Sprintf("storage deposit locked by bodies: %s", formatGNOT(s.BytesHeld*DepositPerByte)),
		ufmt.Sprintf("bodies kept per page: %d", s.Retention),
	}
	return md.H1("Wiki stats") + md.BulletList(rows)
}

// RenderTalk renders a page's discussion: top-level messages oldest first,
// each with its replies.
func RenderTalk(c Ctx, w *Wiki, p *Page, offset, count int, act Action) string {
	var out strings.Builder
	out.WriteString(md.H1("Discussion: " + p.Title.String()))

	nav := []string{md.Link("← back to the article", c.URL(p.Title))}
	if act != nil {
		nav = append(nav, md.Link("add a message", act("Comment", "title", p.Title.String(), "replyTo", "0")))
	}
	out.WriteString(md.Paragraph(strings.Join(nav, " · ")))

	threads := w.Comments(p.Title, offset, count)
	if len(threads) == 0 {
		out.WriteString(md.Paragraph("_No messages yet._"))
		return out.String()
	}

	items := []string{}
	for _, th := range threads {
		item := commentLine(c, th.Root, act, p.Title)
		for _, r := range th.Replies {
			item += "\n" + md.Nested(commentLine(c, r, nil, p.Title), "  - ")
		}
		items = append(items, item)
	}
	out.WriteString(md.BulletList(items))

	total := w.NumComments(p.Title)
	if offset+len(threads) < total {
		out.WriteString(md.Paragraph(md.Link("older →",
			c.Sub(p.Title, "talk")+"?offset="+ufmt.Sprintf("%d", offset+count))))
	}
	return out.String()
}

func commentLine(c Ctx, cm *Comment, act Action, t Title) string {
	head := ufmt.Sprintf("**#%d** · %s · %s",
		cm.ID, cm.Time.Format("2006-01-02 15:04"), shortAddr(cm.Author))
	if cm.Hidden {
		return head + "\n\n_This message was removed by a steward._"
	}
	body := sanitize.Block(cm.Body)
	if act != nil {
		body += "\n\n" + md.Link("reply", act("Comment",
			"title", t.String(), "replyTo", ufmt.Sprintf("%d", cm.ID)))
	}
	return head + body
}

func titleList(c Ctx, titles []Title) string {
	items := []string{}
	for _, t := range titles {
		items = append(items, md.Link(t.String(), c.URL(t)))
	}
	return md.BulletList(items)
}

func changeList(c Ctx, changes []*Change) string {
	if len(changes) == 0 {
		return md.Paragraph("_Nothing has happened yet._")
	}
	items := []string{}
	for _, ch := range changes {
		line := ufmt.Sprintf("%s · %s · %s · %s · rev %d",
			md.Link(ch.Title.String(), c.URL(ch.Title)),
			string(ch.Rev.Kind),
			ch.Rev.Time.Format("2006-01-02 15:04"),
			shortAddr(ch.Rev.Author),
			ch.Rev.ID)
		if ch.Rev.Summary != "" {
			line += " · " + sanitize.InlineText(ch.Rev.Summary)
		}
		items = append(items, line)
	}
	return md.BulletList(items)
}

// shortAddr abbreviates an address for display without losing its prefix.
func shortAddr(a address) string {
	s := a.String()
	if len(s) <= 12 {
		return "`" + s + "`"
	}
	return "`" + s[:10] + "…" + s[len(s)-4:] + "`"
}

// formatGNOT renders a ugnot amount as GNOT.
//
// The zero padding is written out by hand: gno's ufmt supports no width or
// padding flags, so ufmt.Sprintf("%06d", 42) returns "42" silently and the
// fractional part of every amount would be wrong by three orders of magnitude.
func formatGNOT(ugnot int) string {
	whole := ugnot / 1000000
	frac := ugnot % 1000000
	s := ufmt.Sprintf("%d", frac)
	for len(s) < 6 {
		s = "0" + s
	}
	s = strings.TrimRight(s, "0")
	if s == "" {
		return ufmt.Sprintf("%d GNOT", whole)
	}
	return ufmt.Sprintf("%d.%s GNOT", whole, s)
}

// plural renders "1 revision" and "2 revisions".
func plural(n int, one, many string) string {
	if n == 1 {
		return ufmt.Sprintf("%d %s", n, one)
	}
	return ufmt.Sprintf("%d %s", n, many)
}

render_test.gno

package wiki

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func fixture(t *testing.T) (*Wiki, Ctx) {
	t.Helper()
	w := New(2, DefaultMaxBody)
	edit(t, w, 1, alice, "Gno land", "A chain.\n\nSee [[Tendermint2]] and [[Absent page]].\n\n[[Category:Chains]]\n", "create")
	edit(t, w, 2, bob, "Gno land", "A smart-contract chain.\n\nSee [[Tendermint2]].\n\n[[Category:Chains]]\n", "tighten")
	edit(t, w, 3, alice, "Tendermint2", "The consensus engine.\n", "create")
	return w, Ctx{Base: "/r/nym-moultest123/x/wiki/v0", Exists: w.Exists}
}

func act(fn string, args ...string) string {
	out := "/r/nym-moultest123/x/wiki/v0$help&func=" + fn
	for i := 0; i+1 < len(args); i += 2 {
		out += "&" + args[i] + "=" + args[i+1]
	}
	return out
}

func TestRenderArticle(t *testing.T) {
	w, c := fixture(t)
	p, _ := w.Page("Gno land")
	out := RenderArticle(c, w, p, act)

	uassert.True(t, strings.Contains(out, "# Gno land"), "heading")
	uassert.True(t, strings.Contains(out, "A smart-contract chain."), "body text")
	uassert.True(t, strings.Contains(out, "[Tendermint2](/r/nym-moultest123/x/wiki/v0:Tendermint2)"), "resolved wikilink")
	uassert.False(t, strings.Contains(out, "[[Tendermint2]]"), "no raw wikilink survives")
	uassert.True(t, strings.Contains(out, "**Categories:**"), "category footer")
	uassert.True(t, strings.Contains(out, "[Chains](/r/nym-moultest123/x/wiki/v0:Category:Chains)"), "category link")
	uassert.True(t, strings.Contains(out, "func=Edit"), "edit action")
	uassert.True(t, strings.Contains(out, "GNOT of storage deposit"), "cost is shown to the reader")
}

func TestRenderArticleWithoutActionsHasNoEditControls(t *testing.T) {
	w, c := fixture(t)
	p, _ := w.Page("Gno land")
	out := RenderArticle(c, w, p, nil)
	uassert.False(t, strings.Contains(out, "func=Edit"), "a nil Action renders a read-only page")
}

func TestRenderArticleEscapesHostileMarkdown(t *testing.T) {
	w := New(2, DefaultMaxBody)
	body := "<script>alert(1)</script>\n\n# Fake realm heading\n"
	edit(t, w, 1, alice, "Hostile", body, "")
	p, _ := w.Page("Hostile")
	out := RenderArticle(Ctx{Base: "/r/nym-moultest123/x/wiki/v0"}, w, p, nil)

	uassert.True(t, strings.Contains(out, `\<script>`),
		"an HTML block is escaped, not dropped: the reader still sees what was written")
	uassert.False(t, strings.Contains(out, "\n<script>"),
		"no unescaped HTML block reaches the renderer")
	// The realm's own footer must still be there: a CommonMark HTML block of
	// type 1-5 does not close on a blank line, so an unescaped one would
	// swallow every byte the realm appends after the body.
	uassert.True(t, strings.Contains(out, "GNOT of storage deposit"),
		"user content cannot absorb the realm chrome that follows it")
}

func TestRenderMissing(t *testing.T) {
	w, c := fixture(t)
	out := RenderMissing(c, w, MustParseTitle("Absent page"), act)
	uassert.True(t, strings.Contains(out, "does not exist yet"))
	uassert.True(t, strings.Contains(out, "func=Edit"))
	// The first revision of Gno land linked here; the second dropped the link,
	// so nothing should be listed.
	uassert.True(t, strings.Contains(out, "does not exist yet"))
}

func TestRenderHistory(t *testing.T) {
	w, c := fixture(t)
	p, _ := w.Page("Gno land")
	out := RenderHistory(c, p, 0, 10, act)

	uassert.True(t, strings.Contains(out, "# History of Gno land"))
	uassert.True(t, strings.Contains(out, "**rev 2**"))
	uassert.True(t, strings.Contains(out, "**rev 1**"))
	uassert.True(t, strings.Contains(out, "from=1&to=2"), "consecutive revisions get a diff link")
	uassert.True(t, strings.Contains(out, "func=Revert"))
}

func TestRenderDiff(t *testing.T) {
	w, c := fixture(t)
	p, _ := w.Page("Gno land")
	h := p.History(0, 2)
	out := RenderDiff(c, p, h[1], h[0])

	uassert.True(t, strings.Contains(out, "rev 1 → rev 2"))
	uassert.True(t, strings.Contains(out, "-A chain."))
	uassert.True(t, strings.Contains(out, "+A smart-contract chain."))
	uassert.True(t, strings.Contains(out, "```diff"))
}

func TestRenderDiffRefusesEvictedBodies(t *testing.T) {
	w := New(1, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "one\n", "")
	edit(t, w, 2, alice, "A", "two\n", "")
	p, _ := w.Page("A")
	h := p.History(0, 2)
	out := RenderDiff(Ctx{Base: "/r/nym-moultest123/x/wiki/v0"}, p, h[1], h[0])
	uassert.True(t, strings.Contains(out, "no longer held on chain"),
		"an evicted body must be explained, not rendered as an empty diff")
}

func TestRenderRawShowsTheHashAReaderNeeds(t *testing.T) {
	w, c := fixture(t)
	p, _ := w.Page("Gno land")
	out := RenderRaw(c, p, p.Head())
	uassert.True(t, strings.Contains(out, p.Head().Hash), "the full hash, so the bytes can be verified")
	uassert.True(t, strings.Contains(out, "[[Tendermint2]]"), "raw view shows the source, unrewritten")
}

func TestRenderIndexAndSpecials(t *testing.T) {
	w, c := fixture(t)

	idx := RenderIndex(c, w, 10)
	uassert.True(t, strings.Contains(idx, "2 pages"))
	uassert.True(t, strings.Contains(idx, "Recent changes"))

	all := RenderAllPages(c, w, NSMain, 0, 10)
	uassert.True(t, strings.Contains(all, "[Gno land]"))
	uassert.True(t, strings.Contains(all, "[Tendermint2]"))

	cats := RenderCategories(c, w)
	uassert.True(t, strings.Contains(cats, "[Chains](/r/nym-moultest123/x/wiki/v0:Category:Chains) (1)"))

	cat := RenderCategory(c, w, MustParseTitle("Category:Chains"), nil, nil)
	uassert.True(t, strings.Contains(cat, "no description page"))
	uassert.True(t, strings.Contains(cat, "Pages in this category (1)"))

	back := RenderBacklinks(c, w, MustParseTitle("Tendermint2"))
	uassert.True(t, strings.Contains(back, "[Gno land]"))

	stats := RenderStats(c, w)
	uassert.True(t, strings.Contains(stats, "bodies kept per page: 2"))
}

func TestRenderBlankedPage(t *testing.T) {
	w, c := fixture(t)
	now, h := at(9)
	w.Blank(mod, now, h, "Gno land", "policy")
	p, _ := w.Page("Gno land")
	out := RenderArticle(c, w, p, nil)
	uassert.True(t, strings.Contains(out, "was blanked"))
	uassert.True(t, strings.Contains(out, "view history"))
}

func TestRenderRedirect(t *testing.T) {
	w, c := fixture(t)
	edit(t, w, 4, alice, "Gno", "#REDIRECT [[Gno land]]\n", "")
	p, _ := w.Page("Gno")
	out := RenderArticle(c, w, p, nil)
	uassert.True(t, strings.Contains(out, "Redirects to [Gno land](/r/nym-moultest123/x/wiki/v0:Gno_land)"))
}

revision.gno

package wiki

import (
	"crypto/sha256"
	"encoding/hex"
	"time"
)

// Kind labels what a revision did, for the recent-changes feed.
type Kind string

const (
	KindCreate  Kind = "create"
	KindEdit    Kind = "edit"
	KindRevert  Kind = "revert"
	KindMove    Kind = "move"
	KindBlank   Kind = "blank"
	KindProtect Kind = "protect"
)

// Revision is one entry in a page's append-only history.
//
// The exported fields are the permanent spine: they are never evicted, and
// they are what makes the history tamper-evident. Hash is the SHA-256 of the
// body bytes as submitted, so a body recovered from transaction history can be
// checked against the chain's own record of it.
//
// body is the only field under a retention policy. When a revision falls out
// of the page's body window it is evicted, which releases the storage deposit
// those bytes locked.
type Revision struct {
	ID      uint64
	Prev    uint64 // 0 for the first revision of a page
	Kind    Kind
	Author  address
	Time    time.Time
	Height  int64
	Summary string
	Hash    string // hex-encoded SHA-256 of the body
	Size    int    // body length in bytes
	Minor   bool

	body string
	kept bool
}

// Body returns the revision's text and whether it is still held on chain. A
// false second return is not corruption: the body aged out of the retention
// window and must be recovered from the transaction that wrote it, then
// checked against Hash.
func (r *Revision) Body() (string, bool) { return r.body, r.kept }

// Kept reports whether this revision's body is still on chain.
func (r *Revision) Kept() bool { return r.kept }

// evict drops the body and returns the number of bytes released.
func (r *Revision) evict() int {
	if !r.kept {
		return 0
	}
	n := len(r.body)
	r.body = ""
	r.kept = false
	return n
}

// hashBody is the content address of a revision body.
func hashBody(body string) string {
	sum := sha256.Sum256([]byte(body))
	return hex.EncodeToString(sum[:])
}

// ShortHash is the first 12 hex characters of Hash, for display.
func (r *Revision) ShortHash() string {
	if len(r.Hash) < 12 {
		return r.Hash
	}
	return r.Hash[:12]
}

// Change is a recent-changes entry: a revision plus the page it landed on.
type Change struct {
	Title Title
	Rev   *Revision
}

talk.gno

package wiki

import (
	"errors"
	"time"

	"gno.land/p/nym-moultest123/ulist/v0"
	"gno.land/p/nt/avl/v0"
)

// MaxCommentLen bounds one comment in bytes.
const MaxCommentLen = 2000

// MaxReplyDepth is 1: a comment replies to a top-level comment, and that is
// all. Deeper nesting needs recursive rendering with no natural bound, which
// is exactly the shape a query gas ceiling punishes.
const MaxReplyDepth = 1

var (
	ErrCommentTooLong = errors.New("wiki: comment exceeds the size limit")
	ErrEmptyComment   = errors.New("wiki: empty comment")
	ErrNoSuchComment  = errors.New("wiki: no such comment")
	ErrReplyToReply   = errors.New("wiki: replies nest one level only")
)

// Comment is one message in a page's discussion.
//
// Discussion is a comment store rather than a "Talk:" article, which is the
// one place this design departs from MediaWiki on purpose. A talk page is an
// article, so the last editor can rewrite what someone else said, and
// moderating one bad message means editing the whole page. An append-only
// store gives each message its own author, its own timestamp and its own
// moderation, and nobody can silently rewrite anyone else's words.
type Comment struct {
	ID     uint64
	Parent uint64 // 0 for a top-level comment
	Author address
	Time   time.Time
	Height int64
	Body   string
	Hidden bool // a steward hid it; Body is cleared and its deposit released
}

// Comment appends a message to a page's discussion. replyTo is 0 for a
// top-level message, or the id of a top-level message to reply to.
//
// The engine does not decide who may comment: as with Edit, that is the
// realm's call. It does enforce the shape, because the shape is what bounds
// the render.
func (w *Wiki) Comment(author address, now time.Time, height int64, raw, body string, replyTo uint64) (*Comment, error) {
	t, err := ParseTitle(raw)
	if err != nil {
		return nil, err
	}
	if !w.Exists(t) {
		return nil, ErrNoSuchPage
	}
	if body == "" {
		return nil, ErrEmptyComment
	}
	if len(body) > MaxCommentLen {
		return nil, ErrCommentTooLong
	}

	list := w.thread(t, true)
	if replyTo != 0 {
		parent := findComment(list, replyTo)
		if parent == nil {
			return nil, ErrNoSuchComment
		}
		if parent.Parent != 0 {
			return nil, ErrReplyToReply
		}
	}

	w.nextComment++
	c := &Comment{
		ID:     w.nextComment,
		Parent: replyTo,
		Author: author,
		Time:   now,
		Height: height,
		Body:   body,
	}
	list.Append(c)
	w.numComments++
	w.bytesHeld += len(body)
	return c, nil
}

// HideComment clears one message's body and returns the bytes released. The
// message itself stays in the thread, so a deleted comment reads as "removed"
// rather than as a gap someone has to reconstruct from block explorers.
func (w *Wiki) HideComment(raw string, id uint64) (int, error) {
	t, err := ParseTitle(raw)
	if err != nil {
		return 0, err
	}
	list := w.thread(t, false)
	if list == nil {
		return 0, ErrNoSuchComment
	}
	c := findComment(list, id)
	if c == nil {
		return 0, ErrNoSuchComment
	}
	if c.Hidden {
		return 0, nil
	}
	n := len(c.Body)
	c.Body = ""
	c.Hidden = true
	w.bytesHeld -= n
	return n, nil
}

// Comments returns up to count top-level messages of a page's discussion,
// oldest first, skipping offset of them, each paired with its replies in the
// order they were written.
func (w *Wiki) Comments(t Title, offset, count int) []*Thread {
	out := []*Thread{}
	list := w.thread(t, false)
	if list == nil || count <= 0 {
		return out
	}

	// One pass to bucket replies by parent, a second to emit top-level
	// messages in order. Buckets live in an avl rather than a map because
	// this feeds a render, and gno map iteration order is unspecified.
	replies := avl.NewTree()
	list.Iterator(0, list.Size()-1, func(_ int, v any) bool {
		c := v.(*Comment)
		if c.Parent == 0 {
			return false
		}
		key := commentKey(c.Parent)
		var bucket []*Comment
		if b := replies.Get(key); b != nil {
			bucket = b.([]*Comment)
		}
		replies.Set(key, append(bucket, c))
		return false
	})

	skipped := 0
	list.Iterator(0, list.Size()-1, func(_ int, v any) bool {
		c := v.(*Comment)
		if c.Parent != 0 {
			return false
		}
		if skipped < offset {
			skipped++
			return false
		}
		th := &Thread{Root: c}
		if b := replies.Get(commentKey(c.ID)); b != nil {
			th.Replies = b.([]*Comment)
		}
		out = append(out, th)
		return len(out) >= count
	})
	return out
}

// Thread is a top-level comment and its replies.
type Thread struct {
	Root    *Comment
	Replies []*Comment
}

// NumComments returns how many messages a page's discussion holds, replies
// and hidden messages included.
func (w *Wiki) NumComments(t Title) int {
	list := w.thread(t, false)
	if list == nil {
		return 0
	}
	return list.Size()
}

// thread returns a page's comment list, creating it when create is set.
func (w *Wiki) thread(t Title, create bool) *ulist.List {
	v := w.talk.Get(t.Key())
	if v != nil {
		return v.(*ulist.List)
	}
	if !create {
		return nil
	}
	list := ulist.New()
	w.talk.Set(t.Key(), list)
	return list
}

func findComment(list *ulist.List, id uint64) *Comment {
	var found *Comment
	list.Iterator(0, list.Size()-1, func(_ int, v any) bool {
		c := v.(*Comment)
		if c.ID == id {
			found = c
			return true
		}
		return false
	})
	return found
}

// commentKey is only ever used as an avl key for reply buckets, where the
// order does not matter, so a plain decimal is fine here. Anything whose
// ordering IS meaningful needs a fixed-width key: see Title.Key.
func commentKey(id uint64) string {
	if id == 0 {
		return "0"
	}
	var b []byte
	for id > 0 {
		b = append([]byte{byte('0' + id%10)}, b...)
		id /= 10
	}
	return string(b)
}

talk_test.gno

package wiki

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func comment(t *testing.T, w *Wiki, n int, author address, title, body string, replyTo uint64) *Comment {
	t.Helper()
	now, h := at(n)
	c, err := w.Comment(author, now, h, title, body, replyTo)
	uassert.NoError(t, err, title)
	return c
}

func TestCommentThreads(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "the article\n", "")

	root1 := comment(t, w, 2, alice, "A", "First point.\n", 0)
	root2 := comment(t, w, 3, bob, "A", "Second point.\n", 0)
	reply := comment(t, w, 4, mod, "A", "Answering the first.\n", root1.ID)

	title := MustParseTitle("A")
	uassert.Equal(t, 3, w.NumComments(title))

	threads := w.Comments(title, 0, 10)
	uassert.Equal(t, 2, len(threads), "replies do not count as threads")
	uassert.Equal(t, uint64(root1.ID), threads[0].Root.ID)
	uassert.Equal(t, 1, len(threads[0].Replies))
	uassert.Equal(t, uint64(reply.ID), threads[0].Replies[0].ID)
	uassert.Equal(t, uint64(root2.ID), threads[1].Root.ID)
	uassert.Equal(t, 0, len(threads[1].Replies))

	uassert.Equal(t, 1, len(w.Comments(title, 1, 10)), "offset skips whole threads")
}

func TestCommentRejectsBadInput(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "the article\n", "")
	now, h := at(2)

	_, err := w.Comment(alice, now, h, "Missing page", "hi\n", 0)
	uassert.ErrorIs(t, err, ErrNoSuchPage, "a discussion needs a page to be about")

	_, err = w.Comment(alice, now, h, "A", "", 0)
	uassert.ErrorIs(t, err, ErrEmptyComment)

	_, err = w.Comment(alice, now, h, "A", strings.Repeat("x", MaxCommentLen+1), 0)
	uassert.ErrorIs(t, err, ErrCommentTooLong)

	_, err = w.Comment(alice, now, h, "A", "hi\n", 999)
	uassert.ErrorIs(t, err, ErrNoSuchComment)
}

// TestRepliesNestOneLevel pins MaxReplyDepth. Unbounded nesting means
// unbounded recursive rendering, which is the shape the query gas ceiling
// punishes hardest.
func TestRepliesNestOneLevel(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "the article\n", "")
	root := comment(t, w, 2, alice, "A", "root\n", 0)
	reply := comment(t, w, 3, bob, "A", "reply\n", root.ID)

	now, h := at(4)
	_, err := w.Comment(mod, now, h, "A", "reply to a reply\n", reply.ID)
	uassert.ErrorIs(t, err, ErrReplyToReply)
}

func TestHideComment(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "the article\n", "")
	before := w.Stats().BytesHeld
	c := comment(t, w, 2, bob, "A", "unpleasant\n", 0)
	uassert.Equal(t, before+len("unpleasant\n"), w.Stats().BytesHeld,
		"a comment costs its author the bytes it adds")

	released, err := w.HideComment("A", c.ID)
	uassert.NoError(t, err)
	uassert.Equal(t, len("unpleasant\n"), released)
	uassert.Equal(t, before, w.Stats().BytesHeld)

	threads := w.Comments(MustParseTitle("A"), 0, 10)
	uassert.Equal(t, 1, len(threads), "a hidden message stays in the thread")
	uassert.True(t, threads[0].Root.Hidden)
	uassert.Equal(t, "", threads[0].Root.Body)

	// Hiding twice must not double-count the refund.
	released, err = w.HideComment("A", c.ID)
	uassert.NoError(t, err)
	uassert.Equal(t, 0, released)
	uassert.Equal(t, before, w.Stats().BytesHeld)
}

func TestRenderTalk(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "the article\n", "")
	root := comment(t, w, 2, alice, "A", "Is [[B]] the right link?\n", 0)
	comment(t, w, 3, bob, "A", "Yes.\n", root.ID)
	hidden := comment(t, w, 4, mod, "A", "spam\n", 0)
	w.HideComment("A", hidden.ID)

	p, _ := w.Page("A")
	c := Ctx{Base: "/r/nym-moultest123/x/wiki/v0", Exists: w.Exists}
	out := RenderTalk(c, w, p, 0, 10, act)

	uassert.True(t, strings.Contains(out, "# Discussion: A"))
	uassert.True(t, strings.Contains(out, "func=Comment"), "an add-a-message action")
	uassert.True(t, strings.Contains(out, "Yes."), "replies render under their root")
	uassert.True(t, strings.Contains(out, "removed by a steward"))
	uassert.False(t, strings.Contains(out, "spam"), "a hidden body is gone from the render")

	// A comment is user markdown too: it goes through the sanitizer, and it
	// is NOT a wikilink slot, so brackets stay literal rather than linking.
	uassert.True(t, strings.Contains(out, `\[\[B\]\]`), out)
}

func TestRenderTalkEmpty(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "the article\n", "")
	p, _ := w.Page("A")
	out := RenderTalk(Ctx{Base: "/r/nym-moultest123/x/wiki/v0"}, w, p, 0, 10, nil)
	uassert.True(t, strings.Contains(out, "No messages yet"))
}

func TestArticleLinksToItsDiscussion(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "the article\n", "")
	comment(t, w, 2, alice, "A", "hi\n", 0)

	p, _ := w.Page("A")
	out := RenderArticle(Ctx{Base: "/r/nym-moultest123/x/wiki/v0"}, w, p, nil)
	uassert.True(t, strings.Contains(out, "[discussion](/r/nym-moultest123/x/wiki/v0:A/talk) (1)"), out)
}

title.gno

package wiki

import (
	"errors"
	"strings"
	"unicode"

	"gno.land/p/nt/markdown/sanitize/v0"
)

// Namespace partitions the title space the way MediaWiki does: the same name
// can exist once per namespace, and each namespace gets its own rendering and
// its own listing.
type Namespace uint8

// There is deliberately no Talk namespace. Discussion is not an article with
// a prefix: it is an append-only thread attached to a page, which threads
// properly, moderates per message, and cannot be silently rewritten by whoever
// edits last. See talk.gno.
const (
	NSMain     Namespace = iota // articles
	NSUser                      // per-address pages
	NSCategory                  // category descriptions; membership is an index
	NSTemplate                  // reusable fragments
	NSHelp                      // documentation about the wiki itself
	NSSpecial                   // generated listings; never stored
)

// namespaces is the canonical table. The two-character code is the avl key
// prefix: it is fixed-width on purpose, because ufmt in gno supports no width
// or padding flags (ufmt.Sprintf("%02d", 7) returns "7"), so a numeric key
// would sort "0","1","10","2" and silently interleave namespaces past nine.
var namespaces = [...]struct {
	prefix string // canonical display prefix, "" for main
	code   string // fixed-width avl key prefix
}{
	NSMain:     {"", "00"},
	NSUser:     {"User", "01"},
	NSCategory: {"Category", "02"},
	NSTemplate: {"Template", "03"},
	NSHelp:     {"Help", "04"},
	NSSpecial:  {"Special", "05"},
}

// Title is a normalized (namespace, name) pair. The zero Title is invalid;
// build one with ParseTitle.
type Title struct {
	NS   Namespace
	Name string
}

// MaxTitleLen bounds a title name in bytes, matching MediaWiki's limit.
const MaxTitleLen = 255

var (
	ErrEmptyTitle   = errors.New("wiki: empty title")
	ErrTitleTooLong = errors.New("wiki: title too long")
	ErrTitleChar    = errors.New("wiki: illegal character in title")
)

// ParseTitle normalizes a user-supplied title.
//
// The normalization is a deliberate subset of MediaWiki's: underscores become
// spaces, runs of whitespace collapse, the first letter is upper-cased, and a
// recognized "Namespace:" prefix (case-insensitive) selects the namespace.
// "Talk:gno  land" and "talk:Gno_land" both parse to Talk:Gno land.
//
// The accepted character set is narrower than MediaWiki's on purpose. A title
// is rendered inside markdown and inside a URL path, so anything that is
// markdown-significant ("*", "`", "[", "|", "#", "<"), path-significant ("/",
// "?", "%", "&") or invisible (bidi and zero-width controls) is rejected
// rather than escaped. Rejecting keeps Title.String, Title.Slug and the
// sanitized render byte-identical, which is what TestTitleCharsSurviveSanitize
// pins.
func ParseTitle(raw string) (Title, error) {
	s := sanitize.StripBidiAndZeroWidth(raw)
	s = strings.ReplaceAll(s, "_", " ")
	s = strings.Join(strings.Fields(s), " ")
	if s == "" {
		return Title{}, ErrEmptyTitle
	}

	ns := NSMain
	if i := strings.Index(s, ":"); i > 0 {
		if n, ok := namespaceByPrefix(s[:i]); ok {
			ns = n
			s = strings.TrimSpace(s[i+1:])
			if s == "" {
				return Title{}, ErrEmptyTitle
			}
		}
	}

	if len(s) > MaxTitleLen {
		return Title{}, ErrTitleTooLong
	}
	for _, r := range s {
		if !validTitleRune(r) {
			return Title{}, ErrTitleChar
		}
	}
	return Title{NS: ns, Name: upperFirst(s)}, nil
}

// MustParseTitle is ParseTitle for titles known at development time.
func MustParseTitle(raw string) Title {
	t, err := ParseTitle(raw)
	if err != nil {
		panic(err)
	}
	return t
}

func namespaceByPrefix(p string) (Namespace, bool) {
	p = strings.TrimSpace(p)
	for i, e := range namespaces {
		if e.prefix != "" && strings.EqualFold(e.prefix, p) {
			return Namespace(i), true
		}
	}
	return NSMain, false
}

// validTitleRune reports whether r may appear in a title name. ASCII is an
// explicit allowlist; above ASCII only letters and digits are accepted, which
// admits "Élysée" and "東京" while excluding every invisible control.
func validTitleRune(r rune) bool {
	switch {
	case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
		return true
	case r == ' ' || r == '-' || r == '.' || r == ',' || r == '\'' || r == '(' || r == ')' || r == ':':
		return true
	case r < 0x80:
		return false
	default:
		return unicode.IsLetter(r) || unicode.IsDigit(r)
	}
}

func upperFirst(s string) string {
	rs := []rune(s)
	if len(rs) == 0 {
		return s
	}
	rs[0] = unicode.ToUpper(rs[0])
	return string(rs)
}

// String is the canonical display form, "Talk:Gno land".
func (t Title) String() string {
	if t.NS == NSMain {
		return t.Name
	}
	return namespaces[t.NS].prefix + ":" + t.Name
}

// Slug is the URL form used in render paths, "Talk:Gno_land". Titles cannot
// contain "/", so a slug is always exactly one path segment and the segment
// after it is unambiguously a sub-route.
func (t Title) Slug() string {
	return strings.ReplaceAll(t.String(), " ", "_")
}

// Key is the avl key: a fixed-width namespace code followed by the name, so
// iteration yields main-namespace articles first, then Talk, and so on, each
// group in name order.
func (t Title) Key() string {
	return namespaces[t.NS].code + ":" + t.Name
}

// Prefix returns the avl key prefix that selects a whole namespace.
func (ns Namespace) Prefix() string { return namespaces[ns].code + ":" }

// String returns the namespace's display prefix, "" for the main namespace.
func (ns Namespace) String() string { return namespaces[ns].prefix }

title_test.gno

package wiki

import (
	"testing"

	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/uassert/v0"
)

func TestParseTitle(t *testing.T) {
	cases := []struct {
		name    string
		in      string
		wantNS  Namespace
		want    string // canonical String(), "" when an error is expected
		wantErr error
	}{
		{"plain", "Gno land", NSMain, "Gno land", nil},
		{"underscores become spaces", "Gno_land", NSMain, "Gno land", nil},
		{"whitespace collapses", "  Gno   land  ", NSMain, "Gno land", nil},
		{"first letter is upper-cased", "gno land", NSMain, "Gno land", nil},
		{"namespace prefix", "Help:Gno land", NSHelp, "Help:Gno land", nil},
		{"namespace prefix is case-insensitive", "help:gno_land", NSHelp, "Help:Gno land", nil},
		{"category", "Category:Chains", NSCategory, "Category:Chains", nil},
		{"unknown prefix stays in the name", "Foo:Bar", NSMain, "Foo:Bar", nil},
		{"unicode letters are allowed", "Élysée", NSMain, "Élysée", nil},
		{"unicode is upper-cased too", "élysée", NSMain, "Élysée", nil},
		{"zero-width characters are stripped", "Gno​land", NSMain, "Gnoland", nil},
		{"empty", "", NSMain, "", ErrEmptyTitle},
		{"whitespace only", "   ", NSMain, "", ErrEmptyTitle},
		{"namespace with no name", "Help:", NSMain, "", ErrEmptyTitle},
		{"slash is rejected", "Gno/land", NSMain, "", ErrTitleChar},
		{"pipe is rejected", "Gno|land", NSMain, "", ErrTitleChar},
		{"markdown star is rejected", "Gno*land", NSMain, "", ErrTitleChar},
		{"bracket is rejected", "Gno[land", NSMain, "", ErrTitleChar},
		{"hash is rejected", "Gno#land", NSMain, "", ErrTitleChar},
	}
	for _, tc := range cases {
		got, err := ParseTitle(tc.in)
		if tc.wantErr != nil {
			uassert.ErrorIs(t, err, tc.wantErr, tc.name)
			continue
		}
		if !uassert.NoError(t, err, tc.name) {
			continue
		}
		uassert.Equal(t, tc.want, got.String(), tc.name)
		uassert.Equal(t, uint64(tc.wantNS), uint64(got.NS), tc.name+" (namespace)")
	}
}

func TestTitleTooLong(t *testing.T) {
	long := ""
	for i := 0; i <= MaxTitleLen; i++ {
		long += "a"
	}
	_, err := ParseTitle(long)
	uassert.ErrorIs(t, err, ErrTitleTooLong)
}

func TestTitleKeyOrdersByNamespace(t *testing.T) {
	// The avl key must group namespaces, and must keep doing so past nine
	// namespaces, which is why the code is a fixed-width string rather than
	// a ufmt-formatted number.
	uassert.Equal(t, "00:Gno land", MustParseTitle("Gno land").Key())
	uassert.Equal(t, "01:Gno land", MustParseTitle("User:Gno land").Key())
	uassert.True(t, MustParseTitle("Gno land").Key() < MustParseTitle("User:Alpha").Key(),
		"every main-namespace key must sort before every User key")
}

func TestTitleSlug(t *testing.T) {
	uassert.Equal(t, "Gno_land", MustParseTitle("Gno land").Slug())
	uassert.Equal(t, "User:Gno_land", MustParseTitle("User:Gno land").Slug())
	uassert.Equal(t, "Mercury_(planet)", MustParseTitle("Mercury (planet)").Slug())
}

// TestTitleSurvivesTheRenderPipeline pins the coupling between the title
// charset and the markdown sanitizer.
//
// Rendering escapes the whole body first and rewrites wikilinks second, so
// every title character has to survive that round trip: sanitize escapes it,
// ScanLinks finds the link in the escaped text, and unescapeInline hands
// ParseTitle the bytes the author typed. The sanitizer escapes with
// backslashes ("(" becomes "\(") which unescapeInline undoes, but a character
// escaped as an entity ("&" becomes "&amp;") would not survive, which is why
// the charset excludes those. This test fails the day either side changes.
func TestTitleSurvivesTheRenderPipeline(t *testing.T) {
	// The ASCII allowlist plus a couple of accepted non-ASCII letters; the
	// whole set has to fit in one title, so this is not every valid rune.
	chars := "Élysée東京"
	for r := rune(0); r < 0x80; r++ {
		if validTitleRune(r) && r != ' ' {
			chars += string(r)
		}
	}
	want := MustParseTitle(chars)

	escaped := sanitize.BlockRich("[[" + chars + "]]\n")
	links := ScanLinks(escaped, `\[\[`, `\]\]`)
	if !uassert.Equal(t, 1, len(links), "the escaped body must still contain exactly one link") {
		return
	}
	got, err := ParseTitle(unescapeInline(links[0].Target))
	uassert.NoError(t, err)
	uassert.Equal(t, want.String(), got.String())
}

wiki.gno

package wiki

import (
	"errors"
	"time"

	"gno.land/p/nym-moultest123/fifo/v0"
	"gno.land/p/nym-moultest123/ulist/v0"
	"gno.land/p/nt/avl/v0"
)

// Defaults for New. Retention is the number of most-recent revisions per page
// whose body stays on chain; MaxBody caps a single revision.
const (
	DefaultRetention = 3
	DefaultMaxBody   = 32 << 10 // 32 KiB
	DefaultRecent    = 50
	MaxSummaryLen    = 200
)

var (
	ErrNoSuchPage     = errors.New("wiki: no such page")
	ErrPageExists     = errors.New("wiki: page already exists")
	ErrBodyTooLarge   = errors.New("wiki: body exceeds the size limit")
	ErrEmptyBody      = errors.New("wiki: empty body")
	ErrNoChange       = errors.New("wiki: body is identical to the current revision")
	ErrSummaryTooLong = errors.New("wiki: edit summary too long")
	ErrBadProtection  = errors.New("wiki: unknown protection level")
	ErrNoSuchRevision = errors.New("wiki: no such revision")
	ErrBodyEvicted    = errors.New("wiki: that revision's body is no longer held on chain")
	ErrSpecial        = errors.New("wiki: the Special namespace is generated, not stored")
)

// Wiki is the whole encyclopedia: pages, the indexes derived from them, and
// the recent-changes feed.
//
// Every mutating method takes author, now and height from the caller instead
// of reading them from the chain, so the engine has no chain imports and the
// tests drive time and height explicitly.
type Wiki struct {
	pages     *avl.Tree // Title.Key() -> *Page
	backlinks *avl.Tree // target Title.Key() -> *avl.Tree (source key -> Title)
	cats      *avl.Tree // category Title.Key() -> *avl.Tree (member key -> Title)
	talk      *avl.Tree // Title.Key() -> *ulist.List of *Comment (see talk.gno)
	recent    *fifo.List

	nextRev     uint64
	nextComment uint64
	retention int
	maxBody   int

	numPages    int // pages with at least one revision and not blanked
	numRevs     int
	numComments int
	bytesHeld   int // retained body and comment bytes, the realm's visible rent
}

// New returns an empty wiki. A retention or maxBody below 1 falls back to the
// package default.
func New(retention, maxBody int) *Wiki {
	if retention < 1 {
		retention = DefaultRetention
	}
	if maxBody < 1 {
		maxBody = DefaultMaxBody
	}
	return &Wiki{
		pages:     avl.NewTree(),
		backlinks: avl.NewTree(),
		cats:      avl.NewTree(),
		talk:      avl.NewTree(),
		recent:    fifo.New(DefaultRecent),
		retention: retention,
		maxBody:   maxBody,
	}
}

// Stats is a snapshot of the wiki's size and of what it is paying for.
type Stats struct {
	Pages     int
	Revisions int
	Comments  int
	BytesHeld int // bytes of article text and comments currently on chain
	Retention int
}

// Stats returns the current counters.
func (w *Wiki) Stats() Stats {
	return Stats{
		Pages:     w.numPages,
		Revisions: w.numRevs,
		Comments:  w.numComments,
		BytesHeld: w.bytesHeld,
		Retention: w.retention,
	}
}

// Page returns the page stored at raw, without following redirects.
func (w *Wiki) Page(raw string) (*Page, error) {
	t, err := ParseTitle(raw)
	if err != nil {
		return nil, err
	}
	return w.PageByTitle(t)
}

// PageByTitle is Page for an already-parsed title.
func (w *Wiki) PageByTitle(t Title) (*Page, error) {
	v := w.pages.Get(t.Key())
	if v == nil {
		return nil, ErrNoSuchPage
	}
	return v.(*Page), nil
}

// Exists reports whether a title has a page. A blanked page still exists: its
// history is the point of the wiki.
func (w *Wiki) Exists(t Title) bool { return w.pages.Has(t.Key()) }

// Resolve follows at most one redirect hop and returns the destination page
// along with the page that was asked for. MediaWiki also stops at one hop:
// chains are a vandalism vector and a loop is unrenderable.
func (w *Wiki) Resolve(raw string) (dest, asked *Page, err error) {
	p, err := w.Page(raw)
	if err != nil {
		return nil, nil, err
	}
	if p.redirect == "" {
		return p, p, nil
	}
	target, err := w.Page(p.redirect)
	if err != nil {
		return p, p, nil // dangling redirect: render the stub itself
	}
	return target, p, nil
}

// Edit writes a new revision. It does not check authority: the caller decides
// who may write, using Page.Protection and whatever roster it keeps. Passing a
// body byte-identical to the current one is an error, so a no-op edit cannot
// be used to spam the history or the recent-changes feed.
func (w *Wiki) Edit(author address, now time.Time, height int64, raw, body, summary string, minor bool) (*Revision, error) {
	t, err := ParseTitle(raw)
	if err != nil {
		return nil, err
	}
	if t.NS == NSSpecial {
		return nil, ErrSpecial
	}
	if body == "" {
		return nil, ErrEmptyBody
	}
	if len(body) > w.maxBody {
		return nil, ErrBodyTooLarge
	}
	if len(summary) > MaxSummaryLen {
		return nil, ErrSummaryTooLong
	}

	p, _ := w.PageByTitle(t)
	kind := KindEdit
	if p == nil {
		kind = KindCreate
	} else if p.head != nil && p.head.Hash == hashBody(body) {
		return nil, ErrNoChange
	}
	return w.commit(p, t, author, now, height, body, summary, kind, minor), nil
}

// Revert restores the body of an earlier revision as a new revision, the way
// a wiki undo works: the vandalized revision stays in the history, it is just
// no longer current. It fails if that revision's body has aged out of the
// retention window, which is the honest failure mode of a bounded history.
func (w *Wiki) Revert(author address, now time.Time, height int64, raw string, revID uint64, summary string) (*Revision, error) {
	p, err := w.Page(raw)
	if err != nil {
		return nil, err
	}
	old := p.Revision(revID)
	if old == nil {
		return nil, ErrNoSuchRevision
	}
	body, ok := old.Body()
	if !ok {
		return nil, ErrBodyEvicted
	}
	if p.head != nil && p.head.Hash == old.Hash {
		return nil, ErrNoChange
	}
	if len(summary) > MaxSummaryLen {
		return nil, ErrSummaryTooLong
	}
	return w.commit(p, p.Title, author, now, height, body, summary, KindRevert, false), nil
}

// Blank replaces a page's content with a tombstone revision. It is the
// deletion a chain can honestly offer: the page stops rendering and stops
// costing rent as its bodies age out, while the revision spine stays as proof
// that something was there and who removed it. Use Purge to release the
// retained bytes immediately.
func (w *Wiki) Blank(author address, now time.Time, height int64, raw, reason string) (*Revision, error) {
	p, err := w.Page(raw)
	if err != nil {
		return nil, err
	}
	if len(reason) > MaxSummaryLen {
		return nil, ErrSummaryTooLong
	}
	rev := w.commit(p, p.Title, author, now, height, "", reason, KindBlank, false)
	if !p.Blanked {
		p.Blanked = true
		w.numPages--
	}
	return rev, nil
}

// Purge evicts every retained body of a page immediately and returns the
// number of bytes released. The spine, including each body's hash, is
// untouched. This is the lever for content that must stop being served from
// realm state; it cannot and does not remove the transactions that wrote it.
func (w *Wiki) Purge(raw string) (int, error) {
	p, err := w.Page(raw)
	if err != nil {
		return 0, err
	}
	released := 0
	p.revs.Iterator(0, p.revs.Size()-1, func(_ int, v any) bool {
		released += v.(*Revision).evict()
		return false
	})
	w.bytesHeld -= released
	return released, nil
}

// Move renames a page, keeping its history, and leaves a redirect behind at
// the old title so existing links keep resolving.
func (w *Wiki) Move(author address, now time.Time, height int64, from, to, summary string) error {
	src, err := w.Page(from)
	if err != nil {
		return err
	}
	dst, err := ParseTitle(to)
	if err != nil {
		return err
	}
	if dst.NS == NSSpecial {
		return ErrSpecial
	}
	if w.Exists(dst) {
		return ErrPageExists
	}

	old := src.Title
	w.unindex(src)
	w.pages.Remove(old.Key())
	src.Title = dst
	w.pages.Set(dst.Key(), src)
	w.index(src)

	w.pushRecent(src.Title, w.metaRevision(src, author, now, height, "moved from "+old.String(), KindMove))

	stub := "#REDIRECT [[" + dst.String() + "]]\n"
	w.commit(nil, old, author, now, height, stub, "moved to "+dst.String(), KindMove, false)
	return nil
}

// SetProtection changes a page's edit gate.
func (w *Wiki) SetProtection(author address, now time.Time, height int64, raw, level string) error {
	p, err := w.Page(raw)
	if err != nil {
		return err
	}
	lvl, err := ParseProtection(level)
	if err != nil {
		return err
	}
	p.Protection = lvl
	w.pushRecent(p.Title, w.metaRevision(p, author, now, height, "protection: "+lvl.String(), KindProtect))
	return nil
}

// metaRevision records an event that changed a page without changing its text
// (a move, a protection change). It carries no body of its own and inherits
// the current revision's hash and size, so the history reads as "this is still
// the same text" instead of "the article was blanked".
func (w *Wiki) metaRevision(p *Page, author address, now time.Time, height int64, summary string, kind Kind) *Revision {
	rev := w.newRevision(p, author, now, height, "", summary, kind, true)
	rev.kept = false
	if p.head != nil {
		rev.Hash = p.head.Hash
		rev.Size = p.head.Size
	}
	return rev
}

// commit appends a revision, re-derives the page's indexes from the new body
// and enforces the retention window. p may be nil, in which case the page is
// created at t.
func (w *Wiki) commit(p *Page, t Title, author address, now time.Time, height int64, body, summary string, kind Kind, minor bool) *Revision {
	if p == nil {
		p = &Page{Title: t, Created: now, revs: ulist.New()}
		w.pages.Set(t.Key(), p)
		w.numPages++
	} else {
		w.unindex(p)
		if p.Blanked && body != "" {
			p.Blanked = false
			w.numPages++
		}
	}

	rev := w.newRevision(p, author, now, height, body, summary, kind, minor)
	p.head = rev
	w.reindex(p, body)
	w.enforceRetention(p)
	w.pushRecent(p.Title, rev)
	return rev
}

// newRevision allocates the next revision, appends it and accounts its bytes.
func (w *Wiki) newRevision(p *Page, author address, now time.Time, height int64, body, summary string, kind Kind, minor bool) *Revision {
	w.nextRev++
	prev := uint64(0)
	if n := p.revs.Size(); n > 0 {
		prev = p.revs.MustGet(n - 1).(*Revision).ID
	}
	rev := &Revision{
		ID:      w.nextRev,
		Prev:    prev,
		Kind:    kind,
		Author:  author,
		Time:    now,
		Height:  height,
		Summary: summary,
		Hash:    hashBody(body),
		Size:    len(body),
		Minor:   minor,
		body:    body,
		kept:    true,
	}
	p.revs.Append(rev)
	w.numRevs++
	w.bytesHeld += len(body)
	return rev
}

// enforceRetention evicts the body that just fell out of the window.
//
// It counts only revisions that still hold a body, so bodyless move and
// protection entries do not push real text out of the window early. One
// eviction per commit is enough because the window only ever moves by one, and
// the backward walk is bounded by scanLimit so a page with a long run of meta
// revisions cannot make a single edit O(history).
func (w *Wiki) enforceRetention(p *Page) {
	const scanLimit = 64
	kept, scanned := 0, 0
	p.revs.Iterator(p.revs.Size()-1, 0, func(_ int, v any) bool {
		scanned++
		r := v.(*Revision)
		if !r.kept {
			return scanned >= scanLimit
		}
		kept++
		if kept > w.retention {
			w.bytesHeld -= r.evict()
			return true
		}
		return scanned >= scanLimit
	})
}

func (w *Wiki) pushRecent(t Title, r *Revision) {
	w.recent.Prepend(&Change{Title: t, Rev: r})
}

// Recent returns up to n changes, newest first.
func (w *Wiki) Recent(n int) []*Change {
	out := []*Change{}
	for _, e := range w.recent.Entries() {
		if len(out) >= n {
			break
		}
		out = append(out, e.(*Change))
	}
	return out
}

// reindex derives the page's redirect target, outgoing links and categories
// from body, and writes them into the wiki-wide indexes.
func (w *Wiki) reindex(p *Page, body string) {
	p.redirect = redirectTarget(body)
	p.links = nil
	p.cats = nil

	for _, raw := range ScanLinks(body, "[[", "]]") {
		t, err := ParseTitle(raw.Target)
		if err != nil || t == p.Title {
			continue
		}
		if t.NS == NSCategory && !raw.Explicit {
			p.cats = appendUnique(p.cats, t.Key())
			continue
		}
		p.links = appendUnique(p.links, t.Key())
	}
	w.index(p)
}

// index adds the page to every index its current content implies.
func (w *Wiki) index(p *Page) {
	for _, key := range p.links {
		addTo(w.backlinks, key, p)
	}
	for _, key := range p.cats {
		addTo(w.cats, key, p)
	}
}

// unindex removes the page from every index, so the next reindex starts clean.
func (w *Wiki) unindex(p *Page) {
	for _, key := range p.links {
		removeFrom(w.backlinks, key, p.Title.Key())
	}
	for _, key := range p.cats {
		removeFrom(w.cats, key, p.Title.Key())
	}
}

func addTo(idx *avl.Tree, key string, p *Page) {
	v := idx.Get(key)
	var set *avl.Tree
	if v == nil {
		set = avl.NewTree()
		idx.Set(key, set)
	} else {
		set = v.(*avl.Tree)
	}
	set.Set(p.Title.Key(), p.Title)
}

func removeFrom(idx *avl.Tree, key, member string) {
	v := idx.Get(key)
	if v == nil {
		return
	}
	set := v.(*avl.Tree)
	set.Remove(member)
	if set.Size() == 0 {
		idx.Remove(key)
	}
}

func members(idx *avl.Tree, key string) []Title {
	out := []Title{}
	v := idx.Get(key)
	if v == nil {
		return out
	}
	v.(*avl.Tree).Iterate("", "", func(_ string, val any) bool {
		out = append(out, val.(Title))
		return false
	})
	return out
}

// Backlinks returns the titles whose current revision links to t, in key
// order. Redlinks are indexed too, so a page created later immediately knows
// who was already pointing at it.
func (w *Wiki) Backlinks(t Title) []Title { return members(w.backlinks, t.Key()) }

// CategoryMembers returns the pages that declare [[Category:name]].
func (w *Wiki) CategoryMembers(t Title) []Title { return members(w.cats, t.Key()) }

// Categories returns every category that has at least one member.
func (w *Wiki) Categories() []Title {
	out := []Title{}
	w.cats.Iterate("", "", func(key string, _ any) bool {
		out = append(out, Title{NS: NSCategory, Name: key[len(NSCategory.Prefix()):]})
		return false
	})
	return out
}

// Titles returns up to count page titles in key order, skipping offset of
// them. An empty ns prefix walks every namespace.
func (w *Wiki) Titles(prefix string, offset, count int) []Title {
	out := []Title{}
	skipped := 0
	w.pages.Iterate(prefix, "", func(key string, v any) bool {
		if prefix != "" && !hasPrefix(key, prefix) {
			return true
		}
		if skipped < offset {
			skipped++
			return false
		}
		out = append(out, v.(*Page).Title)
		return len(out) >= count
	})
	return out
}

func hasPrefix(s, p string) bool { return len(s) >= len(p) && s[:len(p)] == p }

func appendUnique(list []string, v string) []string {
	for _, e := range list {
		if e == v {
			return list
		}
	}
	return append(list, v)
}

wiki_test.gno

package wiki

import (
	"testing"
	"time"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
	mod   = testutils.TestAddress("mod")
)

// at returns a deterministic timestamp and height for step n, so tests never
// depend on wall-clock time or on where a previous test left the block height.
func at(n int) (time.Time, int64) {
	return time.Unix(int64(1757000000+n*60), 0).UTC(), int64(100 + n)
}

func edit(t *testing.T, w *Wiki, n int, author address, title, body, summary string) *Revision {
	t.Helper()
	now, h := at(n)
	rev, err := w.Edit(author, now, h, title, body, summary, false)
	uassert.NoError(t, err, title)
	return rev
}

func TestEditCreatesAndUpdates(t *testing.T) {
	w := New(DefaultRetention, DefaultMaxBody)

	r1 := edit(t, w, 1, alice, "gno_land", "The first draft.\n", "create")
	uassert.Equal(t, uint64(1), r1.ID)
	uassert.Equal(t, uint64(0), r1.Prev)
	uassert.Equal(t, string(KindCreate), string(r1.Kind))

	r2 := edit(t, w, 2, bob, "Gno land", "The second draft.\n", "expand")
	uassert.Equal(t, uint64(1), r2.Prev)
	uassert.Equal(t, string(KindEdit), string(r2.Kind))

	p, err := w.Page("Gno land")
	uassert.NoError(t, err)
	uassert.Equal(t, 2, p.NumRevisions())
	body, kept := p.Body()
	uassert.True(t, kept)
	uassert.Equal(t, "The second draft.\n", body)

	s := w.Stats()
	uassert.Equal(t, 1, s.Pages, "the two edits are one page")
	uassert.Equal(t, 2, s.Revisions)
}

func TestEditRejectsNoOpAndOversize(t *testing.T) {
	w := New(DefaultRetention, 32)
	now, h := at(1)

	_, err := w.Edit(alice, now, h, "A", "", "empty", false)
	uassert.ErrorIs(t, err, ErrEmptyBody)

	_, err = w.Edit(alice, now, h, "A", "0123456789012345678901234567890123", "too big", false)
	uassert.ErrorIs(t, err, ErrBodyTooLarge)

	edit(t, w, 1, alice, "A", "same\n", "create")
	_, err = w.Edit(alice, now, h, "A", "same\n", "again", false)
	uassert.ErrorIs(t, err, ErrNoChange, "an identical body must not create a revision")

	_, err = w.Edit(alice, now, h, "Special:Anything", "x\n", "", false)
	uassert.ErrorIs(t, err, ErrSpecial)
}

// TestRetentionEvictsOldBodies is the storage design in one test: the spine
// grows by a fixed amount per edit, the held bytes do not.
func TestRetentionEvictsOldBodies(t *testing.T) {
	w := New(2, DefaultMaxBody)
	bodies := []string{"aaaa\n", "bbbbbb\n", "cccccccc\n", "dddddddddd\n"}
	for i, b := range bodies {
		edit(t, w, i+1, alice, "A", b, "edit")
	}

	p, err := w.Page("A")
	uassert.NoError(t, err)
	uassert.Equal(t, 4, p.NumRevisions(), "every revision stays in the history")

	kept := 0
	for _, r := range p.History(0, 10) {
		if r.Kept() {
			kept++
		}
	}
	uassert.Equal(t, 2, kept, "only the retention window keeps bodies")
	uassert.Equal(t, len(bodies[2])+len(bodies[3]), w.Stats().BytesHeld)

	// The spine of an evicted revision is intact, hash included.
	oldest := p.History(0, 10)[3]
	uassert.False(t, oldest.Kept())
	uassert.Equal(t, hashBody(bodies[0]), oldest.Hash)
	uassert.Equal(t, len(bodies[0]), oldest.Size)
}

func TestRevert(t *testing.T) {
	w := New(3, DefaultMaxBody)
	first := edit(t, w, 1, alice, "A", "good\n", "create")
	edit(t, w, 2, bob, "A", "VANDALISM\n", "oops")

	now, h := at(3)
	rev, err := w.Revert(mod, now, h, "A", first.ID, "rv")
	uassert.NoError(t, err)
	uassert.Equal(t, string(KindRevert), string(rev.Kind))

	p, _ := w.Page("A")
	body, _ := p.Body()
	uassert.Equal(t, "good\n", body)
	uassert.Equal(t, 3, p.NumRevisions(), "the vandalism stays in the history")
}

func TestRevertRefusesEvictedAndUnknown(t *testing.T) {
	w := New(1, DefaultMaxBody)
	first := edit(t, w, 1, alice, "A", "one\n", "")
	edit(t, w, 2, alice, "A", "two\n", "")
	now, h := at(3)

	_, err := w.Revert(alice, now, h, "A", first.ID, "")
	uassert.ErrorIs(t, err, ErrBodyEvicted,
		"reverting past the retention window must fail loudly, not silently")

	_, err = w.Revert(alice, now, h, "A", 9999, "")
	uassert.ErrorIs(t, err, ErrNoSuchRevision)
}

func TestBlankAndPurge(t *testing.T) {
	w := New(5, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "content\n", "")
	edit(t, w, 2, alice, "A", "more content\n", "")
	uassert.Equal(t, 1, w.Stats().Pages)

	now, h := at(3)
	_, err := w.Blank(mod, now, h, "A", "policy")
	uassert.NoError(t, err)
	uassert.Equal(t, 0, w.Stats().Pages, "a blanked page stops counting as a page")

	p, _ := w.Page("A")
	uassert.True(t, p.Blanked)
	uassert.Equal(t, 3, p.NumRevisions(), "blanking is a revision, not an erasure")

	released, err := w.Purge("A")
	uassert.NoError(t, err)
	uassert.Equal(t, len("content\n")+len("more content\n"), released)
	uassert.Equal(t, 0, w.Stats().BytesHeld, "purge releases every retained byte")
	uassert.Equal(t, 3, p.NumRevisions(), "purge leaves the spine intact")
}

func TestBlankThenEditRestoresThePage(t *testing.T) {
	w := New(5, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "content\n", "")
	now, h := at(2)
	w.Blank(mod, now, h, "A", "")
	edit(t, w, 3, alice, "A", "back\n", "restore")
	uassert.Equal(t, 1, w.Stats().Pages)
	p, _ := w.Page("A")
	uassert.False(t, p.Blanked)
}

func TestBacklinksAndRedlinks(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "links to [[B]] and [[C]]\n", "")
	edit(t, w, 2, alice, "D", "also links to [[B]]\n", "")

	b := MustParseTitle("B")
	in := w.Backlinks(b)
	uassert.Equal(t, 2, len(in))
	uassert.Equal(t, "A", in[0].String())
	uassert.Equal(t, "D", in[1].String())

	// C does not exist: a redlink is still indexed, so the page knows who is
	// waiting for it the moment it is created.
	uassert.False(t, w.Exists(MustParseTitle("C")))
	uassert.Equal(t, 1, len(w.Backlinks(MustParseTitle("C"))))

	// Editing A to drop the link must un-index it.
	edit(t, w, 3, alice, "A", "links to nothing\n", "")
	uassert.Equal(t, 1, len(w.Backlinks(b)))
	uassert.Equal(t, 0, len(w.Backlinks(MustParseTitle("C"))))
}

func TestCategories(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "text\n[[Category:Chains]]\n", "")
	edit(t, w, 2, alice, "B", "text\n[[Category:Chains]]\n[[Category:Tools]]\n", "")

	chains := MustParseTitle("Category:Chains")
	uassert.Equal(t, 2, len(w.CategoryMembers(chains)))
	uassert.Equal(t, 2, len(w.Categories()))

	// An explicit [[:Category:X]] links to the category instead of joining it.
	edit(t, w, 3, alice, "C", "see [[:Category:Chains]]\n", "")
	uassert.Equal(t, 2, len(w.CategoryMembers(chains)))
	uassert.Equal(t, 1, len(w.Backlinks(chains)))
}

func TestRedirect(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "Gno", "#REDIRECT [[Gno land]]\n", "")
	edit(t, w, 2, alice, "Gno land", "The article.\n", "")

	dest, asked, err := w.Resolve("Gno")
	uassert.NoError(t, err)
	uassert.Equal(t, "Gno land", dest.Title.String())
	uassert.Equal(t, "Gno", asked.Title.String())

	// A dangling redirect renders itself rather than 404ing.
	edit(t, w, 3, alice, "Nowhere", "#REDIRECT [[Absent]]\n", "")
	dest, _, err = w.Resolve("Nowhere")
	uassert.NoError(t, err)
	uassert.Equal(t, "Nowhere", dest.Title.String())
}

func TestMoveKeepsHistoryAndLeavesARedirect(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "Old name", "body linking to [[B]]\n", "")
	edit(t, w, 2, alice, "Old name", "body linking to [[B]], revised\n", "")

	now, h := at(3)
	uassert.NoError(t, w.Move(mod, now, h, "Old name", "New name", "rename"))

	moved, err := w.Page("New name")
	uassert.NoError(t, err)
	uassert.Equal(t, 3, moved.NumRevisions(), "history follows the page")
	body, kept := moved.Body()
	uassert.True(t, kept)
	uassert.Equal(t, "body linking to [[B]], revised\n", body, "a move does not touch the text")

	stub, err := w.Page("Old name")
	uassert.NoError(t, err)
	uassert.Equal(t, "New name", stub.Redirect())

	// The backlink index must follow the rename, not point at the old key.
	in := w.Backlinks(MustParseTitle("B"))
	uassert.Equal(t, 1, len(in))
	uassert.Equal(t, "New name", in[0].String())
}

func TestMoveRefusesAnExistingTarget(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "a\n", "")
	edit(t, w, 2, alice, "B", "b\n", "")
	now, h := at(3)
	uassert.ErrorIs(t, w.Move(mod, now, h, "A", "B", ""), ErrPageExists)
}

func TestProtectionIsRecordedInTheHistory(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "a\n", "")
	now, h := at(2)
	uassert.NoError(t, w.SetProtection(mod, now, h, "A", "locked"))

	p, _ := w.Page("A")
	uassert.Equal(t, "locked", p.Protection.String())
	uassert.Equal(t, 2, p.NumRevisions())

	// The protection entry must not become the current text.
	body, kept := p.Body()
	uassert.True(t, kept)
	uassert.Equal(t, "a\n", body)

	// It carries the current hash, so the history does not read as a blanking.
	last := p.History(0, 1)[0]
	uassert.Equal(t, string(KindProtect), string(last.Kind))
	uassert.Equal(t, hashBody("a\n"), last.Hash)
}

func TestMetaRevisionsDoNotEvictRealBodies(t *testing.T) {
	w := New(2, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "one\n", "")
	edit(t, w, 2, alice, "A", "two\n", "")
	now, h := at(3)
	w.SetProtection(mod, now, h, "A", "locked")
	w.SetProtection(mod, now, h, "A", "open")

	p, _ := w.Page("A")
	kept := 0
	for _, r := range p.History(0, 10) {
		if r.Kept() {
			kept++
		}
	}
	uassert.Equal(t, 2, kept, "two bodyless entries must not push both bodies out of a window of 2")
}

func TestRecentChangesIsNewestFirst(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "a\n", "first")
	edit(t, w, 2, bob, "B", "b\n", "second")

	recent := w.Recent(10)
	uassert.Equal(t, 2, len(recent))
	uassert.Equal(t, "B", recent[0].Title.String())
	uassert.Equal(t, "A", recent[1].Title.String())
}

func TestTitlesWalkOneNamespace(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "Beta", "b\n", "")
	edit(t, w, 2, alice, "Alpha", "a\n", "")
	edit(t, w, 3, alice, "Help:Alpha", "t\n", "")

	main := w.Titles(NSMain.Prefix(), 0, 10)
	uassert.Equal(t, 2, len(main))
	uassert.Equal(t, "Alpha", main[0].String())
	uassert.Equal(t, "Beta", main[1].String())

	help := w.Titles(NSHelp.Prefix(), 0, 10)
	uassert.Equal(t, 1, len(help))
	uassert.Equal(t, "Help:Alpha", help[0].String())

	uassert.Equal(t, 1, len(w.Titles(NSMain.Prefix(), 1, 10)), "offset skips")
}

func TestContributors(t *testing.T) {
	w := New(3, DefaultMaxBody)
	edit(t, w, 1, alice, "A", "1\n", "")
	edit(t, w, 2, bob, "A", "2\n", "")
	edit(t, w, 3, alice, "A", "3\n", "")

	p, _ := w.Page("A")
	c := p.Contributors()
	uassert.Equal(t, 2, len(c))
	uassert.Equal(t, alice.String(), c[0].String())
	uassert.Equal(t, bob.String(), c[1].String())
}

func TestFormatGNOT(t *testing.T) {
	cases := []struct {
		in   int
		want string
	}{
		{0, "0 GNOT"},
		{1000000, "1 GNOT"},
		{1500000, "1.5 GNOT"},
		{100, "0.0001 GNOT"},
		{123456, "0.123456 GNOT"},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, formatGNOT(tc.in))
	}
}