Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

20.4 KB
Raw Blame

Typed Preferences on the Wire

Status: In Progress — all three phases (A declarations and generator, B contract, C enforcement) in one pull request, one commit series per phase Target: Spree 6.0 Depends on: 6.0-json-preferences.md (JSON storage, decimals as exact strings, tiers as a list, secret_preferences), 6.0-money-correctness.md (money and rate string formats) Author: Damian + Claude Last updated: 2026-10-09 (open questions settled, implementation started) Tracking: Linear V-3739 · GitHub spree/spree#14850

Summary

Preferences reach the API in two ways, and both expose the Ruby preferences DSL instead of a contract. Settings on concrete resources (store, channel, seller profile) appear as preferred_* fields: the prefix is the DSL's method name, not a word an API client should see. Configurable subtypes (promotion rules and actions, calculators, payment methods, integrations, delivery method rules, commission rules, order routing rules, price rules, seller requirements, imports) send type plus an untyped preferences: Record<string, unknown>. They also carry a preference_schema written in Ruby type names (decimal, password, array, hash). The real behaviour lives in code no client can see: the parse_on_set lambdas decode prefixed IDs and normalize country codes, an unknown key raises NoMethodError, and :array preferences declare no item type. This plan renames the preferred_* fields to plain names. It compiles every preference declaration to JSON Schema and publishes each family as a discriminated union in OpenAPI and the SDKs. It also validates every preferences write against that schema. The declarations stay the only source: no second schema is written by hand. The result is a configuration contract that the dashboard, plugin authors, AI agents and any non-Ruby implementation can read, type-check and validate in the same way.

