module RailsAiAdmin::Fields::ScalarSchema
A deliberately scalar-only subset of the released Surface schema contract. Core constraints stay outside the extension in an intersection.
Constants
- SHARED_KEYS
- TYPE_KEYS
Public Class Methods
Source
# File lib/rails_ai_admin/fields/scalar_schema.rb, line 18 def self.compile(base, constraints) unless constraints.is_a?(Hash) && constraints.keys.all? { |key| key.is_a?(String) || key.is_a?(Symbol) } && constraints.stringify_keys.size == constraints.size raise ConfigurationError, "Field schema constraints must be a scalar keyword hash" end constraints = constraints.stringify_keys allowed_keys = SHARED_KEYS + TYPE_KEYS.fetch(base.fetch("type")) if (constraints.keys - allowed_keys).any? || constraints.key?("type") && constraints["type"] != base.fetch("type") raise ConfigurationError, "Field schema cannot change the core scalar type or use unsupported keywords" end if constraints["pattern"] && (!constraints["pattern"].is_a?(String) || constraints["pattern"].bytesize > 1000) raise ConfigurationError, "Field schema pattern must be bounded text" end %w[title description].each do |key| raise ConfigurationError, "Field schema text must be bounded" if constraints[key] && (!constraints[key].is_a?(String) || constraints[key].bytesize > 300) end if constraints.key?("const") && !scalar?(constraints["const"]) || constraints.key?("enum") && (!constraints["enum"].is_a?(Array) || !constraints["enum"].all? { |value| scalar?(value) }) raise ConfigurationError, "Field enum and const constraints must contain JSON scalars" end encoded = JSON.generate(constraints) raise ConfigurationError, "Field schema is too large" if encoded.bytesize > 8192 constraints = JSON.parse(encoded) schema = constraints.empty? ? base : base.merge("allOf" => [ constraints ]) validator = JSONSchemer.schema(schema, ref_resolver: ->(*) { raise ConfigurationError, "Field schema references are unsupported" }) raise ConfigurationError, "Invalid scalar field schema" unless validator.valid_schema? [ schema, validator ] rescue JSON::GeneratorError, JSON::ParserError, EncodingError, RegexpError, ArgumentError raise ConfigurationError, "Invalid scalar field schema", cause: nil end