2024-04-03 16:54:50 +00:00
|
|
|
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
|
|
|
|
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
|
|
|
_ "encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"github.com/xeipuuv/gojsonschema"
|
|
|
|
"strings"
|
2024-04-09 19:30:05 +00:00
|
|
|
"embed"
|
|
|
|
"net/http"
|
|
|
|
"log/slog"
|
2024-09-19 08:11:57 +00:00
|
|
|
"decl/internal/folio"
|
2024-04-03 16:54:50 +00:00
|
|
|
)
|
|
|
|
|
2024-09-19 08:11:57 +00:00
|
|
|
//go:embed schemas/config/*.schema.json
|
2024-05-06 00:48:54 +00:00
|
|
|
//go:embed schemas/*.schema.json
|
2024-04-09 19:30:05 +00:00
|
|
|
var schemaFiles embed.FS
|
|
|
|
|
2024-09-19 08:11:57 +00:00
|
|
|
var schemaFilesUri folio.URI = "file://resource/schemas/*.schema.json"
|
|
|
|
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
folio.DocumentRegistry.Schemas[schemaFilesUri] = schemaFiles
|
|
|
|
folio.DocumentRegistry.DefaultSchema = schemaFilesUri
|
|
|
|
}
|
|
|
|
|
2024-04-03 16:54:50 +00:00
|
|
|
type Schema struct {
|
|
|
|
schema gojsonschema.JSONLoader
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSchema(name string) *Schema {
|
2024-07-17 08:34:57 +00:00
|
|
|
path := fmt.Sprintf("file://schemas/%s.schema.json", name)
|
2024-04-03 16:54:50 +00:00
|
|
|
|
2024-04-09 19:30:05 +00:00
|
|
|
return &Schema{schema: gojsonschema.NewReferenceLoaderFileSystem(path, http.FS(schemaFiles))}
|
|
|
|
//return &Schema{schema: gojsonschema.NewReferenceLoader(path)}
|
2024-04-03 16:54:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Schema) Validate(source string) error {
|
|
|
|
// loader := gojsonschema.NewGoLoader(source)
|
|
|
|
loader := gojsonschema.NewStringLoader(source)
|
|
|
|
result, err := gojsonschema.Validate(s.schema, loader)
|
|
|
|
|
|
|
|
if err != nil {
|
2024-04-09 19:30:05 +00:00
|
|
|
slog.Info("schema error", "source", source, "schema", s.schema, "result", result, "err", err)
|
2024-04-03 16:54:50 +00:00
|
|
|
return err
|
|
|
|
}
|
2024-04-09 19:30:05 +00:00
|
|
|
slog.Info("schema", "source", source, "schema", s.schema, "result", result, "err", err)
|
2024-04-03 16:54:50 +00:00
|
|
|
|
|
|
|
if !result.Valid() {
|
|
|
|
schemaErrors := strings.Builder{}
|
|
|
|
for _, err := range result.Errors() {
|
|
|
|
schemaErrors.WriteString(err.String() + "\n")
|
|
|
|
}
|
2024-07-17 08:34:57 +00:00
|
|
|
schemaErrors.WriteString(source)
|
2024-04-03 16:54:50 +00:00
|
|
|
return errors.New(schemaErrors.String())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2024-04-09 19:30:05 +00:00
|
|
|
|
|
|
|
func (s *Schema) ValidateSchema() error {
|
|
|
|
sl := gojsonschema.NewSchemaLoader()
|
|
|
|
sl.Validate = true
|
|
|
|
schemaErr := sl.AddSchemas(s.schema)
|
|
|
|
slog.Info("validate schema definition", "schemaloader", sl, "err", schemaErr)
|
|
|
|
return schemaErr
|
|
|
|
}
|