🤖 Written together with Claude (Fable 5.2), directed, reworked and checked by me.

Motivation

Drupal describes its data in many different ways. Config has config schema, entities and fields have typed data definitions, components have JSON Schema, tools have PHP attributes, and the validation rules live in constraint plugins. As Dries puts it in One description, inside and outside Drupal, the goal is "for Drupal's own systems and software outside Drupal to work from shared descriptions of data and operations".

What we do at the moment is generating JSON Schema from typed data at the edges: in the serialization module, in Tool API, for JSON:API. That works, but it stays a lossy export. So just the JSON Schema export we do right now is not enough:

  • The format we export to has to be a shared one. We want config schema and component schemas to be aligned as well. So we need to make sure that whatever format we export to is that format, and not just what each export happens to emit.
  • We need to know the expressiveness we need. The format has to allow for all our use-cases, so we have to define it upfront and clarify how we express things. Plain JSON Schema does not cover all of it, see below.

The long-term goal is for all of it to provide the same schema. For that we first need to define this "goal schema", and then convert the existing ones towards it, by gradually evolving the existing APIs in the same direction.

So I'd propose:

  • Let's unify the varying ways to provide metadata/schema for data in Drupal.
  • Let's use JSON Schema for it as much as possible. It is the industry standard, people know it, and validators, editors, API tooling and LLMs speak it already.
  • Where plain JSON Schema is not enough for us, let's extend it the way the standard is built to be extended: with a dialect. JSON Schema 2020-12 has dialects and vocabularies for exactly that, and OpenAPI 3.1 defines its own dialect the same way.
  • Let's come up with a dialect that fits our use-cases. Every schema stays valid JSON Schema, so generic tools keep working with the standard part.

Why now

Config schema, component schema, typed data and tool schemas were built as separate systems, but the same data moves through all of them now. Canvas fills component props from entity fields and stores the component inputs in config. A tool takes an input and writes it into a field or a config object. An agent reads a tool's schema and ends up writing content or config. So the schemas have to work together: a value described in one of them has to be understood and validated the same way by the others.

Today every crossing has its own converter: Canvas matches prop shapes to field types, Tool API maps typed data to JSON Schema, core maps config schema to typed data. Each one is lossy, and every new consumer adds more of them. This is what Dries describes in One description, inside and outside Drupal and Drupal's role in agentic workflows: describe data once, and let Drupal's own systems and software outside of Drupal work from it.

Where we describe data today

