feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
package tsgen
import (
"encoding/json/jsontext"
"encoding/json/v2"
"reflect"
"strings"
"testing"
)
type fallbackMap struct {
Name string `json:"name"`
Extra map[string]int `json:",embed"`
}
type fallbackRaw struct {
Name string `json:"name"`
Extra jsontext.Value `json:",embed"`
}
func TestEmbeddedFallbacks(t *testing.T) {
extra := map[string]int{"count": 2}
for _, value := range []any{
fallbackMap{Name: "notes", Extra: extra},
fallbackRaw{Name: "notes", Extra: jsontext.Value(`{"count":2}`)},
struct {
Name string `json:"name"`
Extra *map[string]int `json:",embed"`
}{"notes", &extra},
} {
wire, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
if string(wire) != `{"name":"notes","count":2}` {
t.Fatalf("wire = %s", wire)
}
typ := reflect.TypeOf(value)
if err := Validate(typ); err != nil {
t.Fatal(err)
}
out, err := Generate(Model{Events: []Event{{Name: "payload", Type: typ}}})
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"name: string", "[key: string]: unknown"} {
if !strings.Contains(string(out), want) {
t.Errorf("%v: client lacks %s:\n%s", typ, want, out)
}
}
if strings.Contains(string(out), "Extra:") {
t.Errorf("%v: client exposes a nested fallback:\n%s", typ, out)
}
}
}
func TestEmbeddedFallbackValidation(t *testing.T) {
type bad struct {
Extra map[string]func() `json:",embed"`
}
if err := Validate(reflect.TypeFor[bad]()); err == nil {
t.Fatal("embedded map values bypassed validation")
}
}
+534
View File
@@ -0,0 +1,534 @@
// Package tsgen generates a typed TypeScript client for Go services bound
// with mygo.Bind and events declared with mygo.NewEvent.
//
// Types are derived with reflection following the encoding/json/v2 rules
// used on the wire. Parameter names, documentation and enum values are read
// from the Go sources when they are available.
package tsgen
import (
"bytes"
"fmt"
"maps"
"reflect"
"slices"
"strings"
)
// Model describes the API to generate a client for.
type Model struct {
Services []Service
Events []Event
}
// Service is a bound Go value whose methods are callable from the page.
type Service struct {
Name string
Type reflect.Type
Methods []Method
}
// Method is a bound method. Params excludes the receiver and an optional
// leading context.Context (HasCtx).
type Method struct {
Name string
Params []reflect.Type
// Channels marks the parameters that are channels (mygo.Channel),
// whose Params are the type of their values.
Channels []bool
Variadic bool
Result reflect.Type
HasCtx bool
// PC is the entry of the method's code, used to find its source.
PC uintptr
}
// Event is a typed event sent from Go to pages.
type Event struct {
Name string
Type reflect.Type
// PC, File and Line locate the declaration, used to find its package
// and documentation.
PC uintptr
File string
Line int
}
type generator struct {
src *sources
names map[reflect.Type]string
taken map[string]reflect.Type
decls map[string]string
busy map[reflect.Type]bool
// imported are the types of mygo-runtime the client uses.
imported map[string]bool
}
// runtimeTypes are the types of package mygo whose JSON is a type of
// mygo-runtime, by the Go type's package path and name: the client
// imports that type instead of declaring one, which their JSON methods
// would leave unknown.
var runtimeTypes = map[string]string{
"github.com/egoist/mygo.ThemePreferences": "ThemePreferences",
}
// runtimeSentinel reserves imported and built-in type names in
// generator.taken, so types of the app with those names get others.
type runtimeSentinel struct{}
// Generate renders the TypeScript client.
func Generate(m Model) ([]byte, error) {
for _, s := range m.Services {
if !IsIdentifier(s.Name) || reserved[s.Name] {
return nil, fmt.Errorf("service %q is not a TypeScript binding name", s.Name)
}
if s.Name == "call" || len(m.Events) > 0 && (s.Name == "event" || s.Name == "events") {
return nil, fmt.Errorf("service %q conflicts with a generated TypeScript binding", s.Name)
}
}
g := &generator{
src: newSources(),
names: map[reflect.Type]string{},
taken: map[string]reflect.Type{},
decls: map[string]string{},
busy: map[reflect.Type]bool{},
imported: map[string]bool{},
}
for _, name := range []string{"Promise", "Record"} {
g.taken[name] = reflect.TypeFor[runtimeSentinel]()
}
for _, name := range runtimeTypes {
g.taken[name] = reflect.TypeFor[runtimeSentinel]()
}
// Reserve imported names and learn package directories before declaring types.
type methodSrc struct {
file string
line int
}
locs := map[*Method]methodSrc{}
for si := range m.Services {
for mi := range m.Services[si].Methods {
meth := &m.Services[si].Methods[mi]
// A later method may need Channel after an app type was named.
if slices.Contains(meth.Channels, true) {
g.taken["Channel"] = reflect.TypeFor[runtimeSentinel]()
}
file, line := g.src.learnPC(meth.PC)
locs[meth] = methodSrc{file, line}
}
}
for _, e := range m.Events {
g.src.learnPC(e.PC)
}
g.src.resolvePackages(collectPackages(m))
var services bytes.Buffer
channels := false
for _, s := range m.Services {
base := s.Type
if base.Kind() == reflect.Pointer {
base = base.Elem()
}
writeDoc(&services, "", g.src.typeDoc(base))
fmt.Fprintf(&services, "export const %s = {\n", s.Name)
methodNames := map[string]string{}
for i := range s.Methods {
meth := &s.Methods[i]
name := camel(meth.Name)
if previous, ok := methodNames[name]; ok {
return nil, fmt.Errorf("service %s: methods %s and %s both generate TypeScript name %q", s.Name, previous, meth.Name, name)
}
methodNames[name] = meth.Name
loc := locs[meth]
fd := g.src.funcDecl(loc.file, loc.line, meth.Name)
var names []string
doc := ""
if fd != nil {
names = paramNames(fd)
if meth.HasCtx && len(names) > 0 {
names = names[1:]
}
if fd.Doc != nil {
doc = fd.Doc.Text()
}
}
var params, args, types []string
// Parameters must not shadow the runtime function called below.
used := map[string]bool{"call": true, "bind": true}
for pi, pt := range meth.Params {
name := ""
if pi < len(names) {
name = names[pi]
}
name = safeName(or(name, fmt.Sprintf("arg%d", pi)))
for used[name] {
name += "_"
}
used[name] = true
if meth.Variadic && pi == len(meth.Params)-1 {
params = append(params, "..."+name+": "+arrayOf(g.ts(pt.Elem())))
args = append(args, "..."+name)
types = append(types, "..."+arrayOf(g.ts(pt.Elem())))
continue
}
typ := g.ts(pt)
if pi < len(meth.Channels) && meth.Channels[pi] {
typ = "Channel<" + typ + ">"
channels = true
}
params = append(params, name+": "+typ)
args = append(args, name)
types = append(types, typ)
}
result := "void"
if meth.Result != nil {
result = g.ts(meth.Result)
}
writeDoc(&services, " ", doc)
// The arguments are built at the call, so that the options of
// the call can be given with them.
fmt.Fprintf(&services, " %s: bind<[%s], %s>(%s, (%s) => [%s]),\n",
name, strings.Join(types, ", "), result, quote(s.Name+"."+meth.Name),
strings.Join(params, ", "), strings.Join(args, ", "))
}
services.WriteString("} as const;\n\n")
}
var events bytes.Buffer
if len(m.Events) > 0 {
events.WriteString("/** Events sent by the Go side. Subscribe with `events.name.on(listener)`. */\n")
events.WriteString("export const events = {\n")
eventNames := map[string]string{}
for _, e := range m.Events {
name := eventKey(e.Name)
if previous, ok := eventNames[name]; ok {
return nil, fmt.Errorf("events %q and %q both generate TypeScript name %s", previous, e.Name, name)
}
eventNames[name] = e.Name
writeDoc(&events, " ", g.src.valueDoc(e.File, e.Line))
fmt.Fprintf(&events, " %s: event<%s>(%s),\n", name, g.ts(e.Type), quote(e.Name))
}
events.WriteString("} as const;\n")
}
var out bytes.Buffer
out.WriteString(header)
// The runtime comes from the mygo-runtime package.
var imports []string
if services.Len() > 0 {
imports = append(imports, "bind")
}
if events.Len() > 0 {
imports = append(imports, "event")
}
if channels {
imports = append(imports, "type Channel")
}
for _, name := range slices.Sorted(maps.Keys(g.imported)) {
imports = append(imports, "type "+name)
}
if len(imports) > 0 {
fmt.Fprintf(&out, "import { %s } from %q;\n", strings.Join(imports, ", "), RuntimePackage)
}
if len(g.decls) > 0 {
out.WriteString("\n// ---- Types ----\n\n")
names := make([]string, 0, len(g.decls))
for n := range g.decls {
names = append(names, n)
}
slices.Sort(names)
for _, n := range names {
out.WriteString(g.decls[n])
out.WriteByte('\n')
}
}
if services.Len() > 0 {
if len(g.decls) == 0 {
out.WriteByte('\n')
}
out.WriteString("// ---- Services ----\n\n")
out.Write(services.Bytes())
}
if events.Len() > 0 {
out.WriteString("// ---- Events ----\n\n")
out.Write(events.Bytes())
}
return bytes.TrimRight(out.Bytes(), "\n"), nil
}
func or(s, fallback string) string {
if s == "" {
return fallback
}
return s
}
// collectPackages lists the packages of all named types reachable from m.
func collectPackages(m Model) []string {
seen := map[reflect.Type]bool{}
pkgs := map[string]bool{}
var visit func(t reflect.Type)
visit = func(t reflect.Type) {
if t == nil || seen[t] {
return
}
seen[t] = true
if t.PkgPath() != "" {
pkgs[t.PkgPath()] = true
}
if _, ok := special(t); ok {
return
}
switch t.Kind() {
case reflect.Pointer, reflect.Slice, reflect.Array:
visit(t.Elem())
case reflect.Map:
visit(t.Key())
visit(t.Elem())
case reflect.Struct:
for _, f := range structFields(t) {
visit(f.owner)
visit(f.typ)
}
}
}
for _, s := range m.Services {
visit(s.Type)
for _, meth := range s.Methods {
for _, p := range meth.Params {
visit(p)
}
visit(meth.Result)
}
}
for _, e := range m.Events {
visit(e.Type)
}
out := make([]string, 0, len(pkgs))
for p := range pkgs {
out = append(out, p)
}
slices.Sort(out)
return out
}
func arrayOf(t string) string {
if strings.ContainsAny(t, "|&") || strings.HasPrefix(t, "(") {
return "(" + t + ")[]"
}
return t + "[]"
}
// ts returns the TypeScript type for t, declaring named types as needed.
func (g *generator) ts(t reflect.Type) string {
// Pointers first: *T has the JSON methods of T in its method set.
if t.Kind() == reflect.Pointer {
inner := g.ts(t.Elem())
if strings.HasSuffix(inner, " | null") {
return inner
}
return inner + " | null"
}
if name, ok := runtimeTypes[t.PkgPath()+"."+t.Name()]; ok && t.Name() != "" {
g.imported[name] = true
return name
}
if s, ok := special(t); ok {
return s
}
switch t.Kind() {
case reflect.Bool:
return g.alias(t, "boolean")
case reflect.String:
return g.alias(t, "string")
case reflect.Interface:
return "unknown"
case reflect.Slice, reflect.Array:
return g.alias(t, "")
case reflect.Map:
return g.alias(t, "")
case reflect.Struct:
if t.Name() == "" {
return g.inlineObject(t)
}
return g.declareStruct(t)
}
if isNumber(t.Kind()) {
return g.alias(t, "number")
}
return "unknown"
}
// structural renders the underlying TypeScript type of t, ignoring its name.
func (g *generator) structural(t reflect.Type) string {
switch t.Kind() {
case reflect.Slice, reflect.Array:
return arrayOf(g.ts(t.Elem()))
case reflect.Map:
key := "string"
if isNumber(t.Key().Kind()) {
if _, custom := special(t.Key()); !custom {
key = "number"
}
}
return "Record<" + key + ", " + g.ts(t.Elem()) + ">"
}
return "unknown"
}
// alias returns base for unnamed types and declares an exported alias for
// named ones. Named string and number types with constants become unions.
func (g *generator) alias(t reflect.Type, base string) string {
if t.Name() == "" || t.PkgPath() == "" {
if base == "" {
return g.structural(t)
}
return base
}
if name, ok := g.names[t]; ok {
return name
}
name := g.nameFor(t)
g.busy[t] = true
var body string
if values := g.src.enumValues(t); len(values) > 0 {
body = strings.Join(values, " | ")
} else if base != "" {
body = base
} else {
body = g.structural(t)
}
var b bytes.Buffer
writeDoc(&b, "", g.src.typeDoc(t))
fmt.Fprintf(&b, "export type %s = %s;\n", name, body)
g.decls[name] = b.String()
return name
}
func (g *generator) nameFor(t reflect.Type) string {
if name, ok := g.names[t]; ok {
return name
}
name := typeName(t.Name())
if other, taken := g.taken[name]; taken && other != t {
pkg := t.PkgPath()
if i := strings.LastIndex(pkg, "/"); i >= 0 {
pkg = pkg[i+1:]
}
base := typeName(pkg) + name
name = base
for n := 2; ; n++ {
if _, taken := g.taken[name]; !taken {
break
}
name = fmt.Sprintf("%s%d", base, n)
}
}
g.taken[name] = t
g.names[t] = name
return name
}
func (g *generator) declareStruct(t reflect.Type) string {
name := g.nameFor(t)
if _, done := g.decls[name]; done || g.busy[t] {
return name
}
g.busy[t] = true
var b bytes.Buffer
writeDoc(&b, "", g.src.typeDoc(t))
fmt.Fprintf(&b, "export interface %s %s\n", name, g.object(t, ""))
g.decls[name] = b.String()
return name
}
// inlineObject renders an anonymous struct on one line.
func (g *generator) inlineObject(t reflect.Type) string {
fields := structFields(t)
if len(fields) == 0 {
return "{}"
}
parts := make([]string, 0, len(fields))
for _, f := range fields {
if f.fallback {
parts = append(parts, "[key: string]: unknown")
continue
}
typ, opt := g.fieldType(f)
parts = append(parts, propertyName(f.name)+opt+": "+typ)
}
return "{ " + strings.Join(parts, "; ") + " }"
}
func (g *generator) fieldType(f field) (typ, opt string) {
typ = g.ts(f.typ)
if f.quoted {
t := f.typ
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
if isNumber(t.Kind()) && !implements(t, jsonMarshaler) && !implements(t, jsonMarshalerTo) {
typ = "string"
if f.typ.Kind() == reflect.Pointer {
typ += " | null"
}
}
}
if f.optional {
// Omitted rather than null.
return strings.TrimSuffix(typ, " | null"), "?"
}
return typ, ""
}
// object renders the members of a struct as an object type literal.
func (g *generator) object(t reflect.Type, indent string) string {
fields := structFields(t)
if len(fields) == 0 {
return "{}"
}
var b bytes.Buffer
b.WriteString("{\n")
for _, f := range fields {
if f.fallback {
fmt.Fprintf(&b, "%s [key: string]: unknown;\n", indent)
continue
}
typ, opt := g.fieldType(f)
writeDoc(&b, indent+" ", g.src.fieldDoc(f.owner, f.goName))
fmt.Fprintf(&b, "%s %s%s: %s;\n", indent, propertyName(f.name), opt, typ)
}
b.WriteString(indent + "}")
return b.String()
}
// writeDoc writes a Go doc comment as JSDoc.
func writeDoc(b *bytes.Buffer, indent, doc string) {
doc = strings.TrimSpace(doc)
if doc == "" {
return
}
doc = strings.ReplaceAll(doc, "*/", "*\\/")
lines := strings.Split(doc, "\n")
if len(lines) == 1 {
fmt.Fprintf(b, "%s/** %s */\n", indent, lines[0])
return
}
fmt.Fprintf(b, "%s/**\n", indent)
for _, l := range lines {
if l == "" {
fmt.Fprintf(b, "%s *\n", indent)
} else {
fmt.Fprintf(b, "%s * %s\n", indent, l)
}
}
fmt.Fprintf(b, "%s */\n", indent)
}
const header = "// Code generated by `mygo generate`. DO NOT EDIT.\n\n"
// RuntimePackage is the npm package of the page runtime, which generated
// clients import.
const RuntimePackage = "mygo-runtime"
@@ -0,0 +1,118 @@
// Package fixture declares types used to test the TypeScript generator.
package fixture
import (
"context"
"encoding/json"
"errors"
"time"
)
// Status is the state of a task.
type Status string
// Task states.
const (
StatusTodo Status = "todo"
StatusDone Status = "done"
)
// Priority orders tasks.
type Priority int
// Priorities.
const (
Low Priority = iota
Medium
High
)
// Timestamps is embedded in records.
type Timestamps struct {
CreatedAt time.Time `json:"createdAt"`
}
// Channel groups tasks, and shares its name with the runtime's stream type.
type Channel struct {
Name string `json:"name"`
}
// Record has a map that uses TypeScript's Record utility type.
type Record struct {
Values map[string]string `json:"values"`
}
// Promise shares its name with the return type of generated methods.
type Promise struct {
Done bool `json:"done"`
}
// Task is a unit of work.
type Task struct {
ID int64 `json:"id"`
// Title of the task.
Title string `json:"title"`
Status Status `json:"status"`
Priority Priority `json:"priority"`
Tags []string `json:"tags"`
Due *time.Time `json:"due"`
Meta map[string]any `json:"meta,omitempty"`
Parent *Task `json:"parent,omitzero"`
Channel *Channel `json:"channel,omitzero"`
Record *Record `json:"record,omitzero"`
Promise *Promise `json:"promise,omitzero"`
Secret string `json:"-"`
Count int64 `json:"count,string"`
CountPtr *int64 `json:"countPtr,string"`
Raw json.RawMessage `json:"raw"`
Data []byte `json:"data"`
Scores map[int]float64 `json:"scores"`
Matrix [][]int `json:"matrix"`
Children []*Task `json:"children"`
Extra struct{ A bool } `json:"extra"`
NoTag string
internal int
Timestamps
}
// Page is a page of results.
type Page[T any] struct {
Items []T `json:"items"`
Next string `json:"next,omitempty"`
}
// Tasks manages tasks.
type Tasks struct{}
// List returns tasks with the given status.
func (Tasks) List(ctx context.Context, status Status, limit int) (Page[Task], error) {
return Page[Task]{}, nil
}
// Add adds tasks.
//
// It fails when a task has no title.
func (*Tasks) Add(tasks ...Task) error {
for _, t := range tasks {
if t.Title == "" {
return errors.New("missing title")
}
}
return nil
}
// Count counts tasks.
func (Tasks) Count() int { return 0 }
// Delete removes a task; the parameter is unnamed on purpose.
func (Tasks) Delete(int64) {}
// Dispatch deliberately names parameters after the runtime's call function.
func (Tasks) Dispatch(call, call_ string) {}
// DispatchMany uses the runtime's call name for a variadic parameter.
func (Tasks) DispatchMany(call ...string) {}
// Watch sends the tasks with the given status as they change. The test
// declares updates a channel of tasks.
func (Tasks) Watch(status Status, updates Task) {}
+179
View File
@@ -0,0 +1,179 @@
package tsgen
import (
"strings"
"unicode"
"unicode/utf8"
)
// reserved lists JavaScript/TypeScript words that cannot be used as
// parameter or binding names.
var reserved = map[string]bool{
"arguments": true, "await": true, "break": true, "case": true, "catch": true,
"class": true, "const": true, "continue": true, "debugger": true, "default": true,
"delete": true, "do": true, "else": true, "enum": true, "eval": true,
"export": true, "extends": true, "false": true, "finally": true, "for": true,
"function": true, "if": true, "implements": true, "import": true, "in": true,
"instanceof": true, "interface": true, "let": true, "new": true, "null": true,
"package": true, "private": true, "protected": true, "public": true,
"return": true, "static": true, "super": true, "switch": true, "this": true,
"throw": true, "true": true, "try": true, "typeof": true, "var": true,
"void": true, "while": true, "with": true, "yield": true,
}
// IsIdentifier reports whether s is a valid JavaScript identifier made of
// ASCII letters, digits, '_' and '$'.
func IsIdentifier(s string) bool {
if s == "" {
return false
}
for i, r := range s {
switch {
case r == '_' || r == '$' || ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z'):
case i > 0 && '0' <= r && r <= '9':
default:
return false
}
}
return true
}
// safeName makes s usable as a parameter name.
func safeName(s string) string {
if !IsIdentifier(s) {
s = strings.Map(func(r rune) rune {
if r == '_' || r == '$' || unicode.IsLetter(r) || unicode.IsDigit(r) {
return r
}
return '_'
}, s)
if s == "" || unicode.IsDigit([]rune(s)[0]) {
s = "_" + s
}
}
if reserved[s] {
s += "_"
}
return s
}
// propertyName renders an object property name, quoting it when needed.
func propertyName(s string) string {
if IsIdentifier(s) {
return s
}
return quote(s)
}
// camel converts a Go identifier to lower camel case: "GetUserByID" becomes
// "getUserByID", "URLFor" becomes "urlFor" and "ID" becomes "id".
func camel(s string) string {
runes := []rune(s)
n := 0
for n < len(runes) && unicode.IsUpper(runes[n]) {
n++
}
switch {
case n == 0:
return s
case n == 1 || n == len(runes):
// "Greet" -> "greet", "ID" -> "id"
for i := 0; i < n; i++ {
runes[i] = unicode.ToLower(runes[i])
}
default:
// "URLFor" -> "urlFor": keep the last upper case letter, which
// starts the next word.
for i := 0; i < n-1; i++ {
runes[i] = unicode.ToLower(runes[i])
}
}
return string(runes)
}
// eventKey converts an event name such as "file-changed" or "app:ready" to
// a property name like "fileChanged" / "appReady".
func eventKey(name string) string {
var b strings.Builder
upper := false
for i, r := range name {
if r == '-' || r == '_' || r == ':' || r == '.' || r == ' ' || r == '/' {
upper = b.Len() > 0
continue
}
if upper {
r = unicode.ToUpper(r)
upper = false
} else if i == 0 {
r = unicode.ToLower(r)
}
b.WriteRune(r)
}
key := b.String()
if !IsIdentifier(key) {
return quote(name)
}
return key
}
// typeName turns a reflect type name, possibly with type arguments such as
// "Page[github.com/x/app.User]", into a TypeScript identifier ("PageUser").
func typeName(name string) string {
var b strings.Builder
var part strings.Builder
flush := func() {
p := part.String()
part.Reset()
if i := strings.LastIndexAny(p, "./"); i >= 0 {
p = p[i+1:]
}
if p == "" {
return
}
r, size := utf8.DecodeRuneInString(p)
b.WriteRune(unicode.ToUpper(r))
b.WriteString(p[size:])
}
for _, r := range name {
switch r {
case '[', ']', ',', ' ', '*':
flush()
default:
part.WriteRune(r)
}
}
flush()
return safeName(b.String())
}
func quote(s string) string {
var b strings.Builder
b.WriteByte('"')
for _, r := range s {
switch r {
case '"', '\\':
b.WriteByte('\\')
b.WriteRune(r)
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\t':
b.WriteString(`\t`)
case '
':
b.WriteString(`
`)
case '
':
b.WriteString(`
`)
default:
if r < 0x20 {
b.WriteString(`\u00`)
b.WriteByte("0123456789abcdef"[r>>4])
b.WriteByte("0123456789abcdef"[r&0xf])
} else {
b.WriteRune(r)
}
}
}
b.WriteByte('"')
return b.String()
}
+51
View File
@@ -0,0 +1,51 @@
package tsgen
import (
"encoding/json/v2"
"reflect"
"strings"
"testing"
)
type quotedNumber int64
type customNumber int64
func (customNumber) MarshalJSON() ([]byte, error) { return []byte(`{"value":1}`), nil }
func TestQuotedNumberPointers(t *testing.T) {
type payload struct {
Count *int64 `json:"count,string"`
Nested **int64 `json:"nested,string"`
Optional *int64 `json:"optional,string,omitempty"`
Named *quotedNumber `json:"named,string"`
Custom *customNumber `json:"custom,string"`
}
n := int64(9007199254740993)
p := &n
named, custom := quotedNumber(n), customNumber(1)
value := payload{Count: p, Nested: &p, Named: &named, Custom: &custom}
wire, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
if want := `{"count":"9007199254740993","nested":"9007199254740993","named":"9007199254740993","custom":{"value":1}}`; string(wire) != want {
t.Fatalf("wire = %s", wire)
}
wire, err = json.Marshal(payload{})
if err != nil {
t.Fatal(err)
}
if want := `{"count":null,"nested":null,"named":null,"custom":null}`; string(wire) != want {
t.Fatalf("nil wire = %s", wire)
}
out, err := Generate(Model{Events: []Event{{Name: "payload", Type: reflect.TypeFor[payload]()}}})
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"count: string | null;", "nested: string | null;", "optional?: string;", "named: string | null;", "custom: unknown | null;"} {
if !strings.Contains(string(out), want) {
t.Errorf("client lacks %s:\n%s", want, out)
}
}
}
+40
View File
@@ -0,0 +1,40 @@
package tsgen
import (
"reflect"
"strings"
"testing"
)
func TestServiceExportNames(t *testing.T) {
for _, tc := range []struct {
name string
events, valid bool
}{
{"await", false, false}, {"default", false, false}, {"class", false, false},
{"call", false, false}, {"event", true, false}, {"events", true, false},
{"event", false, true}, {"events", false, true}, {"Tasks", true, true},
} {
name := tc.name
if tc.events {
name += "WithEvents"
}
t.Run(name, func(t *testing.T) {
m := Model{Services: []Service{{Name: tc.name, Type: reflect.TypeFor[struct{}](), Methods: []Method{{Name: "Run"}}}}}
if tc.events {
m.Events = []Event{{Name: "changed", Type: reflect.TypeFor[string]()}}
}
out, err := Generate(m)
if tc.valid {
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(out), `export const `+tc.name+` =`) || !strings.Contains(string(out), `"`+tc.name+`.Run"`) {
t.Fatalf("lost service name: %s", out)
}
} else if err == nil || !strings.Contains(err.Error(), tc.name) {
t.Fatalf("Generate must report service %q rather than write an invalid binding: %v\n%s", tc.name, err, out)
}
})
}
}
+381
View File
@@ -0,0 +1,381 @@
package tsgen
import (
"go/ast"
"go/parser"
"go/token"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
)
// sources reads Go source files to enrich the generated client with
// parameter names, documentation and enum values. Everything it provides is
// optional: the client is still correct when sources are unavailable, e.g.
// in binaries built with -trimpath.
type sources struct {
fset *token.FileSet
files map[string]*ast.File
dirs map[string][]*ast.File
pkgDir map[string]string
}
func newSources() *sources {
return &sources{
fset: token.NewFileSet(),
files: map[string]*ast.File{},
dirs: map[string][]*ast.File{},
pkgDir: map[string]string{},
}
}
func (s *sources) file(path string) *ast.File {
if f, ok := s.files[path]; ok {
return f
}
f, err := parser.ParseFile(s.fset, path, nil, parser.ParseComments|parser.SkipObjectResolution)
if err != nil {
f = nil
}
s.files[path] = f
return f
}
// dirFiles parses the non-test Go files of a directory.
func (s *sources) dirFiles(dir string) []*ast.File {
if files, ok := s.dirs[dir]; ok {
return files
}
var files []*ast.File
entries, _ := os.ReadDir(dir)
for _, e := range entries {
name := e.Name()
if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
continue
}
if f := s.file(filepath.Join(dir, name)); f != nil {
files = append(files, f)
}
}
s.dirs[dir] = files
return files
}
// funcPackage extracts the package path from a runtime function name such
// as "github.com/x/app/svc.(*Greeter).Greet".
func funcPackage(name string) string {
slash := strings.LastIndex(name, "/")
dot := strings.Index(name[slash+1:], ".")
if dot < 0 {
return ""
}
return name[:slash+1+dot]
}
// learnPC records the directory of the package that contains pc.
func (s *sources) learnPC(pc uintptr) (file string, line int) {
fn := runtime.FuncForPC(pc)
if fn == nil {
return "", 0
}
file, line = fn.FileLine(fn.Entry())
if pkg := funcPackage(fn.Name()); pkg != "" && filepath.IsAbs(file) {
if _, ok := s.pkgDir[pkg]; !ok {
s.pkgDir[pkg] = filepath.Dir(file)
}
}
return file, line
}
// resolvePackages asks the go command for the directories of packages that
// were not discovered through program counters.
func (s *sources) resolvePackages(pkgs []string) {
var missing []string
for _, p := range pkgs {
if _, ok := s.pkgDir[p]; !ok && p != "main" && strings.Contains(strings.Split(p, "/")[0], ".") {
missing = append(missing, p)
}
}
if len(missing) == 0 {
return
}
goBin, err := exec.LookPath("go")
if err != nil {
return
}
out, err := exec.Command(goBin, append([]string{"list", "-e", "-f", "{{.ImportPath}} {{.Dir}}"}, missing...)...).Output()
if err != nil {
return
}
for _, line := range strings.Split(string(out), "\n") {
pkg, dir, ok := strings.Cut(line, " ")
if ok && dir != "" {
s.pkgDir[pkg] = dir
}
}
}
// funcDecl finds the declaration of the method containing the given
// source position.
func (s *sources) funcDecl(file string, line int, name string) *ast.FuncDecl {
if file == "" {
return nil
}
f := s.file(file)
if f == nil {
return nil
}
for _, d := range f.Decls {
fd, ok := d.(*ast.FuncDecl)
if !ok || fd.Name.Name != name {
continue
}
start, end := s.fset.Position(fd.Pos()).Line, s.fset.Position(fd.End()).Line
if start <= line && line <= end {
return fd
}
}
return nil
}
// paramNames returns the names of all parameters of fd; unnamed parameters
// yield "".
func paramNames(fd *ast.FuncDecl) []string {
var names []string
for _, p := range fd.Type.Params.List {
if len(p.Names) == 0 {
names = append(names, "")
continue
}
for _, n := range p.Names {
if n.Name == "_" {
names = append(names, "")
} else {
names = append(names, n.Name)
}
}
}
return names
}
// typeDecl finds the declaration of a named type in its package directory.
func (s *sources) typeDecl(t reflect.Type) (*ast.TypeSpec, *ast.GenDecl) {
dir, ok := s.pkgDir[t.PkgPath()]
if !ok {
return nil, nil
}
name := t.Name()
if i := strings.IndexByte(name, '['); i >= 0 {
name = name[:i]
}
for _, f := range s.dirFiles(dir) {
for _, d := range f.Decls {
gd, ok := d.(*ast.GenDecl)
if !ok || gd.Tok != token.TYPE {
continue
}
for _, spec := range gd.Specs {
if ts := spec.(*ast.TypeSpec); ts.Name.Name == name {
return ts, gd
}
}
}
}
return nil, nil
}
// typeDoc returns the documentation of a named type.
func (s *sources) typeDoc(t reflect.Type) string {
ts, gd := s.typeDecl(t)
if ts == nil {
return ""
}
if ts.Doc != nil {
return ts.Doc.Text()
}
if gd.Doc != nil && len(gd.Specs) == 1 {
return gd.Doc.Text()
}
return ""
}
// fieldDoc returns the documentation of a struct field.
func (s *sources) fieldDoc(owner reflect.Type, goName string) string {
if owner.Name() == "" {
return ""
}
ts, _ := s.typeDecl(owner)
if ts == nil {
return ""
}
st, ok := ts.Type.(*ast.StructType)
if !ok {
return ""
}
for _, f := range st.Fields.List {
for _, n := range f.Names {
if n.Name != goName {
continue
}
if f.Doc != nil {
return f.Doc.Text()
}
if f.Comment != nil {
return f.Comment.Text()
}
return ""
}
}
return ""
}
// valueDoc returns the documentation of the variable declared at the
// given position, used for events.
func (s *sources) valueDoc(file string, line int) string {
if file == "" {
return ""
}
f := s.file(file)
if f == nil {
return ""
}
for _, d := range f.Decls {
gd, ok := d.(*ast.GenDecl)
if !ok || gd.Tok != token.VAR {
continue
}
for _, spec := range gd.Specs {
vs := spec.(*ast.ValueSpec)
start, end := s.fset.Position(vs.Pos()).Line, s.fset.Position(vs.End()).Line
if line < start || line > end {
continue
}
if vs.Doc != nil {
return vs.Doc.Text()
}
if gd.Doc != nil && len(gd.Specs) == 1 {
return gd.Doc.Text()
}
return ""
}
}
return ""
}
// enumValues returns TypeScript literals of the constants declared with
// type t, or nil if there are none or one cannot be evaluated.
func (s *sources) enumValues(t reflect.Type) []string {
dir, ok := s.pkgDir[t.PkgPath()]
if !ok || t.Name() == "" {
return nil
}
var values []string
seen := map[string]bool{}
for _, f := range s.dirFiles(dir) {
for _, d := range f.Decls {
gd, ok := d.(*ast.GenDecl)
if !ok || gd.Tok != token.CONST {
continue
}
var lastType ast.Expr
var lastValues []ast.Expr
for iota, spec := range gd.Specs {
vs := spec.(*ast.ValueSpec)
if len(vs.Values) > 0 {
lastType, lastValues = vs.Type, vs.Values
}
ident, ok := lastType.(*ast.Ident)
if !ok || ident.Name != t.Name() {
continue
}
for i := range vs.Names {
if vs.Names[i].Name == "_" {
continue
}
if i >= len(lastValues) {
return nil
}
lit, ok := evalConst(lastValues[i], int64(iota), t.Kind())
if !ok {
return nil
}
if !seen[lit] {
seen[lit] = true
values = append(values, lit)
}
}
}
}
}
return values
}
// evalConst evaluates simple constant expressions (literals and integer
// arithmetic with iota) to a TypeScript literal.
func evalConst(e ast.Expr, iota int64, kind reflect.Kind) (string, bool) {
if kind == reflect.String {
if lit, ok := e.(*ast.BasicLit); ok && lit.Kind == token.STRING {
s, err := strconv.Unquote(lit.Value)
if err != nil {
return "", false
}
return quote(s), true
}
return "", false
}
if !isNumber(kind) {
return "", false
}
v, ok := evalInt(e, iota)
if !ok {
return "", false
}
return strconv.FormatInt(v, 10), true
}
func evalInt(e ast.Expr, iota int64) (int64, bool) {
switch e := e.(type) {
case *ast.BasicLit:
if e.Kind != token.INT {
return 0, false
}
v, err := strconv.ParseInt(strings.ReplaceAll(e.Value, "_", ""), 0, 64)
return v, err == nil
case *ast.Ident:
return iota, e.Name == "iota"
case *ast.ParenExpr:
return evalInt(e.X, iota)
case *ast.UnaryExpr:
v, ok := evalInt(e.X, iota)
switch e.Op {
case token.SUB:
return -v, ok
case token.ADD:
return v, ok
}
return 0, false
case *ast.BinaryExpr:
x, ok1 := evalInt(e.X, iota)
y, ok2 := evalInt(e.Y, iota)
if !ok1 || !ok2 {
return 0, false
}
switch e.Op {
case token.ADD:
return x + y, true
case token.SUB:
return x - y, true
case token.MUL:
return x * y, true
case token.SHL:
return x << y, y >= 0 && y < 63
case token.OR:
return x | y, true
}
}
return 0, false
}
+298
View File
@@ -0,0 +1,298 @@
package tsgen
import (
"context"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/egoist/mygo/internal/tsgen/internal/fixture"
)
func modelOf(name string, svc any) Service {
t := reflect.TypeOf(svc)
s := Service{Name: name, Type: t}
ctxType := reflect.TypeFor[context.Context]()
errType := reflect.TypeFor[error]()
for i := range t.NumMethod() {
m := t.Method(i)
ft := m.Type
meth := Method{Name: m.Name, Variadic: ft.IsVariadic()}
start := 1
if ft.NumIn() > 1 && ft.In(1) == ctxType {
meth.HasCtx, start = true, 2
}
for j := start; j < ft.NumIn(); j++ {
meth.Params = append(meth.Params, ft.In(j))
}
if ft.NumOut() > 0 && ft.Out(0) != errType {
meth.Result = ft.Out(0)
}
if vm, ok := t.Elem().MethodByName(m.Name); ok {
meth.PC = vm.Func.Pointer()
} else {
meth.PC = m.Func.Pointer()
}
s.Methods = append(s.Methods, meth)
}
return s
}
func generate(t *testing.T) string {
t.Helper()
tasks := modelOf("Tasks", &fixture.Tasks{})
for i, m := range tasks.Methods {
if m.Name == "Watch" {
tasks.Methods[i].Channels = []bool{false, true}
}
}
out, err := Generate(Model{
Services: []Service{tasks},
Events: []Event{{Name: "task-added", Type: reflect.TypeFor[fixture.Task]()}},
})
if err != nil {
t.Fatal(err)
}
return string(out)
}
func TestGenerate(t *testing.T) {
src := generate(t)
for _, want := range []string{
`import { bind, event, type Channel } from "mygo-runtime";`,
`export type Status = "todo" | "done";`,
`export type Priority = 0 | 1 | 2;`,
"export interface FixtureChannel {\n name: string;\n}",
"export interface FixtureRecord {\n values: Record<string, string>;\n}",
"export interface FixturePromise {\n done: boolean;\n}",
"/** Task is a unit of work. */\nexport interface Task {",
" id: number;\n",
" /** Title of the task. */\n title: string;\n",
" status: Status;\n",
" priority: Priority;\n",
" tags: string[];\n",
" due: string | null;\n",
" meta?: Record<string, unknown>;\n",
" parent?: Task;\n",
" channel?: FixtureChannel;\n",
" record?: FixtureRecord;\n",
" promise?: FixturePromise;\n",
" count: string;\n",
" countPtr: string | null;\n",
" raw: unknown;\n",
" data: string;\n",
" scores: Record<number, number>;\n",
" matrix: number[][];\n",
" children: (Task | null)[];\n",
" extra: { A: boolean };\n",
" NoTag: string;\n",
" createdAt: string;\n",
"export interface PageTask {\n items: Task[];\n next?: string;\n}",
"/** Tasks manages tasks. */\nexport const Tasks = {",
" /** List returns tasks with the given status. */\n list: bind<[Status, number], PageTask>(\"Tasks.List\", (status: Status, limit: number) => [status, limit]),",
" * It fails when a task has no title.\n",
" add: bind<[...Task[]], void>(\"Tasks.Add\", (...tasks: Task[]) => [...tasks]),",
" count: bind<[], number>(\"Tasks.Count\", () => []),",
" delete: bind<[number], void>(\"Tasks.Delete\", (arg0: number) => [arg0]),",
" dispatch: bind<[string, string], void>(\"Tasks.Dispatch\", (call_: string, call__: string) => [call_, call__]),",
" dispatchMany: bind<[...string[]], void>(\"Tasks.DispatchMany\", (...call_: string[]) => [...call_]),",
" watch: bind<[Status, Channel<Task>], void>(\"Tasks.Watch\", (status: Status, updates: Channel<Task>) => [status, updates]),",
` taskAdded: event<Task>("task-added"),`,
} {
if !strings.Contains(src, want) {
t.Errorf("generated code is missing:\n%s", want)
}
}
for _, unwanted := range []string{"Secret", "internal:", "ctx", "function call", "declare global"} {
if strings.Contains(src, unwanted) {
t.Errorf("generated code should not contain %q", unwanted)
}
}
if t.Failed() {
t.Log(src)
}
}
// TestGeneratedCodeTypeChecks runs tsc on the output, against the
// mygo-runtime package of the workspace, when the repository's dev
// dependencies are installed (bun install).
func TestGeneratedCodeTypeChecks(t *testing.T) {
tsc, err := filepath.Abs("../../node_modules/.bin/tsc")
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(tsc); err != nil {
t.Skip("tsc not installed; run bun install")
}
runtimePkg, err := filepath.Abs("../../packages/runtime")
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(runtimePkg, "dist", "index.d.ts")); err != nil {
t.Skip("mygo-runtime not built; run bun run build")
}
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "node_modules"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(runtimePkg, filepath.Join(dir, "node_modules", "mygo-runtime")); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "client.ts"), []byte(generate(t)), 0o644); err != nil {
t.Fatal(err)
}
usage := `import { Channel, runtime } from "mygo-runtime";
import { Tasks, events, type Task, type Status, type FixtureChannel, type PageTask } from "./client";
const s: Status = "todo";
const page = await Tasks.list(s, 10);
const ac = new AbortController();
const canceled: Promise<PageTask> = Tasks.list.with({ signal: ac.signal })(s, 10);
void canceled;
const first: Task | undefined = page.items[0];
const channel: FixtureChannel | undefined = first?.channel;
channel?.name.toUpperCase();
first?.record?.values["key"]?.toUpperCase();
const done: boolean | undefined = first?.promise?.done;
await Tasks.add({ id: 1, title: "x", status: "done", priority: 2, tags: [], due: null, count: "1", countPtr: "9007199254740993", raw: null, data: "", scores: {}, matrix: [], children: [], extra: { A: true }, NoTag: "", createdAt: "" });
await Tasks.dispatch("first", "second");
await Tasks.dispatchMany("first", "second");
const off = events.taskAdded.on((t) => t.title.toUpperCase());
off();
runtime().window.minimize();
const updates = new Channel<Task>();
const watching = Tasks.watch("todo", updates);
for await (const task of updates) task.title.toUpperCase();
updates.onmessage = (task) => task.id.toFixed();
updates.close();
await watching;
// @ts-expect-error a channel of another type
Tasks.watch("todo", new Channel<string>());
// @ts-expect-error invalid enum value
Tasks.list("nope", 1);
`
if err := os.WriteFile(filepath.Join(dir, "usage.ts"), []byte(usage), 0o644); err != nil {
t.Fatal(err)
}
cmd := exec.Command(tsc, "--noEmit", "--strict", "--noUncheckedIndexedAccess", "--target", "es2022",
"--module", "esnext", "--moduleResolution", "bundler", "--lib", "es2022,dom", "client.ts", "usage.ts")
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("tsc failed: %v\n%s", err, out)
}
}
// Without streaming parameters, an app's Channel keeps its original name.
func TestChannelNameWithoutStreaming(t *testing.T) {
out, err := Generate(Model{Events: []Event{{Name: "channel", Type: reflect.TypeFor[fixture.Channel]()}}})
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"export interface Channel {", `channel: event<Channel>("channel")`} {
if !strings.Contains(string(out), want) {
t.Errorf("client lacks %s:\n%s", want, out)
}
}
}
func TestNames(t *testing.T) {
for in, want := range map[string]string{"Greet": "greet", "GetUserByID": "getUserByID", "URLFor": "urlFor", "ID": "id", "already": "already"} {
if got := camel(in); got != want {
t.Errorf("camel(%q) = %q, want %q", in, got, want)
}
}
for in, want := range map[string]string{"progress": "progress", "file-changed": "fileChanged", "app:ready": "appReady", "a b": "aB", "123": `"123"`} {
if got := eventKey(in); got != want {
t.Errorf("eventKey(%q) = %q, want %q", in, got, want)
}
}
for in, want := range map[string]string{"User": "User", "Page[github.com/x/app.User]": "PageUser", "Pair[main.A,main.B]": "PairAB"} {
if got := typeName(in); got != want {
t.Errorf("typeName(%q) = %q, want %q", in, got, want)
}
}
if safeName("new") != "new_" || safeName("x") != "x" {
t.Error("safeName")
}
}
func TestMethodNameCollision(t *testing.T) {
service := Service{Name: "Links", Type: reflect.TypeFor[struct{}](), Methods: []Method{{Name: "URL"}, {Name: "Url"}}}
out, err := Generate(Model{Services: []Service{service}})
if err == nil || !strings.Contains(err.Error(), "URL") || !strings.Contains(err.Error(), "Url") || !strings.Contains(err.Error(), "url") {
t.Fatalf("Generate = %s, %v; want an error identifying the colliding methods", out, err)
}
if len(out) != 0 {
t.Error("a collision returned a partial client")
}
}
func TestEventNameCollision(t *testing.T) {
out, err := Generate(Model{Events: []Event{
{Name: "file-changed", Type: reflect.TypeFor[string]()},
{Name: "file_changed", Type: reflect.TypeFor[string]()},
}})
if err == nil || !strings.Contains(err.Error(), "file-changed") || !strings.Contains(err.Error(), "file_changed") || !strings.Contains(err.Error(), "fileChanged") {
t.Fatalf("Generate = %s, %v; want an error identifying the colliding events", out, err)
}
if len(out) != 0 {
t.Error("a collision returned a partial client")
}
}
func TestMethodNamesAreScopedToServices(t *testing.T) {
out, err := Generate(Model{Services: []Service{
{Name: "First", Type: reflect.TypeFor[struct{}](), Methods: []Method{{Name: "URL"}}},
{Name: "Second", Type: reflect.TypeFor[struct{}](), Methods: []Method{{Name: "Url"}}},
}})
if err != nil {
t.Fatal(err)
}
for _, want := range []string{`bind<[], void>("First.URL", () => [])`, `bind<[], void>("Second.Url", () => [])`} {
if !strings.Contains(string(out), want) {
t.Errorf("client lacks %s", want)
}
}
}
func TestValidate(t *testing.T) {
type bad struct {
F func()
}
type ok struct {
F func() `json:"-"`
C chan int
}
for _, typ := range []reflect.Type{reflect.TypeFor[chan int](), reflect.TypeFor[bad](), reflect.TypeFor[map[struct{}]int](), reflect.TypeFor[[]complex64]()} {
if Validate(typ) == nil {
t.Errorf("Validate(%v) should fail", typ)
}
}
if err := Validate(reflect.TypeFor[fixture.Task]()); err != nil {
t.Errorf("Validate(Task) = %v", err)
}
_ = ok{}
}
func TestStructFieldConflicts(t *testing.T) {
type A struct{ Name, OnlyA string }
type B struct {
Name string
Tag string `json:"Name2"`
}
type C struct {
A
B
Own string `json:"own"`
}
var names []string
for _, f := range structFields(reflect.TypeFor[C]()) {
names = append(names, f.name)
}
// Name is ambiguous at the same depth and dropped, like encoding/json.
if got := strings.Join(names, ","); got != "OnlyA,Name2,own" {
t.Errorf("fields = %s", got)
}
}
+227
View File
@@ -0,0 +1,227 @@
package tsgen
import (
"encoding"
jsonv1 "encoding/json"
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"reflect"
"strings"
"time"
)
var (
timeType = reflect.TypeFor[time.Time]()
durationType = reflect.TypeFor[time.Duration]()
rawV1Type = reflect.TypeFor[jsonv1.RawMessage]()
rawV2Type = reflect.TypeFor[jsontext.Value]()
jsonMarshaler = reflect.TypeFor[jsonv1.Marshaler]()
jsonMarshalerTo = reflect.TypeFor[json.MarshalerTo]()
textMarshaler = reflect.TypeFor[encoding.TextMarshaler]()
textAppender = reflect.TypeFor[encoding.TextAppender]()
emptyStructFields = []field{}
)
func implements(t, iface reflect.Type) bool {
return t.Implements(iface) || (t.Kind() != reflect.Pointer && reflect.PointerTo(t).Implements(iface))
}
// special returns the TypeScript type of Go types with a custom JSON
// representation.
func special(t reflect.Type) (string, bool) {
switch t {
case timeType:
return "string", true
case durationType:
return "number", true
case rawV1Type, rawV2Type:
return "unknown", true
}
if implements(t, jsonMarshaler) || implements(t, jsonMarshalerTo) {
return "unknown", true
}
if implements(t, textMarshaler) || implements(t, textAppender) {
return "string", true
}
if (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && t.Elem().Kind() == reflect.Uint8 {
// Byte slices and arrays are base64 strings.
return "string", true
}
return "", false
}
func isNumber(k reflect.Kind) bool {
switch k {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
return true
}
return false
}
// Validate reports an error if values of type t cannot cross the IPC
// boundary as JSON.
func Validate(t reflect.Type) error {
return validate(t, map[reflect.Type]bool{})
}
func validate(t reflect.Type, seen map[reflect.Type]bool) error {
if seen[t] {
return nil
}
seen[t] = true
if _, ok := special(t); ok {
return nil
}
switch t.Kind() {
case reflect.Chan, reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
return fmt.Errorf("type %s cannot be encoded as JSON", t)
case reflect.Pointer, reflect.Slice, reflect.Array:
return validate(t.Elem(), seen)
case reflect.Map:
k := t.Key()
if k.Kind() != reflect.String && !isNumber(k.Kind()) && !implements(k, textMarshaler) {
return fmt.Errorf("map key type %s cannot be encoded as JSON", k)
}
return validate(t.Elem(), seen)
case reflect.Struct:
for _, f := range structFields(t) {
if err := validate(f.typ, seen); err != nil {
return fmt.Errorf("field %s: %w", f.goName, err)
}
}
}
return nil
}
// field is a JSON representable struct field.
type field struct {
name string
typ reflect.Type
optional bool
quoted bool
goName string
owner reflect.Type
depth int
tagged bool
fallback bool // an embedded map or jsontext.Value, with no member name
}
type tagOptions []string
func (o tagOptions) has(opt string) bool {
for _, x := range o {
if x == opt {
return true
}
}
return false
}
func parseTag(tag string) (string, tagOptions) {
name, rest, _ := strings.Cut(tag, ",")
if strings.HasPrefix(name, "'") && strings.HasSuffix(name, "'") && len(name) >= 2 {
// json/v2 allows single quoted names.
name = name[1 : len(name)-1]
}
if rest == "" {
return name, nil
}
return name, strings.Split(rest, ",")
}
// structFields lists the JSON members of a struct following encoding/json/v2
// rules: embedded structs are inlined and shallower fields win conflicts.
func structFields(t reflect.Type) []field {
var all []field
var walk func(t reflect.Type, depth int, optional bool, visiting map[reflect.Type]bool)
walk = func(t reflect.Type, depth int, optional bool, visiting map[reflect.Type]bool) {
if visiting[t] {
return
}
visiting[t] = true
defer delete(visiting, t)
for i := range t.NumField() {
sf := t.Field(i)
tag := sf.Tag.Get("json")
if tag == "-" {
continue
}
name, opts := parseTag(tag)
fallback := false
// Go embedding implies JSON embedding unless the field is named;
// the "embed" option requests it explicitly.
if (sf.Anonymous && name == "") || opts.has("embed") {
et, viaPtr := sf.Type, false
if et.Kind() == reflect.Pointer && et.Name() == "" {
et, viaPtr = et.Elem(), true
}
if et.Kind() == reflect.Struct {
if _, custom := special(et); !custom {
walk(et, depth+1, optional || viaPtr, visiting)
continue
}
}
fallback = et == rawV2Type || et.Kind() == reflect.Map && et.Key().Kind() == reflect.String
}
if !sf.IsExported() {
continue
}
f := field{
name: name,
typ: sf.Type,
goName: sf.Name,
owner: t,
depth: depth,
tagged: name != "",
fallback: fallback,
}
if f.name == "" && !fallback {
f.name = sf.Name
}
f.optional = optional || opts.has("omitempty") || opts.has("omitzero")
f.quoted = opts.has("string")
all = append(all, f)
}
}
walk(t, 0, false, map[reflect.Type]bool{})
if len(all) == 0 {
return emptyStructFields
}
byName := map[string][]int{}
for i, f := range all {
byName[f.name] = append(byName[f.name], i)
}
keep := make([]bool, len(all))
for _, idx := range byName {
minDepth := all[idx[0]].depth
for _, i := range idx {
minDepth = min(minDepth, all[i].depth)
}
var shallow, tagged []int
for _, i := range idx {
if all[i].depth == minDepth {
shallow = append(shallow, i)
if all[i].tagged {
tagged = append(tagged, i)
}
}
}
switch {
case len(shallow) == 1:
keep[shallow[0]] = true
case len(tagged) == 1:
keep[tagged[0]] = true
}
}
out := make([]field, 0, len(all))
for i, f := range all {
if keep[i] {
out = append(out, f)
}
}
return out
}