From 40aa887e9b3f812ce3f32e9eec382e4dd4ce8546 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:28:39 +0300 Subject: [PATCH 1/4] Core: speed up WASM validation exports and add benchmarks - move WASM export logic into a js-free API so it is testable natively - memoize goValidate/goParseDomain results and goSpecmeta JSON - cut identifier and modifier-split allocations in the hot parse path - add native benchmarks, a Node WASM smoke harness and measured results Benchstat, Windows/amd64 Ryzen 7 5800X, Go 1.27.4, -count=6+8, base main@8927417 vs PR after re-sync: Specmeta 22.7us -> 3.4ns -100% StudioValidationCycle/same-yaml 2.66ms -> 2.0us -99.9% StudioValidationCycle/changing 2.59ms -> 2.27ms -12.5% SplitIdentifier/simple 192ns -> 16ns -92% ToDatabaseColumnName/simple 183ns -> 5.7ns -97% Validate/entities=2000 18.4ms -> 13.8ms -25% Node, 200 calls, median of 4 interleaved runs, ms/call: goValidate (same) 0.26 -> 0.055 goParseDomain (same) 0.19 -> 0.021 goSpecmeta 0.14 -> 0.016 studio cycle 0.39 -> 0.042 Cold per-call paths are unchanged within noise. --- cmd/wasm-validator/api.go | 140 +++++++++++++++++ cmd/wasm-validator/api_bench_test.go | 146 ++++++++++++++++++ cmd/wasm-validator/api_test.go | 215 +++++++++++++++++++++++++++ cmd/wasm-validator/main.go | 73 ++------- cmd/wasm-validator/smoke.mjs | 93 ++++++++++++ compliance-suite/regressions.tsv | 4 + internal/lexer/lexer.go | 12 +- internal/parser/parser.go | 3 + internal/specmeta/specmeta.go | 5 + internal/specmeta/specmeta_test.go | 62 ++++++++ pkg/textutil/textutil.go | 71 ++++++--- pkg/textutil/textutil_bench_test.go | 50 +++++++ pkg/textutil/textutil_test.go | 74 +++++++++ 13 files changed, 863 insertions(+), 85 deletions(-) create mode 100644 cmd/wasm-validator/api.go create mode 100644 cmd/wasm-validator/api_bench_test.go create mode 100644 cmd/wasm-validator/api_test.go create mode 100644 cmd/wasm-validator/smoke.mjs create mode 100644 pkg/textutil/textutil_bench_test.go diff --git a/cmd/wasm-validator/api.go b/cmd/wasm-validator/api.go new file mode 100644 index 0000000..f67dd20 --- /dev/null +++ b/cmd/wasm-validator/api.go @@ -0,0 +1,140 @@ +// 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" + "sync" + + "github.com/DomainCraft/DomainCraft/internal/lexer" + "github.com/DomainCraft/DomainCraft/internal/parser" + "github.com/DomainCraft/DomainCraft/internal/specmeta" + "github.com/DomainCraft/DomainCraft/internal/validator" +) + +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}) +} + +// 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 { + schema, err := parser.ParseYAML([]byte(yaml)) + 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}) + }) +} + +// 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 +} + +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..fbb2781 --- /dev/null +++ b/cmd/wasm-validator/api_bench_test.go @@ -0,0 +1,146 @@ +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() + } +} + +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..f99bcc2 --- /dev/null +++ b/cmd/wasm-validator/api_test.go @@ -0,0 +1,215 @@ +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) + } +} + +// 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..c469ce3 100644 --- a/cmd/wasm-validator/main.go +++ b/cmd/wasm-validator/main.go @@ -4,30 +4,12 @@ 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)) @@ -39,11 +21,11 @@ func main() { } 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 +43,30 @@ 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, - }) - } - 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 ValidationErrorResult(err.Error()) } - 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 marshal(raw) -} - -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 FieldErrorResult(err.Error()) } - return string(data) + return ParseDomainYAML(input) } diff --git a/cmd/wasm-validator/smoke.mjs b/cmd/wasm-validator/smoke.mjs new file mode 100644 index 0000000..48b9430 --- /dev/null +++ b/cmd/wasm-validator/smoke.mjs @@ -0,0 +1,93 @@ +// 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); + +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); +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..1b594d1 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -95,3 +95,7 @@ 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 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/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) + } + } +} From eddc496652fbf9c59a0242f03b1fa30fa1b60277 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:13:19 +0300 Subject: [PATCH 2/4] Core: add in-memory rendering to WASM exports - expose goGenerate(yaml, bridge, packagesJSON) returning generated files - load the embedded bridges tree through a new fs.FS renderer path - keep CLI rendering byte-identical (TestRenderMemoryMatchesDisk) - stub package resolution and bridge clone/update code for js/wasm The naive build grew from 5.9 MB to 19.4 MB; the WASM-only stubs bring it back to 10.2 MB raw (2.6 MB gzip). RenderMemory adds no disk or symlink machinery, so browser generation stays bounded by the returned JSON. go test ./... -count=1 and make lint pass; Node smoke generates 6 files for admin-alpine in ~9 ms. --- cmd/wasm-validator/api.go | 144 +++++++++++++++++++++++ cmd/wasm-validator/api_bench_test.go | 9 ++ cmd/wasm-validator/api_test.go | 34 ++++++ cmd/wasm-validator/main.go | 20 ++++ cmd/wasm-validator/smoke.mjs | 8 +- compliance-suite/regressions.tsv | 3 + internal/renderer/bridge_disk.go | 17 +++ internal/renderer/bridge_wasm.go | 51 +++++++++ internal/renderer/load.go | 38 +++++-- internal/renderer/memory.go | 158 ++++++++++++++++++++++++++ internal/renderer/memory_test.go | 128 +++++++++++++++++++++ internal/renderer/packages_default.go | 68 +++++++++++ internal/renderer/packages_wasm.go | 30 +++++ internal/renderer/render.go | 70 +----------- internal/renderer/templates.go | 6 +- 15 files changed, 703 insertions(+), 81 deletions(-) create mode 100644 internal/renderer/bridge_disk.go create mode 100644 internal/renderer/bridge_wasm.go create mode 100644 internal/renderer/memory.go create mode 100644 internal/renderer/memory_test.go create mode 100644 internal/renderer/packages_default.go create mode 100644 internal/renderer/packages_wasm.go diff --git a/cmd/wasm-validator/api.go b/cmd/wasm-validator/api.go index f67dd20..6cd23f5 100644 --- a/cmd/wasm-validator/api.go +++ b/cmd/wasm-validator/api.go @@ -4,12 +4,23 @@ package main import ( "encoding/json" + "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 { @@ -131,6 +142,139 @@ 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"` +} + +// 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{}} + chain, err := embeddedBridgeChain(bridgeRef) + if err != nil { + result.Error = err.Error() + return marshal(result) + } + schema, err := parser.ParseYAML([]byte(yamlText)) + if err != nil { + result.Error = err.Error() + 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, err := renderer.NewFromFS(domaincraft.Bridges, chain, nil) + if err != nil { + result.Error = err.Error() + return marshal(result) + } + 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 { diff --git a/cmd/wasm-validator/api_bench_test.go b/cmd/wasm-validator/api_bench_test.go index fbb2781..7621a2f 100644 --- a/cmd/wasm-validator/api_bench_test.go +++ b/cmd/wasm-validator/api_bench_test.go @@ -106,6 +106,15 @@ func BenchmarkSpecmeta(b *testing.B) { } } +// 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() { diff --git a/cmd/wasm-validator/api_test.go b/cmd/wasm-validator/api_test.go index f99bcc2..9bd057f 100644 --- a/cmd/wasm-validator/api_test.go +++ b/cmd/wasm-validator/api_test.go @@ -115,6 +115,40 @@ func TestVersion(t *testing.T) { } } +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 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. diff --git a/cmd/wasm-validator/main.go b/cmd/wasm-validator/main.go index c469ce3..d52dd50 100644 --- a/cmd/wasm-validator/main.go +++ b/cmd/wasm-validator/main.go @@ -15,6 +15,7 @@ func main() { 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 @@ -70,3 +71,22 @@ func parseDomain(_ js.Value, args []js.Value) any { } return ParseDomainYAML(input) } + +func generate(_ js.Value, args []js.Value) any { + input, err := stringArg(args, 0, "YAML input") + if err != nil { + 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 GenerateYAML(input, bridgeRef, packages) +} diff --git a/cmd/wasm-validator/smoke.mjs b/cmd/wasm-validator/smoke.mjs index 48b9430..a0b042e 100644 --- a/cmd/wasm-validator/smoke.mjs +++ b/cmd/wasm-validator/smoke.mjs @@ -25,7 +25,7 @@ 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']; +const required = ['goValidate', 'goParseField', 'goParseDomain', 'goGenerate', 'goSpecmeta', 'goVersion']; for (const name of required) { if (typeof globalThis[name] !== 'function') throw new Error(`missing WASM export: ${name}`); } @@ -61,6 +61,11 @@ 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); +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`); + const version = globalThis.goVersion(); check('goVersion', typeof version === 'string' && version.length > 0, version); @@ -82,6 +87,7 @@ time('goValidate-changed', () => globalThis.goValidate(yaml.replace('Bench', 'Ot 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); +time('goGenerate', () => globalThis.goGenerate(yaml, 'admin-alpine', ''), 30); time('goSpecmeta', () => globalThis.goSpecmeta(), 200); time('goVersion', () => globalThis.goVersion(), 200); diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 1b594d1..844cd9b 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -99,3 +99,6 @@ pkg/textutil/textutil_test.go::TestIdentifierTransformsMatchReference #review id 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 diff --git a/internal/renderer/bridge_disk.go b/internal/renderer/bridge_disk.go new file mode 100644 index 0000000..119889f --- /dev/null +++ b/internal/renderer/bridge_disk.go @@ -0,0 +1,17 @@ +//go:build !js || !wasm + +package renderer + +import "github.com/DomainCraft/DomainCraft/internal/bridge" + +func localBridgePaths(input string) (string, string, error) { + return bridge.LocalBridgePaths(input) +} + +func parseBridgeContractVersion(data []byte) (int, bool, error) { + return bridge.ParseContractVersion(data) +} + +func checkBridgeContractVersion(version int) error { + return bridge.CheckContractVersion(version) +} diff --git a/internal/renderer/bridge_wasm.go b/internal/renderer/bridge_wasm.go new file mode 100644 index 0000000..3edcbb6 --- /dev/null +++ b/internal/renderer/bridge_wasm.go @@ -0,0 +1,51 @@ +//go:build js && wasm + +package renderer + +import ( + "fmt" + "path" + "path/filepath" + + "github.com/DomainCraft/DomainCraft/internal/specmeta" + "gopkg.in/yaml.v3" +) + +// The browser never calls loadSource (bridges come from the embedded fs.FS), +// but the symbols must exist so the 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 +} + +// parseBridgeContractVersion mirrors bridge.ParseContractVersion without +// importing the network-backed bridge package into the WASM binary. +func parseBridgeContractVersion(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 || *cfg.ContractVersion == 0 { + return specmeta.ContractVersion, false, nil + } + if *cfg.ContractVersion < 0 { + return 0, true, fmt.Errorf("invalid contract_version %d", *cfg.ContractVersion) + } + return *cfg.ContractVersion, true, nil +} + +func checkBridgeContractVersion(version int) error { + if version > specmeta.ContractVersion { + return fmt.Errorf("bridge requires contract v%d, but this core implements contract v%d", version, specmeta.ContractVersion) + } + return nil +} diff --git a/internal/renderer/load.go b/internal/renderer/load.go index 191d844..f8b3f08 100644 --- a/internal/renderer/load.go +++ b/internal/renderer/load.go @@ -9,7 +9,6 @@ import ( "sync" "text/template" - "github.com/DomainCraft/DomainCraft/internal/bridge" "github.com/DomainCraft/DomainCraft/internal/ir" "github.com/DomainCraft/DomainCraft/pkg/logger" @@ -24,6 +23,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 +219,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 +233,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 +260,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 := parseBridgeContractVersion(data) if err != nil { return sourceConfig{}, err } - if err := bridge.CheckContractVersion(contractVersion); err != nil { + if err := checkBridgeContractVersion(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. diff --git a/internal/renderer/memory.go b/internal/renderer/memory.go new file mode 100644 index 0000000..60eb6da --- /dev/null +++ b/internal/renderer/memory.go @@ -0,0 +1,158 @@ +package renderer + +import ( + "bytes" + "errors" + "fmt" + "io/fs" + "path" + "path/filepath" + "slices" + "strings" + "text/template" + + "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) + } + 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"` +} + +// 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") + } + + 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 + } + + 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 + } + 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 { + 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) + } + + contexts, err := r.renderContexts(spec.For, project, pkgs) + if err != nil { + return nil, err + } + targetTemplates := make([]*template.Template, 0, len(spec.TargetPatterns())) + for _, pattern := range spec.TargetPatterns() { + tpl, err := template.New("path").Funcs(funcMap).Parse(pattern) + if err != nil { + return nil, fmt.Errorf("parse target path %q: %w", pattern, err) + } + targetTemplates = append(targetTemplates, tpl) + } + + for _, context := range contexts { + if !r.shouldRenderContext(spec, context) { + continue + } + for _, targetTpl := range targetTemplates { + rendered, err := executeTemplateString(targetTpl, context) + if err != nil { + return nil, fmt.Errorf("render target path: %w", err) + } + rel := path.Clean(filepath.ToSlash(rendered)) + if path.IsAbs(rel) || rel == ".." || strings.HasPrefix(rel, "../") { + return nil, fmt.Errorf("template target path escapes output directory: %s", rendered) + } + if spec.IsCustom() { + if customTargets[rel] { + continue + } + customTargets[rel] = true + } + var buf bytes.Buffer + if err := 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..e9fa412 --- /dev/null +++ b/internal/renderer/packages_default.go @@ -0,0 +1,68 @@ +//go:build !js || !wasm + +package renderer + +import ( + "maps" + "slices" + + "github.com/DomainCraft/DomainCraft/internal/ir" + "github.com/DomainCraft/DomainCraft/internal/packages" +) + +// 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. +func (r *Renderer) targetFramework(project *ir.Project) string { + if project != nil && project.Platform != "" { + return project.Platform + } + for _, src := range slices.Backward(r.sources) { + if fw := src.config.TargetFramework; fw != "" { + return fw + } + } + return "" +} + +// 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..d4a8c62 --- /dev/null +++ b/internal/renderer/packages_wasm.go @@ -0,0 +1,30 @@ +//go:build js && wasm + +package renderer + +import ( + "slices" + + "github.com/DomainCraft/DomainCraft/internal/ir" +) + +// targetFramework mirrors the CLI build. Kept here so the in-browser renderer +// shares the same rule without importing the network-backed packages resolver. +func (r *Renderer) targetFramework(project *ir.Project) string { + if project != nil && project.Platform != "" { + return project.Platform + } + for _, src := range slices.Backward(r.sources) { + if fw := src.config.TargetFramework; fw != "" { + return fw + } + } + return "" +} + +// 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..2d4dc4c 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) } @@ -274,7 +272,7 @@ func (r *Renderer) stageTemplates(s *renderSession) error { continue } - tplBytes, err := readBridgeSource(src.dir, spec.Source) + tplBytes, err := readBridgeFile(src, spec.Source) if err != nil { return s.fail(fmt.Errorf("read template %s: %w", spec.Source, err)) } @@ -633,70 +631,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. -func (r *Renderer) targetFramework(project *ir.Project) string { - if project != nil && project.Platform != "" { - return project.Platform - } - for _, src := range slices.Backward(r.sources) { - if fw := src.config.TargetFramework; fw != "" { - return fw - } - } - 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 } From e3ef3523d914419507c7d0ad0fd02a95702c9ac7 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:36:30 +0300 Subject: [PATCH 3/4] Core: cut WASM generation allocations and share bridge helpers - cache compiled templates and the bridge chain across generate calls - compile specs once for both disk and in-memory renderers - validate the model in goGenerate before rendering it - move the contract gate into internal/bridgecontract and reuse specmeta - keep crypto/rand out of the WASM build BenchmarkGenerateYAML before -> after: 2.01ms -> 0.71ms (-65%) 1477KiB -> 587KiB (-60%) 11.5k -> 2.49k allocs/op (-78%) WASM binary: 10.07 MB raw / 2.59 MB gzip. Other exports unchanged in Node. --- cmd/wasm-validator/api.go | 67 +++++++++++-- cmd/wasm-validator/api_test.go | 34 +++++++ cmd/wasm-validator/smoke.mjs | 18 ++-- compliance-suite/regressions.tsv | 2 + internal/bridge/update.go | 63 +++--------- internal/bridgecontract/version.go | 51 ++++++++++ internal/bridgecontract/version_test.go | 55 +++++++++++ internal/fsutil/fsutil.go | 3 +- internal/fsutil/tempname_default.go | 12 +++ internal/fsutil/tempname_wasm.go | 10 ++ internal/renderer/bridge_disk.go | 8 -- internal/renderer/bridge_wasm.go | 38 +------ internal/renderer/load.go | 13 ++- internal/renderer/memory.go | 125 +++++++++++++++++------- internal/renderer/packages_default.go | 15 --- internal/renderer/packages_wasm.go | 20 +--- internal/renderer/render.go | 88 +++++++++++------ 17 files changed, 405 insertions(+), 217 deletions(-) create mode 100644 internal/bridgecontract/version.go create mode 100644 internal/bridgecontract/version_test.go create mode 100644 internal/fsutil/tempname_default.go create mode 100644 internal/fsutil/tempname_wasm.go diff --git a/cmd/wasm-validator/api.go b/cmd/wasm-validator/api.go index 6cd23f5..6c23373 100644 --- a/cmd/wasm-validator/api.go +++ b/cmd/wasm-validator/api.go @@ -4,6 +4,7 @@ package main import ( "encoding/json" + "errors" "fmt" "io/fs" "path" @@ -76,18 +77,27 @@ 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 { - schema, err := parser.ParseYAML([]byte(yaml)) + _, errs, err := parseAndValidateYAML(yaml) 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{ @@ -149,6 +159,39 @@ type generateResult struct { 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 @@ -156,16 +199,26 @@ type generateResult struct { // them when it has them. func GenerateYAML(yamlText, bridgeRef, packagesJSON string) string { result := generateResult{Files: []renderer.MemoryFile{}} - chain, err := embeddedBridgeChain(bridgeRef) + plan, err := generationPlanFor(bridgeRef) if err != nil { result.Error = err.Error() return marshal(result) } - schema, err := parser.ParseYAML([]byte(yamlText)) + 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() @@ -180,11 +233,7 @@ func GenerateYAML(yamlText, bridgeRef, packagesJSON string) string { } } - r, err := renderer.NewFromFS(domaincraft.Bridges, chain, nil) - if err != nil { - result.Error = 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) diff --git a/cmd/wasm-validator/api_test.go b/cmd/wasm-validator/api_test.go index 9bd057f..47f54b6 100644 --- a/cmd/wasm-validator/api_test.go +++ b/cmd/wasm-validator/api_test.go @@ -138,6 +138,40 @@ func TestGenerateYAML(t *testing.T) { } } +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 diff --git a/cmd/wasm-validator/smoke.mjs b/cmd/wasm-validator/smoke.mjs index a0b042e..93e7e43 100644 --- a/cmd/wasm-validator/smoke.mjs +++ b/cmd/wasm-validator/smoke.mjs @@ -25,7 +25,7 @@ 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', 'goGenerate', 'goSpecmeta', 'goVersion']; +const required = ['goValidate', 'goParseField', 'goParseDomain', 'goSpecmeta', 'goVersion']; for (const name of required) { if (typeof globalThis[name] !== 'function') throw new Error(`missing WASM export: ${name}`); } @@ -61,10 +61,14 @@ 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); -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`); +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); @@ -87,7 +91,9 @@ time('goValidate-changed', () => globalThis.goValidate(yaml.replace('Bench', 'Ot 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); -time('goGenerate', () => globalThis.goGenerate(yaml, 'admin-alpine', ''), 30); +if (typeof globalThis.goGenerate === 'function') { + time('goGenerate', () => globalThis.goGenerate(yaml, 'admin-alpine', ''), 30); +} time('goSpecmeta', () => globalThis.goSpecmeta(), 200); time('goVersion', () => globalThis.goVersion(), 200); diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index 844cd9b..e999365 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -102,3 +102,5 @@ internal/specmeta/specmeta_test.go::TestSplitRespectingQuotesFastPathMatchesSlow 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/renderer/bridge_disk.go b/internal/renderer/bridge_disk.go index 119889f..91a5703 100644 --- a/internal/renderer/bridge_disk.go +++ b/internal/renderer/bridge_disk.go @@ -7,11 +7,3 @@ import "github.com/DomainCraft/DomainCraft/internal/bridge" func localBridgePaths(input string) (string, string, error) { return bridge.LocalBridgePaths(input) } - -func parseBridgeContractVersion(data []byte) (int, bool, error) { - return bridge.ParseContractVersion(data) -} - -func checkBridgeContractVersion(version int) error { - return bridge.CheckContractVersion(version) -} diff --git a/internal/renderer/bridge_wasm.go b/internal/renderer/bridge_wasm.go index 3edcbb6..6af6be8 100644 --- a/internal/renderer/bridge_wasm.go +++ b/internal/renderer/bridge_wasm.go @@ -3,49 +3,13 @@ package renderer import ( - "fmt" "path" "path/filepath" - - "github.com/DomainCraft/DomainCraft/internal/specmeta" - "gopkg.in/yaml.v3" ) // The browser never calls loadSource (bridges come from the embedded fs.FS), -// but the symbols must exist so the disk and WASM builds share load.go. +// 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 } - -// parseBridgeContractVersion mirrors bridge.ParseContractVersion without -// importing the network-backed bridge package into the WASM binary. -func parseBridgeContractVersion(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 || *cfg.ContractVersion == 0 { - return specmeta.ContractVersion, false, nil - } - if *cfg.ContractVersion < 0 { - return 0, true, fmt.Errorf("invalid contract_version %d", *cfg.ContractVersion) - } - return *cfg.ContractVersion, true, nil -} - -func checkBridgeContractVersion(version int) error { - if version > specmeta.ContractVersion { - return fmt.Errorf("bridge requires contract v%d, but this core implements contract v%d", version, specmeta.ContractVersion) - } - return nil -} diff --git a/internal/renderer/load.go b/internal/renderer/load.go index f8b3f08..f0c9e26 100644 --- a/internal/renderer/load.go +++ b/internal/renderer/load.go @@ -9,6 +9,7 @@ import ( "sync" "text/template" + "github.com/DomainCraft/DomainCraft/internal/bridgecontract" "github.com/DomainCraft/DomainCraft/internal/ir" "github.com/DomainCraft/DomainCraft/pkg/logger" @@ -260,11 +261,11 @@ func parseSourceConfig(data []byte, dir 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. - contractVersion, contractDeclared, err := parseBridgeContractVersion(data) + contractVersion, contractDeclared, err := bridgecontract.ParseContractVersion(data) if err != nil { return sourceConfig{}, err } - if err := checkBridgeContractVersion(contractVersion); err != nil { + if err := bridgecontract.CheckContractVersion(contractVersion); err != nil { return sourceConfig{}, fmt.Errorf("bridge %q: %w", config.Name, err) } config.ContractVersion = contractVersion @@ -277,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 index 60eb6da..2eb8b6b 100644 --- a/internal/renderer/memory.go +++ b/internal/renderer/memory.go @@ -1,7 +1,6 @@ package renderer import ( - "bytes" "errors" "fmt" "io/fs" @@ -9,8 +8,10 @@ import ( "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" ) @@ -37,6 +38,7 @@ func NewFromFS(fsys fs.FS, bridgePaths []string, log *logger.Logger) (*Renderer, 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, "../") { @@ -59,6 +61,77 @@ type MemoryFile struct { 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 @@ -68,12 +141,7 @@ func (r *Renderer) RenderMemory(project *ir.Project, pkgs map[string]string) ([] if project == nil { return nil, errors.New("ir project is nil") } - - funcMap, err := r.buildFuncMap() - if err != nil { - return nil, fmt.Errorf("build template functions: %w", err) - } - helpers, err := r.parseHelpers(funcMap) + plan, err := r.memoryPlan() if err != nil { return nil, err } @@ -85,58 +153,41 @@ func (r *Renderer) RenderMemory(project *ir.Project, pkgs map[string]string) ([] if !r.shouldRender(spec, project, pkgs) { continue } - 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 { - 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) + 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 } - targetTemplates := make([]*template.Template, 0, len(spec.TargetPatterns())) - for _, pattern := range spec.TargetPatterns() { - tpl, err := template.New("path").Funcs(funcMap).Parse(pattern) - if err != nil { - return nil, fmt.Errorf("parse target path %q: %w", pattern, err) - } - targetTemplates = append(targetTemplates, tpl) - } - for _, context := range contexts { if !r.shouldRenderContext(spec, context) { continue } - for _, targetTpl := range targetTemplates { + for _, targetTpl := range compiled.targets { rendered, err := executeTemplateString(targetTpl, context) if err != nil { return nil, fmt.Errorf("render target path: %w", err) } - rel := path.Clean(filepath.ToSlash(rendered)) - if path.IsAbs(rel) || rel == ".." || strings.HasPrefix(rel, "../") { + // 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 bytes.Buffer - if err := body.Execute(&buf, context); err != nil { + 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() diff --git a/internal/renderer/packages_default.go b/internal/renderer/packages_default.go index e9fa412..48bcf51 100644 --- a/internal/renderer/packages_default.go +++ b/internal/renderer/packages_default.go @@ -10,21 +10,6 @@ import ( "github.com/DomainCraft/DomainCraft/internal/packages" ) -// 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. -func (r *Renderer) targetFramework(project *ir.Project) string { - if project != nil && project.Platform != "" { - return project.Platform - } - for _, src := range slices.Backward(r.sources) { - if fw := src.config.TargetFramework; fw != "" { - return fw - } - } - return "" -} - // 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. diff --git a/internal/renderer/packages_wasm.go b/internal/renderer/packages_wasm.go index d4a8c62..8096c1f 100644 --- a/internal/renderer/packages_wasm.go +++ b/internal/renderer/packages_wasm.go @@ -2,25 +2,7 @@ package renderer -import ( - "slices" - - "github.com/DomainCraft/DomainCraft/internal/ir" -) - -// targetFramework mirrors the CLI build. Kept here so the in-browser renderer -// shares the same rule without importing the network-backed packages resolver. -func (r *Renderer) targetFramework(project *ir.Project) string { - if project != nil && project.Platform != "" { - return project.Platform - } - for _, src := range slices.Backward(r.sources) { - if fw := src.config.TargetFramework; fw != "" { - return fw - } - } - return "" -} +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 diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 2d4dc4c..52b9312 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -261,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. @@ -272,43 +312,18 @@ func (r *Renderer) stageTemplates(s *renderSession) error { continue } - tplBytes, err := readBridgeFile(src, spec.Source) + compiled, err := r.compileSpec(src, spec, s.funcMap, s.helpers) 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)) - } - 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) { @@ -631,6 +646,21 @@ func (r *Renderer) shouldRenderContext(spec TemplateSpec, context RenderContext) return entry.eval(context, name) } +// 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. +func (r *Renderer) targetFramework(project *ir.Project) string { + if project != nil && project.Platform != "" { + return project.Platform + } + for _, src := range slices.Backward(r.sources) { + if fw := src.config.TargetFramework; fw != "" { + return fw + } + } + return "" +} + // 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. From 9a27589603520ec2ebcc3a2328dc045c243e8085 Mon Sep 17 00:00:00 2001 From: Fellmonkey <90258055+Fellmonkey@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:12:30 +0300 Subject: [PATCH 4/4] Core: cut WASM export allocations across parser, validator and renderer - share a sorted-key helper and a flat cycle DFS in the validator - parse strings without a []byte copy and cache feature-field order - cache regexp compilation for field definitions - write goParseField JSON directly and stream result JSON into a builder - grow template output buffers from the previous render size - fix benchmarks that appended a digit to YAML and measured the error path benchstat on corrected benchmarks, base -> this commit: geomean time -36.7%, bytes -28.6%, allocs -24.2% Validate/entities=2000 -28% time GenerateYAML -19% time, -50% bytes ParseField/regex -77% time StudioValidationCycle/changing-yaml -10% time All six exports stay byte-identical: SHA256 matches the previous commit for four models and eight field definitions. WASM binary: 10.14 MB raw. --- cmd/wasm-validator/api.go | 15 +-- cmd/wasm-validator/api_bench_test.go | 15 ++- cmd/wasm-validator/fieldjson.go | 150 +++++++++++++++++++++++++++ cmd/wasm-validator/fieldjson_test.go | 58 +++++++++++ compliance-suite/regressions.tsv | 1 + internal/lexer/lexer.go | 26 ++++- internal/parser/models.go | 22 +++- internal/parser/parser.go | 26 ++++- internal/renderer/memory.go | 2 + internal/renderer/render.go | 5 + internal/validator/validator.go | 106 ++++++++++++------- 11 files changed, 366 insertions(+), 60 deletions(-) create mode 100644 cmd/wasm-validator/fieldjson.go create mode 100644 cmd/wasm-validator/fieldjson_test.go diff --git a/cmd/wasm-validator/api.go b/cmd/wasm-validator/api.go index 6c23373..f40eb79 100644 --- a/cmd/wasm-validator/api.go +++ b/cmd/wasm-validator/api.go @@ -80,7 +80,7 @@ func FieldErrorResult(message string) string { // 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)) + schema, err := parser.ParseYAMLString(yaml) if err != nil { return nil, nil, err } @@ -122,13 +122,13 @@ func ParseFieldDefinition(def, name string) string { if fd.Validations == nil { fd.Validations = make(map[string]string) } - return marshal(fd) + return marshalFieldDefinition(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)) + raw, err := parser.ParseRawSchemaString(yaml) if err != nil { return marshal(map[string]string{"error": err.Error()}) } @@ -325,9 +325,10 @@ func findEmbeddedBridge(ref string) (string, error) { } func marshal(v any) string { - data, err := json.Marshal(v) - if err != nil { - data, _ = json.Marshal(map[string]string{"error": "marshal failed: " + err.Error()}) + var b strings.Builder + if err := json.NewEncoder(&b).Encode(v); err != nil { + data, _ := json.Marshal(map[string]string{"error": "marshal failed: " + err.Error()}) + return string(data) } - return string(data) + return strings.TrimSuffix(b.String(), "\n") } diff --git a/cmd/wasm-validator/api_bench_test.go b/cmd/wasm-validator/api_bench_test.go index 7621a2f..430dbba 100644 --- a/cmd/wasm-validator/api_bench_test.go +++ b/cmd/wasm-validator/api_bench_test.go @@ -3,7 +3,6 @@ package main import ( "fmt" "os" - "strconv" "strings" "testing" ) @@ -47,11 +46,16 @@ func BenchmarkValidate(b *testing.B) { } for _, tc := range cases { b.Run(tc.name, func(b *testing.B) { - yaml := tc.yaml(b) + // A trailing YAML comment gives the single-entry result cache two + // distinct keys without producing an invalid document. Appending a + // digit directly to the YAML made every iteration hit the parse + // error path and hid the validator entirely. + base := tc.yaml(b) + variants := [2]string{base + "\n# v0\n", base + "\n# v1\n"} b.ReportAllocs() i := 0 for b.Loop() { - _ = ValidateYAML(yaml + strconv.Itoa(i%2)) + _ = ValidateYAML(variants[i%2]) i++ } }) @@ -69,11 +73,12 @@ func BenchmarkParseDomain(b *testing.B) { {name: "entities=2000", yaml: func(*testing.B) string { return benchmarkYAML(2000) }}, } { b.Run(tc.name, func(b *testing.B) { - yaml := tc.yaml(b) + base := tc.yaml(b) + variants := [2]string{base + "\n# v0\n", base + "\n# v1\n"} b.ReportAllocs() i := 0 for b.Loop() { - _ = ParseDomainYAML(yaml + strconv.Itoa(i%2)) + _ = ParseDomainYAML(variants[i%2]) i++ } }) diff --git a/cmd/wasm-validator/fieldjson.go b/cmd/wasm-validator/fieldjson.go new file mode 100644 index 0000000..f8678b6 --- /dev/null +++ b/cmd/wasm-validator/fieldjson.go @@ -0,0 +1,150 @@ +package main + +import ( + "slices" + "strings" + "unicode/utf8" + + "github.com/DomainCraft/DomainCraft/internal/lexer" +) + +// marshalFieldDefinition writes the JSON contract of lexer.FieldDefinition +// directly. goParseField runs on every Studio keystroke, and the generic +// encoder spends most of that call reflecting over the 17-field struct. The +// key order and escaping below are exactly encoding/json's: fields in +// declaration order (no JSON tags on FieldDefinition), map keys sorted by +// UTF-8 bytes, HTML characters and U+2028/U+2029 escaped, invalid UTF-8 +// replaced with U+FFFD. +func marshalFieldDefinition(fd *lexer.FieldDefinition) string { + var b strings.Builder + size := 260 + len(fd.Name) + len(fd.Type) + len(fd.TargetEntity) + len(fd.TargetType) + + len(fd.OnDelete) + len(fd.OldName) + len(fd.DefaultValue) + for k, v := range fd.Validations { + size += len(k) + len(v) + 8 + } + b.Grow(size) + + b.WriteString(`{"Name":`) + writeJSONString(&b, fd.Name) + b.WriteString(`,"Type":`) + writeJSONString(&b, fd.Type) + b.WriteString(`,"TargetEntity":`) + writeJSONString(&b, fd.TargetEntity) + b.WriteString(`,"TargetType":`) + writeJSONString(&b, fd.TargetType) + b.WriteString(`,"IsPrimary":`) + writeBool(&b, fd.IsPrimary) + b.WriteString(`,"IsOptional":`) + writeBool(&b, fd.IsOptional) + b.WriteString(`,"IsUnique":`) + writeBool(&b, fd.IsUnique) + b.WriteString(`,"IsHidden":`) + writeBool(&b, fd.IsHidden) + b.WriteString(`,"IsReadonly":`) + writeBool(&b, fd.IsReadonly) + b.WriteString(`,"IsRequired":`) + writeBool(&b, fd.IsRequired) + b.WriteString(`,"OnDelete":`) + writeJSONString(&b, fd.OnDelete) + b.WriteString(`,"IsMany":`) + writeBool(&b, fd.IsMany) + b.WriteString(`,"OldName":`) + writeJSONString(&b, fd.OldName) + b.WriteString(`,"Validations":`) + if fd.Validations == nil { + b.WriteString(`null`) + } else { + b.WriteByte('{') + // Most definitions have <= 8 validation modifiers. A fixed-size local + // buffer keeps the common case stack-allocated; slices.Sorted(maps.Keys()) + // allocates an iterator closure and a slice on every call. + var scratch [8]string + keys := scratch[:0] + for k := range fd.Validations { + keys = append(keys, k) + } + slices.Sort(keys) + for i, k := range keys { + if i > 0 { + b.WriteByte(',') + } + writeJSONString(&b, k) + b.WriteByte(':') + writeJSONString(&b, fd.Validations[k]) + } + b.WriteByte('}') + } + b.WriteString(`,"DefaultValue":`) + writeJSONString(&b, fd.DefaultValue) + b.WriteString(`,"DefaultIsFunc":`) + writeBool(&b, fd.DefaultIsFunc) + b.WriteByte('}') + return b.String() +} + +func writeBool(b *strings.Builder, v bool) { + if v { + b.WriteString("true") + } else { + b.WriteString("false") + } +} + +const hexDigits = "0123456789abcdef" + +// writeJSONString mirrors encoding/json's string escaping byte for byte. +func writeJSONString(b *strings.Builder, s string) { + b.WriteByte('"') + start := 0 + for i := 0; i < len(s); { + c := s[i] + if c < utf8.RuneSelf { + if c >= 0x20 && c != '"' && c != '\\' && c != '<' && c != '>' && c != '&' { + i++ + continue + } + b.WriteString(s[start:i]) + switch c { + case '\\', '"': + b.WriteByte('\\') + b.WriteByte(c) + case '\n': + b.WriteString(`\n`) + case '\r': + b.WriteString(`\r`) + case '\t': + b.WriteString(`\t`) + case '\b': + b.WriteString(`\b`) + case '\f': + b.WriteString(`\f`) + default: + b.WriteString(`\u00`) + b.WriteByte(hexDigits[c>>4]) + b.WriteByte(hexDigits[c&0xf]) + } + i++ + start = i + continue + } + r, size := utf8.DecodeRuneInString(s[i:]) + if r == utf8.RuneError && size == 1 { + b.WriteString(s[start:i]) + b.WriteString("\xef\xbf\xbd") + i++ + start = i + continue + } + if r == '\u2028' || r == '\u2029' { + b.WriteString(s[start:i]) + b.WriteString(`\u202`) + b.WriteByte(hexDigits[r&0xf]) + i += size + start = i + continue + } + i += size + } + b.WriteString(s[start:]) + b.WriteByte('"') +} diff --git a/cmd/wasm-validator/fieldjson_test.go b/cmd/wasm-validator/fieldjson_test.go new file mode 100644 index 0000000..ad801db --- /dev/null +++ b/cmd/wasm-validator/fieldjson_test.go @@ -0,0 +1,58 @@ +package main + +import ( + "encoding/json" + "testing" + + "github.com/DomainCraft/DomainCraft/internal/lexer" +) + +// TestMarshalFieldDefinitionMatchesEncodingJSON guards the hand-written writer +// in fieldjson.go. goParseField returns this JSON to the Studio, so escaping, +// field order and sorted map keys must stay byte-identical to encoding/json. +func TestMarshalFieldDefinitionMatchesEncodingJSON(t *testing.T) { + cases := []struct { + name string + fd lexer.FieldDefinition + }{ + { + name: "empty", + fd: lexer.FieldDefinition{}, + }, + { + name: "all fields", + fd: lexer.FieldDefinition{ + Name: "title", Type: "string", TargetEntity: "User", TargetType: "array(string)", + IsPrimary: true, IsOptional: true, IsUnique: true, IsHidden: true, + IsReadonly: true, IsRequired: true, OnDelete: "set_null", IsMany: true, + OldName: "name", DefaultValue: "now()", DefaultIsFunc: true, + Validations: map[string]string{"min": "2", "max": "255", "regex": "^[a-z]+$"}, + }, + }, + { + name: "escaping", + fd: lexer.FieldDefinition{ + Name: " & \"quoted\" \\ path", + Type: "string", + DefaultValue: "line\nbreak\ttab\r\x01\u2028\u2029\xff", + Validations: map[string]string{ + "a": "1", "b": "2", "c": "3", "d": "4", "e": "5", "f": "6", "g": "7", "h": "8", + "i": "9", "j": "10", "emoji": "🙂", "invalid": string([]byte{0xff}), + }, + }, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + want, err := json.Marshal(&tc.fd) + if err != nil { + t.Fatal(err) + } + got := marshalFieldDefinition(&tc.fd) + if got != string(want) { + t.Fatalf("marshalFieldDefinition mismatch\n got: %s\nwant: %s", got, want) + } + }) + } +} diff --git a/compliance-suite/regressions.tsv b/compliance-suite/regressions.tsv index e999365..4b2bddd 100644 --- a/compliance-suite/regressions.tsv +++ b/compliance-suite/regressions.tsv @@ -104,3 +104,4 @@ internal/renderer/memory_test.go::TestRenderMemoryRejectsEscapingTarget #review 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 +cmd/wasm-validator/fieldjson_test.go::TestMarshalFieldDefinitionMatchesEncodingJSON #review hand-written goParseField JSON writer emitted `{}` instead of `null` for nil Validations diff --git a/internal/lexer/lexer.go b/internal/lexer/lexer.go index f3adaa5..8091a5b 100644 --- a/internal/lexer/lexer.go +++ b/internal/lexer/lexer.go @@ -5,6 +5,7 @@ import ( "fmt" "regexp" "strings" + "sync" "github.com/DomainCraft/DomainCraft/internal/specmeta" ) @@ -228,6 +229,29 @@ func splitModifiers(s string) []string { return specmeta.SplitRespectingQuotes(s) } +// lastRegex caches the result of the most recent regexp.Compile call. Studio +// re-parses the same field definition on every keystroke, and compiling even a +// short pattern allocates hundreds of bytes and dominates goParseField when a +// regex modifier is present. One entry is enough for that pattern and keeps +// the cache bounded regardless of user input. +var lastRegex = struct { + sync.Mutex + pattern string + re *regexp.Regexp + err error +}{} + +func compileRegex(pattern string) (*regexp.Regexp, error) { + lastRegex.Lock() + defer lastRegex.Unlock() + if lastRegex.pattern == pattern { + return lastRegex.re, lastRegex.err + } + re, err := regexp.Compile(pattern) + lastRegex.pattern, lastRegex.re, lastRegex.err = pattern, re, err + return re, err +} + // Validate checks the logical consistency of a FieldDefinition func (fd *FieldDefinition) Validate() error { // Cannot be both primary and optional @@ -257,7 +281,7 @@ func (fd *FieldDefinition) Validate() error { // Validate regex if present if regex, ok := fd.Validations["regex"]; ok { - if _, err := regexp.Compile(regex); err != nil { + if _, err := compileRegex(regex); err != nil { return fmt.Errorf("invalid regex %q: %w", regex, err) } } diff --git a/internal/parser/models.go b/internal/parser/models.go index 1fd3cd1..2ade278 100644 --- a/internal/parser/models.go +++ b/internal/parser/models.go @@ -3,6 +3,7 @@ package parser import ( "bytes" "fmt" + "io" "strings" "github.com/DomainCraft/DomainCraft/internal/specmeta" @@ -407,8 +408,12 @@ func (e *RawEntity) UnmarshalYAML(value *yaml.Node) error { order := make([]string, 0, len(valNode.Content)/2) merged := make(map[string]bool) addField := func(name string, defNode *yaml.Node, fromMerge bool) error { + // A plain string scalar is already decoded in Node.Value. Going + // through Node.Decode allocates a fresh decoder per field. var def string - if err := defNode.Decode(&def); err != nil { + if defNode.Kind == yaml.ScalarNode && defNode.Tag == "!!str" { + def = defNode.Value + } else if err := defNode.Decode(&def); err != nil { return fmt.Errorf("field %q: %w", name, err) } if _, exists := fields[name]; exists { @@ -498,10 +503,21 @@ func (r *RawIndex) UnmarshalYAML(value *yaml.Node) error { type rawIndexAlias RawIndex -// ParseRawSchema reads YAML and converts it to RawSchema +// ParseRawSchema reads YAML bytes and converts them to RawSchema. func ParseRawSchema(data []byte) (*RawSchema, error) { + return parseRawSchema(bytes.NewReader(data)) +} + +// ParseRawSchemaString decodes YAML text without copying it into a []byte. +// WASM exports receive a Go string from JS; copying multi-hundred-kilobyte +// models on every keystroke showed up as a measurable share of total bytes. +func ParseRawSchemaString(data string) (*RawSchema, error) { + return parseRawSchema(strings.NewReader(data)) +} + +func parseRawSchema(reader io.Reader) (*RawSchema, error) { schema := &RawSchema{} - decoder := yaml.NewDecoder(bytes.NewReader(data)) + decoder := yaml.NewDecoder(reader) decoder.KnownFields(true) if err := decoder.Decode(schema); err != nil { return nil, err diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 241a30a..8af1dc8 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -12,6 +12,11 @@ import ( "github.com/DomainCraft/DomainCraft/pkg/textutil" ) +// sortedFeatureFieldNames is the deterministic injection order for feature +// fields. It depends only on the static spec, so compute it once instead of +// sorting the spec map for every entity. +var sortedFeatureFieldNames = slices.Sorted(maps.Keys(specmeta.FeatureFieldDefs)) + // Parser is the main parser for converting RawSchema to ParsedSchema type Parser struct { raw *RawSchema @@ -133,7 +138,6 @@ func (p *Parser) parseEntity(name string, raw RawEntity) (*ParsedEntity, error) Name: name, OldName: raw.OldName, NamePlural: textutil.Pluralize(name), - Features: make(map[string]bool), Fields: make(map[string]*ParsedField), FieldOrder: make([]string, 0), Indexes: make([]*ParsedIndex, 0), @@ -141,6 +145,7 @@ func (p *Parser) parseEntity(name string, raw RawEntity) (*ParsedEntity, error) // Parse features (behavior macros). Duplicates are rejected here: the // Features map cannot carry them, so a later check could never fire. + // Most entities declare no features, so allocate the map on first use. for _, feature := range raw.Features { feature = strings.TrimSpace(feature) if !specmeta.IsFeature(feature) { @@ -149,6 +154,9 @@ func (p *Parser) parseEntity(name string, raw RawEntity) (*ParsedEntity, error) if entity.Features[feature] { return nil, fmt.Errorf("duplicate feature: %s", feature) } + if entity.Features == nil { + entity.Features = make(map[string]bool, len(raw.Features)) + } entity.Features[feature] = true } @@ -250,9 +258,8 @@ func ParseField(name string, fieldDef string) (*ParsedField, error) { // addFeatureFields adds automatic fields based on entity features. // Uses specmeta.FeatureFieldDefs as the single source of truth. func (p *Parser) addFeatureFields(entity *ParsedEntity) { - // Iterate in sorted order for deterministic field generation. - names := slices.Sorted(maps.Keys(specmeta.FeatureFieldDefs)) - for _, fieldName := range names { + // sortedFeatureFieldNames is already in deterministic order. + for _, fieldName := range sortedFeatureFieldNames { def := specmeta.FeatureFieldDefs[fieldName] if !entity.Features[def.Feature] { continue @@ -291,7 +298,16 @@ func generateIndexName(entityName string, fields []string, idx int) string { // ParseYAML is a convenience function for full parsing from YAML bytes func ParseYAML(data []byte) (*ParsedSchema, error) { - raw, err := ParseRawSchema(data) + return parseYAML(ParseRawSchema(data)) +} + +// ParseYAMLString is the string counterpart of ParseYAML: it avoids copying +// the whole document into a []byte when the caller already holds a string. +func ParseYAMLString(data string) (*ParsedSchema, error) { + return parseYAML(ParseRawSchemaString(data)) +} + +func parseYAML(raw *RawSchema, err error) (*ParsedSchema, error) { if err != nil { return nil, fmt.Errorf("error parsing YAML: %w", err) } diff --git a/internal/renderer/memory.go b/internal/renderer/memory.go index 2eb8b6b..9d8bc9f 100644 --- a/internal/renderer/memory.go +++ b/internal/renderer/memory.go @@ -187,9 +187,11 @@ func (r *Renderer) RenderMemory(project *ir.Project, pkgs map[string]string) ([] customTargets[rel] = true } var buf strings.Builder + buf.Grow(int(compiled.sizeHint.Load())) if err := compiled.body.Execute(&buf, context); err != nil { return nil, fmt.Errorf("execute template %s: %w", spec.Source, err) } + compiled.sizeHint.Store(int64(buf.Len())) files[rel] = buf.String() } } diff --git a/internal/renderer/render.go b/internal/renderer/render.go index 52b9312..e2b09cf 100644 --- a/internal/renderer/render.go +++ b/internal/renderer/render.go @@ -8,6 +8,7 @@ import ( "path/filepath" "slices" "strings" + "sync/atomic" "text/template" "github.com/DomainCraft/DomainCraft/internal/fsutil" @@ -267,6 +268,10 @@ func (s *renderSession) fail(err error) error { type compiledSpec struct { body *template.Template targets []*template.Template + // sizeHint is the output length of the most recent render with this spec. + // Growing the destination builder once avoids repeated geometric growth on + // the hot path; it never affects the rendered bytes. + sizeHint atomic.Int64 } func (r *Renderer) compileSpec(src sourceConfig, spec TemplateSpec, funcMap template.FuncMap, helpers *template.Template) (*compiledSpec, error) { diff --git a/internal/validator/validator.go b/internal/validator/validator.go index ee7b3ed..03bb6df 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -278,24 +278,19 @@ func validateInfrastructureConfig(p parser.ProjectConfig) []ValidationError { func (v *Validator) validateCircularRelations() []ValidationError { var errs []ValidationError - // Build adjacency: entity -> list of target entities it references via an FK. - adj := make(map[string][]string) - for _, entityName := range v.schema.EntityOrder { - entity := v.schema.Entities[entityName] - if entity == nil { - continue - } - for _, fieldName := range entity.FieldOrder { - field := entity.Fields[fieldName] - if field == nil || !field.IsRelation() || field.TargetEntity == "" { - continue - } - // Skip many-to-many links (no FK on this side) and self-references. - if field.IsMany || field.TargetEntity == entityName { - continue - } - adj[entityName] = append(adj[entityName], field.TargetEntity) - } + order := v.schema.EntityOrder + n := len(order) + if n == 0 { + return nil + } + + // Walk the FK graph directly instead of materializing an adjacency map. + // EntityOrder is sorted, so index positions double as deterministic node + // ids; one name->index map plus flat slices replace the adjacency/color/ + // inCycle maps and one slice per outgoing edge. + index := make(map[string]int, n) + for i, name := range order { + index[name] = i } // Standard DFS cycle detection (white/gray/black). All nodes on a gray stack @@ -305,23 +300,41 @@ func (v *Validator) validateCircularRelations() []ValidationError { gray black ) - color := make(map[string]int) - inCycle := make(map[string]bool) - stack := make([]string, 0, len(v.schema.EntityOrder)) + color := make([]uint8, n) + inCycle := make([]bool, n) + stack := make([]int, 0, n) - var dfs func(node string) - dfs = func(node string) { + var dfs func(node int) + dfs = func(node int) { color[node] = gray stack = append(stack, node) - for _, target := range adj[node] { - switch color[target] { - case white: - dfs(target) - case gray: - // Back-edge found: target is gray, so it is on the stack. - // Mark everything from target up to the current node. - for _, n := range stack[slices.Index(stack, target):] { - inCycle[n] = true + name := order[node] + entity := v.schema.Entities[name] + if entity != nil { + for _, fieldName := range entity.FieldOrder { + field := entity.Fields[fieldName] + if field == nil || !field.IsRelation() || field.TargetEntity == "" { + continue + } + // Skip many-to-many links (no FK on this side) and self-references. + if field.IsMany || field.TargetEntity == name { + continue + } + target, ok := index[field.TargetEntity] + if !ok { + // A missing target is reported by validateRelationField; it + // cannot close a cycle because it has no outgoing edges here. + continue + } + switch color[target] { + case white: + dfs(target) + case gray: + // Back-edge found: target is gray, so it is on the stack. + // Mark everything from target up to the current node. + for _, i := range stack[slices.Index(stack, target):] { + inCycle[i] = true + } } } } @@ -329,15 +342,17 @@ func (v *Validator) validateCircularRelations() []ValidationError { color[node] = black } - for _, entityName := range v.schema.EntityOrder { - if color[entityName] == white { - dfs(entityName) + for i := range order { + if color[i] == white { + dfs(i) } } - for _, entityName := range slices.Sorted(maps.Keys(inCycle)) { - errs = append(errs, warn(entityName, "", - "entity is part of a circular relation chain (A → B → … → A); generated delete/seed ordering may be ambiguous")) + for i, entityName := range order { + if inCycle[i] { + errs = append(errs, warn(entityName, "", + "entity is part of a circular relation chain (A → B → … → A); generated delete/seed ordering may be ambiguous")) + } } return errs @@ -803,7 +818,7 @@ func validateFieldValidations(entityName, fieldName string, field *parser.Parsed isNumeric := specmeta.IsNumeric(ftype) isString := specmeta.IsStringType(ftype) - for _, mod := range slices.Sorted(maps.Keys(field.Validations)) { + for _, mod := range sortedMapKeys(field.Validations) { val := field.Validations[mod] if specmeta.IsStringOnlyValidationModifier(mod) && !isString { errs = append(errs, warnf(entityName, fieldName, @@ -1380,6 +1395,19 @@ func isValidJSON(s string) bool { // --- helpers --- +// sortedMapKeys returns a map's keys in deterministic order. It replaces +// slices.Sorted(maps.Keys(m)) in hot per-field loops: the iterator form grows +// its result through AppendSeq and allocates more than the single make+sort +// below. A nil or empty map returns an empty slice without allocating. +func sortedMapKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + slices.Sort(keys) + return keys +} + // countPrimaryKeys returns the number of primary key fields in the entity. func countPrimaryKeys(entity *parser.ParsedEntity) int { count := 0