Each use-case, and how it relates to typed data:

  • Entities and fields. Typed data directly: field definitions and their property definitions. It is complete, but computed in PHP per site (bundles, field config, alter hooks), so nothing outside of PHP can see it. JSON:API & co. have to generate their own schema from it.
  • Config schema. Its own YAML language, mapped to typed data: every config schema type becomes a typed data definition at runtime. It had to invent what typed data is missing: types defined as data, and dynamic types like block.settings.[%parent.plugin]. Only Drupal can read it.
  • Validation constraints. Symfony constraints as plugins, attached to typed data definitions. The rules are code, so they cannot be used outside of Drupal.
  • Components (SDC, Canvas). JSON Schema for props, no typed data at all. That shows JSON Schema works well for us, but it is an island: there are no types shared with fields (#3352063), so Canvas has to match prop shapes to field types.
  • Plugin contexts and tools (conditions, blocks, ECA, Tool API). Typed data definitions again. Same as for fields: only at runtime, only in PHP. Tool API declares inputs and outputs with PHP attributes, turns them into typed data and from there into JSON Schema; the mapping of constraints to JSON Schema lives in contrib.

So we have three languages (typed data, config schema, JSON Schema), no good way to convert between them, and typed data and config schema are not useful outside of Drupal.

Adopting JSON Schema

JSON Schema covers most of it out of the box: structure, types, labels, descriptions, defaults, the common constraints. What our use-cases need on top:

  • Dynamic types: the schema of a value depends on another value, e.g. plugin settings by plugin ID. Config schema has that, JSON Schema does not.
  • Site facts: "this plugin exists", "this bundle exists". Values that are checked against what a site has installed. The standard can express them as allowed values, we want to standardize how we handle them.
  • Server-side checks: unique values, valid references, access. A client cannot run them, but it should know that they exist or have a way to optionally run them (e.g. via a callback).
  • The same verdict everywhere: the standard leaves some choices open (e.g. whether format is validated). PHP and JS have to agree, else client-side validation is not worth much.
  • Drupal metadata: translatability and the like, as annotations.

Fortunately JSON Schema has a way to extend it built in: dialects. So we can use a dialect for the missing parts, and we can always export a reduced JSON Schema without our additions if desired. A generic validator may then accept more than ours.

The dialect should stay small: the more we can express with standard keywords, the more existing tools understand our schemas without knowing about Drupal. Where the standard is missing something, we adopt what is common elsewhere (e.g. in OpenAPI) or already part of a JSON Schema draft, before inventing our own keywords.

The proposed architecture

I'd propose a JSON Schema dialect, which is defined in a way that it works well inside and outside of Drupal. For our use that means it has to work consistently at least across PHP (backend) and JS (frontend, agents): the same schema and the same data give the same verdict and the same errors in both.

The schema has two jobs:

  • Describe what the data looks like. Structure, types, labels and allowed values: what a form, a component or an agent needs to read data and to build a UI for it.
  • Validate whether data can be written. Whoever writes data, a form, an API client or an agent, checks it against the schema before sending it and gets the same result as on the server. So the validation rules are part of the schema, and what only the server can check (unique values, references, access) is at least named. When validation passes, one can be pretty much sure that Drupal accepts the data. The server always has the final say, and ideally validates with the same schema again.

The schema is pure data. In our use-cases we must be able to express a schema in JSON or YAML, import it and run it, without losing anything. Component metadata needs exactly that, and it would also allow defining config schema natively in the new format. So the data form is the reference: a builder in PHP is a convenient way to write it. Whatever a builder produces has to round-trip through JSON.

However, plain JSON Schema does not guarantee consistency. The standard leaves choices open, and validators differ in formats, regular expressions and numbers. So the dialect is not only about adding keywords, it also has to pin down the standard part.

The dialect itself is actually generic and has no Drupal dependency. Drupal generates its schemas and types for it, like any other system could. That is what makes the schemas useful for a JS component or an agent that has no Drupal around.

It consists of:

  • A profile of JSON Schema 2020-12. The standard keywords we allow, with fixed rules where the spec leaves a choice, so PHP and JS agree:
    • format is validated, and every allowed format has one pinned check (e.g. email, date-time, uri);
    • pattern uses a regex subset that behaves the same in PCRE and in JS;
    • integers stay in the range JS can represent;
    • unknown keywords are an error, so a typo does not silently validate nothing.
  • A small vocabulary on top, for what the standard cannot express:
    • dynamic types: the schema of a value is selected by another value, e.g. plugin settings by plugin ID;
    • named checks: validation that needs code or the site's data, like unique values or valid references. The schema names the check and the server runs it. A client can ask the server for the result, and where it cannot, it knows the value is unchecked.
    • annotations for metadata like translatability.
  • A shared type library. Generic types with stable IDs, like email, label, text, uri, image or link. Config, fields, component props and tool inputs reference the same types via $ref. Drupal's own types (config types, field types, plugin settings) are generated by Drupal in its own namespace.
  • Catalogs for site facts. The plugins, bundles or languages a site has, as plain JSON Schema (enum, or oneOf with const and title for labeled values). They can be read live or from an export of the site's schemas, so an agent can validate config without a running site.
  • Conformance fixtures. Language-neutral test cases: schema, data, expected result. The spec plus the fixtures define what is correct, not one of the implementations. That is how the consistency is enforced, and it keeps the door open for more languages.
  • Reference validators in PHP and JS, which both pass the fixtures. The result is data: one error per problem, with a location, a stable code and parameters. Messages are generated from that, with one shared, translatable message catalog.

Every schema of the dialect stays valid JSON Schema. A generic validator ignores the added keywords and still checks the structure, and for consumers that only take the standard (e.g. LLM tool definitions) we export plain JSON Schema.

What this architecture enables

  • One validation everywhere. The server, the browser and agents run the same rules and get the same errors. Client-side validation does not have to repeat the rules by hand any more. For what only the server knows, like valid references, the schema names the check, so it is easy for a client to ask the server.
  • Forms generated from the schema. Forms can be generated based on the schema, with labels, limits and allowed values read from it. Once that is done on the PHP side (Form API), it can be done in JS as well, so swapping a PHP form for a JS one becomes easy. Modules like Canvas need that today.
  • UIs generated server- or client-side. Deciding which component to use to render some data can happen directly in JS or in PHP, the same as with the form. This enables us to generate UIs client-side, and paves the way for generative UI for Drupal to work nicely and to take advantage of Drupal's components.
  • Agents that write valid config and content. An agent knows what a config object or an entity needs, including plugin-specific settings, and validates locally before sending. With an export of the site's schemas that works without a running site.
  • Tools, entities, config and components share types. The output of a tool goes into a field, a field value into a component prop, with far less mapping code. Canvas does not have to match prop shapes to field types.
  • Entity and config APIs with full schemas. JSON:API or a similar API serves complete schemas, constraints included. Clients get typed APIs, OpenAPI documents and TypeScript types from the same source.
  • Static checks in CI or IDEs. Config and recipes can be checked against the schemas before a deployment, and text editors that know JSON Schema can validate and autocomplete while typing.
  • Useful outside of Drupal as well. The schema language, the validators and JS UI components do not need Drupal. They become useful outside and can be used for building small apps, e.g. static sites. If such an app needs more later, e.g. Drupal's workflows and permissions, you can easily make Drupal run it.

On top of the schema: data surfaces

The schema itself only describes and validates data. Generating forms, tools or API endpoints from it is a layer on top. Data surfaces by michaellander propose that layer: #3622144: Data surfaces: a definition layer between Form API and storage. The Surface API docs show how forms, Tool API tools and HTTP endpoints run on top of it.

Portable Schema: a draft spec with validators in PHP and JS

To see whether this architecture holds, I've been prototyping it as "Portable Schema": fago/portable-schema. It is a draft spec for such a dialect, with validators in PHP and JS as a proof of how it would work. It's a prototype and not ready yet.

What is there:

  • The spec: the profile, the added keywords and a type library.
  • Validators in PHP and JS (TypeScript), built on existing JSON Schema libraries. Both pass the same fixtures with identical results.
  • Four Drupal showcases, validated in both languages:
    • config with dynamic types: block config and the component config of Canvas;
    • an entity with fields: the article node, generated from its typed data definitions;
    • an agent tool, with its input schema exported as plain JSON Schema;
    • an SDC component whose props use the shared types.

Why not just typed data?

Typed data cannot be used outside of Drupal

Typed data was meant to do exactly that: one generic way to describe data in Drupal which everything else builds upon. For fields, config and plugin contexts that almost worked out. But I think it has one shortcoming which keeps it from being the shared description we need now: definitions and types live in PHP, so nothing outside of the Drupal runtime can read them.

Data definitions are objects of classes, with behaviour in code: properties are computed, definitions get altered and depend on the site. Types are plugin classes, and allowed values come from options providers: PHP code that computes them at runtime. So typed data depends directly on the Drupal runtime and cannot be handed over as it is. The consequences:

  • No schema for agents, JS components or other systems. Agents and other systems have no way to talk with Drupal in its native typed data language, and UI components have no way to reuse it. We can export, but we cannot work with external definitions, like the schemas of UI components.
  • Every type needs a PHP class. A type cannot be defined as data, e.g. as a refinement or a composition of existing types. It must define a PHP class as well.
  • Config schema and SDC each built their own type language. Config schema defines its types in YAML on top of typed data, SDC went with JSON Schema right away. Both did so to work around these shortcomings.

So anything outside of the Drupal runtime has to work with the JSON Schema export. Today that export is lossy; the work in progress in #3635315: [Prototype] Write a setting's rules once, in config schema, and use them for validation, forms and the published JSON Schema adds the constraints. In effect that export, and not typed data, becomes the universal schema language. Typed data then is an extra thing developers and agents have to know for defining data, while what they want is the universal JSON Schema.

Why not evolve typed data into a builder for JSON Schema?

We can evolve typed data to enforce a good export. But we also need the import: taking a schema from outside, e.g. as defined by a UI component, and using it without losing anything. Typed data definitions cannot hold that: a definition declares the structure of a value, and constraints only validate it. In a schema the structure is part of the rules, so alternatives and conditions can bring their own structure as well. Because of that we need to keep the two separate, with a clean builder that maps 1:1 to the schema.

What of typed data stays, and what goes

  • Data definitions go. They describe the data. In the end the schema does that.
  • Typed data objects stay. They give access to the data at runtime, like $entity->get('title').

Next steps for Drupal: A proposal

Phase 0: groundwork

  • We define the format: the dialect, its types and the expressiveness our use-cases need. This is needed for phase 1 later.
  • The work on this has already started. With the Portable Schema and data surfaces prototypes we are working on this.

Phase 1: short-term

  • We adopt the current "export to JSON Schema" approach of typed data, but steer it to an upfront defined JSON Schema dialect.
  • We do the same for config schema, mapping it to JSON Schema directly rather than through typed data, so that features like dynamic types are preserved and the resulting format is aligned.
  • Component schemas are JSON Schema already, in older drafts. Those we gradually evolve towards the dialect and extend to express more.
  • Optionally, a JSON Schema builder for the dialect could be added to core, so we can adopt it natively already now for things like tool input and output definitions. They'd use the builder directly instead of typed data, to allow outside use and save the translation step. That also gives the best parity in validation logic.
  • Where needed, we make typed data, config schema and component schema more expressive, in a way that they align with it and export to it better. Partially, this is already WIP with some issues of the Rosetta initiative, like #3627330: Validation constraints do not contribute to the JSON Schema and #3625989: NotNullConstraintValidator conflates "required" with "non-empty" for lists and complex data; only config schema is exempted.

Phase 2: long-term

We start adopting the dialect natively.

  • Native API use. We require schema-usage to work with it natively. That would mean we start validating based upon the JSON Schema, instead of typed data & Symfony constraints. We gradually improve the APIs, so that everything that uses a schema works with the dialect directly.
  • Native definitions. Once usage works with the schema, we can allow defining data in the dialect directly everywhere, with a JSON Schema builder, next to data definitions. Optionally, that includes config schema, which modules could then define natively in the new format.
  • Deprecations. Where the native way works, we start deprecating the old ways of defining things. That avoids useless and possibly lossy transformations.

Phase 3: last step

  • We remove data definitions. The schema or its builder is used to describe data instead, where applicable.
  • We keep typed data objects for the runtime. Code keeps accessing entities, fields and their values through them, the way it does today. They can leverage the schema where applicable, e.g. for generating forms.

Finally, what this all enables is the work on data surfaces, which does much more with the schema, already in phase 1: forms generated from the description of their data, the same description served as a Tool API tool and as an HTTP endpoint, all with the same validation and permission checks. See the Surface API docs.

Comments

fago created an issue.