diff --git a/cmd/wasm-validator/api.go b/cmd/wasm-validator/api.go new file mode 100644 index 0000000..6c23373 --- /dev/null +++ b/cmd/wasm-validator/api.go @@ -0,0 +1,333 @@ +// Pure WASM API: no syscall/js here, so the exact export logic can be tested +// and benchmarked natively. main.go is only the JS glue. +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "path" + "path/filepath" + "slices" + "strings" + "sync" + + domaincraft "github.com/DomainCraft/DomainCraft" + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/lexer" + "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/renderer" + "github.com/DomainCraft/DomainCraft/internal/seed" + "github.com/DomainCraft/DomainCraft/internal/specmeta" + "github.com/DomainCraft/DomainCraft/internal/validator" + "gopkg.in/yaml.v3" +) + +type validationError struct { + Entity string `json:"entity,omitempty"` + Field string `json:"field,omitempty"` + Message string `json:"message"` + Warning bool `json:"warning"` +} + +type validationResult struct { + Errors []validationError `json:"errors"` + Parse bool `json:"parse"` +} + +// resultCache memoizes the last (input, JSON) pair. Studio re-runs validation +// on an unchanged model, so the second call is free. Only strings are retained: +// an earlier cache of *parser.RawSchema kept a large object graph alive and +// raised GC pressure for every other WASM export. +type resultCache struct { + mu sync.Mutex + valid bool + key string + value string +} + +func (c *resultCache) get(key string, compute func() string) string { + c.mu.Lock() + defer c.mu.Unlock() + if c.valid && c.key == key { + return c.value + } + value := compute() + c.valid, c.key, c.value = true, key, value + return value +} + +var ( + validateCache resultCache + domainCache resultCache +) + +// ValidationErrorResult is the JS-input-contract result for goValidate. +func ValidationErrorResult(message string) string { + return marshal(validationResult{ + Errors: []validationError{{Message: message}}, + Parse: true, + }) +} + +// FieldErrorResult is the JS-input-contract result for goParseField and +// goParseDomain. +func FieldErrorResult(message string) string { + return marshal(map[string]string{"error": message}) +} + +// parseAndValidateYAML is shared by goValidate and goGenerate: the CLI never +// renders a schema that the validator rejected, and the browser must not either. +func parseAndValidateYAML(yaml string) (*parser.ParsedSchema, []validator.ValidationError, error) { + schema, err := parser.ParseYAML([]byte(yaml)) + if err != nil { + return nil, nil, err + } + return schema, validator.New(schema).Validate(), nil +} + +// ValidateYAML is the production path: main.go converts the js.Value once and +// calls this function directly, without a temporary []string. +func ValidateYAML(yaml string) string { + return validateCache.get(yaml, func() string { + _, errs, err := parseAndValidateYAML(yaml) + if err != nil { + return marshal(validationResult{ + Errors: []validationError{{Message: err.Error()}}, + Parse: true, + }) + } + result := make([]validationError, 0, len(errs)) + for _, e := range errs { + result = append(result, validationError{ + Entity: e.Entity, + Field: e.Field, + Message: e.Error(), + Warning: e.Warning, + }) + } + return marshal(validationResult{Errors: result}) + }) +} + +// ParseFieldDefinition is the production path for goParseField. +func ParseFieldDefinition(def, name string) string { + fd, err := lexer.ParseFieldString(def) + if err != nil { + return marshal(map[string]string{"error": err.Error()}) + } + fd.Name = name + // The Studio bridge expects Validations to be an object, never null. + if fd.Validations == nil { + fd.Validations = make(map[string]string) + } + return marshal(fd) +} + +// ParseDomainYAML is the production path for goParseDomain. +func ParseDomainYAML(yaml string) string { + return domainCache.get(yaml, func() string { + raw, err := parser.ParseRawSchema([]byte(yaml)) + if err != nil { + return marshal(map[string]string{"error": err.Error()}) + } + return marshal(raw) + }) +} + +// specmetaJSON is computed once: the constants are static, but marshaling the +// whole table on every call cost ~41 us and 160 allocations in the benchmark. +var specmetaJSON = sync.OnceValue(func() string { + return marshal(specmeta.JSON()) +}) + +// Specmeta mirrors window.goSpecmeta(): the full spec constant table as JSON. +func Specmeta() string { + return specmetaJSON() +} + +// Version mirrors window.goVersion(): the version stamped by -ldflags. +func Version(v string) string { + return v +} + +// generateResult is the JSON returned by window.goGenerate. Files are ordered +// by path so the same model always produces the same bytes. +type generateResult struct { + Files []renderer.MemoryFile `json:"files"` + Error string `json:"error,omitempty"` +} + +// generationPlan holds the static half of a generation: the resolved chain and +// a renderer with compiled templates. Both depend only on the embedded bridges +// tree, never on the user's model, so one entry is enough for the Studio +// pattern (many edits, same bridge). +type generationPlan struct { + renderer *renderer.Renderer +} + +var generationPlanCache = struct { + sync.Mutex + ref string + plan *generationPlan +}{} + +func generationPlanFor(ref string) (*generationPlan, error) { + generationPlanCache.Lock() + defer generationPlanCache.Unlock() + if generationPlanCache.plan != nil && generationPlanCache.ref == ref { + return generationPlanCache.plan, nil + } + chain, err := embeddedBridgeChain(ref) + if err != nil { + return nil, err + } + r, err := renderer.NewFromFS(domaincraft.Bridges, chain, nil) + if err != nil { + return nil, err + } + plan := &generationPlan{renderer: r} + generationPlanCache.ref, generationPlanCache.plan = ref, plan + return plan, nil +} + +// GenerateYAML compiles domain.yaml into files in memory. bridgeRef is a +// registry ID of a bundled bridge (or a path inside the embedded bridges tree). +// packagesJSON is an optional map of package versions; the browser cannot +// resolve NuGet versions without a network round trip, so the caller supplies +// them when it has them. +func GenerateYAML(yamlText, bridgeRef, packagesJSON string) string { + result := generateResult{Files: []renderer.MemoryFile{}} + plan, err := generationPlanFor(bridgeRef) + if err != nil { + result.Error = err.Error() + return marshal(result) + } + schema, errs, err := parseAndValidateYAML(yamlText) + if err != nil { + result.Error = err.Error() + return marshal(result) + } + hard := make([]error, 0, len(errs)) + for _, e := range errs { + if !e.Warning { + hard = append(hard, e) + } + } + if len(hard) > 0 { + result.Error = fmt.Sprintf("validation failed with %d error(s): %v", len(hard), errors.Join(hard...)) + return marshal(result) + } + project, err := ir.Build(schema) + if err != nil { + result.Error = err.Error() + return marshal(result) + } + + var packages map[string]string + if strings.TrimSpace(packagesJSON) != "" { + if err := json.Unmarshal([]byte(packagesJSON), &packages); err != nil { + result.Error = "invalid packages JSON: " + err.Error() + return marshal(result) + } + } + + r := plan.renderer + r.SetSeedData(seed.Normalize(project)) + r.SetMockData(seed.Generate(project, seed.Options{})) + files, err := r.RenderMemory(project, packages) + if err != nil { + result.Error = err.Error() + return marshal(result) + } + result.Files = files + return marshal(result) +} + +// embeddedBridgeChain resolves an extends chain entirely inside the embedded +// bridge tree. No clone, cache or network access exists in the browser. +func embeddedBridgeChain(ref string) ([]string, error) { + if strings.TrimSpace(ref) == "" { + return nil, fmt.Errorf("no bridge provided") + } + seen := make(map[string]bool) + chain := make([]string, 0, 4) + for ref != "" { + dir, err := findEmbeddedBridge(ref) + if err != nil { + return nil, err + } + if seen[dir] { + return nil, fmt.Errorf("cyclic bridge chain at %q", ref) + } + seen[dir] = true + manifest, err := fs.ReadFile(domaincraft.Bridges, path.Join(dir, "bridge.yaml")) + if err != nil { + return nil, fmt.Errorf("read bridge %s: %w", dir, err) + } + var meta struct { + Extends string `yaml:"extends"` + } + if err := yaml.Unmarshal(manifest, &meta); err != nil { + return nil, fmt.Errorf("parse bridge %s: %w", dir, err) + } + chain = append(chain, dir) + ref = meta.Extends + } + slices.Reverse(chain) + return chain, nil +} + +// findEmbeddedBridge resolves a registry ID (the bridge.yaml name) or a path +// inside the embedded tree. Matching by name avoids importing the registry +// package, which pulls the network-backed clone/update code into the WASM +// binary. +func findEmbeddedBridge(ref string) (string, error) { + clean := path.Clean(filepath.ToSlash(ref)) + candidates := []string{path.Join("bridges", clean)} + if strings.HasPrefix(clean, "bridges/") { + candidates = append(candidates, clean) + } + for _, dir := range candidates { + if path.IsAbs(dir) || dir == ".." || strings.HasPrefix(dir, "../") { + continue + } + if _, err := fs.Stat(domaincraft.Bridges, path.Join(dir, "bridge.yaml")); err == nil { + return dir, nil + } + } + var found string + err := fs.WalkDir(domaincraft.Bridges, "bridges", func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || d.Name() != "bridge.yaml" { + return nil + } + data, err := fs.ReadFile(domaincraft.Bridges, p) + if err != nil { + return nil + } + var meta struct { + Name string `yaml:"name"` + } + if err := yaml.Unmarshal(data, &meta); err == nil && meta.Name == ref { + found = path.Dir(p) + return fs.SkipAll + } + return nil + }) + if err != nil { + return "", err + } + if found == "" { + return "", fmt.Errorf("unknown bridge %q", ref) + } + return found, nil +} + +func marshal(v any) string { + data, err := json.Marshal(v) + if err != nil { + data, _ = json.Marshal(map[string]string{"error": "marshal failed: " + err.Error()}) + } + return string(data) +} diff --git a/cmd/wasm-validator/api_bench_test.go b/cmd/wasm-validator/api_bench_test.go new file mode 100644 index 0000000..7621a2f --- /dev/null +++ b/cmd/wasm-validator/api_bench_test.go @@ -0,0 +1,155 @@ +package main + +import ( + "fmt" + "os" + "strconv" + "strings" + "testing" +) + +// benchmarkYAML builds a synthetic model of n entities. Every entity has one +// optional FK to the first entity, so validation walks both field and relation +// checks without producing errors. +func benchmarkYAML(n int) string { + var b strings.Builder + b.WriteString("project:\n name: Bench\ndatabase: postgresql\nauth:\n type: none\nentities:\n") + for i := range n { + fmt.Fprintf(&b, " E%04d:\n fields:\n id: uuid [primary]\n name: string [required, max:255]\n", i) + if i > 0 { + b.WriteString(" parent: relation(E0000) [optional, on_delete:set_null]\n") + } + } + return b.String() +} + +func kitchenSinkYAML(b *testing.B) string { + b.Helper() + data, err := os.ReadFile("../../compliance-suite/kitchen-sink.yaml") + if err != nil { + b.Fatal(err) + } + return string(data) +} + +// BenchmarkValidate measures exactly what window.goValidate does: full YAML +// parse, logical validation and JSON serialization of the result. +func BenchmarkValidate(b *testing.B) { + cases := []struct { + name string + yaml func(*testing.B) string + }{ + {name: "small", yaml: func(*testing.B) string { return validYAML }}, + {name: "kitchen-sink", yaml: kitchenSinkYAML}, + {name: "entities=100", yaml: func(*testing.B) string { return benchmarkYAML(100) }}, + {name: "entities=500", yaml: func(*testing.B) string { return benchmarkYAML(500) }}, + {name: "entities=2000", yaml: func(*testing.B) string { return benchmarkYAML(2000) }}, + } + for _, tc := range cases { + b.Run(tc.name, func(b *testing.B) { + yaml := tc.yaml(b) + b.ReportAllocs() + i := 0 + for b.Loop() { + _ = ValidateYAML(yaml + strconv.Itoa(i%2)) + i++ + } + }) + } +} + +// BenchmarkParseDomain measures window.goParseDomain: raw YAML decode + marshal. +func BenchmarkParseDomain(b *testing.B) { + for _, tc := range []struct { + name string + yaml func(*testing.B) string + }{ + {name: "small", yaml: func(*testing.B) string { return validYAML }}, + {name: "kitchen-sink", yaml: kitchenSinkYAML}, + {name: "entities=2000", yaml: func(*testing.B) string { return benchmarkYAML(2000) }}, + } { + b.Run(tc.name, func(b *testing.B) { + yaml := tc.yaml(b) + b.ReportAllocs() + i := 0 + for b.Loop() { + _ = ParseDomainYAML(yaml + strconv.Itoa(i%2)) + i++ + } + }) + } +} + +// BenchmarkParseField measures window.goParseField across the definition +// shapes the Studio editor produces on every keystroke. +func BenchmarkParseField(b *testing.B) { + for _, tc := range []struct{ name, def string }{ + {name: "simple", def: "string"}, + {name: "modifiers", def: "string [required, unique, min:2, max:255, email, old_name:title]"}, + {name: "relation", def: "relation(Category) [optional, many, on_delete:set_null]"}, + {name: "array-default", def: "array(string) [default:[a, b, c]]"}, + {name: "regex", def: "string [regex:^[a-z]+$]"}, + } { + b.Run(tc.name, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _ = ParseFieldDefinition(tc.def, "fieldName") + } + }) + } +} + +func BenchmarkSpecmeta(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _ = Specmeta() + } +} + +// BenchmarkGenerateYAML measures full in-browser generation: parse, IR build, +// bridge-chain loading and template execution into memory. +func BenchmarkGenerateYAML(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _ = GenerateYAML(validYAML, "admin-alpine", "") + } +} + +func BenchmarkVersion(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _ = Version("dev") + } +} + +// BenchmarkStudioValidationCycle measures the back-to-back calls the editor +// makes after a model change: validate, parse the raw tree, parse a field. +// "same" is the repeated validation of an unchanged model; "changing" uses a +// fresh YAML string each iteration and exercises the cold decode path. +func BenchmarkStudioValidationCycle(b *testing.B) { + base := benchmarkYAML(100) + other := strings.Replace(base, "Bench", "Other", 1) + for _, tc := range []struct { + name string + alternate bool + }{ + {name: "same-yaml"}, + {name: "changing-yaml", alternate: true}, + } { + b.Run(tc.name, func(b *testing.B) { + b.ReportAllocs() + fieldArgs := []string{"string [required, max:255]", "title"} + i := 0 + for b.Loop() { + yaml := base + if tc.alternate && i%2 == 1 { + yaml = other + } + i++ + _ = ValidateYAML(yaml) + _ = ParseDomainYAML(yaml) + _ = ParseFieldDefinition(fieldArgs[0], fieldArgs[1]) + } + }) + } +} diff --git a/cmd/wasm-validator/api_test.go b/cmd/wasm-validator/api_test.go new file mode 100644 index 0000000..47f54b6 --- /dev/null +++ b/cmd/wasm-validator/api_test.go @@ -0,0 +1,283 @@ +package main + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestValidate(t *testing.T) { + t.Run("no input", func(t *testing.T) { + var got validationResult + if err := json.Unmarshal([]byte(ValidationErrorResult("no YAML input provided")), &got); err != nil { + t.Fatal(err) + } + if !got.Parse || len(got.Errors) != 1 || got.Errors[0].Message != "no YAML input provided" { + t.Fatalf("ValidationErrorResult() = %+v", got) + } + }) + t.Run("valid", func(t *testing.T) { + got := ValidateYAML(validYAML) + if got != `{"errors":[],"parse":false}` { + t.Fatalf("ValidateYAML() = %s", got) + } + }) + t.Run("parse error", func(t *testing.T) { + var got validationResult + if err := json.Unmarshal([]byte(ValidateYAML("entities: [")), &got); err != nil { + t.Fatal(err) + } + if !got.Parse || len(got.Errors) != 1 { + t.Fatalf("ValidateYAML() = %+v", got) + } + }) + t.Run("logical error", func(t *testing.T) { + var got validationResult + if err := json.Unmarshal([]byte(ValidateYAML("project:\n name: X\nentities: {}\n")), &got); err != nil { + t.Fatal(err) + } + if got.Parse || len(got.Errors) == 0 { + t.Fatalf("ValidateYAML() = %+v", got) + } + }) +} + +func TestParseField(t *testing.T) { + t.Run("no input", func(t *testing.T) { + if got := FieldErrorResult("no field definition provided"); got != `{"error":"no field definition provided"}` { + t.Fatalf("FieldErrorResult() = %s", got) + } + }) + t.Run("named field", func(t *testing.T) { + got := ParseFieldDefinition("string [required, max:255]", "title") + var fd struct { + Name string + Type string + IsRequired bool + Validations map[string]string + } + if err := json.Unmarshal([]byte(got), &fd); err != nil { + t.Fatal(err) + } + if fd.Name != "title" || fd.Type != "string" || !fd.IsRequired || fd.Validations["max"] != "255" { + t.Fatalf("ParseFieldDefinition() = %+v", got) + } + }) + t.Run("invalid", func(t *testing.T) { + if got := ParseFieldDefinition("no_such_type", "title"); !strings.Contains(got, "unknown type") { + t.Fatalf("ParseFieldDefinition() = %s", got) + } + }) +} + +func TestParseDomain(t *testing.T) { + t.Run("no input", func(t *testing.T) { + if got := FieldErrorResult("no YAML input provided"); got != `{"error":"no YAML input provided"}` { + t.Fatalf("FieldErrorResult() = %s", got) + } + }) + t.Run("valid", func(t *testing.T) { + got := ParseDomainYAML(validYAML) + var raw struct { + Project struct{ Name string } + Entities map[string]json.RawMessage + } + if err := json.Unmarshal([]byte(got), &raw); err != nil { + t.Fatal(err) + } + if raw.Project.Name != "Bench" || raw.Entities["User"] == nil { + t.Fatalf("ParseDomainYAML() = %s", got) + } + }) + t.Run("invalid", func(t *testing.T) { + if got := ParseDomainYAML("entities: ["); !strings.Contains(got, "error") { + t.Fatalf("ParseDomainYAML() = %s", got) + } + }) +} + +func TestSpecmeta(t *testing.T) { + got := Specmeta() + var meta map[string]json.RawMessage + if err := json.Unmarshal([]byte(got), &meta); err != nil { + t.Fatal(err) + } + for _, key := range []string{"fieldTypes", "features", "databases", "apiStyles", "authTypes", "featureFieldDefs"} { + if _, ok := meta[key]; !ok { + t.Errorf("Specmeta() missing %q", key) + } + } +} + +func TestVersion(t *testing.T) { + if got := Version("v0.2.0"); got != "v0.2.0" { + t.Fatalf("Version() = %q", got) + } +} + +func TestGenerateYAML(t *testing.T) { + result := GenerateYAML(validYAML, "admin-alpine", "") + var got generateResult + if err := json.Unmarshal([]byte(result), &got); err != nil { + t.Fatal(err) + } + if got.Error != "" { + t.Fatalf("GenerateYAML() error = %q", got.Error) + } + if len(got.Files) < 4 { + t.Fatalf("GenerateYAML() returned %d files, want at least 4", len(got.Files)) + } + found := false + for _, f := range got.Files { + if f.Path == "admin/index.html" && strings.Contains(f.Content, "Bench") { + found = true + } + } + if !found { + t.Fatalf("GenerateYAML() did not render admin/index.html: %d files", len(got.Files)) + } +} + +func TestGenerateYAMLRejectsInvalidModel(t *testing.T) { + result := GenerateYAML("project:\n name: Bad\nentities:\n Broken:\n fields:\n title: string\n", "admin-alpine", "") + var got generateResult + if err := json.Unmarshal([]byte(result), &got); err != nil { + t.Fatal(err) + } + if got.Error == "" || !strings.Contains(got.Error, "validation failed") { + t.Fatalf("GenerateYAML generated files for an invalid model: %s", result) + } +} + +func TestGenerateYAMLAlternatingModels(t *testing.T) { + for _, name := range []string{"Alpha", "Beta", "Alpha"} { + yaml := strings.Replace(validYAML, "Bench", name, 1) + result := GenerateYAML(yaml, "admin-alpine", "") + var got generateResult + if err := json.Unmarshal([]byte(result), &got); err != nil { + t.Fatal(err) + } + if got.Error != "" { + t.Fatalf("GenerateYAML(%s) error = %q", name, got.Error) + } + found := false + for _, f := range got.Files { + if f.Path == "admin/index.html" && strings.Contains(f.Content, name) { + found = true + } + } + if !found { + t.Fatalf("GenerateYAML(%s) returned stale files", name) + } + } +} + +func TestGenerateYAMLRejectsBadBridge(t *testing.T) { + result := GenerateYAML(validYAML, "does-not-exist", "") + var got generateResult + if err := json.Unmarshal([]byte(result), &got); err != nil { + t.Fatal(err) + } + if got.Error == "" { + t.Fatal("GenerateYAML accepted an unknown bridge") + } +} + +// TestWasmApiContracts pins the exact JSON returned by every WASM export. +// A shape change here breaks the Studio bridge even when tests that unmarshal +// loosely still pass. +func TestWasmApiContracts(t *testing.T) { + t.Parallel() + cases := []struct{ name, got, want string }{ + { + name: "goValidate", + got: ValidateYAML(validYAML), + want: `{"errors":[],"parse":false}`, + }, + { + name: "goValidate-no-input", + got: ValidationErrorResult("no YAML input provided"), + want: `{"errors":[{"message":"no YAML input provided","warning":false}],"parse":true}`, + }, + { + name: "goValidate-type-error", + got: ValidationErrorResult("YAML input must be a string"), + want: `{"errors":[{"message":"YAML input must be a string","warning":false}],"parse":true}`, + }, + { + name: "goParseField-no-input", + got: FieldErrorResult("no field definition provided"), + want: `{"error":"no field definition provided"}`, + }, + { + name: "goParseField-no-validations", + got: ParseFieldDefinition("string", "title"), + want: `{"Name":"title","Type":"string","TargetEntity":"","TargetType":"","IsPrimary":false,"IsOptional":false,"IsUnique":false,"IsHidden":false,"IsReadonly":false,"IsRequired":false,"OnDelete":"","IsMany":false,"OldName":"","Validations":{},"DefaultValue":"","DefaultIsFunc":false}`, + }, + { + name: "goParseField", + got: ParseFieldDefinition("string [required, max:255]", "title"), + want: `{"Name":"title","Type":"string","TargetEntity":"","TargetType":"","IsPrimary":false,"IsOptional":false,"IsUnique":false,"IsHidden":false,"IsReadonly":false,"IsRequired":true,"OnDelete":"","IsMany":false,"OldName":"","Validations":{"max":"255"},"DefaultValue":"","DefaultIsFunc":false}`, + }, + { + name: "goParseDomain", + got: ParseDomainYAML("project:\n name: Bench\nentities: {}\n"), + want: `{"project":{"name":"Bench","deploy":{"domain":"localhost","port":8080},"versioning":{"enabled":true,"default_version":"1.0"},"rate_limit":{"enabled":true,"policy":"fixed","permit_limit":100,"window_seconds":60},"pagination":{"default_page_size":20,"max_page_size":200}},"database":"postgresql","auth":{"type":"none","endpoints":{"login":null,"register":null,"me":null,"setup":null}},"apiStyle":"rest","entities":{}}`, + }, + { + name: "goValidate-bad-yaml", + got: ValidateYAML("entities: ["), + want: `{"errors":[{"message":"error parsing YAML: yaml: line 1: did not find expected node content","warning":false}],"parse":true}`, + }, + { + name: "goParseDomain-bad-yaml", + got: ParseDomainYAML("entities: ["), + want: `{"error":"yaml: line 1: did not find expected node content"}`, + }, + {name: "goVersion", got: Version("dev"), want: "dev"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + if tc.got != tc.want { + t.Fatalf("got %s\nwant %s", tc.got, tc.want) + } + }) + } + if n := len(Specmeta()); n < 2000 { + t.Fatalf("goSpecmeta returned %d bytes, want >= 2000", n) + } +} + +func TestResultCacheAlternatingInputs(t *testing.T) { + t.Parallel() + other := strings.Replace(validYAML, "Bench", "Other", 1) + for i := range 3 { + for _, tc := range []struct{ yaml, name string }{ + {validYAML, "Bench"}, + {other, "Other"}, + } { + if got := ValidateYAML(tc.yaml); !strings.Contains(got, `"errors":[],"parse":false`) { + t.Fatalf("iteration %d: ValidateYAML(%s) = %s", i, tc.name, got) + } + domain := ParseDomainYAML(tc.yaml) + if !strings.Contains(domain, `"name":"`+tc.name+`"`) { + t.Fatalf("iteration %d: ParseDomainYAML(%s) = %s", i, tc.name, domain) + } + } + } +} + +const validYAML = `project: + name: Bench +entities: + User: + fields: + id: uuid [primary] + email: string [required, unique, email] + password: string [required, hidden] +auth: + type: jwt + roles: [Admin, User] + entity: User +` diff --git a/cmd/wasm-validator/main.go b/cmd/wasm-validator/main.go index c9409c5..d52dd50 100644 --- a/cmd/wasm-validator/main.go +++ b/cmd/wasm-validator/main.go @@ -4,46 +4,29 @@ package main import ( - "encoding/json" "fmt" "syscall/js" - - "github.com/DomainCraft/DomainCraft/internal/lexer" - "github.com/DomainCraft/DomainCraft/internal/parser" - "github.com/DomainCraft/DomainCraft/internal/specmeta" - "github.com/DomainCraft/DomainCraft/internal/validator" ) var version = "dev" // set via -ldflags "-X main.version=v0.2.0" -type validationError struct { - Entity string `json:"entity,omitempty"` - Field string `json:"field,omitempty"` - Message string `json:"message"` - Warning bool `json:"warning"` -} - -type validationResult struct { - Errors []validationError `json:"errors"` - Parse bool `json:"parse"` -} - func main() { c := make(chan struct{}) js.Global().Set("goValidate", js.FuncOf(validate)) js.Global().Set("goParseField", js.FuncOf(parseField)) js.Global().Set("goParseDomain", js.FuncOf(parseDomain)) + js.Global().Set("goGenerate", js.FuncOf(generate)) js.Global().Set("goSpecmeta", js.FuncOf(specmetaFunc)) js.Global().Set("goVersion", js.FuncOf(versionFunc)) <-c } func versionFunc(_ js.Value, _ []js.Value) any { - return version + return Version(version) } func specmetaFunc(_ js.Value, _ []js.Value) any { - return marshal(specmeta.JSON()) + return Specmeta() } // stringArg validates the JS API contract. Without a type check an object @@ -61,67 +44,49 @@ func stringArg(args []js.Value, i int, label string) (string, error) { func validate(_ js.Value, args []js.Value) any { raw, err := stringArg(args, 0, "YAML input") if err != nil { - return marshal(validationResult{ - Errors: []validationError{{Message: err.Error()}}, - Parse: true, - }) + return ValidationErrorResult(err.Error()) } - schema, err := parser.ParseYAML([]byte(raw)) - if err != nil { - return marshal(validationResult{ - Errors: []validationError{{Message: err.Error()}}, - Parse: true, - }) - } - errs := validator.New(schema).Validate() - result := make([]validationError, 0, len(errs)) - for _, e := range errs { - result = append(result, validationError{ - Entity: e.Entity, - Field: e.Field, - Message: e.Error(), - Warning: e.Warning, - }) - } - return marshal(validationResult{Errors: result}) + return ValidateYAML(raw) } func parseField(_ js.Value, args []js.Value) any { def, err := stringArg(args, 0, "field definition") if err != nil { - return marshal(map[string]string{"error": err.Error()}) + return FieldErrorResult(err.Error()) } name := "" if len(args) > 1 { name, err = stringArg(args, 1, "field name") if err != nil { - return marshal(map[string]string{"error": err.Error()}) + return FieldErrorResult(err.Error()) } } - fd, err := lexer.ParseFieldString(def) - if err != nil { - return marshal(map[string]string{"error": err.Error()}) - } - fd.Name = name - return marshal(fd) + return ParseFieldDefinition(def, name) } func parseDomain(_ js.Value, args []js.Value) any { input, err := stringArg(args, 0, "YAML input") if err != nil { - return marshal(map[string]string{"error": err.Error()}) - } - raw, err := parser.ParseRawSchema([]byte(input)) - if err != nil { - return marshal(map[string]string{"error": err.Error()}) + return FieldErrorResult(err.Error()) } - return marshal(raw) + return ParseDomainYAML(input) } -func marshal(v any) string { - data, err := json.Marshal(v) +func generate(_ js.Value, args []js.Value) any { + input, err := stringArg(args, 0, "YAML input") if err != nil { - data, _ = json.Marshal(map[string]string{"error": "marshal failed: " + err.Error()}) + return FieldErrorResult(err.Error()) + } + bridgeRef, err := stringArg(args, 1, "bridge") + if err != nil { + return FieldErrorResult(err.Error()) + } + packages := "" + if len(args) > 2 { + packages, err = stringArg(args, 2, "packages") + if err != nil { + return FieldErrorResult(err.Error()) + } } - return string(data) + return GenerateYAML(input, bridgeRef, packages) } diff --git a/cmd/wasm-validator/smoke.mjs b/cmd/wasm-validator/smoke.mjs new file mode 100644 index 0000000..93e7e43 --- /dev/null +++ b/cmd/wasm-validator/smoke.mjs @@ -0,0 +1,105 @@ +// Runs every WASM export in Node using the Go runtime shim. This is the same +// binary the Studio loads; the only difference is the host. Run after building: +// GOOS=js GOARCH=wasm go build -o bin/validate.wasm ./cmd/wasm-validator +// node cmd/wasm-validator/smoke.mjs bin/validate.wasm +import fs from 'node:fs'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; + +const wasmPath = path.resolve(process.argv[2] ?? 'bin/validate.wasm'); +const goroot = process.env.GOROOT ?? execFileSync('go', ['env', 'GOROOT'], { encoding: 'utf8' }).trim(); +const execCandidates = [ + path.join(goroot, 'lib', 'wasm', 'wasm_exec.js'), + path.join(goroot, 'misc', 'wasm', 'wasm_exec.js'), +]; +const execPath = execCandidates.find((p) => fs.existsSync(p)); +if (!execPath) throw new Error(`wasm_exec.js not found under ${goroot}`); + +// wasm_exec.js is an IIFE that installs Go on globalThis. +(0, eval)(fs.readFileSync(execPath, 'utf8')); +if (typeof globalThis.Go !== 'function') throw new Error('wasm_exec.js did not define Go'); + +const go = new globalThis.Go(); +const bytes = fs.readFileSync(wasmPath); +const { instance } = await WebAssembly.instantiate(bytes, go.importObject); +void go.run(instance); // main blocks on a channel; exports are installed first. +await new Promise((resolve) => setImmediate(resolve)); + +const required = ['goValidate', 'goParseField', 'goParseDomain', 'goSpecmeta', 'goVersion']; +for (const name of required) { + if (typeof globalThis[name] !== 'function') throw new Error(`missing WASM export: ${name}`); +} + +const yaml = `project: + name: Bench +entities: + User: + fields: + id: uuid [primary] + email: string [required, unique, email] + password: string [required, hidden] +auth: + type: jwt + roles: [Admin, User] + entity: User +`; + +function check(name, ok, detail) { + console.log(`${ok ? 'ok' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); + if (!ok) process.exitCode = 1; +} + +const validation = JSON.parse(globalThis.goValidate(yaml)); +check('goValidate', Array.isArray(validation.errors) && validation.errors.length === 0 && validation.parse === false); + +const field = JSON.parse(globalThis.goParseField('string [required, max:255]', 'title')); +check('goParseField', field.Name === 'title' && field.Type === 'string' && field.Validations.max === '255'); + +const domain = JSON.parse(globalThis.goParseDomain(yaml)); +check('goParseDomain', domain.project.name === 'Bench' && !!domain.entities.User); + +const specmeta = JSON.parse(globalThis.goSpecmeta()); +check('goSpecmeta', Array.isArray(specmeta.fieldTypes) && specmeta.fieldTypes.length > 0); + +if (typeof globalThis.goGenerate === 'function') { + const generated = JSON.parse(globalThis.goGenerate(yaml, 'admin-alpine', '')); + const index = generated.files?.find((f) => f.path === 'admin/index.html'); + check('goGenerate', !generated.error && !!index && index.content.includes('Bench'), + generated.error || `${generated.files?.length ?? 0} files`); +} else { + console.log('skip goGenerate — this build predates the export'); +} + +const version = globalThis.goVersion(); +check('goVersion', typeof version === 'string' && version.length > 0, version); + +// Time each export from the JS side: this includes the string boundary crossing +// that native Go benchmarks cannot see. +let timeCounter = 0; +function time(name, fn, iterations) { + // Warm up long enough that cached and uncached variants reach the same + // steady state; a short warmup penalizes the variant that allocates less. + for (let i = 0; i < 200; i++) fn(); + const start = performance.now(); + for (let i = 0; i < iterations; i++) fn(); + const ms = (performance.now() - start) / iterations; + console.log(`time ${name.padEnd(14)} ${ms.toFixed(4)} ms/call (${iterations} calls)`); +} + +time('goValidate', () => globalThis.goValidate(yaml), 200); +time('goValidate-changed', () => globalThis.goValidate(yaml.replace('Bench', 'Other' + (timeCounter++ % 2))), 200); +time('goParseField', () => globalThis.goParseField('string [required, max:255]', 'title'), 200); +time('goParseDomain', () => globalThis.goParseDomain(yaml), 200); +time('goParseDomain-changed', () => globalThis.goParseDomain(yaml.replace('Bench', 'Other' + (timeCounter++ % 2))), 200); +if (typeof globalThis.goGenerate === 'function') { + time('goGenerate', () => globalThis.goGenerate(yaml, 'admin-alpine', ''), 30); +} +time('goSpecmeta', () => globalThis.goSpecmeta(), 200); +time('goVersion', () => globalThis.goVersion(), 200); + +// Studio pattern: validate and parse raw with the same YAML back-to-back. +time('studio-cycle', () => { + globalThis.goValidate(yaml); + globalThis.goParseDomain(yaml); +}, 200); + diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 9bf5bdd..e999365 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -95,3 +95,12 @@ cmd/domaincraft/commands_init_test.go::TestRenderScenarioRejectsControlCharacter pkg/logger/logger_test.go::TestNewWithWriterNeverColorsBuffers #review logger colors were decided from process stderr after output had been redirected to a buffer internal/interactive/theme_test.go::TestFitVisible #review wide CJK and emoji counted as one column, so a "fitting" prompt wrapped and broke in-place redraw internal/specmeta/specmeta_test.go::TestSplitArrayDefaultRespectsQuotes #review a comma inside a quoted array default was treated as a separator by the validator and seed generator but not by the lexer +pkg/textutil/textutil_test.go::TestIdentifierTransformsMatchReference #review identifier fast path changed casing of acronyms, separators and unicode names +cmd/wasm-validator/api_test.go::TestWasmApiContracts #review WASM export refactor changed the JSON shape returned to the GUI +cmd/wasm-validator/api_test.go::TestResultCacheAlternatingInputs #review interleaved cached goValidate/goParseDomain calls returned a stale schema +internal/specmeta/specmeta_test.go::TestSplitRespectingQuotesFastPathMatchesSlow #review modifier splitter fast path changed quote or bracket handling +internal/renderer/memory_test.go::TestRenderMemoryMatchesDisk #review in-memory renderer produced files different from the CLI renderer +internal/renderer/memory_test.go::TestRenderMemoryRejectsEscapingTarget #review a template target could escape the generated project root in browser generation +cmd/wasm-validator/api_test.go::TestGenerateYAML #review goGenerate had no native contract test for generated files +cmd/wasm-validator/api_test.go::TestGenerateYAMLRejectsInvalidModel #review goGenerate rendered files for a schema rejected by goValidate +internal/bridgecontract/version_test.go::TestParseContractVersion #review contract gate extraction changed absent, zero or negative contract_version handling diff --git a/internal/bridge/update.go b/internal/bridge/update.go index 1c8e13f..a34b437 100644 --- a/internal/bridge/update.go +++ b/internal/bridge/update.go @@ -12,9 +12,8 @@ import ( "strings" "time" + "github.com/DomainCraft/DomainCraft/internal/bridgecontract" "github.com/DomainCraft/DomainCraft/internal/netutil" - "github.com/DomainCraft/DomainCraft/internal/specmeta" - "gopkg.in/yaml.v3" ) // httpClient is shared by remote version probes. @@ -40,59 +39,19 @@ var httpGetBodyFn = httpGetBody // an invocation does not hit the network every time. const DefaultUpdateInterval = 24 * time.Hour -// CoreContractVersion is the bridge-contract version the current core -// implements. It aliases specmeta.ContractVersion so a bump needs one edit. -// An upstream bridge declaring a higher contract is unsupported and must never -// be applied. -const CoreContractVersion = specmeta.ContractVersion - -// ParseContractVersion reads `contract_version` from bridge.yaml bytes. It is -// the single parser used by both the update gate and the renderer loader, so -// a manifest can never be accepted on one side and rejected on the other. -// Returns the effective version, whether the field was explicitly declared, -// and an error. An absent (or zero) field means the core's contract version; -// every other unreadable value — including a negative one — is a hard error: -// a malformed manifest must never be silently downgraded to "supported". +// CoreContractVersion is the bridge contract implemented by this core. The +// gate lives in internal/bridgecontract so the CLI update path, the disk +// renderer and the in-browser renderer share one implementation. +const CoreContractVersion = bridgecontract.CoreContractVersion + +// ParseContractVersion reads contract_version from bridge.yaml bytes. func ParseContractVersion(data []byte) (int, bool, error) { - // Parse once into a node, then decode from it. A truncated body may still - // be valid YAML (e.g. a scalar or a list), so require a mapping document - // before reading the version. - var doc yaml.Node - if err := yaml.Unmarshal(data, &doc); err != nil { - return 0, false, fmt.Errorf("parse bridge contract version: %w", err) - } - if len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode { - return 0, false, fmt.Errorf("parse bridge contract version: manifest must be a YAML mapping") - } - // A pointer distinguishes an absent field from an explicit 0, while the - // declared flag follows the legacy "0 means absent" behaviour. - var cfg struct { - ContractVersion *int `yaml:"contract_version"` - } - if err := doc.Decode(&cfg); err != nil { - return 0, false, fmt.Errorf("parse bridge contract version: %w", err) - } - if cfg.ContractVersion == nil { - return CoreContractVersion, false, nil - } - if *cfg.ContractVersion < 0 { - return 0, true, fmt.Errorf("invalid contract_version %d", *cfg.ContractVersion) - } - if *cfg.ContractVersion == 0 { - return CoreContractVersion, false, nil - } - return *cfg.ContractVersion, true, nil + return bridgecontract.ParseContractVersion(data) } -// CheckContractVersion verifies that a bridge declaring contractVersion is -// supported by the current core. A newer contract is a hard error — an -// unsupported bridge must never be downloaded/applied. Shared with the -// renderer so both gates move together on a contract bump. -func CheckContractVersion(contractVersion int) error { - if contractVersion > CoreContractVersion { - return fmt.Errorf("bridge requires contract v%d, but this core implements contract v%d", contractVersion, CoreContractVersion) - } - return nil +// CheckContractVersion rejects a bridge that declares a newer contract. +func CheckContractVersion(version int) error { + return bridgecontract.CheckContractVersion(version) } // gateRemoteContract fetches a bridge manifest at ref and applies the contract diff --git a/internal/bridgecontract/version.go b/internal/bridgecontract/version.go new file mode 100644 index 0000000..786f94c --- /dev/null +++ b/internal/bridgecontract/version.go @@ -0,0 +1,51 @@ +// Package bridgecontract holds the bridge-contract version gate. It has no +// filesystem or network dependencies, so the CLI, the update path, the disk +// renderer and the in-browser renderer all share one implementation. +package bridgecontract + +import ( + "fmt" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" + "gopkg.in/yaml.v3" +) + +// CoreContractVersion is the bridge-contract version the current core +// implements. It aliases specmeta.ContractVersion so a bump needs one edit. +const CoreContractVersion = specmeta.ContractVersion + +// ParseContractVersion reads `contract_version` from bridge.yaml bytes. An +// absent (or zero) field means the core's contract version; every other +// unreadable value — including a negative one — is a hard error. +func ParseContractVersion(data []byte) (int, bool, error) { + var doc yaml.Node + if err := yaml.Unmarshal(data, &doc); err != nil { + return 0, false, fmt.Errorf("parse bridge contract version: %w", err) + } + if len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode { + return 0, false, fmt.Errorf("parse bridge contract version: manifest must be a YAML mapping") + } + var cfg struct { + ContractVersion *int `yaml:"contract_version"` + } + if err := doc.Decode(&cfg); err != nil { + return 0, false, fmt.Errorf("parse bridge contract version: %w", err) + } + if cfg.ContractVersion == nil { + return CoreContractVersion, false, nil + } + if *cfg.ContractVersion < 0 { + return 0, true, fmt.Errorf("invalid contract_version %d", *cfg.ContractVersion) + } + // specmeta owns absent/0 → core version; negative values fail closed above. + return specmeta.EffectiveContractVersion(*cfg.ContractVersion), *cfg.ContractVersion != 0, nil +} + +// CheckContractVersion rejects a bridge declaring a newer contract than the +// core implements. +func CheckContractVersion(contractVersion int) error { + if contractVersion > CoreContractVersion { + return fmt.Errorf("bridge requires contract v%d, but this core implements contract v%d", contractVersion, CoreContractVersion) + } + return nil +} diff --git a/internal/bridgecontract/version_test.go b/internal/bridgecontract/version_test.go new file mode 100644 index 0000000..cead2e5 --- /dev/null +++ b/internal/bridgecontract/version_test.go @@ -0,0 +1,55 @@ +package bridgecontract + +import ( + "strings" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" +) + +func TestParseContractVersion(t *testing.T) { + t.Parallel() + tests := []struct { + name string + manifest string + want int + declared bool + wantError bool + }{ + {name: "absent", manifest: "name: demo\n", want: specmeta.ContractVersion}, + {name: "explicit zero", manifest: "contract_version: 0\n", want: specmeta.ContractVersion}, + {name: "matching", manifest: "contract_version: 2\n", want: 2, declared: true}, + {name: "negative", manifest: "contract_version: -1\n", wantError: true}, + {name: "newer", manifest: "contract_version: 99\n", want: 99, declared: true}, + {name: "not a mapping", manifest: "- a\n", wantError: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, declared, err := ParseContractVersion([]byte(tt.manifest)) + if tt.wantError { + if err == nil { + t.Fatal("ParseContractVersion() accepted a bad manifest") + } + return + } + if err != nil { + t.Fatal(err) + } + if got != tt.want || declared != tt.declared { + t.Fatalf("ParseContractVersion() = (%d, %v), want (%d, %v)", got, declared, tt.want, tt.declared) + } + if err := CheckContractVersion(got); (err != nil) != (got > specmeta.ContractVersion) { + t.Fatalf("CheckContractVersion(%d) = %v", got, err) + } + }) + } +} + +func TestCheckContractVersionText(t *testing.T) { + t.Parallel() + err := CheckContractVersion(specmeta.ContractVersion + 1) + if err == nil || !strings.Contains(err.Error(), "requires contract") { + t.Fatalf("CheckContractVersion() = %v", err) + } +} diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index 68cd4c9..9a4e6da 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -4,7 +4,6 @@ package fsutil import ( - "crypto/rand" "encoding/json" "errors" "fmt" @@ -180,7 +179,7 @@ func (o rootAtomicOps) mkdir(dir string) error { return o.root.MkdirAll(dir, 0o7 func (o rootAtomicOps) lstat(name string) (os.FileInfo, error) { return o.root.Lstat(name) } func (o rootAtomicOps) createTemp(_, name string) (*os.File, string, error) { - tmp := name + ".tmp-" + rand.Text() + tmp := name + ".tmp-" + atomicTempSuffix() f, err := o.root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { return nil, "", err diff --git a/internal/fsutil/tempname_default.go b/internal/fsutil/tempname_default.go new file mode 100644 index 0000000..27d4097 --- /dev/null +++ b/internal/fsutil/tempname_default.go @@ -0,0 +1,12 @@ +//go:build !js || !wasm + +package fsutil + +import "crypto/rand" + +// atomicTempSuffix keeps a random collision-free suffix out of the shared +// fsutil file so the WASM build does not link crypto/rand for code it never +// calls (RenderMemory has no disk writes). +func atomicTempSuffix() string { + return rand.Text() +} diff --git a/internal/fsutil/tempname_wasm.go b/internal/fsutil/tempname_wasm.go new file mode 100644 index 0000000..93699c9 --- /dev/null +++ b/internal/fsutil/tempname_wasm.go @@ -0,0 +1,10 @@ +//go:build js && wasm + +package fsutil + +// atomicTempSuffix is unreachable in the browser: the in-memory renderer +// never creates temp files. Keeping it constant avoids pulling crypto/rand +// into the WASM binary. +func atomicTempSuffix() string { + return "mem" +} diff --git a/internal/lexer/lexer.go b/internal/lexer/lexer.go index c81ffca..f3adaa5 100644 --- a/internal/lexer/lexer.go +++ b/internal/lexer/lexer.go @@ -47,9 +47,9 @@ func Parse(input string) (*FieldDefinition, error) { func parse(input string, extraStringMods []string) (*FieldDefinition, error) { input = strings.TrimSpace(input) - fd := &FieldDefinition{ - Validations: make(map[string]string), - } + // Validations is created on first use. Most field definitions carry no + // validation modifiers, so the map would be pure garbage. + fd := &FieldDefinition{} // Split into type and modifiers: "string [required, max:255]". Split at the // first "[" only; the rest (modifiers, which may themselves contain brackets, @@ -169,6 +169,9 @@ func parseModifiers(modStr string, fd *FieldDefinition, extraStringMods []string switch { case specmeta.IsValidationModifier(key, extraStringMods): + if fd.Validations == nil { + fd.Validations = make(map[string]string, 2) + } fd.Validations[key] = value case key == "default": // Check for function-style defaults like now(), uuid() @@ -199,6 +202,9 @@ func parseModifiers(modStr string, fd *FieldDefinition, extraStringMods []string // Bare string flags live in specmeta alongside their key:value forms. if specmeta.IsStringFlagValidationModifier(mod) { + if fd.Validations == nil { + fd.Validations = make(map[string]string, 2) + } fd.Validations[mod] = "true" continue } diff --git a/internal/parser/parser.go b/internal/parser/parser.go index fd27c0e..241a30a 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -219,6 +219,9 @@ func ParseField(name string, fieldDef string) (*ParsedField, error) { // Sync required flag to validations map so templates can use HasValidation "required" if fd.IsRequired { + if fd.Validations == nil { + fd.Validations = make(map[string]string, 1) + } fd.Validations["required"] = "true" } diff --git a/internal/renderer/bridge_disk.go b/internal/renderer/bridge_disk.go new file mode 100644 index 0000000..91a5703 --- /dev/null +++ b/internal/renderer/bridge_disk.go @@ -0,0 +1,9 @@ +//go:build !js || !wasm + +package renderer + +import "github.com/DomainCraft/DomainCraft/internal/bridge" + +func localBridgePaths(input string) (string, string, error) { + return bridge.LocalBridgePaths(input) +} diff --git a/internal/renderer/bridge_wasm.go b/internal/renderer/bridge_wasm.go new file mode 100644 index 0000000..6af6be8 --- /dev/null +++ b/internal/renderer/bridge_wasm.go @@ -0,0 +1,15 @@ +//go:build js && wasm + +package renderer + +import ( + "path" + "path/filepath" +) + +// The browser never calls loadSource (bridges come from the embedded fs.FS), +// but the symbol must exist so disk and WASM builds share load.go. +func localBridgePaths(input string) (string, string, error) { + clean := filepath.ToSlash(filepath.Clean(input)) + return clean, path.Join(clean, "bridge.yaml"), nil +} diff --git a/internal/renderer/load.go b/internal/renderer/load.go index 191d844..f0c9e26 100644 --- a/internal/renderer/load.go +++ b/internal/renderer/load.go @@ -9,7 +9,7 @@ import ( "sync" "text/template" - "github.com/DomainCraft/DomainCraft/internal/bridge" + "github.com/DomainCraft/DomainCraft/internal/bridgecontract" "github.com/DomainCraft/DomainCraft/internal/ir" "github.com/DomainCraft/DomainCraft/pkg/logger" @@ -24,6 +24,19 @@ type sourceConfig struct { // contractDeclared records whether bridge.yaml explicitly declared // `contract_version` (vs. being absent → treated as 1). contractDeclared bool + // readSource loads a bridge file by relative path. Nil means the real + // filesystem; an embedded fs.FS supplies the in-browser implementation. + readSource func(dir, rel string) ([]byte, error) +} + +// readBridgeFile is the single reader for templates, helpers and mappings. +// Disk sources keep the symlink-safe os.Root path; embedded sources read +// through fs.ReadFile with the same lexical containment rule. +func readBridgeFile(src sourceConfig, rel string) ([]byte, error) { + if src.readSource != nil { + return src.readSource(src.dir, rel) + } + return readBridgeSource(src.dir, rel) } // Renderer reads bridge.yaml and renders files from IR. @@ -207,7 +220,7 @@ func storeParsedSource(key string, src sourceConfig) { // loadSource loads a single bridge directory (its bridge.yaml). func loadSource(bridgePath string) (sourceConfig, error) { - bridgeDir, configPath, err := bridge.LocalBridgePaths(bridgePath) + bridgeDir, configPath, err := localBridgePaths(bridgePath) if err != nil { return sourceConfig{}, err } @@ -221,6 +234,18 @@ func loadSource(bridgePath string) (sourceConfig, error) { return src, nil } + src, err := parseSourceConfig(data, bridgeDir) + if err != nil { + return sourceConfig{}, err + } + storeParsedSource(key, src) + return src, nil +} + +// parseSourceConfig validates one bridge.yaml. Both the disk loader and the +// in-memory (embedded fs.FS) loader go through here so contract and condition +// rules can never diverge between CLI and browser generation. +func parseSourceConfig(data []byte, dir string) (sourceConfig, error) { var config BridgeConfig if err := yaml.Unmarshal(data, &config); err != nil { return sourceConfig{}, fmt.Errorf("parse bridge config: %w", err) @@ -236,19 +261,15 @@ func loadSource(bridgePath string) (sourceConfig, error) { } // Contract version: use the same parser/gate as the bridge update path so // a manifest cannot be accepted on one side and rejected on the other. - // An absent declaration defaults to the core's version (with a deprecation - // notice from the caller); a negative or newer declaration is a hard error. - contractVersion, contractDeclared, err := bridge.ParseContractVersion(data) + contractVersion, contractDeclared, err := bridgecontract.ParseContractVersion(data) if err != nil { return sourceConfig{}, err } - if err := bridge.CheckContractVersion(contractVersion); err != nil { + if err := bridgecontract.CheckContractVersion(contractVersion); err != nil { return sourceConfig{}, fmt.Errorf("bridge %q: %w", config.Name, err) } config.ContractVersion = contractVersion - src := sourceConfig{dir: bridgeDir, config: config, contractDeclared: contractDeclared} - storeParsedSource(key, src) - return src, nil + return sourceConfig{dir: dir, config: config, contractDeclared: contractDeclared}, nil } // New loads a single (leaf) bridge. @@ -257,10 +278,16 @@ func New(bridgePath string, log *logger.Logger) (*Renderer, error) { if err != nil { return nil, err } + warnUndeclaredContract(src, log) + return &Renderer{sources: []sourceConfig{src}, log: log}, nil +} + +// warnUndeclaredContract keeps CLI and in-browser bridge loading diagnostics +// identical. A nil logger is a silent host, which is the WASM case. +func warnUndeclaredContract(src sourceConfig, log *logger.Logger) { if !src.contractDeclared && log != nil { log.Warn("bridge %q does not declare `contract_version`; assuming contract v%d (deprecated — please add it)", src.config.Name, src.config.ContractVersion) } - return &Renderer{sources: []sourceConfig{src}, log: log}, nil } // Extends reports the base bridge this bridge composes on top of (a path, diff --git a/internal/renderer/memory.go b/internal/renderer/memory.go new file mode 100644 index 0000000..2eb8b6b --- /dev/null +++ b/internal/renderer/memory.go @@ -0,0 +1,209 @@ +package renderer + +import ( + "errors" + "fmt" + "io/fs" + "path" + "path/filepath" + "slices" + "strings" + "sync" + "text/template" + + "github.com/DomainCraft/DomainCraft/internal/fsutil" + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/pkg/logger" +) + +// NewFromFS loads a bridge chain from an fs.FS, typically the `//go:embed +// bridges` tree shipped inside the CLI and the WASM binary. bridgePaths are +// base-first; the adapter is last. The disk renderer's contract, condition and +// type-mapping rules are shared with the CLI through parseSourceConfig. +func NewFromFS(fsys fs.FS, bridgePaths []string, log *logger.Logger) (*Renderer, error) { + if fsys == nil { + return nil, errors.New("bridge filesystem is nil") + } + sources := make([]sourceConfig, 0, len(bridgePaths)) + for _, raw := range bridgePaths { + dir := path.Clean(filepath.ToSlash(raw)) + if path.IsAbs(dir) || dir == ".." || strings.HasPrefix(dir, "../") { + return nil, fmt.Errorf("unsafe bridge path %q", raw) + } + data, err := fs.ReadFile(fsys, path.Join(dir, "bridge.yaml")) + if err != nil { + return nil, fmt.Errorf("read bridge config %s: %w", dir, err) + } + src, err := parseSourceConfig(data, dir) + if err != nil { + return nil, fmt.Errorf("bridge %s: %w", dir, err) + } + warnUndeclaredContract(src, log) + src.readSource = func(dir, rel string) ([]byte, error) { + clean := path.Clean(filepath.ToSlash(rel)) + if path.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, "../") { + return nil, fmt.Errorf("unsafe bridge source path %q", rel) + } + return fs.ReadFile(fsys, path.Join(dir, clean)) + } + sources = append(sources, src) + } + if len(sources) == 0 { + return nil, errors.New("empty bridge chain") + } + return &Renderer{sources: sources, log: log}, nil +} + +// MemoryFile is one rendered output file. Paths use forward slashes and are +// always relative to the generated project root. +type MemoryFile struct { + Path string `json:"path"` + Content string `json:"content"` +} + +// memoryPlan is the static half of a generation: functions, helpers and parsed +// templates. It depends only on bridge files, never on the domain model, so a +// single entry is enough for a Studio that edits the model but keeps the bridge. +type memoryPlan struct { + funcMap template.FuncMap + helpers *template.Template + compiled map[string]*compiledSpec +} + +// memoryPlanCache mirrors the bounded parsedSourceCache: one entry, cleared +// when the bridge chain changes. +var memoryPlanCache = struct { + sync.Mutex + key string + plan *memoryPlan +}{} + +func (r *Renderer) memoryPlan() (*memoryPlan, error) { + key := r.memoryPlanKey() + memoryPlanCache.Lock() + defer memoryPlanCache.Unlock() + if memoryPlanCache.plan != nil && memoryPlanCache.key == key { + return memoryPlanCache.plan, nil + } + + funcMap, err := r.buildFuncMap() + if err != nil { + return nil, fmt.Errorf("build template functions: %w", err) + } + helpers, err := r.parseHelpers(funcMap) + if err != nil { + return nil, err + } + plan := &memoryPlan{funcMap: funcMap, helpers: helpers, compiled: make(map[string]*compiledSpec)} + for _, src := range r.sources { + for _, spec := range src.config.Templates { + k := src.dir + "\x00" + spec.Source + "\x00" + strings.Join(spec.TargetPatterns(), "\x00") + compiled, err := r.compileSpec(src, spec, funcMap, helpers) + if err != nil { + return nil, err + } + plan.compiled[k] = compiled + } + } + memoryPlanCache.key, memoryPlanCache.plan = key, plan + return plan, nil +} + +func (r *Renderer) memoryPlanKey() string { + var b strings.Builder + left, right := r.delimiters() + b.WriteString(left) + b.WriteByte('\x00') + b.WriteString(right) + for _, src := range r.sources { + b.WriteString(src.dir) + b.WriteByte('\x00') + b.WriteString(src.config.Helpers) + b.WriteByte('\x00') + for _, spec := range src.config.Templates { + b.WriteString(spec.For) + b.WriteByte(':') + b.WriteString(spec.Source) + b.WriteByte(':') + b.WriteString(spec.When) + b.WriteByte('\x00') + } + } + return b.String() +} + +// RenderMemory executes the same templates as Render but writes into memory. +// It deliberately has no filesystem, symlink or rollback machinery: in a +// browser there is no output directory, and the caller decides what to do with +// the returned files. Packages are supplied by the caller — resolving them +// from NuGet would require a network round trip from the browser. +func (r *Renderer) RenderMemory(project *ir.Project, pkgs map[string]string) ([]MemoryFile, error) { + if project == nil { + return nil, errors.New("ir project is nil") + } + plan, err := r.memoryPlan() + if err != nil { + return nil, err + } + + files := make(map[string]string) + customTargets := make(map[string]bool) + for _, src := range r.sources { + for _, spec := range src.config.Templates { + if !r.shouldRender(spec, project, pkgs) { + continue + } + k := src.dir + "\x00" + spec.Source + "\x00" + strings.Join(spec.TargetPatterns(), "\x00") + compiled := plan.compiled[k] + if compiled == nil { + return nil, fmt.Errorf("no compiled template for %s", spec.Source) + } + + contexts, err := r.renderContexts(spec.For, project, pkgs) + if err != nil { + return nil, err + } + for _, context := range contexts { + if !r.shouldRenderContext(spec, context) { + continue + } + for _, targetTpl := range compiled.targets { + rendered, err := executeTemplateString(targetTpl, context) + if err != nil { + return nil, fmt.Errorf("render target path: %w", err) + } + // The same lexical containment rule as the disk renderer; + // a browser has no symlinks, but `..` and volume names must + // never escape the generated project root. + _, rel, err := fsutil.LocalPathWithin(".", rendered) + if err != nil || rel == "." { + return nil, fmt.Errorf("template target path escapes output directory: %s", rendered) + } + rel = filepath.ToSlash(rel) + if spec.IsCustom() { + if customTargets[rel] { + continue + } + customTargets[rel] = true + } + var buf strings.Builder + if err := compiled.body.Execute(&buf, context); err != nil { + return nil, fmt.Errorf("execute template %s: %w", spec.Source, err) + } + files[rel] = buf.String() + } + } + } + } + + paths := make([]string, 0, len(files)) + for p := range files { + paths = append(paths, p) + } + slices.Sort(paths) + out := make([]MemoryFile, 0, len(paths)) + for _, p := range paths { + out = append(out, MemoryFile{Path: p, Content: files[p]}) + } + return out, nil +} diff --git a/internal/renderer/memory_test.go b/internal/renderer/memory_test.go new file mode 100644 index 0000000..e99b1f7 --- /dev/null +++ b/internal/renderer/memory_test.go @@ -0,0 +1,128 @@ +package renderer + +import ( + "os" + "path/filepath" + "testing" + "testing/fstest" + + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/parser" +) + +func memoryTestProject(t *testing.T) *ir.Project { + t.Helper() + schema, err := parser.ParseYAML([]byte(`project: + name: Shop +database: postgresql +entities: + User: + fields: + id: uuid [primary] + email: string [required, unique, email] + password: string [required, hidden] + Product: + fields: + id: uuid [primary] + title: string [required, max:255] +auth: + type: jwt + roles: [Admin, User] + entity: User +`)) + if err != nil { + t.Fatal(err) + } + project, err := ir.Build(schema) + if err != nil { + t.Fatal(err) + } + return project +} + +func TestRenderMemoryMatchesDisk(t *testing.T) { + project := memoryTestProject(t) + fsys := os.DirFS(filepath.Join("..", "..", "bridges")) + + memory, err := NewFromFS(fsys, []string{"admin"}, nil) + if err != nil { + t.Fatal(err) + } + files, err := memory.RenderMemory(project, nil) + if err != nil { + t.Fatal(err) + } + if len(files) < 4 { + t.Fatalf("RenderMemory returned %d files, want at least 4", len(files)) + } + + disk, err := New(filepath.Join("..", "..", "bridges", "admin"), nil) + if err != nil { + t.Fatal(err) + } + out := t.TempDir() + _, _, err = disk.Render(project, out) + if err != nil { + t.Fatal(err) + } + + for _, file := range files { + got, err := os.ReadFile(filepath.Join(out, filepath.FromSlash(file.Path))) + if err != nil { + t.Errorf("disk render missing %s: %v", file.Path, err) + continue + } + if string(got) != file.Content { + t.Errorf("%s differs: memory %d bytes, disk %d bytes", file.Path, len(file.Content), len(got)) + } + } +} + +func TestRenderMemoryComposesBaseFirst(t *testing.T) { + project := memoryTestProject(t) + fsys := os.DirFS(filepath.Join("..", "..", "bridges")) + + // react-rest extends ts-client extends ts-core. All three manifests must + // load from the embedded-style tree without cloning anything. + r, err := NewFromFS(fsys, []string{"typescript/core", "typescript/client", "typescript/react"}, nil) + if err != nil { + t.Fatal(err) + } + files, err := r.RenderMemory(project, nil) + if err != nil { + t.Fatal(err) + } + if len(files) == 0 { + t.Fatal("RenderMemory returned no files for the TS chain") + } + seen := make(map[string]bool) + for _, f := range files { + seen[f.Path] = true + if f.Content == "" { + t.Errorf("empty generated file %s", f.Path) + } + } + if !seen["package.json"] { + t.Errorf("adapter did not render package.json: %v", seen) + } +} + +func TestRenderMemoryRejectsEscapingTarget(t *testing.T) { + fsys := fstest.MapFS{ + "bridge/bridge.yaml": &fstest.MapFile{Data: []byte(`name: evil +contract_version: 2 +templates: + - for: project + source: templates/evil.tmpl + target: "../evil.txt" +`)}, + "bridge/templates/evil.tmpl": &fstest.MapFile{Data: []byte("bad")}, + } + r, err := NewFromFS(fsys, []string{"bridge"}, nil) + if err != nil { + t.Fatal(err) + } + if _, err := r.RenderMemory(memoryTestProject(t), nil); err == nil { + t.Fatal("RenderMemory accepted a target outside the project root") + } +} diff --git a/internal/renderer/packages_default.go b/internal/renderer/packages_default.go new file mode 100644 index 0000000..48bcf51 --- /dev/null +++ b/internal/renderer/packages_default.go @@ -0,0 +1,53 @@ +//go:build !js || !wasm + +package renderer + +import ( + "maps" + "slices" + + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/packages" +) + +// resolvePackages resolves all package versions from the package registry, +// cached per bridge so repeated runs don't hit the registry every time. +// Registry packages from the chain are merged base-first, adapter wins. +func (r *Renderer) resolvePackages(project *ir.Project) map[string]string { + framework := r.targetFramework(project) + + merged := make(map[string]string) + for _, src := range r.sources { + maps.Copy(merged, src.config.RegistryPackages) + } + if len(merged) == 0 { + return nil + } + + registryURL := r.config().RegistryURL + if registryURL == "" { + for _, src := range slices.Backward(r.sources) { + if src.config.RegistryURL != "" { + registryURL = src.config.RegistryURL + break + } + } + } + if registryURL == "" { + r.log.Warn("no registry_url configured in any bridge in the chain; skipping package resolution") + return nil + } + + result := make(map[string]string, len(merged)) + for _, key := range slices.Sorted(maps.Keys(merged)) { + packageID := merged[key] + version, err := packages.ResolveVersionCachedForFramework(r.cacheNamespace(), registryURL, packageID, framework) + if err != nil { + r.log.Warn("failed to resolve package %s: %v", packageID, err) + } + if version != "" { + result[key] = version + } + } + return result +} diff --git a/internal/renderer/packages_wasm.go b/internal/renderer/packages_wasm.go new file mode 100644 index 0000000..8096c1f --- /dev/null +++ b/internal/renderer/packages_wasm.go @@ -0,0 +1,12 @@ +//go:build js && wasm + +package renderer + +import "github.com/DomainCraft/DomainCraft/internal/ir" + +// resolvePackages is a no-op in the browser: NuGet resolution needs HTTP and a +// filesystem cache. The caller passes package versions to RenderMemory, and +// templates without version references render unchanged. +func (r *Renderer) resolvePackages(_ *ir.Project) map[string]string { + return nil +} diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 187b22c..52b9312 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -4,7 +4,6 @@ package renderer import ( "errors" "fmt" - "maps" "os" "path/filepath" "slices" @@ -13,7 +12,6 @@ import ( "github.com/DomainCraft/DomainCraft/internal/fsutil" "github.com/DomainCraft/DomainCraft/internal/ir" - "github.com/DomainCraft/DomainCraft/internal/packages" ) // readBridgeSource reads a template, helper or mapping declared by bridge.yaml. @@ -181,7 +179,7 @@ func (r *Renderer) parseHelpers(funcMap template.FuncMap) (*template.Template, e if src.config.Helpers == "" { continue } - helperBytes, err := readBridgeSource(src.dir, src.config.Helpers) + helperBytes, err := readBridgeFile(src, src.config.Helpers) if err != nil { return nil, fmt.Errorf("read helpers %s: %w", src.config.Helpers, err) } @@ -263,6 +261,46 @@ func (s *renderSession) fail(err error) error { return rollbackError(err, rollbackWrites(s.staged, s.committed)) } +// compiledSpec is the static part of a template spec: the body and its target +// path templates. It depends only on bridge files, not on the domain model, so +// both the disk and in-memory renderers compile it the same way. +type compiledSpec struct { + body *template.Template + targets []*template.Template +} + +func (r *Renderer) compileSpec(src sourceConfig, spec TemplateSpec, funcMap template.FuncMap, helpers *template.Template) (*compiledSpec, error) { + tplBytes, err := readBridgeFile(src, spec.Source) + if err != nil { + return nil, fmt.Errorf("read template %s: %w", spec.Source, err) + } + + tplName := filepath.Base(spec.Source) + var body *template.Template + if helpers != nil { + body, err = helpers.Clone() + if err != nil { + return nil, fmt.Errorf("clone helpers for %s: %w", spec.Source, err) + } + body, err = r.applyDelimiters(body.New(tplName)).Parse(string(tplBytes)) + } else { + body, err = r.applyDelimiters(template.New(tplName).Funcs(funcMap)).Parse(string(tplBytes)) + } + if err != nil { + return nil, fmt.Errorf("parse template %s: %w", spec.Source, err) + } + + patterns := spec.TargetPatterns() + targets := make([]*template.Template, len(patterns)) + for i, pattern := range patterns { + targets[i], err = template.New("path").Funcs(funcMap).Parse(pattern) + if err != nil { + return nil, fmt.Errorf("parse target path %q: %w", pattern, err) + } + } + return &compiledSpec{body: body, targets: targets}, nil +} + // stageTemplates parses each selected template and renders every target into a // temp file next to it. Nothing is written to outputDir until all templates // executed successfully; a failure drops the temp files staged so far. @@ -274,43 +312,18 @@ func (r *Renderer) stageTemplates(s *renderSession) error { continue } - tplBytes, err := readBridgeSource(src.dir, spec.Source) - if err != nil { - return s.fail(fmt.Errorf("read template %s: %w", spec.Source, err)) - } - - tplName := filepath.Base(spec.Source) - var parsedTemplate *template.Template - if s.helpers != nil { - // Clone helpers so all named templates are available - parsedTemplate, err = s.helpers.Clone() - if err != nil { - return s.fail(fmt.Errorf("clone helpers for %s: %w", spec.Source, err)) - } - parsedTemplate, err = r.applyDelimiters(parsedTemplate.New(tplName)).Parse(string(tplBytes)) - } else { - parsedTemplate, err = r.applyDelimiters(template.New(tplName).Funcs(s.funcMap)).Parse(string(tplBytes)) - } + compiled, err := r.compileSpec(src, spec, s.funcMap, s.helpers) if err != nil { - return s.fail(fmt.Errorf("parse template %s: %w", spec.Source, err)) + return s.fail(err) } + parsedTemplate := compiled.body + targetTemplates := compiled.targets contexts, err := r.renderContexts(spec.For, s.project, s.pkgs) if err != nil { return s.fail(err) } - // A target pattern is static for the spec; only the context changes. - // Parse once instead of once per (entity, pattern) pair. - targetPatterns := spec.TargetPatterns() - targetTemplates := make([]*template.Template, len(targetPatterns)) - for i, pattern := range targetPatterns { - targetTemplates[i], err = template.New("path").Funcs(s.funcMap).Parse(pattern) - if err != nil { - return s.fail(fmt.Errorf("parse target path %q: %w", pattern, err)) - } - } - for _, context := range contexts { // Check if this specific context should be rendered based on "When" condition if !r.shouldRenderContext(spec, context) { @@ -633,11 +646,6 @@ func (r *Renderer) shouldRenderContext(spec TemplateSpec, context RenderContext) return entry.eval(context, name) } -// resolvePackages resolves all package versions from the package registry, -// cached per bridge so repeated runs don't hit the registry every time. -// When the renderer is composed (extends chain), registry_packages from all -// bridges are merged base-first so inner layers can declare their own -// dependencies; the adapter's values win on conflicts. // targetFramework returns the project's declared platform, then the framework // declared by the bridge chain (adapter first, base later). An absent framework // leaves version selection unconstrained — the core bakes in no TFM. @@ -653,50 +661,6 @@ func (r *Renderer) targetFramework(project *ir.Project) string { return "" } -func (r *Renderer) resolvePackages(project *ir.Project) map[string]string { - framework := r.targetFramework(project) - - // Merge registry_packages from all sources in the chain (base-first, - // adapter wins on conflicts — consistent with type_mappings merge). - merged := make(map[string]string) - for _, src := range r.sources { - maps.Copy(merged, src.config.RegistryPackages) - } - if len(merged) == 0 { - return nil - } - - // Use the adapter's registry_url; fall back to any source with one. - registryURL := r.config().RegistryURL - if registryURL == "" { - for _, src := range slices.Backward(r.sources) { - if src.config.RegistryURL != "" { - registryURL = src.config.RegistryURL - break - } - } - } - if registryURL == "" { - r.log.Warn("no registry_url configured in any bridge in the chain; skipping package resolution") - return nil - } - - result := make(map[string]string, len(merged)) - for _, key := range slices.Sorted(maps.Keys(merged)) { - packageID := merged[key] - version, err := packages.ResolveVersionCachedForFramework(r.cacheNamespace(), registryURL, packageID, framework) - if err != nil { - // A cache-write failure still carries the resolved version; warn - // once and use it instead of emitting a package-less project. - r.log.Warn("failed to resolve package %s: %v", packageID, err) - } - if version != "" { - result[key] = version - } - } - return result -} - // cacheNamespace returns a stable, filesystem-safe identifier for this bridge, // used to keep its package-version cache separate from other bridges'. The // bridge.yaml name is preferred; a path-based fallback covers nameless bridges. diff --git a/internal/renderer/templates.go b/internal/renderer/templates.go index 5f219ac..f1f5fa4 100644 --- a/internal/renderer/templates.go +++ b/internal/renderer/templates.go @@ -105,10 +105,10 @@ func (r *Renderer) buildFuncMap() (template.FuncMap, error) { // loadTypeMappings reads a bridge directory's type_mappings.yaml. It returns nil // (no error) when the file is absent — a bridge with no mappings contributes // nothing, and the merged result drives the language functions. -func (r *Renderer) loadTypeMappings(dir string) (*typeMappings, error) { +func (r *Renderer) loadTypeMappings(src sourceConfig) (*typeMappings, error) { // Same guard as templates and helpers: a symlinked mapping file must not // pull configuration from outside the bridge directory. - data, err := readBridgeSource(dir, "type_mappings.yaml") + data, err := readBridgeFile(src, "type_mappings.yaml") if err != nil { if errors.Is(err, os.ErrNotExist) { return nil, nil @@ -172,7 +172,7 @@ func mergeMaps[V any](dst, src map[string]V) map[string]V { func (r *Renderer) getBridgeSpecificFuncs() (map[string]any, error) { var merged *typeMappings for _, src := range r.sources { - m, err := r.loadTypeMappings(src.dir) + m, err := r.loadTypeMappings(src) if err != nil { return nil, err } diff --git a/internal/specmeta/specmeta.go b/internal/specmeta/specmeta.go index c49225d..a0594cb 100644 --- a/internal/specmeta/specmeta.go +++ b/internal/specmeta/specmeta.go @@ -382,6 +382,11 @@ func ParseArrayInner(dbType string) string { // defaults, so a comma inside a quoted value cannot be read as a separator by // one consumer and as data by another. func SplitRespectingQuotes(s string) []string { + // Most modifier clauses have neither quotes nor nested defaults. A single + // Split allocates only the result slice and reuses the input backing array. + if !strings.ContainsAny(s, "'\"[]") { + return strings.Split(s, ",") + } var out []string var cur strings.Builder depth := 0 diff --git a/internal/specmeta/specmeta_test.go b/internal/specmeta/specmeta_test.go index d2896c8..8b49036 100644 --- a/internal/specmeta/specmeta_test.go +++ b/internal/specmeta/specmeta_test.go @@ -568,6 +568,68 @@ func TestSplitArrayDefaultRespectsQuotes(t *testing.T) { } } +// referenceSplitRespectingQuotes is the pre-fast-path implementation. The +// fast path must produce the same tokens for every clause it claims. +func referenceSplitRespectingQuotes(s string) []string { + var out []string + var cur strings.Builder + depth := 0 + var quote byte + for i := 0; i < len(s); i++ { + c := s[i] + if quote != 0 { + cur.WriteByte(c) + if c == quote { + quote = 0 + } + continue + } + switch c { + case '\'', '"': + quote = c + cur.WriteByte(c) + case '[': + depth++ + cur.WriteByte(c) + case ']': + if depth > 0 { + depth-- + } + cur.WriteByte(c) + case ',': + if depth == 0 { + out = append(out, cur.String()) + cur.Reset() + continue + } + cur.WriteByte(c) + default: + cur.WriteByte(c) + } + } + return append(out, cur.String()) +} + +func TestSplitRespectingQuotesFastPathMatchesSlow(t *testing.T) { + t.Parallel() + for _, s := range []string{ + "", "required", "required, max:255", "a,b,c", + `default:["a,b", c], required`, "default:[a, b, c]", + `regex:^a,b$`, `default:'x,y'`, "a,,b", "default:[nested,[x,y]], later", + } { + got, want := SplitRespectingQuotes(s), referenceSplitRespectingQuotes(s) + if len(got) != len(want) { + t.Errorf("SplitRespectingQuotes(%q) = %q, want %q", s, got, want) + continue + } + for i := range want { + if got[i] != want[i] { + t.Errorf("SplitRespectingQuotes(%q)[%d] = %q, want %q", s, i, got[i], want[i]) + } + } + } +} + func TestEffectiveContractVersion(t *testing.T) { t.Parallel() cases := []struct { diff --git a/pkg/textutil/textutil.go b/pkg/textutil/textutil.go index a83169c..d758465 100644 --- a/pkg/textutil/textutil.go +++ b/pkg/textutil/textutil.go @@ -61,6 +61,15 @@ func PascalCase(value string) string { if value == "" { return "" } + // The common path (a plain lowercase identifier) needs one allocation, + // not the parts slice plus per-part strings of the general path. + if isSimpleIdentifier(value) { + b := []byte(value) + if b[0] >= 'a' && b[0] <= 'z' { + b[0] -= 'a' - 'A' + } + return string(b) + } parts := SplitIdentifier(value) for i := range parts { if parts[i] == "" { @@ -99,6 +108,11 @@ func FKName(name string) string { // ToDatabaseColumnName converts camelCase/PascalCase to snake_case. // Uses SplitIdentifier to correctly handle acronyms (e.g. "HTTPPort" -> "http_port"). func ToDatabaseColumnName(fieldName string) string { + // Already canonical: no separator, no camel/acronym boundary, no uppercase. + // Returning the input avoids a parts slice and a Builder allocation. + if isSimpleIdentifier(fieldName) { + return fieldName + } return strings.ToLower(strings.Join(SplitIdentifier(fieldName), "_")) } @@ -106,39 +120,60 @@ func ToDatabaseColumnName(fieldName string) string { // and camelCase boundaries (e.g. "firstName" -> ["first", "Name"], // "HTMLParser" -> ["HTML", "Parser"]). func SplitIdentifier(value string) []string { - // Normalize separators - normalized := strings.ReplaceAll(value, "-", "_") - normalized = strings.ReplaceAll(normalized, " ", "_") + // Plain lowercase ASCII identifiers (the overwhelming majority of field + // names) have no boundary to split on. + if isSimpleIdentifier(value) { + return []string{value} + } - // Insert separator at camelCase boundaries - runes := []rune(normalized) - var withSeps []rune + // Treat '-' and ' ' as separators in the same pass; the previous two + // ReplaceAll calls allocated a copy of the whole string each. + runes := []rune(value) + parts := make([]string, 0, 4) + var cur strings.Builder + flush := func() { + if cur.Len() > 0 { + parts = append(parts, cur.String()) + cur.Reset() + } + } for i, r := range runes { + switch r { + case '-', ' ', '_': + flush() + continue + } if i > 0 { prev := runes[i-1] // camelCase boundary: lowercase -> Uppercase if unicode.IsUpper(r) && unicode.IsLower(prev) { - withSeps = append(withSeps, '_') + flush() } // ACRONYM boundary: UPPERCASE -> Uppercase+lowercase (e.g., HTMLParser -> HTML_Parser) if i+1 < len(runes) && unicode.IsUpper(r) && unicode.IsUpper(prev) && unicode.IsLower(runes[i+1]) { - withSeps = append(withSeps, '_') + flush() } } - withSeps = append(withSeps, r) + cur.WriteRune(r) + } + flush() + if len(parts) == 0 { + return []string{value} } + return parts +} - parts := strings.Split(string(withSeps), "_") - var result []string - for _, p := range parts { - if p != "" { - result = append(result, p) +// isSimpleIdentifier reports whether value is already in canonical lowercase +// form with no separators and no camel/acronym boundary. Such a string is +// returned unchanged by ToDatabaseColumnName and splits into one part. +func isSimpleIdentifier(value string) bool { + for i := 0; i < len(value); i++ { + c := value[i] + if c == '-' || c == ' ' || c == '_' || c >= utf8.RuneSelf || (c >= 'A' && c <= 'Z') { + return false } } - if len(result) == 0 { - return []string{value} - } - return result + return true } func isVowel(r rune) bool { diff --git a/pkg/textutil/textutil_bench_test.go b/pkg/textutil/textutil_bench_test.go new file mode 100644 index 0000000..77a072a --- /dev/null +++ b/pkg/textutil/textutil_bench_test.go @@ -0,0 +1,50 @@ +package textutil + +import "testing" + +func BenchmarkSplitIdentifier(b *testing.B) { + for _, tc := range []struct{ name, value string }{ + {name: "simple", value: "name"}, + {name: "snake", value: "created_at"}, + {name: "camel", value: "firstName"}, + {name: "acronym", value: "HTTPServer"}, + {name: "unicode", value: "èCafé_Наименование"}, + } { + b.Run(tc.name, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _ = SplitIdentifier(tc.value) + } + }) + } +} + +func BenchmarkToDatabaseColumnName(b *testing.B) { + for _, tc := range []struct{ name, value string }{ + {name: "simple", value: "name"}, + {name: "camel", value: "IPv4Address"}, + {name: "acronym", value: "HTTPServer"}, + } { + b.Run(tc.name, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _ = ToDatabaseColumnName(tc.value) + } + }) + } +} + +func BenchmarkPascalCase(b *testing.B) { + for _, tc := range []struct{ name, value string }{ + {name: "simple", value: "name"}, + {name: "snake", value: "created_at"}, + {name: "acronym", value: "HTTPServer"}, + } { + b.Run(tc.name, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _ = PascalCase(tc.value) + } + }) + } +} diff --git a/pkg/textutil/textutil_test.go b/pkg/textutil/textutil_test.go index 82a3a5d..4d65ac9 100644 --- a/pkg/textutil/textutil_test.go +++ b/pkg/textutil/textutil_test.go @@ -1,7 +1,9 @@ package textutil import ( + "strings" "testing" + "unicode" "unicode/utf8" ) @@ -194,3 +196,75 @@ func TestSplitIdentifier(t *testing.T) { }) } } + +// referenceSplitIdentifier is the pre-optimization implementation. Keeping it +// in the test makes the fast path provably behaviour-preserving on a corpus, +// including separators, acronyms and non-ASCII identifiers. +func referenceSplitIdentifier(value string) []string { + normalized := strings.ReplaceAll(value, "-", "_") + normalized = strings.ReplaceAll(normalized, " ", "_") + runes := []rune(normalized) + var withSeps []rune + for i, r := range runes { + if i > 0 { + prev := runes[i-1] + if unicode.IsUpper(r) && unicode.IsLower(prev) { + withSeps = append(withSeps, '_') + } + if i+1 < len(runes) && unicode.IsUpper(r) && unicode.IsUpper(prev) && unicode.IsLower(runes[i+1]) { + withSeps = append(withSeps, '_') + } + } + withSeps = append(withSeps, r) + } + parts := strings.Split(string(withSeps), "_") + var result []string + for _, p := range parts { + if p != "" { + result = append(result, p) + } + } + if len(result) == 0 { + return []string{value} + } + return result +} + +func TestIdentifierTransformsMatchReference(t *testing.T) { + t.Parallel() + for _, value := range []string{ + "", "name", "firstName", "first_name", "first-name", "first name", + "HTMLParser", "HTTPSServer", "IPv4Address", "HTTP20xOK", "a", "123", + "__", "--", "a_b-c d", "èCafé_Наименование", "ÜBERStraße", "xY", "XYz", + "магазин", "магазин_товары", + } { + wantParts := referenceSplitIdentifier(value) + gotParts := SplitIdentifier(value) + if len(gotParts) != len(wantParts) { + t.Errorf("SplitIdentifier(%q) = %v, want %v", value, gotParts, wantParts) + continue + } + for i := range wantParts { + if gotParts[i] != wantParts[i] { + t.Errorf("SplitIdentifier(%q)[%d] = %q, want %q", value, i, gotParts[i], wantParts[i]) + } + } + + wantDB := strings.ToLower(strings.Join(wantParts, "_")) + if got := ToDatabaseColumnName(value); got != wantDB { + t.Errorf("ToDatabaseColumnName(%q) = %q, want %q", value, got, wantDB) + } + + wantPascal := "" + for _, p := range wantParts { + if p == "" { + continue + } + first, size := utf8.DecodeRuneInString(p) + wantPascal += string(unicode.ToUpper(first)) + strings.ToLower(p[size:]) + } + if got := PascalCase(value); got != wantPascal { + t.Errorf("PascalCase(%q) = %q, want %q", value, got, wantPascal) + } + } +}