Repository navigation
feat: relations, and reference fields as entry pickers - #1928
Conversation
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
`handleContentCreate`/`handleContentUpdate` already accept a `references` body key, but the zod schemas didn't list it, so `parseBody` silently stripped it before it reached the handler.
Creating a reference field now creates its backing relation def transactionally, updating the field's label PATCHes the relation's childLabel, and deleting the field deletes the relation and its edges. The admin no longer has to orchestrate these multi-step writes itself. Also fixes withTransaction to short-circuit when already inside a transaction (db.isTransaction), rather than attempting an illegal nested .transaction() call — required for the field-create/update/ delete handlers to nest their relation writes with SchemaRegistry's own internally-transacted field writes. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Type STORAGELESS_FIELD_TYPES as ReadonlySet<string> so membership checks against DB-sourced field types need no cast, resolving the lint diagnostic introduced with stripStoragelessDataKeys. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Reference fields are storage-less, so a seed defining one now creates the backing relation (like the schema handler) and writes a $ref value in the field's data as a content-reference edge instead of a table column. Previously applySeed threw "no such column" for any seed using a reference field. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- resolveEntries now attaches a display `title` (entry `title`, then `name`, else null) to every EntryRef, so picked entries and backlinks show a readable label instead of a slug; hydrated through content GET and the admin editor/backlinks sidebar. - Wire the relation and reference-edge API routes into injectCoreRoutes; they existed but were never registered, so /_emdash/api/relations 404'd and the "Referenced by" panel silently hid itself. - Preserve `targetCollection` and `multiple` on reference field validation so the create handler no longer rejects the field for a missing target. - Backlinks sidebar resolves relations by translation_group, not name. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
# Conflicts: # packages/core/src/api/handlers/content.ts
🦋 Changeset detectedLatest commit: 97d0eae The changes in this PR will be included in the next version bump. This PR includes changesets to release 12 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Scope checkThis PR changes 3,014 lines across 34 files. Large PRs are harder to review and more likely to be closed without review. If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs. See CONTRIBUTING.md for contribution guidelines. |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-test
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-loader
@emdash-cms/registry-moderation
@emdash-cms/registry-verification
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
# Conflicts: # packages/admin/src/components/ContentEditor.tsx # packages/admin/src/router.tsx
The legacy reference backfill sent one INSERT per edge, and a rerun after an interruption resent every edge, so a field too large for one Worker invocation's subrequest budget failed at the same point on every boot. Edges are now written sixteen to a statement, within D1's bind-parameter ceiling, and a rerun reads the edges its relation already has and sends only the missing ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…route A merge from main reintroduced routes the branch already registers under its own headings (relations, relations/[id], and the reference children/ parents edge routes), plus a registration for api/relations/[id]/translations.ts, a route file this branch deleted. The dead registration broke astro build with an ENOENT on translations.mjs and the duplicates tripped Astro's route-collision warning. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Tested Found one restore gap: publish an original block with references The initial revision has no |
Renumber the branch's relation migrations to 085/086 after main's 083_block_types and 084_site_transfer. Seeds apply relations, then block types, then collections; seeded content is blocks-normalized before reference values are split into edges. Site transfer still targets the pre-085 relations schema; its tests fail until it is updated in a follow-up. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Renumber this branch's migrations to 086_relations_structural and 087_reference_field_relations, after main's 085_taxonomy_def_groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FieldEditor fetched both lists whenever it mounted, whatever the field type. Enable the queries only while the dialog is open on a reference field, as the block-types query already does for blocks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…2153/emdash into feat/reference-field-admin-ui
|
@saariuslystoned Good catch. Fixed with regression tests. |
The relations API no longer exposes GET /_emdash/api/relations/:id/translations, so the injected-routes spec expected a JSON 404 from a route that is not registered and received Astro's HTML 404 instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
What does this PR do?
Adds relations as first-class schema objects, and turns
referencefields into entry pickers that link through them — core storage, the site query API, generated types, seeds and export, two migrations, and the admin surface for all of it.A relation joins two collections under a site-unique slug, with a label for each side and an optional limit on how many entries each side may link. A reference field binds to a relation and views its links from one end, so one relation can back a field on either collection. Links live in
_emdash_content_referenceskeyed by translation group, not in a column on the collection table, so a selection is shared across an entry's translations.Feature Discussion: #386
Closes #2403
Core (
emdash)Schema.
_emdash_relationsbecomes one row per relation keyed by a uniqueslug(migration083_relations_structural, replacing the per-locale rows migration 043 created), and_emdash_content_references.relation_groupbecomesrelation_id. Relation IDs are preserved, so existing links stay valid. A relation carries a label and an optional singular form for each role, plus a per-side limit. Deleting a reference field no longer deletes its relation unless the caller passesdeleteRelation=true; deleting a collection removes every relation it is an end of, along with the fields on the far collection that view them. Reading a relation reports what deleting it would take: the fields bound to it and how many links it holds.Storage. A bound reference field adds no column.
SchemaRegistryskips the DDL for it,createContentTableapplies the same guard for seeded fields, and a selection is written as edges in the same transaction as the entry.relationsjoins the reserved collection slugs, since the admin serves its screen at that path.Writes. Entry create and update bodies carry
references, keyed by field slug. Required and selection-limit constraints are enforced on both ends of the relation, so a field on the parent side that would hand a selected entry more parents than the relation allows is refused, not only one that selects too many children itself. Large replacements are chunked for D1's bind-parameter limit.Drafts. On a collection that keeps revisions, a selection changed on a published entry is staged in the draft and becomes live when the entry is published — through the publish action, a scheduled publish, or a revision restore — and is discarded with the draft. Publishing re-checks the whole selection against the relation's limits, so a draft cannot carry a selection past a schema change that would now reject it. Revision compare reports
_referenceson both sides, filled in from the published selection for the fields a draft did not stage, so an unchanged reference field does not read as one the draft removed.Reads.
getEmDashEntrytakes areferencesoption naming the fields a page renders;getEmDashReferenceswalks past the first page with the cursor it returned. Both default to 50 entries per field and accept at most 100. A referenced entry is a mappedContentEntrywith a workingeditproxy scoped to itself; bylines and taxonomy terms are not hydrated onto them. The reads go into the entry's cached snapshot, and the returnedcacheHintnames the referenced rows, so a route-cached page expires when a referenced entry changes and not only when the entry itself does.Types. A collection with a bound reference field gets a
{Collection}Referencesinterface, andgetEmDashEntrynarrows its result to the fields the call named. Type-level assertions run under a newvitest.types.config.ts/tsconfig.typecheck.json.Seeds. A top-level
relationsarray,validation.relation(andvalidation.relationSidefor a self-relation) on a reference field, and$ref:links applied from the parent end. Re-applying a seed that names atargetCollectionfor a field that predates relations binds that field.export-seedemits relations, and--with-contentemits each entry's links as$ref:values.Upgrade. Migration
084_reference_field_relationsbinds each reference field that named a target collection inoptions.collectionand copies the entry IDs in its column in as links, so those fields become working pickers with their selections intact. It skips a field with no resolvable target, one marked searchable or indexed, one whose relation slug{collection}_{field}is already taken, and one whose locale rows disagree about what they select. A skipped field keeps its column and behaves exactly as it did, and can be bound by hand under Content Types. The column is never dropped.The relation routes and the reference-edge reads are wired into
injectCoreRoutes;/relations/[id]/translationsis removed with the per-locale rows. Links are written only with the entry that holds them, so a selection cannot bypass staging.Admin (
@emdash-cms/admin)Performance
Two fixture routes measure the cost of the read path. Loading an author and six related posts on
/relatedis 9 queries against 6 for/related-baseline, the same page without references: one reference-field-map read (request-cached, and in the schema object-cache namespace), one link read per field, and one entry read per distinct target collection — not one per entry. A page that asks for no references runs none of those. The D1 snapshot shows the same delta (25 cold / 13 warm against 22 / 10). Both are recorded inscripts/query-counts.snapshot.{sqlite,d1}.json.Documentation
New:
guides/relations, the task path from defining a relation to reading its links, including picking entries, seeing what links to one, deletion, and binding a field that has no relation. Sidebar entry after Taxonomies.Updated:
deployment/updating(an upgrade entry for what the update binds, what it leaves unbound, and how to bind those by hand),reference/rest-api(thereferenceswrite and read surface; relation and edge routes restated as internal; the section that no longer covers relations renamed),reference/field-types(all four reference validation keys and both ways to declare the field),themes/seed-files(therelationsarray; the field forms now link tofield-typesrather than restating them),guides/querying-content(reading and paginating references, preview behavior, generated types),reference/api(ReferencePage,getEmDashReferences),concepts/collections,guides/internationalization(a selection is shared across translations rather than synced), and thebuilding-emdash-siteskill references. Both changesets now link the guide and the upgrade note.Type of change
Checklist
pnpm typecheckpassespnpm lintpasses (lint:jsonreports 0 diagnostics)pnpm testpasses — see the output belowpnpm formathas been runmessages.pochanges includedemdash: minor,@emdash-cms/admin: minor)AI-generated code disclosure
Screenshots / test output
https://youtu.be/Vt9FhTgPFyI
The two core failures are
tests/integration/database/media-usage-projection-admission-measurement.test.tsandtests/unit/components/inline-portable-text-code-block.test.ts. Neither file is touched by this branch, and both pass when run on their own; they fail only under full-suite concurrency on my machine.pnpm build,pnpm typecheckandpnpm lint:json(0 diagnostics) are clean.The full admin suite runs under Vitest browser mode, which drops its websocket partway through on this machine, so the numbers above are the suites this PR touches rather than the whole package.
Note for reviewers
This PR is large (about 15,800 added lines across 119 files) because relations, the reference field, and the admin surface for both only make sense together: a field with no relation has nothing to point at, and a relation with no field has nothing to edit it. The maintainers agreed to review it as one change rather than a stack.
🤖 Generated with Claude Code
https://claude.ai/code/session_01BCzkfnJcdsiPK8AbbBFw3w