A platform for community discussion. Free, open, simple.
DEV: Support versioned default sorts in JSON:API (#43735)
Loïc Guitaut1210ef439771
diff --git a/app/controllers/json_api_kit/base_controller/fetching.rb b/app/controllers/json_api_kit/base_controller/fetching.rbindex 214fc541742..48c7d1cf0af 100644--- a/app/controllers/json_api_kit/base_controller/fetching.rb+++ b/app/controllers/json_api_kit/base_controller/fetching.rb@@ -19,7 +19,7 @@ module JsonApiKitprivate- def client = Client.new(guardian:, glossary:, urls:)+ def client = Client.new(guardian:, edition:, urls:)def urlsUrls.new(diff --git a/app/controllers/json_api_kit/base_controller/versioning.rb b/app/controllers/json_api_kit/base_controller/versioning.rbindex 664ccd8996f..e87ba289ea0 100644--- a/app/controllers/json_api_kit/base_controller/versioning.rb+++ b/app/controllers/json_api_kit/base_controller/versioning.rb@@ -19,7 +19,9 @@ module JsonApiKitdef requested_version = request.headers[ApiVersion::HEADER]- def glossary = @glossary ||= Glossary.resource(version)+ def edition = @edition ||= Edition.for(version)++ def glossary = edition.glossaryendendenddiff --git a/lib/json_api_kit/client.rb b/lib/json_api_kit/client.rbindex 153003fc1df..b3755a80b5c 100644--- a/lib/json_api_kit/client.rb+++ b/lib/json_api_kit/client.rb@@ -1,5 +1,6 @@# frozen_string_literal: truemodule JsonApiKit- Client = Data.define(:guardian, :glossary, :urls)+ Client =+ Data.define(:guardian, :edition, :urls) { delegate :glossary, :default_sorts, to: :edition }enddiff --git a/lib/json_api_kit/declarations/relationship.rb b/lib/json_api_kit/declarations/relationship.rbindex 3481fbca0d5..cb98c00e6e4 100644--- a/lib/json_api_kit/declarations/relationship.rb+++ b/lib/json_api_kit/declarations/relationship.rb@@ -16,7 +16,9 @@ module JsonApiKitverify_readable_blockend- def listing(params, guardian:, scoped_to:) = resource.all(params, guardian:, scoped_to:)+ def listing(params, guardian:, scoped_to:, default_sorts:)+ resource.all(params, guardian:, scoped_to:, default_sorts:)+ enddef resolves?(path) = resource.resolves?(path)diff --git a/lib/json_api_kit/declarations/sorts.rb b/lib/json_api_kit/declarations/sorts.rbindex d6cf5c45471..31e979c6d0b 100644--- a/lib/json_api_kit/declarations/sorts.rb+++ b/lib/json_api_kit/declarations/sorts.rb@@ -5,18 +5,17 @@ module JsonApiKitclass Sortsdelegate :fetch, to: :sorts- def initialize(sorts, schema:, default: {}, unique_by: nil)+ def initialize(sorts, schema:, unique_by: nil)@sorts = sorts.index_by(&:name)@schema = schema- @default = default.to_h.transform_keys(&:to_s)@unique_by = Array(unique_by.presence || schema.primary_key)end- def keyset(ordering = {}) = Pagination::Keyset.new(keys(ordering.presence || default))+ def keyset(ordering) = Pagination::Keyset.new(keys(ordering))private- attr_reader :sorts, :schema, :default, :unique_by+ attr_reader :sorts, :schema, :unique_bydef keys(ordering)[diff --git a/lib/json_api_kit/default_sort.rb b/lib/json_api_kit/default_sort.rbnew file mode 100644index 00000000000..a19c2c2598f--- /dev/null+++ b/lib/json_api_kit/default_sort.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++module JsonApiKit+ class DefaultSort+ attr_reader :type, :ordering++ def initialize(type, ordering)+ @type = type.to_s+ @ordering = ordering.to_h.transform_keys(&:to_s).freeze+ @ordering.each_value { Pagination::Direction.for(it) }+ end++ def convert_names(&conversion)+ self.class.new(+ conversion.call(Name::Type.new(value: type)).value,+ converted_ordering(&conversion),+ )+ end++ private++ def converted_ordering+ ordering+ .group_by { |name, _direction| yield(Name::Sort.new(value: name, type:)) }+ .to_h { |name, entries| [name.value, direction_for(name, entries)] }+ end++ def direction_for(name, entries)+ entries.map(&:last).uniq.sole+ rescue Enumerable::SoleItemExpectedError+ raise ArgumentError, "The default sort for #{type} has conflicting directions for #{name}."+ end+ end+enddiff --git a/lib/json_api_kit/default_sorts.rb b/lib/json_api_kit/default_sorts.rbnew file mode 100644index 00000000000..f5bb33f90e7--- /dev/null+++ b/lib/json_api_kit/default_sorts.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++module JsonApiKit+ class DefaultSorts+ def initialize(changes)+ @changes = changes+ @orderings = {}+ end++ def for(resource) = orderings[resource] ||= ordering_for(resource)++ private++ attr_reader :changes, :orderings++ def ordering_for(resource)+ defaults+ .fetch(resource.type) { return resource.default_ordering }+ .then { resource.default_ordering(it.ordering) }+ end++ def defaults+ @defaults ||= changes.reduce({}) { |defaults, change| advance(defaults, through: change) }+ end++ def advance(defaults, through:)+ translated_defaults(defaults, through:).merge(+ through.current_default_sorts.index_by(&:type),+ ) { |_type, earlier_default, _later_default| earlier_default }+ end++ def translated_defaults(defaults, through:)+ defaults+ .values+ .map { |default| default.convert_names { through.current_names(it).sole } }+ .index_by(&:type)+ end+ end+enddiff --git a/lib/json_api_kit/document.rb b/lib/json_api_kit/document.rbindex e28c83feb05..45c16a142d7 100644--- a/lib/json_api_kit/document.rb+++ b/lib/json_api_kit/document.rb@@ -6,15 +6,9 @@ module JsonApiKitprivatedef build(raw, resource:, client:)- parameters =- Request::Parameters.new(- raw.to_hash.deep_stringify_keys,- resource:,- glossary: client.glossary,- )- contract = contract_class.for(parameters.to_h, resource:, glossary: client.glossary)- return Errors.new(*contract.refusals) if contract.invalid?- assemble(new(yield(contract.to_hash), client:, fieldsets: parameters.fieldsets))+ input = input_class.new(raw, resource:, edition: client.edition)+ return Errors.new(*input.refusals) if input.invalid?+ assemble(new(yield(input.to_h), client:, fieldsets: input.fieldsets))rescue Error => errorErrors.new(error)enddiff --git a/lib/json_api_kit/document/collection.rb b/lib/json_api_kit/document/collection.rbindex 7d1998c3c9d..3822b27089a 100644--- a/lib/json_api_kit/document/collection.rb+++ b/lib/json_api_kit/document/collection.rb@@ -4,11 +4,16 @@ module JsonApiKitclass Documentclass Collection < Documentclass << self- def contract_class = Request::Contract::Collection+ def input_class = Request::Input::Collectiondef for(parameters, resource:, client:, scoped_to: nil)build(parameters, resource:, client:) do- resource.all(it, guardian: client.guardian, scoped_to:)+ resource.all(+ it,+ guardian: client.guardian,+ scoped_to:,+ default_sorts: client.default_sorts,+ )endendenddiff --git a/lib/json_api_kit/document/individual.rb b/lib/json_api_kit/document/individual.rbindex b3a8df181a8..dcca09bc2f4 100644--- a/lib/json_api_kit/document/individual.rb+++ b/lib/json_api_kit/document/individual.rb@@ -4,10 +4,12 @@ module JsonApiKitclass Documentclass Individual < Documentclass << self- def contract_class = Request::Contract::Individual+ def input_class = Request::Input::Individualdef for(id, parameters, resource:, client:)- build(parameters, resource:, client:) { resource.find(id, it, guardian: client.guardian) }+ build(parameters, resource:, client:) do+ resource.find(id, it, guardian: client.guardian, default_sorts: client.default_sorts)+ endendenddiff --git a/lib/json_api_kit/edition.rb b/lib/json_api_kit/edition.rbnew file mode 100644index 00000000000..21161fc3d53--- /dev/null+++ b/lib/json_api_kit/edition.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++module JsonApiKit+ class Edition+ class << self+ def for(version) = new(VersionChanges.core.after(version))++ def current = new([])+ end++ def initialize(changes)+ @changes = changes.dup.freeze+ end++ def glossary+ @glossary ||= Glossary.new([Glossary::CasingRule, Glossary::VersionRule.new(changes)])+ end++ def default_sorts = @default_sorts ||= DefaultSorts.new(changes)++ private++ attr_reader :changes+ end+enddiff --git a/lib/json_api_kit/glossary.rb b/lib/json_api_kit/glossary.rbindex 32c739eb89a..59e01c75b61 100644--- a/lib/json_api_kit/glossary.rb+++ b/lib/json_api_kit/glossary.rb@@ -42,11 +42,7 @@ module JsonApiKitdef arguments = [names]end- class << self- def kit = new([CasingRule])-- def resource(version) = new([CasingRule, VersionRule.new(version)])- end+ def self.kit = new([CasingRule])def initialize(rules)@rules = rulesdiff --git a/lib/json_api_kit/glossary/version_rule.rb b/lib/json_api_kit/glossary/version_rule.rbindex b79bc53299a..aef1f7e6ba8 100644--- a/lib/json_api_kit/glossary/version_rule.rb+++ b/lib/json_api_kit/glossary/version_rule.rb@@ -3,8 +3,8 @@module JsonApiKitclass Glossaryclass VersionRule- def initialize(version)- @changes = VersionChanges.core.after(version)+ def initialize(changes)+ @changes = changesenddef declared_attributes(attributes)diff --git a/lib/json_api_kit/request.rb b/lib/json_api_kit/request.rbindex b95e04b3d0e..02d62d1d0e9 100644--- a/lib/json_api_kit/request.rb+++ b/lib/json_api_kit/request.rb@@ -5,15 +5,16 @@ module JsonApiKitLIST = ","SORT_DIRECTIONS = { "-" => :desc, "" => :asc }.freeze- attr_reader :guardian+ attr_reader :guardian, :default_sorts- def initialize(params = {}, guardian:)+ def initialize(params = {}, guardian:, default_sorts:)@params = ActiveSupport::HashWithIndifferentAccess.new(params)@page_params = @params[:page].to_h.symbolize_keys@guardian = guardian+ @default_sorts = default_sortsend- def ordering = @ordering ||= params[:sort].to_h+ def ordering = params.fetch(:sort)def filtering = @filtering ||= params[:filter].to_hdiff --git a/lib/json_api_kit/request/contract/paging.rb b/lib/json_api_kit/request/contract/paging.rbindex dd5cb0342b8..617a79d4a39 100644--- a/lib/json_api_kit/request/contract/paging.rb+++ b/lib/json_api_kit/request/contract/paging.rb@@ -85,7 +85,7 @@ module JsonApiKitdef raw_sort = options[:raw_parameters][:sort]- def ordering = raw_sort.nil? ? {} : INDIFFERENT_HASH.cast(raw_sort)+ def ordering = INDIFFERENT_HASH.cast(raw_sort)def sortable?return false unless orderingdiff --git a/lib/json_api_kit/request/family/sort.rb b/lib/json_api_kit/request/family/sort.rbindex 52cc008bf50..d720f24ecb8 100644--- a/lib/json_api_kit/request/family/sort.rb+++ b/lib/json_api_kit/request/family/sort.rb@@ -20,9 +20,7 @@ module JsonApiKitenddef declared_value(value, path)- Keys- .parse(value, path)- .try { it.declare { |key| declared_name(sort_name(key.name), key.path) } } || value+ Keys.parse(value, path).declare { |key| declared_name(sort_name(key.name), key.path) }endprivatediff --git a/lib/json_api_kit/request/family/sort/keys.rb b/lib/json_api_kit/request/family/sort/keys.rbindex 25a7e312606..3a70bbeed39 100644--- a/lib/json_api_kit/request/family/sort/keys.rb+++ b/lib/json_api_kit/request/family/sort/keys.rb@@ -6,6 +6,7 @@ module JsonApiKitclass Sortclass KeysKey = Data.define(:name, :direction, :path)+ Invalid = Data.define(:value) { def declare = value }class << selfdef parse(value, path)@@ -17,6 +18,8 @@ module JsonApiKit)when String, Symbolnew(value.to_s.split(LIST, -1).map { key(it, path) }, path)+ else+ Invalid.new(value)endend@@ -37,6 +40,7 @@ module JsonApiKitkeys.group_by { yield(it) }.to_h { |declared, same_name| [declared, shared_direction(same_name)] }+ .presenceendprivatediff --git a/lib/json_api_kit/request/input.rb b/lib/json_api_kit/request/input.rbnew file mode 100644index 00000000000..d74e1f0f0c4--- /dev/null+++ b/lib/json_api_kit/request/input.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true++module JsonApiKit+ class Request+ class Input+ def self.with_defaults(parameters, resource:, default_sorts:)+ parameters.to_h.stringify_keys.then do |params|+ return params unless params["sort"].nil?+ params.merge("sort" => default_sorts.for(resource))+ end+ end++ def initialize(raw, resource:, edition:)+ @resource = resource+ @edition = edition+ @parameters = Parameters.new(raw.to_hash.deep_stringify_keys, resource:, glossary:)+ end++ delegate :invalid?, :refusals, to: :contract+ delegate :fieldsets, to: :parameters++ def to_h = contract.to_hash++ private++ attr_reader :resource, :edition, :parameters++ delegate :glossary, :default_sorts, to: :edition, private: true++ def contract = @contract ||= contract_class.for(contract_parameters, resource:, glossary:)++ def contract_parameters = parameters.to_h+ end+ end+enddiff --git a/lib/json_api_kit/request/input/collection.rb b/lib/json_api_kit/request/input/collection.rbnew file mode 100644index 00000000000..9348656c1a5--- /dev/null+++ b/lib/json_api_kit/request/input/collection.rb@@ -0,0 +1,17 @@+# frozen_string_literal: true++module JsonApiKit+ class Request+ class Input+ class Collection < Input+ private++ def contract_class = Contract::Collection++ def contract_parameters+ self.class.with_defaults(super, resource:, default_sorts:)+ end+ end+ end+ end+enddiff --git a/lib/json_api_kit/request/input/individual.rb b/lib/json_api_kit/request/input/individual.rbnew file mode 100644index 00000000000..32188265859--- /dev/null+++ b/lib/json_api_kit/request/input/individual.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++module JsonApiKit+ class Request+ class Input+ class Individual < Input+ private++ def contract_class = Contract::Individual+ end+ end+ end+enddiff --git a/lib/json_api_kit/resource/anchoring.rb b/lib/json_api_kit/resource/anchoring.rbindex 66d1b4bc129..0af61567190 100644--- a/lib/json_api_kit/resource/anchoring.rb+++ b/lib/json_api_kit/resource/anchoring.rb@@ -24,7 +24,7 @@ module JsonApiKitdeclared_anchor(anchoring.name).try { it.accepts?(anchoring) } || falseend- def anchored_by?(anchor_name:, ordering: {})+ def anchored_by?(anchor_name:, ordering:)declared_anchor(anchor_name).then { it.nil? || it.locatable_in?(order(ordering)) }enddiff --git a/lib/json_api_kit/resource/paging.rb b/lib/json_api_kit/resource/paging.rbindex f35dd1b049b..b07de6e8f83 100644--- a/lib/json_api_kit/resource/paging.rb+++ b/lib/json_api_kit/resource/paging.rb@@ -25,7 +25,7 @@ module JsonApiKitdef max_page_size = page_limits.max- def paged_from?(cursor, ordering: {}) = order(ordering).compatible_with?(cursor:)+ def paged_from?(cursor, ordering:) = order(ordering).compatible_with?(cursor:)endendenddiff --git a/lib/json_api_kit/resource/query_interface.rb b/lib/json_api_kit/resource/query_interface.rbindex 4bd313707f9..92f74e81f45 100644--- a/lib/json_api_kit/resource/query_interface.rb+++ b/lib/json_api_kit/resource/query_interface.rb@@ -11,6 +11,8 @@ module JsonApiKitendclass_methods do+ delegate :default_sorts, to: "JsonApiKit::Edition.current", prefix: :current, private: true+def scope(&block)self.declared_scope = blockend@@ -20,12 +22,27 @@ module JsonApiKitdeclared_scope.call(guardian)end- def all(params = {}, guardian:, scoped_to: nil)- Query::Collection.new(self, Request::Collection.new(params, guardian:), scoped_to:)+ def all(params = {}, guardian:, scoped_to: nil, default_sorts: current_default_sorts)+ Query::Collection.new(+ self,+ Request::Collection.new(+ Request::Input.with_defaults(params, resource: self, default_sorts:),+ guardian:,+ default_sorts:,+ ),+ scoped_to:,+ )end- def find(id, params = {}, guardian:)- Query::Individual.new(self, Request::Individual.new(params.merge(id:), guardian:))+ def find(id, params = {}, guardian:, default_sorts: current_default_sorts)+ Query::Individual.new(+ self,+ Request::Individual.new(+ Request::Input.with_defaults(params, resource: self, default_sorts:).merge(id:),+ guardian:,+ default_sorts:,+ ),+ )endendenddiff --git a/lib/json_api_kit/resource/sorting.rb b/lib/json_api_kit/resource/sorting.rbindex 1cce7d776ee..64e85dc531e 100644--- a/lib/json_api_kit/resource/sorting.rb+++ b/lib/json_api_kit/resource/sorting.rb@@ -31,8 +31,13 @@ module JsonApiKitenddef default_sort(ordering)+ self.declared_default_sort = default_ordering(ordering)+ end++ def default_ordering(ordering = declared_default_sort)verify_sorts(ordering.keys)- self.declared_default_sort = ordering+ ordering.each_value { Pagination::Direction.for(it) }+ ordering.transform_keys(&:to_s).freezeenddef unique_by(*columns)@@ -41,19 +46,14 @@ module JsonApiKitdef sort_names = declared_sorts.map(&:name)- def order(ordering = {}) = Pagination::Order.new(sorts.keyset(ordering), type:)+ def order(ordering) = Pagination::Order.new(sorts.keyset(ordering), type:)def sortable_by?(ordering:) = (ordering.keys - sort_names).empty?privatedef sorts- Declarations::Sorts.new(- declared_sorts,- schema:,- default: declared_default_sort,- unique_by: declared_unique_by,- )+ Declarations::Sorts.new(declared_sorts, schema:, unique_by: declared_unique_by)enddef verify_sorts(names)diff --git a/lib/json_api_kit/sideload.rb b/lib/json_api_kit/sideload.rbindex 42a126ad983..1584cbb3406 100644--- a/lib/json_api_kit/sideload.rb+++ b/lib/json_api_kit/sideload.rb@@ -25,6 +25,7 @@ module JsonApiKitrelationship.listing(request.for_sideload(paths),guardian: request.guardian,+ default_sorts: request.default_sorts,scoped_to: relationship.scoping(association),)enddiff --git a/lib/json_api_kit/version_change.rb b/lib/json_api_kit/version_change.rbindex af8d9afc62d..724b1df2e24 100644--- a/lib/json_api_kit/version_change.rb+++ b/lib/json_api_kit/version_change.rb@@ -16,7 +16,13 @@ module JsonApiKitenddef resource(type, &declarations)- transformations.concat(Declarations.new(type).tap { it.instance_eval(&declarations) }.to_a)+ Declarations+ .new(type)+ .tap { it.instance_eval(&declarations) }+ .then do+ transformations.concat(it.transformations)+ default_sorts.concat(it.default_sorts)+ endenddef transformations = @transformations ||= []@@ -29,6 +35,8 @@ module JsonApiKitenddef type_renames = @type_renames ||= []++ def default_sorts = @default_sorts ||= []enddelegate :version, :description, to: :class@@ -39,6 +47,7 @@ module JsonApiKit@source = source@transformations = Transformations.new(self.class.transformations)@type_renames = TypeRenames.new(self.class.type_renames)+ @default_sorts = DefaultSorts.new(self.class.default_sorts)enddef verify!@@ -48,11 +57,10 @@ module JsonApiKitraise ArgumentError, "#{source} is dated on or before the first release."endraise ArgumentError, "#{source} has no description." if description.blank?- transformations.verify!- type_renames.verify!+ [transformations, type_renames, default_sorts].each(&:verify!)return if File.basename(source).start_with?(version.to_s)raise ArgumentError, "The file name must start with the version #{version}: #{source}."- rescue NameChanges::Conflict => conflict+ rescue NameChanges::Conflict, DefaultSorts::Conflict => conflictraise ArgumentError, "#{source} #{conflict.message}"end@@ -70,9 +78,13 @@ module JsonApiKittransformations.previous_values(attributes).transform_keys { previous_type(it) }end+ def current_default_sorts+ default_sorts.convert_names { transformations.current_names(it).sole }+ end+private- attr_reader :transformations, :type_renames+ attr_reader :transformations, :type_renames, :default_sortsdef current_type(name) = name.convert_type { type_renames.current(it) }diff --git a/lib/json_api_kit/version_change/declarations.rb b/lib/json_api_kit/version_change/declarations.rbindex dd2db96e394..5a51d99f4ad 100644--- a/lib/json_api_kit/version_change/declarations.rb+++ b/lib/json_api_kit/version_change/declarations.rb@@ -6,8 +6,13 @@ module JsonApiKitdef initialize(type)@type = type@transformations = []+ @default_sorts = []end+ attr_reader :transformations, :default_sorts++ def changed_default_sort(from:) = default_sorts << DefaultSort.new(type, from)+def renamed_attribute(**) = declare(Declaration::RenamedAttribute.new(type, **))def merged_attributes(**) = declare(Declaration::MergedAttributes.new(type, **))@@ -26,11 +31,9 @@ module JsonApiKitdeclare(Declaration::RenamedName.new(type, [Name::Relationship, Name::Field], from:, to:))end- def to_a = transformations-private- attr_reader :type, :transformations+ attr_reader :typedef declare(declaration) = transformations.concat(declaration.transformations)enddiff --git a/lib/json_api_kit/version_change/default_sorts.rb b/lib/json_api_kit/version_change/default_sorts.rbnew file mode 100644index 00000000000..503ab226172--- /dev/null+++ b/lib/json_api_kit/version_change/default_sorts.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++module JsonApiKit+ class VersionChange+ class DefaultSorts+ Conflict = Class.new(StandardError)++ def initialize(defaults)+ @defaults = defaults.dup+ end++ def verify!+ defaults+ .map(&:type)+ .tally+ .detect { |_type, count| count > 1 }+ .try { |type, _count| raise Conflict, "changes the default sort for #{type} twice." }+ end++ def convert_names(&) = defaults.map { it.convert_names(&) }++ private++ attr_reader :defaults+ end+ end+enddiff --git a/spec/integration/json_api_kit/default_sorts_spec.rb b/spec/integration/json_api_kit/default_sorts_spec.rbnew file mode 100644index 00000000000..5736252f4f1--- /dev/null+++ b/spec/integration/json_api_kit/default_sorts_spec.rb@@ -0,0 +1,298 @@+# frozen_string_literal: true++require_relative "support"++module JsonApiKitSpec+ class DefaultSortPostResource < JsonApiKit::Resource+ model Post+ type :posts++ attribute :post_number+ sort :post_number+ default_sort post_number: :asc+ end++ class DefaultSortTopicResource < JsonApiKit::Resource+ model Topic+ type :topics++ attribute :title+ attribute :created_at+ sort :created_at+ sort :title+ default_sort title: :asc+ anchor :created_at+ anchor :title+ page default: 10, max: 20++ has_many :posts, resource: DefaultSortPostResource+ includes "posts"+ end++ class DefaultSortTopicsController < JsonApiKit::BaseController+ resource DefaultSortTopicResource+ end++ class ChangeTopicDefaultSort < JsonApiKit::VersionChange+ version "2026-09-01"+ description "Topics use their title as the default sort."++ resource :topics do+ changed_default_sort from: { created_at: :desc }+ end++ resource :posts do+ changed_default_sort from: { post_number: :desc }+ end+ end+end++RSpec.describe "JSON:API default sorts", type: :request do+ include_context "with a listing of topics"++ let(:version) { JsonApiKit::Timeline::FIRST_RELEASE.to_s }+ let(:changes) { [JsonApiKitSpec::ChangeTopicDefaultSort.new(__FILE__)] }+ let(:version_changes) { JsonApiKit::VersionChanges.new(changes) }+ let(:path) { "/api/default-sort-topics" }+ let(:body) { JSON.parse(response.body) }+ let(:ids) { body.fetch("data").map { it.fetch("id") } }+ let(:error) { body.fetch("errors").sole }+ let(:cursor) do+ JsonApiKitSpec::DefaultSortTopicResource+ .order("created_at" => :desc)+ .locate(Topic.where(id: newest.id))+ .cursor+ .to_s+ end++ before do+ freeze_time(Date.new(2026, 9, 5))+ allow(JsonApiKit::VersionChanges).to receive(:core).and_return(version_changes)+ Rails.application.routes.disable_clear_and_finalize = true+ Rails.application.routes.draw do+ get "/api/default-sort-topics" => "json_api_kit_spec/default_sort_topics#index"+ get "/api/default-sort-topics/:id" => "json_api_kit_spec/default_sort_topics#show"+ end+ Rails.application.routes.disable_clear_and_finalize = false+ end++ after { Rails.application.reload_routes! }++ describe "a client edition" do+ subject(:document) do+ JsonApiKit::Document::Collection.for(+ {},+ resource: JsonApiKitSpec::DefaultSortTopicResource,+ client:,+ )+ end++ let(:client) do+ JsonApiKit::Client.new(+ guardian:,+ edition: JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE),+ urls:,+ )+ end+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ version "2026-09-01"+ description "Topics change their title name and default sort."++ resource :topics do+ renamed_attribute from: :legacy_heading, to: :title+ changed_default_sort from: { created_at: :desc }+ end+ end+ .new(__FILE__),+ ]+ end+ let(:headings) do+ document.to_h.fetch(:data).map { it.fetch(:attributes).fetch("legacyHeading") }+ end++ it "uses the edition's vocabulary and default ordering" do+ expect(headings).to eq([newest.title, middle.title, oldest.title])+ end+ end++ describe "GET collection" do+ before { get path, headers: { "HTTP_API_VERSION" => version }, params: query }++ it "uses the historical default" do+ expect(ids).to eq([newest.id, middle.id, oldest.id].map(&:to_s))+ end++ context "when the pin includes the default change" do+ let(:version) { "2026-09-01" }++ it "uses the current default" do+ expect(ids).to eq([oldest.id, newest.id, middle.id].map(&:to_s))+ end+ end++ context "when the client supplies an explicit sort" do+ let(:query) { { "sort" => "title" } }++ it "uses the client's ordering" do+ expect(ids).to eq([oldest.id, newest.id, middle.id].map(&:to_s))+ end+ end++ context "when the client supplies an invalid sort" do+ let(:query) { { "sort" => "unknown" } }++ it "refuses the sort" do+ expect(error).to include("status" => "400", "title" => "No such sort")+ end+ end++ context "when the client follows a page link without a sort" do+ let(:query) { { "page" => { "size" => "1" } } }++ before { get body.fetch("links").fetch("next"), headers: { "HTTP_API_VERSION" => version } }++ it "continues the historical ordering" do+ expect(JSON.parse(response.body).fetch("data").map { it.fetch("id") }).to eq(+ [middle.id.to_s],+ )+ end+ end++ context "when a cursor matches the historical default" do+ let(:query) { { "page" => { "after" => cursor } } }++ it "accepts the cursor" do+ expect(ids).to eq([middle.id, oldest.id].map(&:to_s))+ end+ end++ context "when an anchor matches the historical default" do+ let(:query) do+ { "page" => { "anchor" => { "createdAt" => middle.created_at.iso8601 }, "size" => "2" } }+ end++ it "enters the historical ordering at the anchor" do+ expect(ids).to eq([middle.id, oldest.id].map(&:to_s))+ end+ end++ context "when an anchor matches only the current default" do+ let(:query) { { "page" => { "anchor" => { "title" => middle.title }, "size" => "2" } } }++ it "refuses the incompatible anchor" do+ expect(error).to include("status" => "400", "title" => "Anchor does not match the sort")+ end+ end++ context "when the new pin receives a cursor for the old default" do+ let(:version) { "2026-09-01" }+ let(:query) { { "page" => { "after" => cursor } } }++ it "refuses the incompatible cursor" do+ expect(error).to include("status" => "400", "title" => "Invalid cursor")+ end+ end++ context "when the client provides an empty sort string" do+ let(:query) { { "sort" => "" } }++ it "uses the historical default" do+ expect(ids).to eq([newest.id, middle.id, oldest.id].map(&:to_s))+ end+ end++ context "when the default has an old sort and resource name" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ version "2026-09-01"+ description "Discussions change their default sort."+ resource(:discussions) { changed_default_sort from: { posted_at: :desc } }+ end+ .new(__FILE__),+ Class+ .new(JsonApiKit::VersionChange) do+ version "2026-09-02"+ description "Discussions become topics with a renamed creation sort."+ renamed_type from: :discussions, to: :topics+ resource(:topics) { renamed_sort from: :posted_at, to: :created_at }+ end+ .new(__FILE__),+ ]+ end++ it "uses the translated historical ordering" do+ expect(ids).to eq([newest.id, middle.id, oldest.id].map(&:to_s))+ end++ it "retains the historical response type" do+ expect(body.fetch("data").map { it.fetch("type") }).to all(eq("discussions"))+ end+ end++ context "when the historical default has no named sort" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ version "2026-09-01"+ description "Topics acquire a default title sort."+ resource(:topics) { changed_default_sort from: {} }+ end+ .new(__FILE__),+ ]+ end++ it "uses only the uniqueness ordering" do+ expect(ids).to eq([oldest.id, middle.id, newest.id].map(&:to_s))+ end+ end+ end++ describe "GET related resources" do+ fab!(:first_post) { Fabricate(:post, topic: newest, post_number: 1) }+ fab!(:second_post) { Fabricate(:post, topic: newest, post_number: 2) }++ let(:path) { "/api/default-sort-topics/#{newest.id}" }+ let(:query) { { "include" => "posts" } }+ let(:post_ids) do+ body.fetch("data").fetch("relationships").fetch("posts").fetch("data").map { it.fetch("id") }+ end++ before { get path, headers: { "HTTP_API_VERSION" => version }, params: query }++ it "uses the related resource's historical default" do+ expect(post_ids).to eq([second_post.id, first_post.id].map(&:to_s))+ end++ context "when the pin includes the default change" do+ let(:version) { "2026-09-01" }++ it "uses the related resource's current default" do+ expect(post_ids).to eq([first_post.id, second_post.id].map(&:to_s))+ end+ end++ context "when the primary collection has an explicit sort" do+ let(:path) { "/api/default-sort-topics" }+ let(:query) { super().merge("sort" => "title") }+ let(:post_ids) do+ body+ .fetch("data")+ .detect { it["id"] == newest.id.to_s }+ .fetch("relationships")+ .fetch("posts")+ .fetch("data")+ .map { it.fetch("id") }+ end++ it "uses the related resource's own default" do+ expect(post_ids).to eq([second_post.id, first_post.id].map(&:to_s))+ end+ end+ end+enddiff --git a/spec/integration/json_api_kit/errors_spec.rb b/spec/integration/json_api_kit/errors_spec.rbindex 12b8dea0816..7b3007059da 100644--- a/spec/integration/json_api_kit/errors_spec.rb+++ b/spec/integration/json_api_kit/errors_spec.rb@@ -24,6 +24,38 @@ RSpec.describe "a refused request" doendend+ context "when the sort is an empty array" do+ let(:params) { { sort: [] } }++ it "refuses the sort" do+ expect(document).to eq(+ errors: [+ refusal(+ title: "Invalid sort parameter",+ detail: "sort must be a comma-separated list, as in sort=-createdAt.",+ parameter: "sort",+ ),+ ],+ )+ end+ end++ context "when the sort is false" do+ let(:params) { { sort: false } }++ it "refuses the sort" do+ expect(document).to eq(+ errors: [+ refusal(+ title: "Invalid sort parameter",+ detail: "sort must be a comma-separated list, as in sort=-createdAt.",+ parameter: "sort",+ ),+ ],+ )+ end+ end+context "when the sort is a string the resource does not declare" dolet(:params) { { sort: "secrets" } }diff --git a/spec/integration/json_api_kit/support.rb b/spec/integration/json_api_kit/support.rbindex 60ce2869280..3331381d5a9 100644--- a/spec/integration/json_api_kit/support.rb+++ b/spec/integration/json_api_kit/support.rb@@ -98,9 +98,9 @@ RSpec.shared_context "with a listing of topics" dolet(:current) { "https://example.com/api/topics" }let(:query) { {} }let(:scoped_to) { nil }- let(:glossary) { JsonApiKit::Glossary.kit }+ let(:edition) { JsonApiKit::Edition.current }let(:urls) { JsonApiKit::Urls.new(base:, current:, parameters: query) }- let(:client) { JsonApiKit::Client.new(guardian:, glossary:, urls:) }+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }let(:document) doJsonApiKit::Document::Collection.for(params, resource:, client:, scoped_to:).to_hend@@ -114,7 +114,7 @@ RSpec.shared_context "with a listing of topics" doparameters,resource:,client:- JsonApiKit::Client.new(guardian:, glossary:, urls: JsonApiKit::Urls.new(base:, current:)),+ JsonApiKit::Client.new(guardian:, edition:, urls: JsonApiKit::Urls.new(base:, current:)),scoped_to:,).to_hend@@ -205,7 +205,7 @@ RSpec.shared_context "with a listing of topics" dodef parameters_of(url) = Rack::Utils.parse_nested_query(URI.parse(url).query)- def cursor_of_record(record, of: resource, sort: {})+ def cursor_of_record(record, of: resource, sort: of.default_ordering)order = of.order(sort.transform_keys(&:to_s))order.locate(of.model.where(id: record.id)).cursor.to_senddiff --git a/spec/lib/json_api_kit/declarations/relationship_spec.rb b/spec/lib/json_api_kit/declarations/relationship_spec.rbindex f04857b2637..9b1e25769f3 100644--- a/spec/lib/json_api_kit/declarations/relationship_spec.rb+++ b/spec/lib/json_api_kit/declarations/relationship_spec.rb@@ -40,19 +40,27 @@ RSpec.describe JsonApiKit::Declarations::Relationship dolet(:requested) { JsonApiKit::Page::Requested.for }describe "#listing" do- subject(:related_listing) { relationship.listing(params, guardian:, scoped_to:) }+ subject(:related_listing) do+ relationship.listing(params, guardian:, scoped_to:, default_sorts:)+ endlet(:params) { { fields: { "users" => %w[username] } } }let(:guardian) { Guardian.new(author) }let(:scoped_to) { JsonApiKit::Scoping.for(User.where(id: author.id)) }let(:listing) { instance_double(JsonApiKit::Query::Collection) }+ let(:default_sorts) { JsonApiKit::Edition.current.default_sorts }before { allow(users_resource).to receive(:all).and_return(listing) }it "asks the resource on the other side for a listing" dorelated_listing- expect(users_resource).to have_received(:all).with(params, guardian:, scoped_to:)+ expect(users_resource).to have_received(:all).with(+ params,+ guardian:,+ scoped_to:,+ default_sorts:,+ )endit "returns the listing that resource reads" do@@ -125,7 +133,7 @@ RSpec.describe JsonApiKit::Declarations::Relationship dodescribe "#linkage" dosubject(:linkage) { relationship.linkage(records) }- let(:order) { posts_resource.order }+ let(:order) { posts_resource.order({}) }let(:records) doJsonApiKit::Records.new([first_post, second_post, third_post].map dodiff --git a/spec/lib/json_api_kit/declarations/sorts_spec.rb b/spec/lib/json_api_kit/declarations/sorts_spec.rbindex cdea86eb497..77dd0017c56 100644--- a/spec/lib/json_api_kit/declarations/sorts_spec.rb+++ b/spec/lib/json_api_kit/declarations/sorts_spec.rb@@ -1,14 +1,13 @@# frozen_string_literal: trueRSpec.describe JsonApiKit::Declarations::Sorts do- subject(:sorts) { described_class.new(declarations, schema:, default: default_sort, unique_by:) }+ subject(:sorts) { described_class.new(declarations, schema:, unique_by:) }let(:schema) { JsonApiKit::Schema.new(Topic) }let(:sort_class) { JsonApiKit::Declarations::Sort }let(:declarations) do[sort_class.new(:created_at), sort_class.new(:ran_at, column: :last_posted_at)]end- let(:default_sort) { {} }let(:unique_by) { [] }describe "#fetch" do@@ -64,16 +63,7 @@ RSpec.describe JsonApiKit::Declarations::Sorts doendend- context "when only the default sort exists" do- let(:ordering) { {} }- let(:default_sort) { { ran_at: :desc } }-- it "orders by the sort the resource declares" do- expect(keyset.keys.map(&:name)).to eq(%i[last_posted_at id])- end- end-- context "when neither the ordering nor the default sort exists" do+ context "when the ordering is empty" dolet(:ordering) { {} }it "orders by the key that makes each row unique, upwards" dodiff --git a/spec/lib/json_api_kit/default_sort_spec.rb b/spec/lib/json_api_kit/default_sort_spec.rbnew file mode 100644index 00000000000..26dd682af09--- /dev/null+++ b/spec/lib/json_api_kit/default_sort_spec.rb@@ -0,0 +1,52 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::DefaultSort do+ subject(:default_sort) { described_class.new("topics", ordering) }++ let(:ordering) { { created_at: :desc, title: :asc } }++ describe ".new" do+ context "when a direction is invalid" do+ let(:ordering) { { created_at: :sideways } }++ it "rejects the direction" do+ expect { default_sort }.to raise_error(ArgumentError, /unknown direction: sideways/)+ end+ end+ end++ describe "#ordering" do+ it "normalizes sort names" do+ expect(default_sort.ordering).to eq("created_at" => :desc, "title" => :asc)+ end+ end++ describe "#convert_names" do+ subject(:converted) { default_sort.convert_names { it.convert { |value| "new_#{value}" } } }++ it "translates the resource type" do+ expect(converted.type).to eq("new_topics")+ end++ it "preserves the ordering of translated sort names" do+ expect(converted.ordering.to_a).to eq([["new_created_at", :desc], ["new_title", :asc]])+ end++ context "when two names become one with conflicting directions" do+ subject(:converted) do+ default_sort.convert_names do |name|+ case name+ when JsonApiKit::Name::Sort+ name.with(value: "combined")+ else+ name+ end+ end+ end++ it "rejects the conflicting default" do+ expect { converted }.to raise_error(ArgumentError, /conflicting directions/)+ end+ end+ end+enddiff --git a/spec/lib/json_api_kit/default_sorts_spec.rb b/spec/lib/json_api_kit/default_sorts_spec.rbnew file mode 100644index 00000000000..4fad27de5ed--- /dev/null+++ b/spec/lib/json_api_kit/default_sorts_spec.rb@@ -0,0 +1,209 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::DefaultSorts do+ subject(:defaults) { described_class.new(changes) }++ let(:resource) do+ Class.new(JsonApiKit::Resource) do+ model Topic+ type :topics+ sort :created_at+ sort :title+ default_sort title: :asc+ end+ end+ let(:changes) { [] }++ describe "#for" do+ subject(:ordering) { defaults.for(resource) }++ it "returns the current default without version changes" do+ expect(ordering).to eq("title" => :asc)+ end++ context "when the default changed after the pin" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:topics) { changed_default_sort from: { created_at: :desc } }+ end+ .new(__FILE__),+ ]+ end++ it "returns the historical default" do+ expect(ordering).to eq("created_at" => :desc)+ end+ end++ context "when the default changed several times" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:topics) { changed_default_sort from: { created_at: :asc } }+ end+ .new(__FILE__),+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:topics) { changed_default_sort from: { created_at: :desc } }+ end+ .new(__FILE__),+ ]+ end++ it "uses the earliest default after the pin" do+ expect(ordering).to eq("created_at" => :asc)+ end+ end++ context "when the historical default is empty" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) { resource(:topics) { changed_default_sort from: {} } }+ .new(__FILE__),+ ]+ end++ it "preserves the empty ordering" do+ expect(ordering).to be_empty+ end+ end++ context "when the same change renames a sort and its resource type" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ renamed_type from: :discussions, to: :topics+ resource :topics do+ renamed_sort from: :posted_at, to: :created_at+ changed_default_sort from: { posted_at: :desc }+ end+ end+ .new(__FILE__),+ ]+ end++ it "uses the current sort name" do+ expect(ordering).to eq("created_at" => :desc)+ end+ end++ context "when sorts and types change before and after the default declaration" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:discussions) { renamed_sort from: :posted_at, to: :published_at }+ end+ .new(__FILE__),+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:discussions) { changed_default_sort from: { published_at: :desc } }+ end+ .new(__FILE__),+ Class+ .new(JsonApiKit::VersionChange) do+ renamed_type from: :discussions, to: :topics+ resource(:topics) { renamed_sort from: :published_at, to: :created_at }+ end+ .new(__FILE__),+ ]+ end++ it "translates from the declaration's version" do+ expect(ordering).to eq("created_at" => :desc)+ end+ end++ context "when an earlier rename reuses the historical default's spelling" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ renamed_sort from: :created_at, to: :title+ renamed_sort from: :posted_at, to: :created_at+ end+ end+ .new(__FILE__),+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:topics) { changed_default_sort from: { created_at: :desc } }+ end+ .new(__FILE__),+ ]+ end++ it "does not apply changes preceding the default declaration" do+ expect(ordering).to eq("created_at" => :desc)+ end+ end++ context "when a later change merges two default sort names" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:topics) do+ changed_default_sort from: { posted_date: :desc, posted_time: :desc }+ end+ end+ .new(__FILE__),+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ merged_attributes from: %i[posted_date posted_time],+ to: :created_at,+ up: ->(date, time) { "#{date} #{time}" },+ down: ->(time) { time.split(" ") }+ end+ end+ .new(__FILE__),+ ]+ end++ it "uses the merged sort once" do+ expect(ordering).to eq("created_at" => :desc)+ end+ end++ context "when the historical sort is undeclared" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:topics) { changed_default_sort from: { unknown: :asc } }+ end+ .new(__FILE__),+ ]+ end++ it "raises a declaration error" do+ expect { ordering }.to raise_error(+ JsonApiKit::Resource::Sorting::UndeclaredDefault,+ /unknown/,+ )+ end+ end++ context "when the change belongs to another resource" do+ let(:changes) do+ [+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:users) { changed_default_sort from: { username: :desc } }+ end+ .new(__FILE__),+ ]+ end++ it "uses the resource's current default" do+ expect(ordering).to eq("title" => :asc)+ end+ end+ end+enddiff --git a/spec/lib/json_api_kit/document/collection_spec.rb b/spec/lib/json_api_kit/document/collection_spec.rbindex 5422a0183f7..0890c056cb8 100644--- a/spec/lib/json_api_kit/document/collection_spec.rb+++ b/spec/lib/json_api_kit/document/collection_spec.rb@@ -9,8 +9,8 @@ RSpec.describe JsonApiKit::Document::Collection dofab!(:second_topic) doFabricate(:topic, title: "Cursors and their values", created_at: Time.utc(2026, 8, 2))end- let(:glossary) { JsonApiKit::Glossary.kit }- let(:client) { JsonApiKit::Client.new(guardian:, glossary:, urls:) }+ let(:edition) { JsonApiKit::Edition.current }+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }let(:fieldsets) { JsonApiKit::Request::Fieldsets.parse({}) }let(:resource) doClass.new(JsonApiKit::Resource) dodiff --git a/spec/lib/json_api_kit/document/individual_spec.rb b/spec/lib/json_api_kit/document/individual_spec.rbindex 1c40f61312e..f4fde73c7c7 100644--- a/spec/lib/json_api_kit/document/individual_spec.rb+++ b/spec/lib/json_api_kit/document/individual_spec.rb@@ -4,8 +4,8 @@ RSpec.describe JsonApiKit::Document::Individual dosubject(:document) { described_class.new(reading, client:, fieldsets:) }fab!(:topic) { Fabricate(:topic, title: "One record read on its own") }- let(:glossary) { JsonApiKit::Glossary.kit }- let(:client) { JsonApiKit::Client.new(guardian:, glossary:, urls:) }+ let(:edition) { JsonApiKit::Edition.current }+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }let(:fieldsets) { JsonApiKit::Request::Fieldsets.parse({}) }let(:resource) doClass.new(JsonApiKit::Resource) dodiff --git a/spec/lib/json_api_kit/document/relationship_object_spec.rb b/spec/lib/json_api_kit/document/relationship_object_spec.rbindex 86bf0d1d577..e55d175cb7d 100644--- a/spec/lib/json_api_kit/document/relationship_object_spec.rb+++ b/spec/lib/json_api_kit/document/relationship_object_spec.rb@@ -7,8 +7,8 @@ RSpec.describe JsonApiKit::Document::RelationshipObject dofab!(:topic)let(:guardian) { Guardian.new }- let(:glossary) { JsonApiKit::Glossary.kit }- let(:client) { JsonApiKit::Client.new(guardian:, glossary:, urls:) }+ let(:edition) { JsonApiKit::Edition.current }+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }let(:urls) doJsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/topics")end@@ -49,7 +49,7 @@ RSpec.describe JsonApiKit::Document::RelationshipObject dodescribe "#to_h" docontext "when the current relationship name has several words" dolet(:name) { "ordered_posts" }- let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:edition) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE) }let(:version_change) doClass.new(JsonApiKit::VersionChange) do@@ -73,7 +73,7 @@ RSpec.describe JsonApiKit::Document::RelationshipObject doendcontext "when the type has a historical name" do- let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:edition) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE) }let(:version_change) doClass.new(JsonApiKit::VersionChange) { renamed_type from: :topic_authors, to: :users }diff --git a/spec/lib/json_api_kit/document/resource_object_spec.rb b/spec/lib/json_api_kit/document/resource_object_spec.rbindex afb22c42006..20e9cde8b22 100644--- a/spec/lib/json_api_kit/document/resource_object_spec.rb+++ b/spec/lib/json_api_kit/document/resource_object_spec.rb@@ -4,8 +4,8 @@ RSpec.describe JsonApiKit::Document::ResourceObject dosubject(:resource_object) { described_class.new(record, client:, fieldsets:, meta:) }fab!(:topic) { Fabricate(:topic, title: "A row a document renders") }- let(:glossary) { JsonApiKit::Glossary.kit }- let(:client) { JsonApiKit::Client.new(guardian:, glossary:, urls:) }+ let(:edition) { JsonApiKit::Edition.current }+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }let(:fieldsets) { JsonApiKit::Request::Fieldsets.parse({}) }let(:guardian) { Guardian.new }let(:resource) do@@ -103,7 +103,7 @@ RSpec.describe JsonApiKit::Document::ResourceObject dobefore { allow(JsonApiKit::Document::RelationshipObject).to receive(:new).and_call_original }context "when the relationship has a historical name" do- let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:edition) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE) }let(:version_change) doClass.new(JsonApiKit::VersionChange) dodiff --git a/spec/lib/json_api_kit/document_spec.rb b/spec/lib/json_api_kit/document_spec.rbindex ec87b273018..f1d08ec1fd5 100644--- a/spec/lib/json_api_kit/document_spec.rb+++ b/spec/lib/json_api_kit/document_spec.rb@@ -18,11 +18,11 @@ RSpec.describe JsonApiKit::Document doendendlet(:guardian) { Guardian.new }- let(:glossary) { JsonApiKit::Glossary.kit }+ let(:edition) { JsonApiKit::Edition.current }let(:urls) doJsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/topics")end- let(:client) { JsonApiKit::Client.new(guardian:, glossary:, urls:) }+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }let(:parameters) { {} }describe "Collection.for" dodiff --git a/spec/lib/json_api_kit/edition_spec.rb b/spec/lib/json_api_kit/edition_spec.rbnew file mode 100644index 00000000000..65121722806--- /dev/null+++ b/spec/lib/json_api_kit/edition_spec.rb@@ -0,0 +1,86 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::Edition do+ subject(:edition) { described_class.for(version) }++ let(:version) { JsonApiKit::Timeline::FIRST_RELEASE }+ let(:title) { JsonApiKit::Name::Field.new(value: "title", type: "topics") }+ let(:member_name) { edition.glossary.member_name(title).value }+ let(:ordering) { edition.default_sorts.for(resource) }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ renamed_attribute from: :heading, to: :title+ changed_default_sort from: { created_at: :desc }+ end+ end+ .new(__FILE__)+ end+ let(:changes) { [version_change] }+ let(:resource) do+ Class.new(JsonApiKit::Resource) do+ model Topic+ type :topics+ sort :created_at+ sort :title+ default_sort title: :asc+ end+ end++ before do+ allow(JsonApiKit::VersionChanges.core).to receive(:after).with(version).and_return(changes, [])+ end++ describe ".for" do+ it "selects one change set for names and defaults" do+ expect([member_name, ordering]).to eq(["heading", { "created_at" => :desc }])+ end++ it "selects the pin's changes once" do+ edition.glossary+ edition.default_sorts+ expect(JsonApiKit::VersionChanges.core).to have_received(:after).with(version).once+ end++ context "when the registry's array changes after construction" do+ before do+ edition+ changes.clear+ end++ it "retains the edition's selected changes" do+ expect([member_name, ordering]).to eq(["heading", { "created_at" => :desc }])+ end+ end+ end++ describe ".current" do+ subject(:edition) { described_class.current }++ it "uses current names and defaults" do+ expect([member_name, ordering]).to eq(["title", { "title" => :asc }])+ end+ end++ describe "#glossary" do+ before { allow(JsonApiKit::Glossary).to receive(:new).and_call_original }++ it "builds the glossary with casing and version rules" do+ edition.glossary+ expect(JsonApiKit::Glossary).to have_received(:new).with(+ [JsonApiKit::Glossary::CasingRule, an_instance_of(JsonApiKit::Glossary::VersionRule)],+ )+ end++ it "retains the glossary for the edition" do+ expect(edition.glossary).to equal(edition.glossary)+ end+ end++ describe "#default_sorts" do+ it "retains the resolver for the edition" do+ expect(edition.default_sorts).to equal(edition.default_sorts)+ end+ end+enddiff --git a/spec/lib/json_api_kit/glossary/relationship_names_spec.rb b/spec/lib/json_api_kit/glossary/relationship_names_spec.rbindex 31bfb9674a0..8e1b943da2b 100644--- a/spec/lib/json_api_kit/glossary/relationship_names_spec.rb+++ b/spec/lib/json_api_kit/glossary/relationship_names_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe JsonApiKit::Glossary do- subject(:glossary) { described_class.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ subject(:glossary) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE).glossary }let(:type) { "discussion_threads" }let(:earlier_change) dodiff --git a/spec/lib/json_api_kit/glossary/split_attributes_spec.rb b/spec/lib/json_api_kit/glossary/split_attributes_spec.rbindex 7b7171a2305..ebc5d6ca6b1 100644--- a/spec/lib/json_api_kit/glossary/split_attributes_spec.rb+++ b/spec/lib/json_api_kit/glossary/split_attributes_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe JsonApiKit::Glossary do- subject(:glossary) { described_class.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ subject(:glossary) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE).glossary }let(:size) { JsonApiKit::Name::Field.new(value: "sizePair", type: "pictures") }let(:width) { JsonApiKit::Name::Field.new(value: "image_width", type: "images") }diff --git a/spec/lib/json_api_kit/glossary/version_rule_spec.rb b/spec/lib/json_api_kit/glossary/version_rule_spec.rbindex f64266a75b3..f3591dc6cab 100644--- a/spec/lib/json_api_kit/glossary/version_rule_spec.rb+++ b/spec/lib/json_api_kit/glossary/version_rule_spec.rb@@ -51,19 +51,14 @@ module JsonApiKitSpecendRSpec.describe JsonApiKit::Glossary::VersionRule do- subject(:rule) { described_class.new(version) }+ subject(:rule) { described_class.new(changes) }- let(:version) { JsonApiKit::ApiVersion.parse("2026-09-01") }let(:first_change) { JsonApiKitSpec::FirstRuleChange.new(__FILE__) }let(:second_change) { JsonApiKitSpec::SecondRuleChange.new(__FILE__) }let(:changes) { [first_change, second_change] }let(:name) { JsonApiKit::Name::Field.new(value:, type: "topics") }let(:value) { "posted_at" }- before do- allow(JsonApiKit::VersionChanges.core).to receive(:after).with(version).and_return(changes)- end-describe "#declared_attributes" dosubject(:declared_attributes) { rule.declared_attributes(attributes) }diff --git a/spec/lib/json_api_kit/glossary_spec.rb b/spec/lib/json_api_kit/glossary_spec.rbindex f08c7a91bc6..24fc1517d62 100644--- a/spec/lib/json_api_kit/glossary_spec.rb+++ b/spec/lib/json_api_kit/glossary_spec.rb@@ -72,27 +72,6 @@ RSpec.describe JsonApiKit::Glossary doendend- describe ".resource" do- subject(:resource) { described_class.resource(version) }-- before do- allow(described_class).to receive(:new).and_call_original- allow(described_class::VersionRule).to receive(:new).and_call_original- end-- it "builds a glossary with the wire format rules and the version rule" do- resource- expect(described_class).to have_received(:new).with(- [described_class::CasingRule, an_instance_of(described_class::VersionRule)],- )- end-- it "builds the version rule for the version" do- resource- expect(described_class::VersionRule).to have_received(:new).with(version)- end- end-describe "#declared_attributes" dosubject(:declared_attributes) { glossary.declared_attributes(attributes) }@@ -111,7 +90,7 @@ RSpec.describe JsonApiKit::Glossary doendcontext "with a version rule" do- subject(:glossary) { described_class.resource(version) }+ subject(:glossary) { JsonApiKit::Edition.for(version).glossary }let(:attributes) { { name => %w[Anchors and pages] } }let(:value) { "words" }@@ -200,7 +179,7 @@ RSpec.describe JsonApiKit::Glossary dosubject(:declared_name) { glossary.declared_name(name) }context "when a casing correction precedes a type change" do- let(:glossary) { described_class.resource(version) }+ let(:glossary) { JsonApiKit::Edition.for(version).glossary }let(:name) { JsonApiKit::Name::Field.new(value:, type: "discussions") }let(:value) { "created_at" }let(:version_change) do@@ -278,7 +257,7 @@ RSpec.describe JsonApiKit::Glossary doendcontext "with a version rule" do- subject(:glossary) { described_class.resource(version) }+ subject(:glossary) { JsonApiKit::Edition.for(version).glossary }let(:value) { "postedAt" }@@ -343,7 +322,7 @@ RSpec.describe JsonApiKit::Glossary doendcontext "when the type has a historical name" do- let(:glossary) { described_class.resource(version) }+ let(:glossary) { JsonApiKit::Edition.for(version).glossary }let(:version_change) doClass.new(JsonApiKit::VersionChange) do@@ -372,7 +351,7 @@ RSpec.describe JsonApiKit::Glossary doendcontext "with a version rule" do- subject(:glossary) { described_class.resource(version) }+ subject(:glossary) { JsonApiKit::Edition.for(version).glossary }before doallow(JsonApiKit::VersionChanges.core).to receive(:after).with(version).and_return(@@ -421,7 +400,7 @@ RSpec.describe JsonApiKit::Glossary doendcontext "with a version rule" do- subject(:glossary) { described_class.resource(version) }+ subject(:glossary) { JsonApiKit::Edition.for(version).glossary }before doallow(JsonApiKit::VersionChanges.core).to receive(:after).with(version).and_return(diff --git a/spec/lib/json_api_kit/query/collection_spec.rb b/spec/lib/json_api_kit/query/collection_spec.rbindex cbb290ee306..a573762415b 100644--- a/spec/lib/json_api_kit/query/collection_spec.rb+++ b/spec/lib/json_api_kit/query/collection_spec.rb@@ -21,12 +21,24 @@ RSpec.describe JsonApiKit::Query::Collection dodefault_sort created_at: :ascendend- let(:request) { JsonApiKit::Request::Collection.new(params, guardian:) }+ let(:request) do+ JsonApiKit::Request::Collection.new(+ JsonApiKit::Request::Input.with_defaults(params, resource:, default_sorts:),+ guardian:,+ default_sorts:,+ )+ end+ let(:default_sorts) { JsonApiKit::Edition.current.default_sorts }let(:params) { {} }let(:guardian) { Guardian.new }let(:scoped_to) { nil }- def request_for(params) = JsonApiKit::Request::Collection.new(params, guardian: Guardian.new)+ def request_for(params) =+ JsonApiKit::Request::Collection.new(+ JsonApiKit::Request::Input.with_defaults(params, resource:, default_sorts:),+ guardian: Guardian.new,+ default_sorts:,+ )describe ".new" dolet(:params) { { sort: { secrets: :asc } } }diff --git a/spec/lib/json_api_kit/query/individual_spec.rb b/spec/lib/json_api_kit/query/individual_spec.rbindex 5ffd9540faf..ad8ccc1566f 100644--- a/spec/lib/json_api_kit/query/individual_spec.rb+++ b/spec/lib/json_api_kit/query/individual_spec.rb@@ -13,7 +13,14 @@ RSpec.describe JsonApiKit::Query::Individual doattribute :titleendend- let(:request) { JsonApiKit::Request::Individual.new(params, guardian:) }+ let(:request) do+ JsonApiKit::Request::Individual.new(+ JsonApiKit::Request::Input.with_defaults(params, resource:, default_sorts:),+ guardian:,+ default_sorts:,+ )+ end+ let(:default_sorts) { JsonApiKit::Edition.current.default_sorts }let(:params) { { id: topic.id } }let(:guardian) { Guardian.new }let(:title) { JsonApiKit::Name::Field.new(value: "title", type: "topics") }diff --git a/spec/lib/json_api_kit/relationship_paths/unscoped_position_spec.rb b/spec/lib/json_api_kit/relationship_paths/unscoped_position_spec.rbindex 19c6ccbf97e..a770d685362 100644--- a/spec/lib/json_api_kit/relationship_paths/unscoped_position_spec.rb+++ b/spec/lib/json_api_kit/relationship_paths/unscoped_position_spec.rb@@ -3,7 +3,7 @@RSpec.describe JsonApiKit::RelationshipPaths::UnscopedPosition dosubject(:position) { described_class.new(glossary:) }- let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:glossary) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE).glossary }let(:version_change) doClass.new(JsonApiKit::VersionChange) dodiff --git a/spec/lib/json_api_kit/relationship_paths_spec.rb b/spec/lib/json_api_kit/relationship_paths_spec.rbindex 6ceed94fb57..ebe9b0a9d8e 100644--- a/spec/lib/json_api_kit/relationship_paths_spec.rb+++ b/spec/lib/json_api_kit/relationship_paths_spec.rb@@ -23,7 +23,7 @@ RSpec.describe JsonApiKit::RelationshipPaths::Position dodescribed_class.new(resource: JsonApiKitSpec::PathTopicsResource, glossary:)end- let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:glossary) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE).glossary }let(:version_change) doClass.new(JsonApiKit::VersionChange) do@@ -117,7 +117,7 @@ endRSpec.describe JsonApiKit::RelationshipPaths dosubject(:paths) { described_class.new(resource: JsonApiKitSpec::PathTopicsResource, glossary:) }- let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:glossary) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE).glossary }let(:version_change) doClass.new(JsonApiKit::VersionChange) dodiff --git a/spec/lib/json_api_kit/request/contract/collection_spec.rb b/spec/lib/json_api_kit/request/contract/collection_spec.rbindex 005ba3b0247..267d1426243 100644--- a/spec/lib/json_api_kit/request/contract/collection_spec.rb+++ b/spec/lib/json_api_kit/request/contract/collection_spec.rb@@ -1,11 +1,11 @@# frozen_string_literal: trueRSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do- subject(:contract) { described_class.for(params, resource:, glossary:) }+ subject(:contract) { described_class.for({ sort: {} }.merge(params), resource:, glossary:) }let(:params) { {} }let(:glossary) { JsonApiKit::Glossary.kit }- let(:cursor) { JsonApiKit::Pagination::Cursor.new([resource.order.digest, 0, 12]).to_s }+ let(:cursor) { JsonApiKit::Pagination::Cursor.new([resource.order({}).digest, 0, 12]).to_s }let(:related) doClass.new(JsonApiKit::Resource) domodel User@@ -220,10 +220,10 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model dolet(:params) { { page: {} } }let(:cursor_not_matching_segment) do- JsonApiKit::Pagination::Cursor.new([resource.order.digest, 7, 12]).to_s+ JsonApiKit::Pagination::Cursor.new([resource.order({}).digest, 7, 12]).to_sendlet(:cursor_not_matching_length) do- JsonApiKit::Pagination::Cursor.new([resource.order.digest, 0]).to_s+ JsonApiKit::Pagination::Cursor.new([resource.order({}).digest, 0]).to_sendbefore { contract.valid? }diff --git a/spec/lib/json_api_kit/request/family/sort/keys_spec.rb b/spec/lib/json_api_kit/request/family/sort/keys_spec.rbindex 7f3d4ac7aa3..6292c3db966 100644--- a/spec/lib/json_api_kit/request/family/sort/keys_spec.rb+++ b/spec/lib/json_api_kit/request/family/sort/keys_spec.rb@@ -27,8 +27,32 @@ RSpec.describe JsonApiKit::Request::Family::Sort::Keys docontext "when the sort is an array" dolet(:value) { %w[postedDate] }- it "returns nothing" do- expect(keys).to be_nil+ it "preserves the value for validation" do+ expect(declared_sort).to eq(value)+ end+ end++ context "when the sort is an empty array" do+ let(:value) { [] }++ it "preserves the value for validation" do+ expect(declared_sort).to eq(value)+ end+ end++ context "when the sort is false" do+ let(:value) { false }++ it "preserves the value for validation" do+ expect(declared_sort).to be(false)+ end+ end++ context "when the sort is absent" do+ let(:value) { nil }++ it "preserves the absence of a sort" do+ expect(declared_sort).to be_nilendendend@@ -40,6 +64,22 @@ RSpec.describe JsonApiKit::Request::Family::Sort::Keys doexpect(declared_sort).to eq("posted_at" => :asc, "title" => :desc)end+ context "when the sort is an empty string" do+ let(:value) { "" }++ it "returns no explicit ordering" do+ expect(declared_sort).to be_nil+ end+ end++ context "when the sort is an empty hash" do+ let(:value) { {} }++ it "returns no explicit ordering" do+ expect(declared_sort).to be_nil+ end+ end+context "when two keys declare one name" dolet(:value) { "postedDate,postedTime" }diff --git a/spec/lib/json_api_kit/request/input/collection_spec.rb b/spec/lib/json_api_kit/request/input/collection_spec.rbnew file mode 100644index 00000000000..9ac8426a3bc--- /dev/null+++ b/spec/lib/json_api_kit/request/input/collection_spec.rb@@ -0,0 +1,109 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::Request::Input::Collection do+ subject(:input) { described_class.new(parameters, resource:, edition:) }++ let(:parameters) { {} }+ let(:edition) { JsonApiKit::Edition.new([version_change]) }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ renamed_attribute from: :posted_at, to: :created_at+ changed_default_sort from: { posted_at: :desc }+ end+ end+ .new(__FILE__)+ end+ let(:resource) do+ Class.new(JsonApiKit::Resource) do+ model Topic+ type :topics+ attribute :created_at+ attribute :title+ sort :created_at+ sort :title+ default_sort title: :asc+ end+ end++ describe "#to_h" do+ subject(:ordering) { input.to_h.fetch(:sort) }++ before { input.invalid? }++ it "supplies the historical default in current names" do+ expect(ordering).to eq("created_at" => :desc)+ end++ context "when the client supplies a sort" do+ let(:parameters) { { sort: "postedAt" } }++ it "translates the explicit ordering" do+ expect(ordering).to eq("created_at" => :asc)+ end+ end++ context "when the client supplies an empty sort" do+ let(:parameters) { { sort: "" } }++ it "supplies the historical default" do+ expect(ordering).to eq("created_at" => :desc)+ end+ end+ end++ describe "#invalid?" do+ it { is_expected.not_to be_invalid }++ context "when the client supplies a sort with an invalid shape" do+ let(:parameters) { { sort: false } }++ it { is_expected.to be_invalid }+ end++ context "when an explicit sort accompanies an invalid historical default" do+ let(:parameters) { { sort: "title" } }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource(:topics) { changed_default_sort from: { unknown: :asc } }+ end+ .new(__FILE__)+ end++ it "validates the explicit sort without resolving the unused default" do+ expect(input).not_to be_invalid+ end+ end+ end++ describe "#refusals" do+ subject(:refusals) { input.refusals }++ let(:parameters) { { sort: "neverDeclared" } }++ before { input.invalid? }++ it "reports validation errors in the client's vocabulary" do+ expect(refusals.sole).to have_attributes(+ detail: "There is no sort named neverDeclared.",+ source: {+ parameter: "sort",+ },+ )+ end+ end++ describe "#fieldsets" do+ subject(:attributes) do+ input.fieldsets.keep("topics", "postedAt" => "date", "title" => "A topic")+ end++ let(:parameters) { { fields: { topics: "postedAt" } } }++ it "retains the fieldset in the client's vocabulary" do+ expect(attributes).to eq("postedAt" => "date")+ end+ end+enddiff --git a/spec/lib/json_api_kit/request/input/individual_spec.rb b/spec/lib/json_api_kit/request/input/individual_spec.rbnew file mode 100644index 00000000000..e443f92b957--- /dev/null+++ b/spec/lib/json_api_kit/request/input/individual_spec.rb@@ -0,0 +1,57 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::Request::Input::Individual do+ subject(:input) { described_class.new(parameters, resource:, edition:) }++ let(:parameters) { {} }+ let(:edition) { JsonApiKit::Edition.current }+ let(:resource) do+ Class.new(JsonApiKit::Resource) do+ model Topic+ type :topics+ attribute :title+ sort :title+ default_sort title: :asc+ end+ end++ describe "#invalid?" do+ it "accepts an individual request without adding a sort parameter" do+ expect(input).not_to be_invalid+ end++ context "when the client supplies collection parameters" do+ let(:parameters) { { sort: "title", page: { size: 1 }, filter: { title: "A topic" } } }++ it { is_expected.to be_invalid }+ end+ end++ describe "#refusals" do+ subject(:sources) { input.refusals.map(&:source) }++ let(:parameters) { { sort: "title", page: { size: 1 }, filter: { title: "A topic" } } }++ before { input.invalid? }++ it "reports each collection parameter" do+ expect(sources).to contain_exactly(+ { parameter: "sort" },+ { parameter: "page" },+ { parameter: "filter" },+ )+ end+ end++ describe "#to_h" do+ subject(:fields) { input.to_h.fetch(:fields) }++ let(:parameters) { { fields: { topics: "title" } } }++ before { input.invalid? }++ it "returns the contract's parameters" do+ expect(fields).to eq("topics" => ["title"])+ end+ end+enddiff --git a/spec/lib/json_api_kit/request/input_spec.rb b/spec/lib/json_api_kit/request/input_spec.rbnew file mode 100644index 00000000000..96ac22f1bd2--- /dev/null+++ b/spec/lib/json_api_kit/request/input_spec.rb@@ -0,0 +1,52 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::Request::Input do+ let(:resource) do+ Class.new(JsonApiKit::Resource) do+ model Topic+ type :topics+ sort :title+ default_sort title: :asc+ end+ end+ let(:default_sorts) { JsonApiKit::Edition.current.default_sorts }++ describe ".with_defaults" do+ subject(:parameters) { described_class.with_defaults(input, resource:, default_sorts:) }++ let(:input) { { page: { size: 1 } } }++ it "adds the default to the request parameters" do+ expect(parameters).to eq("page" => { size: 1 }, "sort" => { "title" => :asc })+ end++ it "preserves the original parameters" do+ parameters+ expect(input).to eq(page: { size: 1 })+ end++ context "when the request already has an ordering" do+ let(:input) { { "sort" => { "title" => :desc } } }++ it "preserves the explicit ordering" do+ expect(parameters).to eq(input)+ end+ end++ context "when the request has an empty ordering" do+ let(:input) { { "sort" => {} } }++ it "preserves the resolved empty ordering" do+ expect(parameters).to eq(input)+ end+ end++ context "when the request has an invalid ordering" do+ let(:input) { { "sort" => false } }++ it "preserves the value for validation" do+ expect(parameters).to eq(input)+ end+ end+ end+enddiff --git a/spec/lib/json_api_kit/request/parameters_spec.rb b/spec/lib/json_api_kit/request/parameters_spec.rbindex 72d3d8f0c70..98b91870622 100644--- a/spec/lib/json_api_kit/request/parameters_spec.rb+++ b/spec/lib/json_api_kit/request/parameters_spec.rb@@ -107,7 +107,7 @@ RSpec.describe JsonApiKit::Request::Parameters docontext "when both relationships have historical names" dolet(:parameters) { { "include" => "olderPosts.author,olderPosts" } }- let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:glossary) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE).glossary }let(:version_change) doClass.new(JsonApiKit::VersionChange) do@@ -207,7 +207,7 @@ RSpec.describe JsonApiKit::Request::Parameters doendcontext "with a version change" do- let(:glossary) { JsonApiKit::Glossary.resource(version) }+ let(:glossary) { JsonApiKit::Edition.for(version).glossary }let(:version) { JsonApiKit::Timeline::FIRST_RELEASE }let(:version_change) { JsonApiKitSpec::ParametersChange.new(__FILE__) }@@ -365,7 +365,7 @@ RSpec.describe JsonApiKit::Request::Parameters doendcontext "when a type changes after a field name" do- let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:glossary) { JsonApiKit::Edition.for(JsonApiKit::Timeline::FIRST_RELEASE).glossary }let(:field_change) doClass.new(JsonApiKit::VersionChange) dodiff --git a/spec/lib/json_api_kit/request_spec.rb b/spec/lib/json_api_kit/request_spec.rbindex d7ad2f726cc..8da237e7264 100644--- a/spec/lib/json_api_kit/request_spec.rb+++ b/spec/lib/json_api_kit/request_spec.rb@@ -1,7 +1,13 @@# frozen_string_literal: trueRSpec.describe JsonApiKit::Request do- subject(:request) { described_class::Collection.new(params, guardian:) }+ subject(:request) do+ described_class::Collection.new(+ params,+ guardian:,+ default_sorts: JsonApiKit::Edition.current.default_sorts,+ )+ endlet(:params) { {} }let(:guardian) { Guardian.new }@@ -16,7 +22,13 @@ RSpec.describe JsonApiKit::Request doendcontext "when a caller asks for one record" do- subject(:request) { described_class::Individual.new(params, guardian:) }+ subject(:request) do+ described_class::Individual.new(+ params,+ guardian:,+ default_sorts: JsonApiKit::Edition.current.default_sorts,+ )+ endlet(:params) { { id: topic.id } }@@ -60,7 +72,13 @@ RSpec.describe JsonApiKit::Request doendcontext "when a caller asks for one record" do- subject(:request) { described_class::Individual.new(params, guardian:) }+ subject(:request) do+ described_class::Individual.new(+ params,+ guardian:,+ default_sorts: JsonApiKit::Edition.current.default_sorts,+ )+ endlet(:params) { { id: 12, fields: { users: %w[username] } } }@@ -108,7 +126,15 @@ RSpec.describe JsonApiKit::Request docontext "when there is no sort parameter" dolet(:params) { {} }- it "returns no sort" do+ it "requires a resolved ordering" do+ expect { ordering }.to raise_error(KeyError, /sort/)+ end+ end++ context "when the request has an explicit empty ordering" do+ let(:params) { { sort: {} } }++ it "preserves the empty ordering" doexpect(ordering).to be_emptyendenddiff --git a/spec/lib/json_api_kit/resource_spec.rb b/spec/lib/json_api_kit/resource_spec.rbindex 6d9d6a19fce..bfefb5f756f 100644--- a/spec/lib/json_api_kit/resource_spec.rb+++ b/spec/lib/json_api_kit/resource_spec.rb@@ -282,8 +282,8 @@ RSpec.describe JsonApiKit::Resource doenddescribe ".default_sort" do- it "orders a listing as the resource declares" do- expect(topic_resource.order.leading.name).to eq(:last_posted_at)+ it "retains the declared ordering" do+ expect(topic_resource.default_ordering).to eq("ran_at" => :desc)endcontext "when the resource declares no such sort" do@@ -296,6 +296,67 @@ RSpec.describe JsonApiKit::Resource do}.to raise_error(JsonApiKit::Resource::Sorting::UndeclaredDefault, /creatd_at/)endend++ context "when the direction is invalid" do+ it "rejects the declaration" do+ expect {+ Class.new(described_class) do+ model Topic+ sort :created_at+ default_sort created_at: :sideways+ end+ }.to raise_error(ArgumentError, /unknown direction: sideways/)+ end+ end+ end++ describe ".default_ordering" do+ subject(:ordering) { topic_resource.default_ordering(historical_ordering) }++ let(:historical_ordering) { { created_at: :asc } }++ it "returns the supplied ordering with string names" do+ expect(ordering).to eq("created_at" => :asc)+ end++ it "returns an immutable ordering" do+ expect(ordering).to be_frozen+ end++ context "when a historical ordering has been requested" do+ before { ordering }++ it "preserves the resource's current default" do+ expect(topic_resource.default_ordering).to eq("ran_at" => :desc)+ end+ end++ context "when the ordering is empty" do+ let(:historical_ordering) { {} }++ it "preserves the empty ordering" do+ expect(ordering).to be_empty+ end+ end++ context "when the sort is undeclared" do+ let(:historical_ordering) { { unknown: :asc } }++ it "rejects the ordering" do+ expect { ordering }.to raise_error(+ JsonApiKit::Resource::Sorting::UndeclaredDefault,+ /unknown/,+ )+ end+ end++ context "when the direction is invalid" do+ let(:historical_ordering) { { created_at: :sideways } }++ it "rejects the ordering" do+ expect { ordering }.to raise_error(ArgumentError, /unknown direction: sideways/)+ end+ endenddescribe ".unique_by" do@@ -528,7 +589,7 @@ RSpec.describe JsonApiKit::Resource doendcontext "when the resource declares no anchor by that name" do- it { is_expected.to be_anchored_by(anchor_name: :first_unread) }+ it { is_expected.to be_anchored_by(anchor_name: :first_unread, ordering:) }endend@@ -581,6 +642,35 @@ RSpec.describe JsonApiKit::Resource doscoped_to: nil,)end++ context "when the resource's default sort changes between queries" do+ fab!(:first_topic) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }+ fab!(:second_topic) { Fabricate(:topic, created_at: Time.utc(2026, 8, 2)) }++ before do+ allow(JsonApiKit::Query::Collection).to receive(:new).and_call_original+ topic_resource.default_sort created_at: :asc+ end++ it "uses the updated default for the next query" do+ expect { topic_resource.default_sort created_at: :desc }.to change {+ topic_resource.all(guardian:).records.map(&:record)+ }.from([first_topic, second_topic]).to([second_topic, first_topic])+ end+ end+ end++ describe ".find" do+ before { allow(JsonApiKit::Query::Individual).to receive(:new) }++ it "resolves the default ordering before constructing the request" do+ topic_resource.find(12, guardian:)++ expect(JsonApiKit::Query::Individual).to have_received(:new).with(+ topic_resource,+ an_object_having_attributes(ordering: { "ran_at" => :desc }, guardian:),+ )+ endenddescribe ".paged_from?" dodiff --git a/spec/lib/json_api_kit/sideload_spec.rb b/spec/lib/json_api_kit/sideload_spec.rbindex 0084eec6d6c..8d62fc70978 100644--- a/spec/lib/json_api_kit/sideload_spec.rb+++ b/spec/lib/json_api_kit/sideload_spec.rb@@ -20,7 +20,13 @@ RSpec.describe JsonApiKit::Sideload dolet(:records) { [topic] }let(:rows) { records.map { JsonApiKit::Pagination::Row.new(record: it, segment: nil) } }let(:params) { {} }- let(:request) { JsonApiKit::Request::Collection.new(params, guardian: Guardian.new) }+ let(:request) do+ JsonApiKit::Request::Collection.new(+ params,+ guardian: Guardian.new,+ default_sorts: JsonApiKit::Edition.current.default_sorts,+ )+ endlet(:schema) { JsonApiKit::Schema.new(Topic) }describe "#linkage_for" dodiff --git a/spec/lib/json_api_kit/sideloads_spec.rb b/spec/lib/json_api_kit/sideloads_spec.rbindex 69bf389d25d..3adff9fe196 100644--- a/spec/lib/json_api_kit/sideloads_spec.rb+++ b/spec/lib/json_api_kit/sideloads_spec.rb@@ -39,7 +39,13 @@ RSpec.describe JsonApiKit::Sideloads doendlet(:paths) { JsonApiKit::Paths.new(nil) }let(:rows) { [JsonApiKit::Pagination::Row.new(record: topic, segment: nil)] }- let(:request) { JsonApiKit::Request::Collection.new({}, guardian: Guardian.new) }+ let(:request) do+ JsonApiKit::Request::Collection.new(+ {},+ guardian: Guardian.new,+ default_sorts: JsonApiKit::Edition.current.default_sorts,+ )+ endlet(:schema) { JsonApiKit::Schema.new(Topic) }describe "#linkage_for" dodiff --git a/spec/lib/json_api_kit/version_change/default_sorts_spec.rb b/spec/lib/json_api_kit/version_change/default_sorts_spec.rbnew file mode 100644index 00000000000..09b3c86bb7a--- /dev/null+++ b/spec/lib/json_api_kit/version_change/default_sorts_spec.rb@@ -0,0 +1,135 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::VersionChange::DefaultSorts do+ subject(:default_sorts) { described_class.new(defaults) }++ let(:topic_default) { JsonApiKit::DefaultSort.new(:topics, posted_at: :desc) }+ let(:user_default) { JsonApiKit::DefaultSort.new(:users, username: :asc) }+ let(:defaults) { [topic_default, user_default] }++ describe "#verify!" do+ subject(:verify) { default_sorts.verify! }++ it "accepts one default per resource" do+ expect { verify }.not_to raise_error+ end++ context "when the collection is empty" do+ let(:defaults) { [] }++ it "accepts the collection" do+ expect { verify }.not_to raise_error+ end+ end++ context "when two defaults belong to the same resource" do+ let(:defaults) { [topic_default, JsonApiKit::DefaultSort.new(:topics, title: :asc)] }++ it "reports the conflicting resource" do+ expect { verify }.to raise_error(+ described_class::Conflict,+ "changes the default sort for topics twice.",+ )+ end+ end+ end++ describe "#convert_names" do+ subject(:converted_defaults) { default_sorts.convert_names { it.with(value: it.value.upcase) } }++ it "converts the names in every default" do+ expect(converted_defaults).to match(+ [+ have_attributes(type: "TOPICS", ordering: { "POSTED_AT" => :desc }),+ have_attributes(type: "USERS", ordering: { "USERNAME" => :asc }),+ ],+ )+ end++ context "when the collection is empty" do+ let(:defaults) { [] }++ it "returns no defaults" do+ expect(converted_defaults).to be_empty+ end+ end+ end+end++RSpec.describe JsonApiKit::VersionChange do+ subject(:version_change) { change_class.new("2026-09-01_default_sort.rb") }++ let(:change_class) do+ Class.new(described_class) do+ version "2026-09-01"+ description "Topics use a different default sort."++ resource :topics do+ changed_default_sort from: { posted_at: :desc }+ renamed_sort from: :posted_at, to: :created_at+ end+ end+ end++ describe ".resource" do+ context "when a default declares an invalid direction" do+ subject(:declare_default) do+ change_class.resource(:posts) { changed_default_sort from: { post_number: :sideways } }+ end++ it "rejects the declaration" do+ expect { declare_default }.to raise_error(ArgumentError, /unknown direction: sideways/)+ end+ end+ end++ describe "#current_default_sorts" do+ subject(:default_sorts) { version_change.current_default_sorts }++ it "translates sort names within the declaring change" do+ expect(default_sorts.sole).to have_attributes(+ type: "topics",+ ordering: {+ "created_at" => :desc,+ },+ )+ end++ context "when the change has no default declaration" do+ let(:change_class) { Class.new(described_class) }++ it "returns no default overrides" do+ expect(default_sorts).to be_empty+ end+ end+ end++ describe "#verify!" do+ subject(:verify) { version_change.verify! }++ before { freeze_time(Date.new(2026, 9, 2)) }++ it "accepts one default change per resource" do+ expect { verify }.not_to raise_error+ end++ context "when a resource changes its default twice" do+ before { change_class.resource(:topics) { changed_default_sort from: {} } }++ it "reports the conflicting resource with its source file" do+ expect { verify }.to raise_error(+ ArgumentError,+ "2026-09-01_default_sort.rb changes the default sort for topics twice.",+ )+ end+ end++ context "when two resources change their defaults" do+ before { change_class.resource(:posts) { changed_default_sort from: { post_number: :asc } } }++ it "accepts the independent defaults" do+ expect { verify }.not_to raise_error+ end+ end+ end+enddiff --git a/spec/resources/group_resource_spec.rb b/spec/resources/group_resource_spec.rbindex 028b53221af..761a5c6e1aa 100644--- a/spec/resources/group_resource_spec.rb+++ b/spec/resources/group_resource_spec.rb@@ -3,11 +3,11 @@RSpec.describe GroupResource dofab!(:group) { Fabricate(:group, name: "a_group") }let(:guardian) { Guardian.new }- let(:glossary) { JsonApiKit::Glossary.kit }+ let(:edition) { JsonApiKit::Edition.current }let(:urls) doJsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/groups")end- let(:client) { JsonApiKit::Client.new(guardian:, glossary:, urls:) }+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }let(:document) doJsonApiKit::Document::Individual.for(group.id, {}, resource: described_class, client:)enddiff --git a/spec/resources/user_resource_spec.rb b/spec/resources/user_resource_spec.rbindex 25659c9f728..e27d95f4e3b 100644--- a/spec/resources/user_resource_spec.rb+++ b/spec/resources/user_resource_spec.rb@@ -3,11 +3,11 @@RSpec.describe UserResource dofab!(:user) { Fabricate(:user, username: "someone") }let(:guardian) { Guardian.new }- let(:glossary) { JsonApiKit::Glossary.kit }+ let(:edition) { JsonApiKit::Edition.current }let(:urls) doJsonApiKit::Urls.new(base: "https://example.com/api", current: "https://example.com/api/users")end- let(:client) { JsonApiKit::Client.new(guardian:, glossary:, urls:) }+ let(:client) { JsonApiKit::Client.new(guardian:, edition:, urls:) }let(:document) doJsonApiKit::Document::Individual.for(user.id, {}, resource: described_class, client:)enddiff --git a/spec/support/matchers/json_api_kit/sort_by_default.rb b/spec/support/matchers/json_api_kit/sort_by_default.rbindex fd7e44c5d7f..32d46ce58b1 100644--- a/spec/support/matchers/json_api_kit/sort_by_default.rb+++ b/spec/support/matchers/json_api_kit/sort_by_default.rb@@ -31,7 +31,7 @@ module JsonApiKitMatchersdef leading_keys@leading_keys ||=resource- .order+ .order(resource.default_ordering).first.keyset.keys