Key Decisions (do not deviate without discussion)

  • The preference declarations remain the single source (continuing 6.0-json-preferences.md). The JSON Schema, the OpenAPI components, the SDK types, the /…/types responses and write validation are all generated from preference :name, :type, …. Nothing is maintained by hand.

  • Declarations become complete. :array requires of:. :hash requires keys: and values:. An ID list declares of: :id, model:, scope:, which replaces its parse_on_set decoding lambda. Money values declare the :money type. Fixed vocabularies declare choices:. Domain formats (:currency, :iso_country, :date, :timezone) declare format:. A declaration the generator cannot compile fails a spec, not production.

  • :any is removed. No production declaration uses it any more (the three counted by 6.0-json-preferences.md are gone); only specs did, and they move to real types.

  • Type mapping:

    Declaration JSON Schema
    :string, :text string (text adds x-spree-widget: textarea)
    :boolean boolean
    :integer integer
    :decimal string, canonical decimal pattern
    :money string, canonical decimal pattern, format: money (the money plan's preference type)
    :array, of: array with typed items; of: :id gives format: prefixed-id and x-spree-prefix
    :hash, keys:, values: object with propertyNames and additionalProperties
    :password string, writeOnly: true, x-spree-secret: true
    :date string, format: date
    choices: enum
    format: :currency / :iso_country string, format: currency / format: iso-country (drives the dashboard's currency select and country combobox)

    Defaults become default, except for secrets, which never carry one.

  • Families are open unions. Each family is published as oneOf with discriminator: { propertyName: type }. It has one member per built-in subtype, and one final fallback member: { type: string, preferences: object }. The SDK type is ItemTotalRule | CountryRule | … | UnknownPromotionRule. Narrowing on type types preferences for built-in subtypes, while a plugin subtype still type-checks. This respects the existing rule that registry-driven type values cannot be closed enums: registries fill after serializers load.

  • Built-in subtypes are static and every subtype is discoverable. OpenAPI and the SDKs carry the subtypes Spree ships. The /…/types endpoints return { type, label, schema } for every registered subtype, plugins included, from the same generator. schema replaces preference_schema.

  • preference_schema leaves resource rows. It describes a class, not a record. Today it is repeated on every serialized rule, action and integration. Clients read it from /…/types.

  • Writes are validated before assignment. Admin and Seller controllers validate preferences against the subtype's schema with json_schemer. An unknown key, a wrong type, a malformed or foreign ID, or a value outside choices returns 422 invalid_preferences, with a JSON pointer per failure (/preferences/channel_ids/1). A non-Ruby implementation validates the same schema with Ajv or Zod, so the two cannot drift.

  • ID decoding becomes declarative. format: prefixed-id with x-spree-prefix tells the server which values to decode, and to decode only those. Controllers that skip normalize_params to protect opaque provider values (Admin::PaymentMethodsController) no longer need that exception for preferences.

  • The secret round trip is specified, not just implemented. A secret reads back masked ("••••1234"). Writing the masked value back leaves the secret unchanged. null clears it. Any other string replaces it. This lives in the contract (x-spree-secret) and in the conformance spec, not only in Spree::Preferences::Masking.masked?.

  • preferred_* fields are renamed. On resources whose settings are a fixed set (store, channel, seller profile and any other serializer exposing preferred_*), the wire name drops the prefix: preferred_guest_checkout becomes guest_checkout, and preferred_timezone becomes timezone. The model owns the bridge, following the existing read/write symmetry rule: Preferable gains exposes_preferences :guest_checkout, :timezone, …, which defines plain readers and writers. Serializers and controllers use only the plain names. Typed by the same mapping above.

  • order.preferred_stock_location_id is not renamed. It is an association whose domain name is "preferred stock location", not a preference.

  • One calculator shape. Delivery methods move from flat calculator_type plus calculator_preferences to the nested calculator: { type, preferences } used by promotion actions, on both read and write.

  • The preferences field name stays. It is plain English, not a Ruby term. The leaks were the untyped values and the preferred_ prefix.

  • Breaking in 6.0, for every v3 API. Consistent with the Ruby-class-name change (#14837). Every renamed field and every removed preference_schema is listed in the upgrade guide. Inventory (2026-10-09) found the Store API unaffected: the cart's only preferred_* field is preferred_stock_location_id, which stays, and the seller profile belongs to the Seller API.

  • One pull request, one commit series per phase (decided 2026-10-09). The three phases below are delivered together so every breaking 6.0 change is reviewed and released at once.

  • storefront_url is the store setting's plain name; its reader keeps the fallback (decided 2026-10-09, narrowed the same day in review). Dropping the prefix collides with Store#storefront_url. The setting takes the name on the wire and in the model, no second method is introduced, and the model's reader still answers the first non-loopback allowed origin and then the store's own URL when nothing is set, so customer emails and the product feed never get an empty base URL. The API's storefront_url field returns the stored setting (null when unset), while url keeps returning the effective address: review found that serving the fallback made the dashboard show a "View store" link for stores without a storefront, and save the fallback back as if the merchant had typed it.

  • Incomplete declarations warn in 6.0 and raise in 6.1 (decided 2026-10-09). An :array without of:, a :hash without keys:/values:, or :any logs a deprecation naming the missing option, and its schema accepts any value for that key, so an un-updated plugin keeps working. Every declaration Spree ships is complete, and a spec enforces it.

  • exposes_preferences does not grant write access to anyone (decided 2026-10-09). It defines the plain model reader and writer only. Each API keeps its own permitted list, and Seller controllers keep using additional_seller_permitted_attributes, so exposing a setting never makes it seller-writable.

Settled during implementation (2026-10-09)

  • An id list names its model, not its prefix. of: :id, model: 'Spree::Channel', scope: ->(rule) { … }. The prefix (x-spree-prefix) is read from the model, and the model is needed anyway to check that every id exists inside scope. model: takes a class name or a block (-> { Spree.customer_class }), so a declaration never loads another class. normalize_id_preference stays one release as a deprecated bridge.
  • The SDK narrows through a map, not a union with a catch-all member. TypeScript does not narrow on type when one member's type is string, so the plan's ItemTotalRule | … | UnknownPromotionRule would type nothing. Each family ships <Family>PreferencesMap (an interface, so an extension adds its types by declaration merging, as with WebhookEventMap) and Typed<Family>, the resource narrowed by type. The generated resource type keeps preferences: Record<string, unknown>, which is what a plugin type reads as.
  • OpenAPI carries the family union on preferences, without a discriminator. The specs are OpenAPI 3.0.3, and type sits outside the preferences object, so a discriminator cannot apply. Each family is an anyOf of its subtypes plus a plain object, with x-spree-preferences-by-type mapping each type to its component. Nullable types use nullable: true; propertyNames becomes x-spree-property-names.
  • Secrets are not writeOnly. They read back masked, so the property is in responses; x-spree-secret marks them. A secret is always nullable, because an unset one reads as null.
  • Defaults computed at read time are not in the schema. A default given as a block (the default store's currency) differs per store and needs the database, so it is left out and does not make the value nullable. The schema can then be generated without a database.
  • Internal preferences are refused on write. They are not in the schema, so sending one is an unknown key (422), not a silent no-op.
  • An id that is well formed but outside the store, or missing, is a 422 invalid_preferences, with the pointer of the list, rather than a 404.
  • normalize_params leaves preferences alone. It decoded every *_ids value inside nested hashes, which would have turned valid prefixed ids into integers before the schema saw them.
  • Old preferred_* keys are still accepted on write for one release (found in review), with a deprecation warning, on the store, channel and import endpoints; responses use only the plain names. Without it a 5.x client's change was silently dropped with a 200. preferred_auto_capture and preferred_auto_capture_on_dispatch stay accepted until 6.1, as already promised.
  • Deprecated preferences stay writable until their removal (found in review). They are in the schema with deprecated: true, so a write is accepted with the existing deprecation warning; forms and reads leave them out.
  • The old delivery-method calculator parameters are bridged too (found in review): calculator_type and calculator_preferences are still accepted on write until 6.1, with a deprecation warning.
  • An id list declared without of: still has its prefixed ids decoded in 6.0, as the API did for every *_ids key before, so an extension that has not completed its declarations keeps working until 6.1.
  • A calculator is attached only after its settings are accepted (found in review). On a saved delivery method, assigning a new calculator replaces the stored one at once, so a refused update used to leave a free rate behind.
  • /payment_methods/types lists every provider, with installed. An installed provider's edit form reads its schema from that list now that rows no longer carry one, so the list may not leave it out; pickers filter on installed. Reading it needs read access, not create.
  • A failure inside a nested payload names its row: /rules/1/preferences/channel_ids/0, /actions/0/calculator/preferences/amount, /calculator/preferences/amount.
  • Values stored before the declarations were typed read back in the declared form, so a delivery method saved with numeric amounts can be re-saved unchanged.
  • Validation errors on an exposed setting use its plain name. A model validates preferred_<name>; the API reports the error as <name>.
  • preference_attributes Model, :name, … in serializers types each exposed setting from its declaration, so the generated SDK types follow the model. Store decimal settings are now exact strings.
  • Money is the money plan's :money type, not a money: option (settled 2026-10-09 when rebasing onto the money changes): preference :amount, :money compiles to format: money, and reads keep that plan's formatting in the calculator's currency.
  • Calculators are typed in the SDKs' generated resource types (decided 2026-10-09 with the author): calculator is TypedDeliveryCalculator | null and TypedPromotionCalculator | null, generated through the serializers' type hints. Each settings shape is emitted as a type rather than an interface, so it stays assignable to the Record<string, unknown> that generic forms take.
  • Aligned with Rails 8.2's has_json where it costs little (decided 2026-10-09 with the author). Storage is already the same flat JSON object; strings, integers and booleans now cast through ActiveModel::Type, as has_json does; and exposes_preferences defines the reader, writer and ? predicate has_delegated_json would. No migration to has_json is planned: it covers only those three types, with no decimals, lists, secrets, nullability or published schema.
  • ItemTotal's operator_min/operator_max declare no choices: yet. Their defaults are >/< while the code compares against gt/gte; fixing that needs a data upgrade for stored rules and is left for a follow-up.

Design Details

Declaration additions

preference :amount_min,    :money
preference :channel_ids,   :array, of: :id, model: 'Spree::Channel', scope: ->(rule) { rule.store.channels }, default: []
preference :country_codes, :array, of: :string, format: :iso_country, default: []
preference :match_policy,  :string, choices: %w[any all none], default: 'any'
preference :amounts,       :hash, keys: :currency, values: :money, default: {}
preference :tiers,         :array, of: :object, properties: { threshold: :money, value: :decimal }, default: []
preference :secret_key,    :password

parse_on_set stays available for normalization a schema cannot express. It may not change the type, and the generator ignores it.

Generator

Spree::PreferenceSchema::JsonSchema.for(klass) compiles a class's declarations (deprecated and internal preferences excluded, as today) into a JSON Schema object with additionalProperties: false. It is memoized per class, like preference_schema. It is used by:

  1. The OpenAPI components. swagger_helper registers one component per built-in subtype (PromotionRuleItemTotal) and one union per family (PromotionRule), so rswag emits them. The specs stay generated; nothing in docs/api-reference/*.yaml is edited by hand.
  2. Typelizer. Serializers type preferences per family with the union name. The generated TypeScript and Zod schemas follow through the existing pipeline.
  3. The /…/types endpoints. These return schema for every registered subtype.
  4. Write validation. In the shared Admin and Seller resource controller, for every controller that permits preferences.

Conformance spec

One spec walks every registered subtype in every family:

  • The schema compiles.
  • A record built from its factory serializes preferences that validate against the schema.
  • Defaults validate.
  • Each declared ID list rejects a foreign prefix.
  • Each secret round-trips masked, unchanged on mask, and cleared on null.
  • A key not in the schema returns 422.

This is the black-box check a second implementation must also pass.

Dashboard

The generic preference form (rule, action, calculator and integration editors) renders from schema instead of preference_schema. Widgets are chosen by format and x-spree-widget: currency select, country combobox, prefixed-ID resource picker, textarea, and masked secret input. Hand-written per-subtype forms keep working, and gain types from the unions.

Migration Path

PR A: declarations and generator (no wire change)

  1. Add of:, keys:/values:, money:, format:, model: and scope: to Preferable declarations. Complete every :array and :hash declaration in core and providers. Resolve the :any declarations.
  2. Replace the ID-decoding parse_on_set lambdas with of: :id, model:, scope:.
  3. Add PreferenceSchema::JsonSchema and a spec that fails for any registered subtype whose schema does not compile.

PR B: contract (breaking)

  1. Add OpenAPI components and family unions in swagger_helper; serializers type preferences with them; run the type generation pipeline.
  2. /…/types endpoints return schema; remove preference_schema from resource serializers.
  3. Add exposes_preferences; rename every preferred_* wire field (except preferred_stock_location_id) on read and write.
  4. Move delivery methods to the nested calculator shape.
  5. Update the dashboard's generic preference form and every reference to renamed fields; e2e coverage for one subtype per family.
  6. Docs: docs/developer/customization/model-preferences.mdx (new declaration options), the Admin API pages for each family, docs/developer/upgrades/5.6-to-6.0.mdx (rename table, removed preference_schema, calculator shape), docs/changelog.mdx, and an SDK changeset.

PR C: enforcement

  1. Validate preferences writes with json_schemer; 422 invalid_preferences with JSON pointers.
  2. Drop the normalize_params exception for preferences in Admin::PaymentMethodsController, since IDs are now decoded by schema.
  3. Add the conformance spec.

Verification per PR: pnpm test:changed, then pnpm test:rspec core and pnpm test:rspec api one at a time; pnpm typecheck and pnpm test for packages/sdk, packages/admin-sdk, packages/seller-sdk and packages/dashboard; dashboard e2e for the preference editors.

Constraints on Current Work

  • A new preference declares its full type: of: on arrays, keys:/values: on hashes, the :money type for money, choices: on fixed vocabularies, format: for currencies, countries and dates. Never :any.
  • An ID list is of: :id, model:, scope:, never a parse_on_set decoding lambda.
  • Never add a preferred_* attribute to a serializer or a permitted-params list. Expose the setting under its plain name through the model.
  • Never add preference_schema to a new serializer. Subtype schemas belong to the family's /…/types endpoint.
  • A new configurable family publishes a /…/types endpoint and a typed union, with the fallback member, from day one.
  • A new calculator-bearing resource uses calculator: { type, preferences }.

Open Questions

None. The three questions raised during design were settled on 2026-10-09 (see Key Decisions): the only name collision is storefront_url; exposes_preferences leaves seller permissions alone; incomplete plugin declarations warn in 6.0.

References

  • docs/plans/6.0-json-preferences.md: storage, decimals as strings, tiers as a list, encrypted secrets
  • docs/plans/6.0-money-correctness.md: money and rate string formats used by format: money and :decimal
  • spree/spree#14837: Ruby class names replaced with short names; the precedent for this change
  • spree/core/app/models/concerns/spree/preference_schema.rb, spree/core/lib/spree/core/preferences/masking.rb
  • CLAUDE.md, "Typed values" and "Read and write attribute names must match"