package main import ( "bytes" "crypto/sha1" "encoding/hex" "fmt" "html/template" "io/fs" "os" "path" "path/filepath" "sort" "strings" "time" ) const repoURL = "https://github.com/tobychui/arozos" // siteModel holds everything the pages are drawn from. type siteModel struct { Version string API *API Guides []*Guide Refs []*RefPage Samples []*Sample Icons map[string]template.HTML Year int md *markdown syms map[string]string assetVer string tpl *template.Template } // libIcons picks an icon of the website's set for each library card. var libIcons = map[string]string{ "core": "terminal", "db": "database", "user": "users", "filelib": "folder", "imagelib": "image", "http": "globe", "share": "share", "appdata": "box", "sysinfo": "gauge", "ziplib": "layers", "sqlite": "database", "llm": "sparkles", "cnn": "eye", "office": "doc", "ffmpeg": "film", "websocket": "plug", "scheduler": "clock", "sharedspace": "users", "meetroom": "video", "notification": "send", "audio": "bell", "git": "git", "email": "mail", "cluster": "server", } // builtinRefs are drawn under "Built-in functions" instead of "Libraries". var builtinRefs = map[string]bool{"core": true, "db": true, "user": true} // ---------- page models ---------- type navItem struct { Title string URL string // from the docs root Key string Sub string // small text after the title Icon string } type navGroup struct { Title string Items []navItem } type tocItem struct { Level int ID string Title string Code bool } type headingView struct { Level int ID string Aliases []string HTML template.HTML } type sigView struct { Name string Args string Also []string Ret string Desc string } type fnView struct { Level int ID string Aliases []string Sigs []sigView Badges []string Body template.HTML Examples []string Missing bool // documented here but not in api.json } type itemView struct { Heading *headingView Body template.HTML Fn *fnView } type indexRow struct { Name, Ret, Desc, Anchor string } type guideView struct { Guide *Guide Intro template.HTML Items []itemView } type refView struct { Page *RefPage Intro template.HTML Index []indexRow Items []itemView Builtin bool Play string // how the playground serves it: "runs", or the tool window that answers } type libCard struct { Title, URL, Desc, Icon string Count int Builtin bool } type homeView struct { Builtins []libCard Libraries []libCard FnCount int Samples int Start []navItem } type page struct { Kind string // home, guide, ref, playground Key string Title string Desc string Root string Site *siteModel Nav []navGroup TOC []tocItem Prev *navItem Next *navItem Edit string // the source file on GitHub Home *homeView Guide *guideView Ref *refView } // ---------- rendering ---------- func (s *siteModel) render(out string, rep *report) error { s.md = newMarkdown() s.Year = time.Now().Year() s.buildSymbols() if err := s.copyStatic(out); err != nil { return err } if err := s.parseTemplates(); err != nil { return err } nav := s.nav() order := flatten(nav) write := func(p *page, file string) error { p.Site = s p.Nav = nav if p.Kind == "guide" || p.Kind == "ref" { for i, it := range order { if it.Key == p.Key { if i > 0 { prev := order[i-1] p.Prev = &prev } if i < len(order)-1 { next := order[i+1] p.Next = &next } } } } var buf bytes.Buffer if err := s.tpl.ExecuteTemplate(&buf, "layout", p); err != nil { return fmt.Errorf("%s: %w", file, err) } return writeFile(filepath.Join(out, filepath.FromSlash(file)), buf.Bytes()) } if err := write(s.homePage(), "index.html"); err != nil { return err } for _, g := range s.Guides { p, err := s.guidePage(g) if err != nil { return fmt.Errorf("pages/%s.md: %w", g.Slug, err) } if err := write(p, g.Slug+".html"); err != nil { return err } } for _, r := range s.Refs { p, err := s.refPage(r) if err != nil { return fmt.Errorf("reference/%s.md: %w", r.ID, err) } if err := write(p, "reference/"+r.ID+".html"); err != nil { return err } } if err := write(&page{Kind: "playground", Key: "playground", Title: "Playground", Desc: "Run AGI scripts in your browser against a virtual file system and mocked services."}, "playground.html"); err != nil { return err } if err := writeJSON(filepath.Join(out, "search.json"), s.searchIndex()); err != nil { return err } if err := writeJSON(filepath.Join(out, "playground", "catalog.json"), s.catalog()); err != nil { return err } return writeJSON(filepath.Join(out, "playground", "samples.json"), s.Samples) } // buildSymbols maps every function name and library id to the URL of its // documentation, for linking `code` in the prose. func (s *siteModel) buildSymbols() { s.syms = map[string]string{} for _, r := range s.Refs { url := "reference/" + r.ID + ".html" if r.Load != "" { s.syms[r.ID] = url } for _, f := range r.AllFunctions() { for _, n := range f.Names { if _, taken := s.syms[n]; !taken { s.syms[n] = url + "#" + f.Anchor } } } } } func (s *siteModel) nav() []navGroup { var groups []navGroup for _, g := range s.Guides { if len(groups) == 0 || groups[len(groups)-1].Title != g.Group { groups = append(groups, navGroup{Title: g.Group}) } last := &groups[len(groups)-1] last.Items = append(last.Items, navItem{Title: g.Title, URL: g.Slug + ".html", Key: "guide:" + g.Slug}) } builtin := navGroup{Title: "Built-in functions"} libs := navGroup{Title: "Libraries"} for _, r := range s.Refs { it := navItem{Title: r.Title, URL: "reference/" + r.ID + ".html", Key: "ref:" + r.ID, Icon: libIcons[r.ID]} if builtinRefs[r.ID] { builtin.Items = append(builtin.Items, it) } else { libs.Items = append(libs.Items, it) } } return append(groups, builtin, libs) } func flatten(groups []navGroup) []navItem { var out []navItem for _, g := range groups { out = append(out, g.Items...) } return out } func (s *siteModel) homePage() *page { h := &homeView{Samples: len(s.Samples)} for _, r := range s.Refs { n := len(r.AllFunctions()) h.FnCount += n c := libCard{Title: r.Title, URL: "reference/" + r.ID + ".html", Desc: r.Desc, Icon: libIcons[r.ID], Count: n, Builtin: builtinRefs[r.ID]} if c.Icon == "" { c.Icon = "puzzle" } if c.Builtin { h.Builtins = append(h.Builtins, c) } else { h.Libraries = append(h.Libraries, c) } } for _, g := range s.Guides { if g.Group == "Getting started" { h.Start = append(h.Start, navItem{Title: g.Title, URL: g.Slug + ".html", Sub: g.Summary}) } } return &page{Kind: "home", Key: "home", Title: "AGI Developer Documentation", Desc: "Reference, guides and a browser playground for AGI, the server-side JavaScript runtime of ArozOS WebApps.", Home: h} } func (s *siteModel) guidePage(g *Guide) (*page, error) { rc := &renderCtx{Root: "", Syms: s.syms} body := strings.ReplaceAll(g.Body, "{{agiVersion}}", s.Version) intro, blocks := splitBlocks(body) v := &guideView{Guide: g} var err error if v.Intro, err = s.md.render(intro, rc); err != nil { return nil, err } ids := idSet{} var toc []tocItem for _, b := range blocks { hv, err := s.heading(b, rc, ids) if err != nil { return nil, err } bodyHTML, err := s.md.render(b.Body, rc) if err != nil { return nil, err } v.Items = append(v.Items, itemView{Heading: hv, Body: bodyHTML}) if b.Level <= 3 { toc = append(toc, tocItem{Level: b.Level, ID: hv.ID, Title: plainText(b.Heading)}) } } return &page{ Kind: "guide", Key: "guide:" + g.Slug, Title: g.Title, Desc: g.Summary, TOC: toc, Guide: v, Edit: repoURL + "/edit/master/scripts/agidocgen/pages/" + g.Slug + ".md", }, nil } func (s *siteModel) heading(b *Block, rc *renderCtx, ids idSet) (*headingView, error) { h, err := s.md.inline(b.Heading, rc) if err != nil { return nil, err } hv := &headingView{Level: b.Level, ID: ids.take(slugify(b.Heading)), HTML: h} if gh := githubSlug(b.Heading); gh != "" && gh != hv.ID { hv.Aliases = append(hv.Aliases, ids.take(gh)) } if hv.Level < 2 { hv.Level = 2 } return hv, nil } func (s *siteModel) refPage(r *RefPage) (*page, error) { rc := &renderCtx{Root: "../", Syms: s.syms} v := &refView{Page: r, Builtin: builtinRefs[r.ID], Play: playMode(r.ID)} var err error if v.Intro, err = s.md.render(strings.ReplaceAll(r.Intro, "{{agiVersion}}", s.Version), rc); err != nil { return nil, err } ids := idSet{} var toc []tocItem addEntry := func(f *Function, level int) { fv := &fnView{Level: level, ID: ids.take(anchorFor(f.Names())), Sigs: []sigView{entrySig(f)}} if f.Example != "" { fv.Examples = []string{f.Example} } v.Items = append(v.Items, itemView{Fn: fv}) toc = append(toc, tocItem{Level: level, ID: fv.ID, Title: fv.Sigs[0].Name, Code: true}) } for _, f := range r.Leading { addEntry(f, 2) } for _, b := range r.Blocks { if !b.IsFn { hv, err := s.heading(b, rc, ids) if err != nil { return nil, err } bodyHTML, err := s.md.render(b.Body, rc) if err != nil { return nil, err } v.Items = append(v.Items, itemView{Heading: hv, Body: bodyHTML}) if b.Level <= 3 { toc = append(toc, tocItem{Level: b.Level, ID: hv.ID, Title: plainText(b.Heading)}) } continue } fv, err := s.fnBlock(b, rc, ids) if err != nil { return nil, err } v.Items = append(v.Items, itemView{Fn: fv}) toc = append(toc, tocItem{Level: fv.Level, ID: fv.ID, Title: fv.Sigs[0].Name, Code: true}) for _, f := range b.After { addEntry(f, fv.Level) } } for _, it := range v.Items { if it.Fn == nil { continue } for _, sg := range it.Fn.Sigs { v.Index = append(v.Index, indexRow{Name: sg.Name, Ret: sg.Ret, Desc: sg.Desc, Anchor: it.Fn.ID}) } } for i := range toc { if toc[i].Level > 3 { toc[i].Level = 3 } } return &page{ Kind: "ref", Key: "ref:" + r.ID, Title: r.Title, Desc: r.Desc, Root: "../", TOC: toc, Ref: v, Edit: repoURL + "/edit/master/scripts/agidocgen/reference/" + r.ID + ".md", }, nil } // fnBlock draws a function heading as a card: the api.json signature, // return type and summary, then the Markdown, then any api.json example the // Markdown does not already show. func (s *siteModel) fnBlock(b *Block, rc *renderCtx, ids idSet) (*fnView, error) { skip := map[string]bool{} for _, n := range b.Names() { skip[n] = true } for _, f := range b.Entries { for _, n := range f.Names() { skip[n] = true } } brc := &renderCtx{Root: rc.Root, Syms: rc.Syms, Skip: skip} body, err := s.md.render(strings.ReplaceAll(b.Body, "{{agiVersion}}", s.Version), brc) if err != nil { return nil, err } fv := &fnView{Level: b.Level, Body: body, Badges: b.Badges} if fv.Level < 2 { fv.Level = 2 } if len(b.Entries) > 0 { // The Markdown's own examples win: the api.json one (written for the // Terminal's short help) is only added where the page shows no code. hasCode := len(codeBlocks(b.Body)) > 0 for _, f := range b.Entries { sv := entrySig(f) if sv.Ret == "" { sv.Ret = b.Ret } fv.Sigs = append(fv.Sigs, sv) if f.Example != "" && !hasCode { fv.Examples = append(fv.Examples, f.Example) } } } else { fv.Missing = true desc := firstSentence(b.Body) for _, sp := range b.Sigs { name, args := splitSig(sp.Sig) fv.Sigs = append(fv.Sigs, sigView{Name: name, Args: args, Ret: b.Ret}) } if len(fv.Sigs) == 1 { fv.Sigs[0].Desc = desc } } fv.ID = ids.take(anchorFor(b.Names())) if gh := githubSlug(b.Heading); gh != "" && gh != fv.ID { fv.Aliases = append(fv.Aliases, ids.take(gh)) } return fv, nil } func entrySig(f *Function) sigView { sig := f.Sig if sig == "" { sig = f.Name } name, args := splitSig(sig) sv := sigView{Name: name, Args: args, Ret: f.Ret, Desc: f.Desc} for _, n := range f.Names() { if n != name { sv.Also = append(sv.Also, n) } } return sv } // splitSig separates "filelib.readFile(vpath)" into its name and arguments. func splitSig(sig string) (string, string) { sig = strings.TrimSpace(sig) if i := strings.Index(sig, "("); i > 0 { return strings.TrimSpace(sig[:i]), sig[i:] } return sig, "" } // ---------- search and playground data ---------- type searchEntry struct { T string `json:"t"` // title S string `json:"s"` // where it lives U string `json:"u"` // URL from the docs root D string `json:"d,omitempty"` // summary K string `json:"k"` // page, section or fn } func (s *siteModel) searchIndex() []searchEntry { var out []searchEntry for _, g := range s.Guides { out = append(out, searchEntry{T: g.Title, S: "Guide", U: g.Slug + ".html", D: g.Summary, K: "page"}) _, blocks := splitBlocks(g.Body) ids := idSet{} for _, b := range blocks { id := ids.take(slugify(b.Heading)) if gh := githubSlug(b.Heading); gh != "" && gh != id { ids.take(gh) } out = append(out, searchEntry{T: plainText(b.Heading), S: g.Title, U: g.Slug + ".html#" + id, K: "section"}) } } for _, r := range s.Refs { url := "reference/" + r.ID + ".html" kind := "Library" if builtinRefs[r.ID] { kind = "Built-in functions" } out = append(out, searchEntry{T: r.Title, S: kind, U: url, D: r.Desc, K: "page"}) for _, f := range r.AllFunctions() { ret := "" if f.Ret != "" { ret = " → " + f.Ret } for _, n := range f.Names { out = append(out, searchEntry{T: n, S: r.Title + ret, U: url + "#" + f.Anchor, D: f.Desc, K: "fn"}) } } } out = append(out, searchEntry{T: "Playground", S: "Tool", U: "playground.html", D: "Run AGI scripts in your browser.", K: "page"}) return out } // catalogLib tells the playground which functions each library has, so the // libraries it cannot run for real still exist and answer with mock data. type catalogLib struct { ID string `json:"id"` Title string `json:"title"` Load string `json:"load,omitempty"` Play string `json:"play"` Fns []FnInfo `json:"fns"` } func (s *siteModel) catalog() []catalogLib { var out []catalogLib for _, r := range s.Refs { out = append(out, catalogLib{ID: r.ID, Title: r.Title, Load: r.Load, Play: playMode(r.ID), Fns: r.AllFunctions()}) } return out } // playModes says how the playground serves each page: "runs" for what its // engine does for real (on the virtual drive and session), otherwise the // tool window whose answers the library returns. Libraries not listed are // generic mocks answered from the Services window. Keep in step with // playground.NativeLibs. var playModes = map[string]string{ "core": "runs", "db": "runs", "user": "runs", "filelib": "runs", "imagelib": "runs", "appdata": "runs", "ziplib": "runs", "share": "runs", "websocket": "runs", "scheduler": "runs", "notification": "runs", "http": "HTTP", "llm": "LLM", "cnn": "CNN", "sqlite": "Services", "sysinfo": "Services", } func playMode(id string) string { if m, ok := playModes[id]; ok { return m } return "Services" } // ---------- static files and templates ---------- // copyStatic copies static/ into the output and derives the cache-busting // version from the content of every file. func (s *siteModel) copyStatic(out string) error { h := sha1.New() err := filepath.WalkDir("static", func(p string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() { return err } raw, err := os.ReadFile(p) if err != nil { return err } rel, _ := filepath.Rel("static", p) h.Write([]byte(filepath.ToSlash(rel))) h.Write(raw) return writeFile(filepath.Join(out, rel), raw) }) if err != nil { return err } h.Write([]byte(s.Version)) s.assetVer = hex.EncodeToString(h.Sum(nil))[:10] return nil } func (s *siteModel) parseTemplates() error { funcs := template.FuncMap{ "icon": func(name string) (template.HTML, error) { ic, ok := s.Icons[name] if !ok { return "", fmt.Errorf("no icon named %q", name) } return ic, nil }, "asset": func(root, p string) string { return root + p + "?v=" + s.assetVer }, "ver": func() string { return s.assetVer }, "lower": strings.ToLower, "base": path.Base, "heading": func(level int, id string, aliases []string, inner template.HTML) template.HTML { if level < 2 { level = 2 } if level > 6 { level = 6 } var b strings.Builder fmt.Fprintf(&b, ``, level, template.HTMLEscapeString(id)) for _, a := range aliases { fmt.Fprintf(&b, ``, template.HTMLEscapeString(a)) } fmt.Fprintf(&b, `%s#`, inner, template.HTMLEscapeString(id), level) return template.HTML(b.String()) }, } files, err := filepath.Glob(filepath.Join("templates", "*.html")) if err != nil { return err } sort.Strings(files) t, err := template.New("").Funcs(funcs).ParseFiles(files...) if err != nil { return err } s.tpl = t return nil }