diff --git a/.changeset/37112-view-holds-lists-only.md b/.changeset/37112-view-holds-lists-only.md new file mode 100644 index 00000000000..eb73ae4b1f9 --- /dev/null +++ b/.changeset/37112-view-holds-lists-only.md @@ -0,0 +1,54 @@ +--- +'@objectstack/spec': minor +'@objectstack/cli': minor +'@objectstack/lint': minor +'@objectstack/metadata-core': minor +'@objectstack/metadata-protocol': minor +'@objectstack/rest': minor +'@objectstack/runtime': minor +'@objectstack/plugin-auth': minor +'@object-ui/console': minor +'@object-ui/app-shell': minor +'@object-ui/core': minor +'@object-ui/types': minor +--- + +feat!: protocol 19 — a `view` holds lists only, and a form is its own `form` item (ADR-0159 D7) + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed +Skills-docs: `skills/objectstack-i18n/SKILL.md` sends a form's heading and thank-you panel to the `forms` group and drops `title` / `submitBehavior` from the `_views` row; `skills/objectstack-ui/rules/list-views.md` already teaches `forms:` and refuses a form inside a view + +**BREAKING — read this first: record New and Edit dialogs no longer read a form.** On protocol 19 a record's New and Edit dialogs lay out by the object's `fieldGroups` (and each field's `showOnCreate`), never by a form. A create or edit form that a view declared (the container's default `form`, `formViews.default`, `formViews.create`, an item marked `isDefault` or named `OBJECT.create`) stops applying: its sections, tabs, wizard steps, create defaults and form-level required rules no longer shape those dialogs, and nothing converts them into field groups. If your app relied on one, declare the object's `fieldGroups` (and `showOnCreate: false` on the fields a create should not ask for) before you upgrade. `os migrate meta --from 18` deletes such a form from your sources, and the upgrade command removes stored ones of that kind; its report carries each removed form's body and says, per object, whether the object declares field groups. A form that declares a public link (`sharing.publicLink`, switched on or off), one a `type: 'form'` action opens, and one that declares `overrides` is never deleted: it moves. + +**BREAKING — the three old form shapes are refused.** FROM a form authored inside a view TO a `form` item in the stack's `forms:`: + +| Old shape (protocol 18) | Protocol 19 | +|---|---| +| `defineView({ object, form: { … } })` | `defineForm({ name: 'OBJECT.form', object, … })` in `forms:` | +| `defineView({ object, formViews: { KEY: { … } } })` | `defineForm({ name: 'OBJECT.KEY', object, … })` in `forms:` | +| `defineViewItem({ name: 'OBJECT.KEY', viewKind: 'form', config: { … } })` | `defineForm({ name: 'OBJECT.KEY', object, … })`, the `config` body at the top level | +| `translation.objects.OBJECT._views.KEY.title` / `.submitBehavior` | `translation.forms['OBJECT.KEY'].title` / `.submitBehavior` | + +The one-line fix: run `os migrate meta --from 18 --write` and apply by hand the edits it lists but cannot prove. The form keeps the name it is served under, so a `type: 'form'` action and a public link keep reaching it. Each old shape is refused with that prescription at `os validate`, at `defineStack` and at the metadata save door: a `view` save that carries `form`, `formViews` or `viewKind: 'form'` answers `422 INVALID_METADATA`, located at that key, and writes nothing. For API callers this changes one error code: a `view` save that carried a form at a public link another form already holds used to answer `FORM_ADDRESS_TAKEN`; it now answers `422 INVALID_METADATA` for the shape, and `FORM_ADDRESS_TAKEN` is answered by `form` saves. `GetUiViewResponse` loses its `form` and `formViews` members the same way; `getUiView` for `type: 'form'` answers the form scaffold `{ object, form }`, typed `GetUiViewFormScaffold`. + +**What a `view` read serves.** A `view` list serves lists only: it drops the form members of a stored old-shape container, a stored `viewKind: 'form'` row answers no item by name, and a `form` read serves no form out of a stored old-shape row. The stored rows are neither refused nor rewritten by a read: a stored old-shape container is served by name as stored, and saving that body back through the `view` door is refused (`422`), so no stored state is lost. The Console follows: the list switcher, the Studio view editor and the view preview handle lists only (a view created in Studio is a list), and a form is edited as a `form` item. + +**Stored forms: convert, then switch.** A deployment's stored forms in an old shape move only through `os migrate protocol --to 19 --apply --yes`, all or nothing, after `os migrate protocol --to 19` (and `os migrate stored-forms`) previewed what moves and whether the deployment can switch (see *Check stored forms before the next major* in the deployment docs). On protocol 19, `os serve` (and so `os dev` and `os start`) refuses to start, with `FORM_TYPE_SWITCH_REQUIRED`, on a database an earlier release created until that command has recorded the switch; its refusal names the command. A database with no stored form runs it once too and finds nothing to move. A database the server creates from empty is recorded as switched at its first start. No variable or flag skips the refusal. A row that holds the switch is listed with the action for its cause, taken on the release you are running. + +**Withdrawn public forms stay closed.** A public form an administrator switched off before the upgrade stays switched off after it, and so does a form that one package ships over another package's object when its withdrawal is stored for that package. `os migrate organization-ownership --apply` carries an organization's public-form withdrawal onto the `form` item a package ships at protocol 19, saved into that package's writable pair when the package itself is not writable; a withdrawal it cannot carry blocks the step and nothing is opened. + +**Until the switch, a stored old-shape form is not served.** On protocol 19 a form held only in a stored old-shape row (a container's `form` / `formViews` member, or a `viewKind: 'form'` row) answers `404` on the `form` and `view` doors, whoever asks, until `os migrate protocol --to 19 --apply --yes` has moved it; once moved, it is served as a `form` item under the same name and link. This includes a pre-19 stored copy of a package's form saved open, which protocol 18 served at its link: on protocol 19 it opens nothing until the ceremony moves it, including on a host that assembles its own kernel without the boot guard. A withdrawal stored in such a row keeps its form closed before and after the move. + +**Fixes.** A form save into a package's writable pair no longer hangs on SQLite when legacy organization rows exist: the read of those rows joins the save's own transaction instead of waiting for a second connection. `os migrate packageless-overlays` now says that a view container it cannot move is deleted only after `os migrate protocol --to 19 --apply` has moved its form members. + +**Validators follow the `form` type.** The form rules now judge `form` saves and `forms:` items, not `view`: `validateFormLayout`, `validatePublicFormFileFields`, `validateThankYouRecordFields`, `validateVisibilityPredicates` and `validatePredicatePathRefs` list `form` where they listed `view`. A `form` save is now refused for a public form's file field (`public-form-file-field`), a thank-you panel's record field (`thank-you-record-field`) and the visibility-predicate family, and a `form` save and read carry the advisories `form-field-unknown` and `form-section-group-unknown`. A `view` save keeps `validateStackExpressions`, `validatePresetComparands` and `validateReferenceIntegrity`; `view-key-collision` judges list views only. `GET /api/v1/meta/form/NAME` serves a package's declared `.custom` override of a form, as the `form` list does. + +**Removed exports** (FROM → TO): + +- `@objectstack/spec` (`@objectstack/spec/ui`): the `formOverlay` member of `VIEW_METADATA_MEMBERS`, the `'formOverlay'` entry of `VIEW_METADATA_BRANCHES` and that value of the type `ViewMetadataBranch` → none; a flat `viewKind: 'form'` body is read by `VIEW_METADATA_MEMBERS.listOverlay`, whose `viewKind` answers the prescription above, and `selectViewMetadataBranch` names `'listOverlay'` for it. +- `@objectstack/lint`: `validateInternalFormViews`, `FORM_VIEW_INTERNAL_NOT_LOADED` and `InternalFormViewFinding` → none; the rule `form-view-internal-not-loaded` is retired, so the author-time rule count `os validate` prints drops by one. Its successor, the advisory `form-consumer-less`, reports a `form` item with no public link that no `type: 'form'` action opens. + +**New exports:** `@objectstack/spec` `ServedViewItem`, `expandServedViewContainer` and `isServedViewItem` (a container expanded to the list items a `view` read serves), `GetUiViewFormScaffold`, and the error code `FORM_TYPE_SWITCH_REQUIRED`; `@objectstack/runtime` `FormTypeSwitchBootGuardPlugin`, `FormTypeSwitchBirthMarkerPlugin`, `FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE`, `isFormTypeSwitchBootRefusal` and their companions. + + diff --git a/content/docs/concepts/architecture.mdx b/content/docs/concepts/architecture.mdx index 5ffb1e28176..8d21bd6ec04 100644 --- a/content/docs/concepts/architecture.mdx +++ b/content/docs/concepts/architecture.mdx @@ -230,8 +230,9 @@ Kernel **orchestrates** these rules at runtime, independent of the data structur // src/views/customer.view.ts import { defineView } from '@objectstack/spec'; -// A view is authored with defineView({ list, form }); the list/form configs -// are nested, and the data source declares which object the view reads. +// A view container holds lists only: the list config is nested under `list`, +// and the data source declares which object the view reads. A form is its +// own `form` item, named OBJECT.KEY (see the next example). export const CustomerView = defineView({ list: { type: 'grid', diff --git a/content/docs/concepts/metadata-lifecycle.mdx b/content/docs/concepts/metadata-lifecycle.mdx index 9f1279b920d..6993a37e3ae 100644 --- a/content/docs/concepts/metadata-lifecycle.mdx +++ b/content/docs/concepts/metadata-lifecycle.mdx @@ -190,7 +190,7 @@ document **whole** for every read that serves the base's name > **ADR-0131 D6 — the per-organization overlay axis is retired.** The `/meta` doors (REST and the runtime dispatcher) carry no organization into a metadata write or read: a Studio or `PUT /api/v1/meta/...` write of the five ✅ types below lands **environment-wide** (since ADR-0131 D7 the `sys_metadata` family declares no organization column) and is served to every organization, and an organization admin holding only the retired `manage_org_presentation` capability is refused (`403`). The protocol itself refuses every organization-scoped write, and every read — item, list, layers, cached, history, diff, audit, drafts and the commit timeline — is environment → code, whatever organization a caller names. An overlay row an earlier release stored under an organization — under the `single` posture, every Studio save of these types, filed under the Default Organization — is served by no read, and on a SQL database (SQLite, PostgreSQL, MySQL) still holding one a v18 `os serve` refuses to start until the v18 migration ceremony (ADR-0131 C7: `os migrate organization-ownership --out PLAN`, then `--apply --plan-file PLAN`) has carried such a row to the environment layer and dropped the column; nothing deletes or rewrites it before then. The anonymous form doors read the environment alone too: the ceremony carries every organization-layer public-form withdrawal onto the environment, fail-closed. The table still records which types take an overlay of a shipped item. -> **ADR-0146 D11 — the tier no longer opens a write door onto a packaged item.** A write naming no package — a save, a publish, a reset (`DELETE`) or a rollback — onto a ✅-type item that one installed read-only package ships is refused `403 NOT_OVERRIDABLE`, and the sentence names the base's pair: save it into `?package=.custom`, declaring `overrides` ([above](#customizing-an-installed-package-the-paired-custom-override-adr-0146)); for an item a kernel package (scope `system` or `cloud`) ships, the same write is refused with a sentence that names no pair, because kernel objects are not customizable in this version and a kernel package has no pair. A package-less row stored before the close is still served until `os migrate packageless-overlays` moves it into the pair as a declared override; the ✅ row is now the set that ceremony moves and the read path honours for an unmoved row. A package-less write of a name no package ships is environment metadata, and stays open. So does the package-less write of a view container (`list` and `listViews`, and the `form` / `formViews` members a row stored before protocol 19 still holds, which `os migrate protocol --to 19 --apply` moves to `form` rows): only a single view declares an override, so the ceremony lists the container and leaves it, and its views move into the pair one by one, each as a single view. +> **ADR-0146 D11 — the tier no longer opens a write door onto a packaged item.** A write naming no package — a save, a publish, a reset (`DELETE`) or a rollback — onto a ✅-type item that one installed read-only package ships is refused `403 NOT_OVERRIDABLE`, and the sentence names the base's pair: save it into `?package=.custom`, declaring `overrides` ([above](#customizing-an-installed-package-the-paired-custom-override-adr-0146)); for an item a kernel package (scope `system` or `cloud`) ships, the same write is refused with a sentence that names no pair, because kernel objects are not customizable in this version and a kernel package has no pair. A package-less row stored before the close is still served until `os migrate packageless-overlays` moves it into the pair as a declared override; the ✅ row is now the set that ceremony moves and the read path honours for an unmoved row. A package-less write of a name no package ships is environment metadata, and stays open. So does the package-less write of a view container (`list` and `listViews`; since protocol 19 a write that carries a `form` or `formViews` member is refused `422 INVALID_METADATA` with a prescription naming `forms:`, and the members a row stored before it still holds are moved to `form` rows by `os migrate protocol --to 19 --apply`): only a single view declares an override, so the ceremony lists the container and leaves it, and its views move into the pair one by one, each as a single view. | Type | `allowEnvironmentOverlay` | Rationale | | :--- | :---: | :--- | diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 9bf3d9de583..d31a621b793 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (90)... + → Running author-time rules (89)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... @@ -1562,8 +1562,8 @@ where the data lives. | `os migrate comment-parent-pair` | Stamp the parent pair (`object_name`, `record_id`) on the `sys_comment` rows written before it existed. Until it runs, a broad comment read past 2,000 candidate rows omits comments the reader may see, and its total agrees with the short list, so run it at once after upgrading. No flag; idempotent | | `os migrate meta --stored` | Replay the metadata conversion chain over this deployment's `sys_metadata` rows and rewrite the ones still carrying a pre-protocol shape. Hygiene, not a gate — nothing depends on it having run | | `os migrate security-catalog-overlays` | List the environment-wide permission-set and position rows (the legacy plurals `permissions` / `positions` included) stored over a name a configured package holds — the rows a v18 cold boot refuses — each with the package that holds its name; `--apply` deletes them, one history tombstone per row. Run it before the first v18 boot, with the flags and environment the deployment boots with: the platform security plugin's sets are held only where `os serve` composes it (an auth secret set, and the `auth` tier on), and the step takes `serve`'s `--preset` and `--dev` with `serve`'s meaning. Adopts nothing; exits 1 while it lists a row | -| `os migrate packageless-overlays` | List the package-less view, dashboard, report, translation and email-template rows stored over a name exactly one installed package ships — the customizations Setup saved before ADR-0146 D11 closed that write — and with `--apply` move each into that package's paired `.custom` (created when absent) as a declared override, `basedOn` the base's installed version; the package-less row is deleted only after the moved one reads back as served. A name no package ships is environment metadata and is not touched; a name several packages ship, or one the pair already holds a row of, is listed and left with the reason. So is a view container (`list`, `listViews`, `form`, `formViews`): only a single view declares an override, so it is listed `cannot_declare` and never attempted, with the way out — save each of its views into the pair as a single view, then delete the container row. Takes `serve`'s `--preset` and `--dev`. Idempotent: a second run moves nothing. Run it once after upgrading | -| `os migrate stored-forms` | Read-only: list what the upgrade to the next protocol major does with every stored row that still holds a form in an old shape (a view container's `form`, a `formViews` entry, a `viewKind: 'form'` item) — kept, moved, folded, removed as an internal record form, or left in place — and whether that upgrade can switch, naming each row that holds it (its `.custom` pair cannot be created, or its form content cannot be read) with the action for its cause, and listing the old-shape drafts that cannot be published after the upgrade. No `--apply`: the move runs only inside the upgrade command. Takes `serve`'s `--preset` and `--dev`. See [Check stored forms before the next major](/docs/deployment/stored-forms-upgrade) | +| `os migrate packageless-overlays` | List the package-less view, dashboard, report, translation and email-template rows stored over a name exactly one installed package ships — the customizations Setup saved before ADR-0146 D11 closed that write — and with `--apply` move each into that package's paired `.custom` (created when absent) as a declared override, `basedOn` the base's installed version; the package-less row is deleted only after the moved one reads back as served. A name no package ships is environment metadata and is not touched; a name several packages ship, or one the pair already holds a row of, is listed and left with the reason. So is a view container (`list` and `listViews`, and the `form` / `formViews` members a row stored before protocol 19 holds): only a single view declares an override, so it is listed `cannot_declare` and never attempted, with the way out — save each of its lists into the pair as a single view, then, once `os migrate protocol --to 19 --apply` has moved its form members, delete the container row. Takes `serve`'s `--preset` and `--dev`. Idempotent: a second run moves nothing. Run it once after upgrading | +| `os migrate stored-forms` | Read-only: list what the upgrade to protocol 19 does with every stored row that still holds a form in an old shape (a view container's `form`, a `formViews` entry, a `viewKind: 'form'` item) — kept, moved, folded, removed as an internal record form, or left in place — and whether that upgrade can switch, naming each row that holds it (its `.custom` pair cannot be created, or its form content cannot be read) with the action for its cause, and listing the old-shape drafts that cannot be published after the upgrade. No `--apply`: the move runs only inside the upgrade command. Takes `serve`'s `--preset` and `--dev`. See [Check stored forms before the next major](/docs/deployment/stored-forms-upgrade) | | `os migrate protocol --to 19` | The protocol-19 switch of one deployment. Previews by default: what the switch does with every stored form in an old shape, and whether it can switch, exiting `1` with each holding row and its action when it cannot. `--apply` moves the stored forms all or nothing, runs the check again, and only when nothing is left to move or remove records the switch as a verified `sys_migration` row (`adr-0159-form-type-switch`); a held run writes nothing. Refused on a database whose driver cannot roll back a transaction. Takes `serve`'s `--preset` and `--dev`, and `--json`. See [What the upgrade command writes](/docs/deployment/stored-forms-upgrade#what-the-upgrade-command-writes) | | `os migrate stored-references` | List the stored references the upgrade left naming no package because the one resolution rule (ADR-0150 D3) refuses them: a user's permission-set assignment, an audience-binding suggestion, a managed sharing rule, a queue membership, an open approval request, a paused flow run, a flow credential, a flow dispatch key, a connector connection, an assignment cursor or a legacy email template whose name more than one package holds, each with its row id and every candidate by its qualified address (`namespace/name`). A suggestion a package wrote naming an environment-authored permission set, or one held only outside the package's declared dependencies, is listed with the fix and is never bindable. Also lists the packaged fields whose picklist the rule refuses (served with no options) the names two packages held before the one-holder rule, and each installed package whose namespace spells a literal segment of the address grammar (`actions`, `connectors`, `global`, `hooks`, `oauth`, `runs`, `trigger`): the boot keeps it with one warning, its items are read with `?package=ID`, and only a rename of its namespace gives them qualified addresses at the door that reads the literal (for `runs` that door is the inbound hook alone, reached at its bare address until then). Read-only, and `--json` prints the same bytes on every run. Run before the release's first boot, it reads a table that has no package column yet as nothing bound yet, lists the rows that boot's backfill will leave unbound, and says so once; it adds no column. A table this composition does not carry (automation, approvals) is named, not skipped: compose as `os serve` does, with `--preset`/`--dev`. Then `os migrate stored-references bind --table T --id ID --package P` writes the package you chose into that one row: it asks the rule again first and refuses, writing nothing, when the row is already bound, now resolves on its own, or the package is no longer a candidate (a stale report), and refuses (`duplicate`) a bind the table's unique key refuses because a row bound to that package already holds the key, such as a connector connection the instance already has in that organization. Each bind leaves a `sys_audit_log` row; a second run writes nothing. Confirm with `--yes` | | `os migrate duplicates` | Report business identifiers already minted twice across the organization partitions, and the rows blocking the boot-time NULL-safe index tightenings — a read-only inventory as JSON on stdout. Renumbers nothing and writes no row and no schema; run it before the boot-time tenancy repair, which overwrites part of the evidence | diff --git a/content/docs/deployment/stored-forms-upgrade.mdx b/content/docs/deployment/stored-forms-upgrade.mdx index f98bc5de608..ede91d291c1 100644 --- a/content/docs/deployment/stored-forms-upgrade.mdx +++ b/content/docs/deployment/stored-forms-upgrade.mdx @@ -6,8 +6,9 @@ description: What `os migrate stored-forms` reports about the forms your databas A form used to be stored as a view: a view container's `form`, a `formViews` entry, or a view item with `viewKind: 'form'`. Forms are now their own -metadata type, and the next protocol major stops reading those three shapes. -Whatever your database still stores in them is moved by the major's upgrade +metadata type, and the next protocol major, 19, refuses those three shapes at +every write door (`422`, naming the stack's `forms:`) and serves no form from +them. Whatever your database still stores in them is moved by the major's upgrade command, in the same run that switches to the major. The move and the switch are all or nothing: if one stored row cannot be moved, the upgrade does not switch, and the deployment stays on the release it is running. @@ -142,8 +143,13 @@ After the transaction commits, the command runs the check once more. Only when that check finds the deployment can switch, with nothing left to move or remove, does it record the switch: a verified `sys_migration` row, `adr-0159-form-type-switch`. A run the check holds records nothing, that row -included. The row is the switch's record; no server start reads it in this -release. +included. The row is the switch's record, and a protocol-19 server reads it at +start: `os serve` (and so `os dev` and `os start`) refuses to start on a +database an earlier release created until the row is there and verified, and +its refusal names this command. A database with no stored form runs the +command once too: it finds nothing to move and records the switch. A database +the server creates from empty is given the record at its first start, since it +stores no form. ## Clearing a row that holds the upgrade @@ -155,7 +161,7 @@ release. | The package is a kernel package, which has no `.custom` package in this version | The platform maintainers | Report it before upgrading. | | Two rows would land in one slot of an app's `.custom` package, or one row that several packages serve would not be treated alike by all of them | No one, on this release | No exit from it was measured: the deployment stays on the release it is running, and every address keeps answering as it does today. Where the row is read at two packages of one app that would both move it, the app shipping the form from one of those packages only lets it be read at that package alone. Where the row waits on another hold of its own, it takes that hold's row above. | | Another package ships a `form` item under the form's name, so the row would be written over a managed package's item, which is sealed | The author of the package that ships it | No exit from it was measured: the deployment stays on the release it is running, and the row keeps working as it does today. | -| The stored view's form content cannot be read | The administrator | Save the view again with its form content repaired (a `form` or `formViews` entry that is an object), then run the check again. On the release you are running, both public doors answer for the row as they do today. On the next major its links close, and that server's start-up log names each such row and points to this command. | +| The stored view's form content cannot be read | The administrator | Save the view again with its form content repaired (a `form` or `formViews` entry that is an object), then run the check again. On the release you are running, both public doors answer for the row as they do today. The row holds the switch, and a protocol-19 server does not start on a database whose switch is not recorded, so the repair is made on the release you are running. | ## Also listed diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 39306d40c23..f279ec111e5 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -874,7 +874,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (90)... + → Running author-time rules (89)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 061957318f5..33154bdd32a 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -378,7 +378,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (90)... + → Running author-time rules (89)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index daa45afc79b..a24a4a0a575 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -24,7 +24,7 @@ failure direction below is discoverable from the key being written: |:---|:---|:---|:---| | standalone **ViewItem record** | a nested `config` | `ViewItemNameSchema` — `QUALIFIED_ITEM_NAME_PATTERN`, dot REQUIRED | **rejected**, located at `["name"]` | | flattened runtime **overlay** | an inline view config; no `config`, no container slot | `z.string().optional()` — no grammar at all | accepted | -| `defineView` **container** | a container slot (`list` / `form` / `listViews` / `formViews`) | `z.string().optional()` on `ViewSchema` — no grammar at all | accepted, and normally IS flat | +| `defineView` **container** | a container slot (`list` / `listViews`; a body that names the retired `form` / `formViews` is read as a container too, and refused with their prescription) | `z.string().optional()` on `ViewSchema` — no grammar at all | accepted, and normally IS flat | The two permissive rows are deliberate, not gaps left to tighten later: @@ -2114,9 +2114,9 @@ Tab configuration for multi-tab view interface | **label** | `string \| Record` | optional | Human-readable label shown in metadata lists. | | **object** | `string` | optional | Object this container binds to — how a stack-level `views: [...]` entry says which object its views belong to; read by `getViewsByObject()` / `GET /meta/view?object=`. | | **list** | `{ name?: string; label?: string \| Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }` | optional | | -| **form** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | optional | | +| **form** | `never` | optional | [REMOVED] `view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and a `view` holds lists only. Move the form to the stack's `forms:` as a `form` item named `OBJECT.form` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); a record's New and Edit dialogs lay out by the object's `fieldGroups` and read no form, so a create or edit form that nothing else opens is deleted, not moved. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047) | -| **formViews** | `Record; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }>` | optional | Additional named form views | +| **formViews** | `never` | optional | [REMOVED] `view.formViews` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and a `view` holds lists only. Move each entry to the stack's `forms:` as a `form` item named `OBJECT.KEY` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); the name stays the one it is served under, so a `type: 'form'` action and a public link keep reaching it. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -2178,34 +2178,6 @@ Tab configuration for multi-tab view interface | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | | **userFilters** | `{ element?: Enum<'dropdown' \| 'toggle'>; fields?: object[] }` | optional | | -### Nested Shape: `View.form` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - ### Nested Shape: `View.listViews[string]` | Property | Type | Required | Description | @@ -2258,34 +2230,6 @@ Tab configuration for multi-tab view interface | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | | **userFilters** | `{ element?: Enum<'dropdown' \| 'toggle'>; fields?: object[] }` | optional | | -### Nested Shape: `View.formViews[string]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - ### Nested Shape: `View.protection` | Property | Type | Required | Description | @@ -2503,7 +2447,7 @@ This schema accepts one of the following structures: | **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | | **overrides** | `{ package: string; basedOn: string }` | optional | Override declaration (ADR-0146 D2): `{ package, basedOn }` — this item of "``.custom" replaces the base package's same-named item whole. `basedOn` is recorded and never gates; a base's upgrade plan reads it only as advice. | -### Nested Shape: `ViewItem[viewKind='list'].config` +### Nested Shape: `ViewItem.config` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2555,7 +2499,7 @@ This schema accepts one of the following structures: | **emptyState** | `{ title?: string \| Record; message?: string \| Record; icon?: string; link?: object }` | optional | Empty state configuration when no records found | | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | -### Nested Shape: `ViewItem[viewKind='list'].protection` +### Nested Shape: `ViewItem.protection` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2563,78 +2507,7 @@ This schema accepts one of the following structures: | **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | | **docsUrl** | `string` | optional | Optional URL the Studio banner links to for more context. | -### Nested Shape: `ViewItem[viewKind='list'].overrides` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **package** | `string` | ✅ | The base package id whose same-named item this item replaces whole (e.g. "com.acme.crm"). Only an item of the base's paired "``.custom" package declares an override. | -| **basedOn** | `string` | ✅ | Recorded, never a gate: the base package's `manifest.version` this override was taken from (e.g. "3.2.0"), not a history version of the item. Nothing is refused, merged or rebased on it; it tells a person re-basing the override where it started. One reader, as advice: a base's upgrade plan lists an override whose `basedOn` is not the installed base version as stale, beside each override whose base item the upgrade changes (ADR-0146 D2, as amended). | - ---- - -#### Option 2 - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **viewKind** | `'form'` | ✅ | | -| **config** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | ✅ | Form view configuration. | -| **name** | `string` | ✅ | Globally-unique view id, `.`. | -| **object** | `string` | ✅ | Bound object name — the foreign key used to aggregate views. | -| **label** | `string \| Record` | optional | Display label (supports i18n). | -| **isDefault** | `boolean` | optional | Whether this is the object's default view in the switcher. | -| **order** | `integer` | optional | Sort order within the object's view switcher / left rail. | -| **scope** | `Enum<'package' \| 'shared'>` | optional | Identity layer (defaults to `package` for source-loaded views). | -| **owner** | `never` | optional | [REMOVED] `view.owner` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it named the user a `personal` view item belonged to, and nothing ever read it: the view switcher (`GET /meta/view?object=`) serves every item bound to the object without looking at `owner`, so a view marked as one user's was listed for every user who can read the object. Delete the key. Nothing restricts a view item to one user — personal named views are a user-owned record, not a view item (ADR-0017) — so a view item is visible to everyone who can read its object. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **hidden** | `never` | optional | [REMOVED] `view.hidden` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it promised to hide a view item from the switcher, and nothing ever read it: `GET /meta/view?object=` and the console's view switcher list every item bound to the object, `hidden: true` included. Delete the key; to take a view out of the switcher, delete the view item itself (or stop shipping it from source). Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | -| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | -| **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | -| **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | -| **_provenance** | `Enum<'package' \| 'org' \| 'env-forced' \| 'platform'>` | optional | Origin of the item (package \| org \| env-forced \| platform). | -| **_packageId** | `string` | optional | Owning package machine id. | -| **_packageVersion** | `string` | optional | Owning package version. | -| **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | -| **overrides** | `{ package: string; basedOn: string }` | optional | Override declaration (ADR-0146 D2): `{ package, basedOn }` — this item of "``.custom" replaces the base package's same-named item whole. `basedOn` is recorded and never gates; a base's upgrade plan reads it only as advice. | - -### Nested Shape: `ViewItem[viewKind='form'].config` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - -### Nested Shape: `ViewItem[viewKind='form'].protection` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | ✅ | Lock policy — none \| no-overlay \| no-delete \| full. | -| **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | -| **docsUrl** | `string` | optional | Optional URL the Studio banner links to for more context. | - -### Nested Shape: `ViewItem[viewKind='form'].overrides` +### Nested Shape: `ViewItem.overrides` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2692,7 +2565,7 @@ This schema accepts one of the following structures: | **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | -### Nested Shape: `ViewItemWire[viewKind='list'].config` +### Nested Shape: `ViewItemWire.config` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2744,83 +2617,7 @@ This schema accepts one of the following structures: | **emptyState** | `{ title?: string \| Record; message?: string \| Record; icon?: string; link?: object }` | optional | Empty state configuration when no records found | | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | -### Nested Shape: `ViewItemWire[viewKind='list'].protection` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | ✅ | Lock policy — none \| no-overlay \| no-delete \| full. | -| **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | -| **docsUrl** | `string` | optional | Optional URL the Studio banner links to for more context. | - -### Nested Shape: `ViewItemWire[viewKind='list'].overrides` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **package** | `string` | ✅ | The base package id whose same-named item this item replaces whole (e.g. "com.acme.crm"). Only an item of the base's paired "``.custom" package declares an override. | -| **basedOn** | `string` | ✅ | Recorded, never a gate: the base package's `manifest.version` this override was taken from (e.g. "3.2.0"), not a history version of the item. Nothing is refused, merged or rebased on it; it tells a person re-basing the override where it started. One reader, as advice: a base's upgrade plan lists an override whose `basedOn` is not the installed base version as stale, beside each override whose base item the upgrade changes (ADR-0146 D2, as amended). | - ---- - -#### Option 2 - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **viewKind** | `'form'` | ✅ | | -| **config** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | ✅ | Form view configuration. | -| **name** | `string` | ✅ | Globally-unique view id, `.`. | -| **object** | `string` | ✅ | Bound object name — the foreign key used to aggregate views. | -| **label** | `string \| Record` | optional | Display label (supports i18n). | -| **isDefault** | `boolean` | optional | Whether this is the object's default view in the switcher. | -| **order** | `integer` | optional | Sort order within the object's view switcher / left rail. | -| **scope** | `Enum<'package' \| 'shared'>` | optional | Identity layer (defaults to `package` for source-loaded views). | -| **owner** | `never` | optional | [REMOVED] `view.owner` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it named the user a `personal` view item belonged to, and nothing ever read it: the view switcher (`GET /meta/view?object=`) serves every item bound to the object without looking at `owner`, so a view marked as one user's was listed for every user who can read the object. Delete the key. Nothing restricts a view item to one user — personal named views are a user-owned record, not a view item (ADR-0017) — so a view item is visible to everyone who can read its object. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **hidden** | `never` | optional | [REMOVED] `view.hidden` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it promised to hide a view item from the switcher, and nothing ever read it: `GET /meta/view?object=` and the console's view switcher list every item bound to the object, `hidden: true` included. Delete the key; to take a view out of the switcher, delete the view item itself (or stop shipping it from source). Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | -| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | -| **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | -| **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | -| **_provenance** | `Enum<'package' \| 'org' \| 'env-forced' \| 'platform'>` | optional | Origin of the item (package \| org \| env-forced \| platform). | -| **_packageId** | `string` | optional | Owning package machine id. | -| **_packageVersion** | `string` | optional | Owning package version. | -| **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | -| **overrides** | `{ package: string; basedOn: string }` | optional | Override declaration (ADR-0146 D2): `{ package, basedOn }` — this item of "``.custom" replaces the base package's same-named item whole. `basedOn` is recorded and never gates; a base's upgrade plan reads it only as advice. | -| **isPinned** | `boolean` | optional | Console round-trip: the view is pinned in the object's view switcher. Written by the console's pin toggle through the `view` metadata API and read back to draw the pinned group. Stored on the view's row, which has no per-user scope. Not authored. | -| **sortOrder** | `integer` | optional | Console round-trip: the view's position among the object's saved views in the switcher, 0-based and counted over saved views only (a code-defined view carries none). Written by the console's drag-reorder and read back to order the tabs. Not authored: `order` is the authored default position. | -| **visibility** | `Enum<'private' \| 'team' \| 'organization' \| 'public'>` | optional | Console round-trip: the group the switcher files this view's tab under (private, team, organization or public). Display grouping only, NOT access control: nothing restricts who can list or open the view by this value. No console control sets it; the console carries a stored value forward when it re-saves the row. Not authored. | -| **columnState** | `never` | optional | [REMOVED] `view.columnState` was removed in @objectstack/spec 19.0.0 (ADR-0049 enforce-or-remove) — it held one column order and set of widths on a shared view row; nothing writes it any more, and a stored layout is no longer applied, so every reader sees the view's own column order and widths. The console keeps column widths in each reader's browser and saves a column order into the view itself. Delete the key. To ship a column order, list `columns` in that order (or set `fieldOrder`); to ship a width, set `width` on the column. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **options** | `never` | optional | Refused: a view item record carries no top-level `options` bag. Its per-kind blocks live under `config` (`config.kanban`, `config.timeline`, …); the legacy `options.KIND` bag belongs to the flattened list overlay only. | - -### Nested Shape: `ViewItemWire[viewKind='form'].config` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - -### Nested Shape: `ViewItemWire[viewKind='form'].protection` +### Nested Shape: `ViewItemWire.protection` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2828,7 +2625,7 @@ This schema accepts one of the following structures: | **reason** | `string` | ✅ | User-visible reason shown when the lock blocks an action. | | **docsUrl** | `string` | optional | Optional URL the Studio banner links to for more context. | -### Nested Shape: `ViewItemWire[viewKind='form'].overrides` +### Nested Shape: `ViewItemWire.overrides` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | @@ -2842,12 +2639,11 @@ This schema accepts one of the following structures: ## ViewKind -Whether `config` is a ListView (list family) or a FormView. +The family of the view: a list (`form` was retired in protocol 19 — a form is a `form` item). ### Allowed Values * `list` -* `form` --- diff --git a/content/docs/ui/create-vs-edit-form.mdx b/content/docs/ui/create-vs-edit-form.mdx index 96369bed48e..dfdbe8b30a8 100644 --- a/content/docs/ui/create-vs-edit-form.mdx +++ b/content/docs/ui/create-vs-edit-form.mdx @@ -10,7 +10,7 @@ description: One flat, grouped field set gives both the create form and the edit ## Recommended solution -**Author one field set on the object. Group it with `fieldGroups`, and mark the fields a create should not ask for with `showOnCreate: false`.** The Console's create and edit forms both come from that one set. They load no `form` item: a form is served only where a form action or a public link names it, so there is no create or edit form to author. An app that still declares an internal form inside its view container installs and runs, that form changes nothing on create or edit, and `os validate` reports it as `form-view-internal-not-loaded`. +**Author one field set on the object. Group it with `fieldGroups`, and mark the fields a create should not ask for with `showOnCreate: false`.** The Console's create and edit forms both come from that one set. They load no `form` item: a form is served only where a form action or a public link names it, so there is no create or edit form to author. A view holds lists only since protocol 19, so a form inside a view container is refused at parse; `os migrate meta --from 18` deletes an old create or edit form that nothing else opens and that declares no `overrides`, rather than moving it, and reports each one it deletes. A `form` item with no public link that no `type: 'form'` action opens changes nothing on create or edit either, and `os validate` reports it as `form-consumer-less`. ### 1. Put the intent on the fields diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 7142d727674..55339c58206 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (90)... + → Running author-time rules (89)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/ui/translations.mdx b/content/docs/ui/translations.mdx index 1e2fc99feff..1be563e6e9f 100644 --- a/content/docs/ui/translations.mdx +++ b/content/docs/ui/translations.mdx @@ -71,8 +71,8 @@ export default defineStack({ | Field labels, help text, placeholders | `objects..fields..label` / `help` / `placeholder` | | Inline child-grid heading of a master-detail field (drawn on the parent's form) | `objects..fields..inlineTitle` — keyed on the child object that owns the field; untranslated it keeps its authored text, with no fallback to the child's plural label | | Picklist option labels | `objects..fields..options.` | -| View titles, descriptions, empty states | `objects.._views.` | -| A form view's thank-you panel (shown after a submit) | `objects.._views..submitBehavior.title` / `.message` — only when the form's `submitBehavior` is `kind: 'thank-you'`, and only copy the form authors: a key cannot add a `message` the form leaves to the default wording | +| View labels, descriptions, empty states | `objects.._views..label` / `description` / `emptyState` | +| A form's heading, label, description and thank-you panel (shown after a submit) | `forms.
.title` / `label` / `description` and `forms..submitBehavior.title` / `.message` — keyed by the `form` item's name (`.`, dots included). The panel is translated only when the form's `submitBehavior` is `kind: 'thank-you'`, and only copy the form authors: a key cannot add a `message` the form leaves to the default wording. The `_views..title` and `.submitBehavior` keys a form held in a view used are refused since protocol 19; `os migrate meta --from 18` moves them here | | Bulk-action copy on a list view (button, confirm prompt, dialog fields) | `objects.._views..bulkActions..label` / `.confirmText` / `.confirmLabel` / `.params..label` / `.help` / `.placeholder` — a bulk param's hint is `help`, not `helpText` | | Action labels, confirm text, success messages, disabled reasons, param dialog submit labels, confirm and param dialog dismiss labels | `objects.._actions.` | | Action result dialogs (title / description / acknowledge / field labels) | `objects.._actions..resultDialog` | @@ -90,7 +90,7 @@ export default defineStack({ | Page labels and `page:header` copy | `pages..label` / `description` / `title` / `subtitle` — on a `kind: 'slotted'` page the header under `slots.header` is the page's header | | Page component copy, by component id | `pages..components..title` / `description` / `label` / `placeholder` / `emptyText` — reached under `regions[].components[]` and `slots.`, through `properties.children` and a `page:tabs` / `page:accordion` panel's `items[].children` | | Page tab labels (`page:tabs` items) | `pages..components..items..label` — keyed by the tabs component's `id` and the item's `value`; an item without a `value` has no key (localize it with an inline locale map), and `page:accordion` panels have none | -| A page `object-form`'s thank-you panel | `pages..components..submitBehavior.title` / `.message` — keyed by the `object-form` component's `id` (a form without an `id` has no key), by the same rules as a form view's panel | +| A page `object-form`'s thank-you panel | `pages..components..submitBehavior.title` / `.message` — keyed by the `object-form` component's `id` (a form without an `id` has no key), by the same rules as a form's panel | | Screen-flow wizards (flow label, screen headings and body text, screen field copy) | `flows..label` / `flows..screens..title` / `.description` / `.fields..label` / `.placeholder` / `.inlineHelpText` — a screen field's help text is `inlineHelpText`, the key the field itself declares, not `help`; see the boundary note below | | Flow step names (each step a drawing of the flow shows, such as a manual's flow embed) | `flows..nodes..label` — keyed by the node's `id`, for a start, decision, notify, end or any other step; an `approval` step's name is `flows..approvals..label` and a screen's is its heading, `flows..screens..title`, so `os validate` points a `nodes` key over either there. `os lint` asks for every step a flow embed draws at its default business altitude | | Text a flow writes into a record (a `create_record` / `update_record` field value marked `{ dialect: 'template', source }`) | `flows..records..fields.` — picked in the organization's language (the Localization setting when set, else the app's `i18n.defaultLocale`), never the run starter's; see [Flows](/docs/automation/flows#text-a-record-keeps--a-field-value-marked-as-text) | diff --git a/content/docs/upgrading.mdx b/content/docs/upgrading.mdx index db36c842477..318425ed2be 100644 --- a/content/docs/upgrading.mdx +++ b/content/docs/upgrading.mdx @@ -161,9 +161,19 @@ os migrate protocol --to 19 --apply --yes # move them, check again, record the ``` A row that holds the switch is listed with the action for its cause, taken on -the release you are running. See +the release you are running. Until the switch is recorded, a protocol-19 +`os serve` (and so `os dev` and `os start`) refuses to start on a database an +earlier release created, and its refusal names this command. See [What the upgrade command writes](/docs/deployment/stored-forms-upgrade#what-the-upgrade-command-writes). +Your sources move on their own clock: protocol 19 refuses `view.form`, +`view.formViews` and `viewKind: 'form'` with a prescription naming the stack's +`forms:`, and `os migrate meta --from 18` lists the edits that move each such +form to a `form` item named `OBJECT.KEY` (`--write` applies the ones it can +prove). A create or edit form that nothing else opens is deleted and reported, +not moved: a record's New and Edit dialogs lay out by the object's +`fieldGroups`. + ### A runtime move can still force metadata edits The table at the top of this page says a runtime move does not touch your diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md index ea7e630c5a5..7a111d9752e 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `ui/` | 233 | 223 | 6 | 0 | 4 | +| `ui/` | 231 | 221 | 6 | 0 | 4 | ## `ui/` — sites @@ -45,9 +45,9 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `report.zod.ts` | 4 | | `responsive.zod.ts` | 1 | | `sharing.zod.ts` | 1 | -| `view.zod.ts` | 67 | +| `view.zod.ts` | 65 | | `widget.zod.ts` | 1 | -| **total** | **233** | +| **total** | **231** | ## `ui/` — open @@ -55,15 +55,15 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**4 strip of 233**, in 4 file(s). +**4 strip of 231**, in 4 file(s). | File | Strip | Sites | |---|---|---| | `action-params.zod.ts` | 1 | 1 | | `app.zod.ts` | 1 | 20 | -| `view.zod.ts` | 1 | 67 | +| `view.zod.ts` | 1 | 65 | | `widget.zod.ts` | 1 | 1 | -| **total** | **4** | **233** | +| **total** | **4** | **231** | | Bucket | Sites | |---|---| diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts index 975d2c65dae..e79a950f965 100644 --- a/packages/cli/src/commands/doctor.ts +++ b/packages/cli/src/commands/doctor.ts @@ -906,10 +906,13 @@ export function detectCircularDependencies(objects: any[]): string[] { } // ── Object-reference walking ──────────────────────────────────────── -// A `config.views` entry is a ViewSchema CONTAINER (`{ list, form, listViews, -// formViews }` — the defineView() shape): the object binding lives on each -// sub-view at `data.object` (provider 'object'), never on a top-level -// `view.object`. Legacy flat ViewItems (top-level `object`) are still read. +// A `config.views` entry is a ViewSchema CONTAINER (`{ list, listViews }` — +// the defineView() shape): the object binding lives on each sub-view at +// `data.object` (provider 'object'), never on a top-level `view.object`. +// Legacy flat ViewItems (top-level `object`) are still read. A config a +// protocol-18 author wrote may still hold a form in the container (`form`, +// `formViews`): the walk below keeps reading those slots, so the doctor +// reports on the file as it is written. function* subViewsOf(view: any): Generator<[slot: string, subView: any]> { if (!view || typeof view !== 'object') return; diff --git a/packages/cli/src/commands/explain.ts b/packages/cli/src/commands/explain.ts index e7d3b003104..406fbd04069 100644 --- a/packages/cli/src/commands/explain.ts +++ b/packages/cli/src/commands/explain.ts @@ -99,9 +99,9 @@ export const SCHEMAS: Record = { // view's own keys are shown inside the example's slots. view: { name: 'View (container)', - description: 'Per-object container holding that object\'s views. It is NOT a single view: the container\'s own keys are `list`, `form`, `listViews` and `formViews`, and a single view\'s keys (type, columns, filter, sort, …) go INSIDE one of those slots. List views render as grid / kanban / gallery / calendar / timeline / gantt / map / chart / tree / page; form views as simple / tabbed / wizard.', + description: 'Per-object container holding that object\'s list views. It is NOT a single view: the container\'s own keys are `list` and `listViews`, and a single view\'s keys (type, columns, filter, sort, …) go INSIDE one of those slots. List views render as grid / kanban / gallery / calendar / timeline / gantt / map / chart / tree / page. A view holds lists only: a form is its own item, written with defineForm() under the stack\'s `forms:`.', required: [ - { name: 'list | form | listViews | formViews', type: 'at least one slot', description: 'A container must register at least one view — defineView() refuses one that registers none, and a flat view literal parses to an empty container. `list` / `form` are the object\'s default views; `listViews` / `formViews` are Record maps of additional NAMED views.' }, + { name: 'list | listViews', type: 'at least one slot', description: 'A container must register at least one view — defineView() refuses one that registers none, and a flat view literal parses to an empty container. `list` is the object\'s default list view; `listViews` is a Record map of additional NAMED list views.' }, ], optional: [ { name: 'name', type: 'string', description: 'Item name — supplied by the metadata door; for an object-scoped container it is the object name' }, diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts index 4fa61374e37..a897a4bea7d 100644 --- a/packages/cli/src/commands/generate.ts +++ b/packages/cli/src/commands/generate.ts @@ -368,13 +368,13 @@ export default ${toCamelCase(name)}; }, view: { - description: 'List or form view', + description: 'List view', defaultDir: 'src/views', /** * A view CONTAINER — which is what a `view` artifact is (commit 79c71d29d). * - * `ViewSchema` is `.strict()` and its view slots are `list` / `form` / - * `listViews` / `formViews`; `type` and `objectName` belong to a single + * `ViewSchema` is `.strict()` and its view slots are `list` / + * `listViews`; `type` and `objectName` belong to a single * VIEW, not to the container holding it. The template used to write both * spellings at once: a flat list view's keys on the container AND a `list` * block. `defineView` has guarded the flat shape since the container was @@ -400,8 +400,8 @@ export default ${toCamelCase(name)}; * * - The container is registered under the key * `deriveViewContainerObject` returns (`@objectstack/metadata`, - * `view-container.ts`): its own `object`, else `list.data.object` / - * `form.data.object`, and only then `name`. With `object` set, `name` + * `view-container.ts`): its own `object`, else `list.data.object`, + * and only then `name`. With `object` set, `name` * is never the key. Its one reader is `viewContainerNameRefusal` * (`@objectstack/objectql`), which refuses a `name` that is set AND * differs from that key, and passes a container with no `name`. So @@ -409,7 +409,7 @@ export default ${toCamelCase(name)}; * ledger's `dead` (`packages/spec/liveness/view.json`) — and the * refusal's own remedy is "drop `name`". * - A container's `label` reaches no reader: every ViewItem the container - * expands into takes the label of its list or form entry + * expands into takes the label of its list entry * (`expandViewContainerWithDiagnostics`), never the container's. * * So both are dropped, and the label a person sees is the list view's diff --git a/packages/cli/src/commands/migrate/apply.organization-ownership-birth.integration.test.ts b/packages/cli/src/commands/migrate/apply.organization-ownership-birth.integration.test.ts index eff0000f26f..bd71e843c79 100644 --- a/packages/cli/src/commands/migrate/apply.organization-ownership-birth.integration.test.ts +++ b/packages/cli/src/commands/migrate/apply.organization-ownership-birth.integration.test.ts @@ -33,8 +33,17 @@ import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import Database from 'better-sqlite3'; -import { ORGANIZATION_OWNERSHIP_MIGRATION_ID, ORGANIZATION_OWNERSHIP_SHAPE_GENERATION } from '@objectstack/spec/system'; -import { assertOrganizationOwnershipMigrated, isOrganizationOwnershipBootRefusal } from '@objectstack/runtime'; +import { + FORM_TYPE_SWITCH_MIGRATION_ID, + ORGANIZATION_OWNERSHIP_MIGRATION_ID, + ORGANIZATION_OWNERSHIP_SHAPE_GENERATION, +} from '@objectstack/spec/system'; +import { + assertFormTypeSwitched, + assertOrganizationOwnershipMigrated, + isFormTypeSwitchBootRefusal, + isOrganizationOwnershipBootRefusal, +} from '@objectstack/runtime'; import { isExitSignal } from '../../utils/format.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; import MigrateApply from './apply.js'; @@ -42,6 +51,14 @@ import MigrateApply from './apply.js'; // Pay the first transform of the dist-resolved workspace deps the command // reaches through dynamic `import()`s at MODULE LOAD, not inside a case. import '@objectstack/objectql'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/driver-sql'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/platform-objects/system'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/metadata-protocol'; const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); @@ -119,7 +136,10 @@ const markerRows = (file: string): Array> => * the data stack alone registers no `sys_migration`, and the guard is inert * there — it would admit every file. Case (b)'s refusal is the control. */ -async function guardVerdict(file: string): Promise { +async function guardVerdict( + file: string, + judge: (engine: never) => Promise = (engine) => assertOrganizationOwnershipMigrated(engine), +): Promise { const stack = await bootSchemaStack({ jsonOutput: false, databaseUrl: `file:${file}`, @@ -131,7 +151,7 @@ async function guardVerdict(file: string): Promise { }); try { const engine = (stack.kernel as { getService: (name: string) => unknown }).getService('objectql'); - await assertOrganizationOwnershipMigrated(engine as never); + await judge(engine as never); } finally { await stack.shutdown(); } @@ -239,3 +259,47 @@ describe('os migrate apply writes the organization-ownership birth marker on a d expect(markerRows(file)).toEqual(before); }, CASE_TIMEOUT_MS); }); + +/** + * [ADR-0159 D7; ruling record 7308112533] The same flush writes the + * protocol-19 switch's BIRTH MARKER, on the same counts: a database `os + * migrate apply` created from empty stores no form, so its switch is recorded + * at birth and the served boot's guard (`assertFormTypeSwitched`, read as + * above on a boot that creates nothing) admits it. A database the apply did + * not create gets none, though the flush creates a table in it, and the guard + * still refuses it, naming the switch command. + */ +describe('os migrate apply writes the protocol-19 switch birth marker on a database it created from empty', () => { + const switchRows = (file: string): Array> => + withDb(file, (db) => db.prepare('SELECT * FROM sys_migration WHERE id = ?').all(FORM_TYPE_SWITCH_MIGRATION_ID) as Array>); + const switchVerdict = (file: string) => guardVerdict(file, (engine) => assertFormTypeSwitched(engine)); + + it('an empty file: one verified birth row naming protocol 19, no ceremony claimed, and the guard admits it', async () => { + expect(freshApply.exitCode, JSON.stringify(freshApply.payload).slice(0, 400)).toBe(0); + const rows = switchRows(freshDb); + expect(rows).toHaveLength(1); + expect(rows[0].verified_at).not.toBeNull(); + expect(rows[0].applied_at).toBeNull(); + expect(Number(rows[0].blocking)).toBe(0); + expect(JSON.parse(String(rows[0].details)).birth).toMatchObject({ protocol: 19 }); + + await expect(switchVerdict(freshDb)).resolves.toBeUndefined(); + }, CASE_TIMEOUT_MS); + + it('a database the apply did not create: no birth marker, though the flush creates a table, and the guard refuses it', async () => { + const file = copyOfFresh((db) => { + db.prepare('DELETE FROM sys_migration WHERE id = ?').run(FORM_TYPE_SWITCH_MIGRATION_ID); + db.exec(`DROP TABLE ${DROPPED_TABLE}`); + }); + + const { payload, exitCode } = await runJson(applyArgv(file)); + expect(exitCode, JSON.stringify(payload).slice(0, 400)).toBe(0); + expect(payload.created).toEqual([expect.objectContaining({ table: DROPPED_TABLE, kind: 'create_table' })]); + + expect(switchRows(file)).toEqual([]); + const refusal = await switchVerdict(file).then(() => null, (error: unknown) => error); + expect(isFormTypeSwitchBootRefusal(refusal), String(refusal)).toBe(true); + expect((refusal as { reason?: string }).reason).toBe('absent'); + expect((refusal as Error).message).toContain("'os migrate protocol --to 19 --apply --yes'"); + }, CASE_TIMEOUT_MS); +}); diff --git a/packages/cli/src/commands/migrate/organization-ownership.ts b/packages/cli/src/commands/migrate/organization-ownership.ts index b10121ce007..6c5afebe23f 100644 --- a/packages/cli/src/commands/migrate/organization-ownership.ts +++ b/packages/cli/src/commands/migrate/organization-ownership.ts @@ -937,7 +937,7 @@ export default class OrganizationOwnershipCeremony extends Command { }; }, }, - // [ADR-0146 D1, D3] A withdrawal onto a read-only package's view goes + // [ADR-0146 D1, D3] A withdrawal onto a read-only package's item goes // into its `.custom` pair: the save door's own writability predicate, // and the ensure door, in process. pairs: protocolCustomizationPairs({ @@ -952,13 +952,15 @@ export default class OrganizationOwnershipCeremony extends Command { (engine.registry as { getPackage?(id: string): { manifest?: { version?: unknown } } | undefined } | undefined) ?.getPackage?.(packageId)?.manifest?.version, }), - views: { - // The env-wide view list, exactly as the anonymous form doors read it. + forms: { + // [ADR-0159 D7] The env-wide `form` list the anonymous form doors + // offer their candidates from: since protocol 19 a form is its own + // item, and the served views hold lists only. list: async () => { if (typeof protocol?.getMetaItems !== 'function') { throw new Error('no metadata protocol is composed on this stack'); } - const result = await protocol.getMetaItems({ type: 'view' }); + const result = await protocol.getMetaItems({ type: 'form' }); const items = Array.isArray(result) ? result : (result?.items ?? []); return items.filter((i): i is Record => !!i && typeof i === 'object'); }, diff --git a/packages/cli/src/commands/migrate/organization-ownership.withdrawal-pair.integration.test.ts b/packages/cli/src/commands/migrate/organization-ownership.withdrawal-pair.integration.test.ts index 5ef2c2ad3bd..ce2bd4ea66a 100644 --- a/packages/cli/src/commands/migrate/organization-ownership.withdrawal-pair.integration.test.ts +++ b/packages/cli/src/commands/migrate/organization-ownership.withdrawal-pair.integration.test.ts @@ -12,20 +12,31 @@ * ## The fixture * * A project whose config is a booted code package (read-only: its manifest is - * registered at boot) shipping an object and a public form view, over a - * database a served boot of this tree left behind, shaped like v17: - * `sys_metadata` carries `organization_id`, and an organization's row of the - * form view withdraws it (`sharing.enabled: false`). + * registered at boot) shipping an object and a public form, over a database a + * served boot of this tree left behind, shaped like v17: `sys_metadata` + * carries `organization_id`, and an organization's row of the form view + * withdraws it (`sharing.enabled: false`). [ADR-0159 D7] Since protocol 19 + * the package ships the form as a `form` item under `forms:` (a view holds + * lists only and the parse refuses a form a view holds); the organization's + * row stays the stored 17.x `view` row it is. * * ## What each case measures * * The real command, in process through oclif (plan, then `--apply`): the step * carries the withdrawal into the pair, the pair is in `sys_packages`, its row - * declares the override at the base's version, and the env-wide view list the - * anonymous doors judge by serves the form withdrawn. A second `--apply` over + * declares the override at the base's version, and the anonymous doors' + * reading (the effective `form` list, judged against the withdrawal layer of + * both types, as the doors build it) serves the form withdrawn. A second `--apply` over * the same database finds the step checkpointed and writes nothing. (A re-run * of the carry itself, with no checkpoint, is pinned in * `organization-ownership-apply.test.ts`.) + * + * Each case runs under one tenancy posture (`OS_TENANCY_POSTURE`). Under + * `single` the organization's row is promoted to an environment row; under + * `isolated` it stays the organization's, reported, so the env-wide reading + * the doors judge holds no withdrawal but the one the carry writes: there the + * served form is withdrawn only if the carry reads the served `form` items + * and saves the withdrawal as the pair's `form` override. */ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; @@ -35,7 +46,7 @@ import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { anonymousFormIntakeCandidates, anonymousFormIntakeWithdrawnIn } from '@objectstack/metadata-core'; +import { formIntakeLayer, openFormAt } from '@objectstack/spec/ui'; import { isExitSignal } from '../../utils/format.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; import MigrateOrganizationOwnership from './organization-ownership.js'; @@ -45,6 +56,14 @@ import MigrateOrganizationOwnership from './organization-ownership.js'; import '@objectstack/runtime'; import '@objectstack/objectql'; import '@objectstack/metadata-protocol'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/driver-sql'; +import '@objectstack/platform-objects/system'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/spec/automation'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; import { PackageServicePlugin } from '@objectstack/service-package'; const HERE = dirname(fileURLToPath(import.meta.url)); @@ -53,7 +72,7 @@ const CASE_TIMEOUT_MS = 240_000; const OVERRIDING_ENV = [ 'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', 'OS_ARTIFACT_PATH', - 'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', 'OS_MULTI_ORG_ENABLED', + 'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', 'OS_MULTI_ORG_ENABLED', 'OS_TENANCY_POSTURE', ] as const; const BASE = 'com.example.wdpair'; @@ -68,10 +87,13 @@ const FORM = { sections: [{ name: 'main', label: 'Main', columns: 1, fields: [{ field: 'name' }] }], sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, }; +/** The shipped form, as protocol 19 authors it: a `form` item, its binding lifted to `object`. */ +const { data: _binding, ...FORM_BODY } = FORM; const CONFIG = { manifest: { id: BASE, name: 'Withdrawal Pair', version: VERSION, type: 'app', namespace: 'wdp' }, objects: [{ name: 'wdp_lead', label: 'Lead', fields: { name: { type: 'text', label: 'Name' } } }], - views: [{ list: { label: 'Leads', type: 'grid', data: DATA, columns: [{ field: 'name' }] }, formViews: { intake: FORM } }], + views: [{ list: { label: 'Leads', type: 'grid', data: DATA, columns: [{ field: 'name' }] } }], + forms: [{ name: VIEW, object: 'wdp_lead', label: 'Intake', ...FORM_BODY }], }; /** The organization's 17.x row of the form view: the served body, the form withdrawn. */ const WITHDRAWN = { @@ -132,22 +154,42 @@ async function applyOver(dbFile: string, tag: string): Promise<{ report: any; ex const promotion = (report: any): { status: string; summary: Record; blockers: string[] } => report.steps.find((s: { step: string }) => s.step === 'metadata-promotion'); -/** The stored `view` rows of the form, `package/state`, with the declaration each body carries. */ +/** + * The stored `form` rows of the form, by package, with the switch and the + * declaration each body carries ([ADR-0159 D7] a `form` body keeps its + * `sharing` at the top level). + */ function storedForm(dbFile: string): Array<{ pkg: string; enabled: unknown; overrides: unknown }> { const db = new Database(dbFile, { readonly: true }); try { - return (db.prepare(`SELECT package_id, metadata FROM sys_metadata WHERE type = 'view' AND name = ? ORDER BY package_id`) + return (db.prepare(`SELECT package_id, metadata FROM sys_metadata WHERE type = 'form' AND name = ? ORDER BY package_id`) .all(VIEW) as Array<{ package_id: string | null; metadata: string }>) .map((row) => { - const body = JSON.parse(row.metadata) as { config?: { sharing?: { enabled?: unknown } }; overrides?: unknown }; - return { pkg: row.package_id ?? '-', enabled: body.config?.sharing?.enabled, overrides: body.overrides }; + const body = JSON.parse(row.metadata) as { sharing?: { enabled?: unknown }; overrides?: unknown }; + return { pkg: row.package_id ?? '-', enabled: body.sharing?.enabled, overrides: body.overrides }; }); } finally { db.close(); } } -/** On a fresh boot of `dbFile`: the base's served form, and the views the anonymous doors serve the slug from. */ +/** The stored rows of the form's name, of either type, bound to `pkg`. */ +function boundTo(dbFile: string, pkg: string): Array<{ type: string }> { + const db = new Database(dbFile, { readonly: true }); + try { + return db.prepare(`SELECT type FROM sys_metadata WHERE name = ? AND package_id = ? ORDER BY type`).all(VIEW, pkg) as Array<{ type: string }>; + } finally { + db.close(); + } +} + +/** + * On a fresh boot of `dbFile`: the base's served form (its `sharing`), and the + * forms the anonymous doors serve the slug from, read as the doors read them + * since protocol 19: the effective `form` list for the candidates, judged + * against the withdrawal layer of both types (the stored old-shape `view` + * rows included, `getViewItemsWithStoredForms`) and the per-package layers. + */ async function served(dbFile: string): Promise<{ base: unknown; open: string[] }> { process.chdir(projectDir); const stack = await bootSchemaStack({ @@ -157,13 +199,20 @@ async function served(dbFile: string): Promise<{ base: unknown; open: string[] } }); try { const protocol = stack.kernel.getService('protocol') as any; - const base = (await protocol.getMetaItem({ type: 'view', name: VIEW, packageId: BASE }))?.item; - const listed = await protocol.getMetaItems({ type: 'view' }); - const list = ((Array.isArray(listed) ? listed : listed?.items) ?? []) as Array>; - const open = list - .filter((v) => anonymousFormIntakeCandidates(v).some((c) => c.slug === SLUG && !anonymousFormIntakeWithdrawnIn(list, v, c))) - .map((v) => `${String(v.name)}|${String(v._packageId ?? '')}`); - return { base: (base as { config?: { sharing?: unknown } } | undefined)?.config?.sharing, open }; + const listOf = (listed: any): Array> => + ((Array.isArray(listed) ? listed : listed?.items) ?? []) as Array>; + const base = (await protocol.getMetaItem({ type: 'form', name: VIEW, packageId: BASE }))?.item; + const forms = listOf(await protocol.getMetaItems({ type: 'form' })); + const views = listOf(await protocol.getViewItemsWithStoredForms({ type: 'view' })); + const layer = formIntakeLayer({ + forms: [...forms, ...listOf(await protocol.getMetaItemsPerPackage({ type: 'form' }))], + views: [...views, ...listOf(await protocol.getMetaItemsPerPackage({ type: 'view' }))], + unreadable: await protocol.getUnreadableFormBodies(), + }); + const open = forms + .filter((f) => openFormAt([f], layer, SLUG) !== null) + .map((f) => `${String(f.name)}|${String(f._packageId ?? '')}`); + return { base: (base as { sharing?: unknown } | undefined)?.sharing, open }; } finally { await stack.shutdown(); process.chdir(savedCwd); @@ -215,30 +264,47 @@ afterAll(() => { rmSync(dir, { recursive: true, force: true }); }); -describe('organization-ownership --apply: a withdrawal onto a read-only package\'s view goes into its .custom pair', () => { - it('⭐ carried into the pair, declared as the override of the base; the served form is withdrawn; a re-run carries nothing', async () => { - const dbFile = join(dir, 'case.db'); - copyFileSync(templateDb, dbFile); - expect((await served(dbFile)).open, 'PRECONDITION: the shipped form is served open').toEqual([`${VIEW}|${BASE}`]); - - const { report } = await applyOver(dbFile, 'first'); - const step = promotion(report); - expect(step.blockers.filter((b) => b.includes(VIEW))).toEqual([]); - expect(step.summary.withdrawalsCarried).toBe(1); - expect(storedForm(dbFile).filter((r) => r.pkg === PAIR)).toEqual([ - { pkg: PAIR, enabled: false, overrides: { package: BASE, basedOn: VERSION } }, - ]); - // ⛔ Nothing bound to the read-only base itself. - expect(storedForm(dbFile).filter((r) => r.pkg === BASE)).toEqual([]); - - const after = await served(dbFile); - expect(after.base).toMatchObject({ enabled: false }); - expect(after.open).toEqual([]); - - // A re-run finds the step checkpointed and writes nothing more. - const rows = storedForm(dbFile); - const again = await applyOver(dbFile, 'again'); - expect(promotion(again.report).status).toBe('checkpointed'); - expect(storedForm(dbFile)).toEqual(rows); - }, CASE_TIMEOUT_MS); +/** Run `body` with `OS_TENANCY_POSTURE` set to `posture`, restored after. */ +async function underPosture(posture: 'single' | 'isolated', body: () => Promise): Promise { + const saved = process.env.OS_TENANCY_POSTURE; + process.env.OS_TENANCY_POSTURE = posture; + try { + return await body(); + } finally { + if (saved === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = saved; + } +} + +describe('organization-ownership --apply: a withdrawal onto a read-only package\'s form goes into its .custom pair', () => { + for (const posture of ['single', 'isolated'] as const) { + it(`⭐ ${posture}: carried into the pair, declared as the override of the base; the served form is withdrawn; a re-run carries nothing`, async () => { + await underPosture(posture, async () => { + const dbFile = join(dir, `case-${posture}.db`); + copyFileSync(templateDb, dbFile); + expect((await served(dbFile)).open, 'PRECONDITION: the shipped form is served open').toEqual([`${VIEW}|${BASE}`]); + + const { report } = await applyOver(dbFile, `first-${posture}`); + const step = promotion(report); + expect(step.blockers.filter((b) => b.includes(VIEW))).toEqual([]); + expect(step.summary.withdrawalsCarried).toBe(1); + expect(storedForm(dbFile).filter((r) => r.pkg === PAIR)).toEqual([ + { pkg: PAIR, enabled: false, overrides: { package: BASE, basedOn: VERSION } }, + ]); + // ⛔ Nothing bound to the read-only base itself. + expect(storedForm(dbFile).filter((r) => r.pkg === BASE)).toEqual([]); + expect(boundTo(dbFile, BASE)).toEqual([]); + + const after = await served(dbFile); + expect(after.base).toMatchObject({ enabled: false }); + expect(after.open).toEqual([]); + + // A re-run finds the step checkpointed and writes nothing more. + const rows = storedForm(dbFile); + const again = await applyOver(dbFile, `again-${posture}`); + expect(promotion(again.report).status).toBe('checkpointed'); + expect(storedForm(dbFile)).toEqual(rows); + }); + }, CASE_TIMEOUT_MS); + } }); diff --git a/packages/cli/src/commands/migrate/packageless-overlays.integration.test.ts b/packages/cli/src/commands/migrate/packageless-overlays.integration.test.ts index fda880ab11b..1fd1c7d2b35 100644 --- a/packages/cli/src/commands/migrate/packageless-overlays.integration.test.ts +++ b/packages/cli/src/commands/migrate/packageless-overlays.integration.test.ts @@ -46,6 +46,10 @@ import MigratePackagelessOverlays from './packageless-overlays.js'; import '@objectstack/runtime'; import '@objectstack/metadata-protocol'; import '@objectstack/platform-objects/plugin'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); @@ -189,9 +193,9 @@ async function storedPackages(dbFile: string): Promise { } } -interface RunResult { payload: any; exitCode: number } +interface RunResult { payload: any; exitCode: number; printed: string } -/** Run the command through oclif and capture its one JSON document. */ +/** Run the command through oclif and capture its one JSON document (and, without `--json`, the lines it prints). */ async function runJson(argv: string[]): Promise { const savedExit = process.exitCode; const swallow = ((_chunk: unknown, ...rest: unknown[]) => { @@ -201,7 +205,7 @@ async function runJson(argv: string[]): Promise { }) as typeof process.stdout.write; const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); vi.spyOn(process.stderr, 'write').mockImplementation(swallow); - vi.spyOn(console, 'log').mockImplementation(() => {}); + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); vi.spyOn(console, 'warn').mockImplementation(() => {}); vi.spyOn(console, 'error').mockImplementation(() => {}); let thrownExit: number | undefined; @@ -215,7 +219,8 @@ async function runJson(argv: string[]): Promise { const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); let payload: any; try { payload = JSON.parse(out); } catch { payload = { unparsed: out.slice(-400) }; } - return { payload, exitCode: thrownExit ?? (process.exitCode as number | undefined) ?? 0 }; + const printed = log.mock.calls.map((c) => c.map(String).join(' ')).join('\n'); + return { payload, exitCode: thrownExit ?? (process.exitCode as number | undefined) ?? 0, printed }; } finally { process.exitCode = savedExit; vi.restoreAllMocks(); @@ -426,6 +431,15 @@ describe('os migrate packageless-overlays: a package-less view container', () => expect(preview.payload.movable).toBe(0); expect(preview.payload.left).toBe(1); + // The printed remedy orders the container row's delete after the protocol-19 switch moves its form members. + const text = await runJson(['--database-url', `file:${db}`]); + expect(text.exitCode).toBe(0); + const line = text.printed.split('\n').find((l) => l.includes(`view "${CONTAINER}"`)) ?? text.printed.slice(-600); + expect(line).toContain('it is a view container'); + expect(line).toContain( + 'then, only once `os migrate protocol --to 19 --apply` has moved its form members, delete this row with a delete naming no package.', + ); + const { payload, exitCode } = await runJson(['--apply', '--yes', '--database-url', `file:${db}`, '--json']); expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); expect(exitCode).toBe(0); diff --git a/packages/cli/src/commands/migrate/packageless-overlays.ts b/packages/cli/src/commands/migrate/packageless-overlays.ts index 41066b4666e..1a185b7d3ec 100644 --- a/packages/cli/src/commands/migrate/packageless-overlays.ts +++ b/packages/cli/src/commands/migrate/packageless-overlays.ts @@ -66,14 +66,19 @@ function reasonOf(row: CensusRow): string { case 'cannot_declare': // [#30261] Its shape refuses the `overrides` key, so the move's declared save can never land. return (row.type === 'view' - ? 'it is a view container (list/listViews/form/formViews), and only a single view can declare an override, ' + ? 'it is a view container (list/listViews), and only a single view can declare an override, ' : 'its shape cannot carry an `overrides` declaration, ') + 'so it cannot be moved as one. Left as it is: ' + (row.type === 'view' ? `save each of its views into '${row.pair}' as a single view named . (?package=${row.pair}) — ` + `one '${row.base}' ships declaring overrides: { package: '${row.base}', basedOn }, a new one declaring nothing — ` : `save its content into '${row.pair}' in a shape that declares overrides: { package: '${row.base}', basedOn } — `) - + `then delete this row with a delete naming ${row.boundToBase ? `'${row.base}'` : 'no package'}.`; + // A container stored before protocol 19 may hold `form` / `formViews` members: its row is deleted + // only after the protocol-19 switch has moved them (the order the `cli.mdx` row gives). + + (row.type === 'view' + ? 'then, only once `os migrate protocol --to 19 --apply` has moved its form members, delete this row' + : 'then delete this row') + + ` with a delete naming ${row.boundToBase ? `'${row.base}'` : 'no package'}.`; case 'foreign_declaration': return `its body already carries an \`overrides\` key that does not name '${row.base}'. Left as it is: ` + (row.boundToBase diff --git a/packages/cli/src/commands/migrate/protocol.integration.test.ts b/packages/cli/src/commands/migrate/protocol.integration.test.ts index c5b67cfcf66..9f4553cf2a4 100644 --- a/packages/cli/src/commands/migrate/protocol.integration.test.ts +++ b/packages/cli/src/commands/migrate/protocol.integration.test.ts @@ -8,8 +8,9 @@ * ## The fixture * * A compiled artifact (`dist/objectstack.json`) whose package ships an object - * and a linked public form in an old shape (`formViews.contact`), over a - * database an older release left behind with, bound to no package: + * and a linked public form as a `form` item (the only shape a protocol-19 + * artifact loads: the stack is refused at boot with `view.formViews` in it), + * over a database an older release left behind with, bound to no package: * * - a `viewKind: 'form'` row of the package's form that switches it off * (moves into the package's pair as a declared override); @@ -20,6 +21,14 @@ * preview writes nothing; `--apply` over a held deployment writes nothing * either (no row, no pair, no marker); `--apply` over a deployment that can * switch moves the row and records the verified `sys_migration` marker. + * + * ## The marker is what the served boot reads + * + * `os serve`'s protocol-19 guard (`assertFormTypeSwitched`, + * `@objectstack/runtime`) is asked here on a boot that creates nothing, so its + * verdict is the marker's alone: it refuses the database before the switch, + * still refuses it after a held `--apply`, and admits it once the command has + * recorded the switch. */ import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; @@ -28,6 +37,7 @@ import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { SqlDriver } from '@objectstack/driver-sql'; +import { assertFormTypeSwitched, isFormTypeSwitchBootRefusal } from '@objectstack/runtime'; import { isExitSignal } from '../../utils/format.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; import MigrateProtocol from './protocol.js'; @@ -56,12 +66,17 @@ const FORM = `${OBJECT}.contact`; const BROKEN = `${OBJECT}.broken`; const CREATE = `${OBJECT}.create`; const SLUG = 'contact-m37111'; -const formBody = (enabled: boolean) => ({ +/** A form's own content: what a `form` item carries at its top level. */ +const formContent = (enabled: boolean) => ({ type: 'simple', sections: [{ fields: ['name'] }], - data: { provider: 'object', object: OBJECT }, sharing: { publicLink: `/forms/${SLUG}`, enabled, allowAnonymous: true }, }); +/** The same content as an older release stored it, under a `viewKind: 'form'` row's `config`. */ +const formBody = (enabled: boolean) => ({ + ...formContent(enabled), + data: { provider: 'object', object: OBJECT }, +}); const ARTIFACT = { manifest: { id: PKG, name: 'm37111', version: '2.3.0', type: 'app', namespace: 'm37111' }, objects: [{ @@ -70,7 +85,8 @@ const ARTIFACT = { sharingModel: 'private', fields: { name: { name: 'name', label: 'Name', type: 'text' } }, }], - views: [{ object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }, formViews: { contact: formBody(true) } }], + views: [{ object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }], + forms: [{ name: FORM, object: OBJECT, label: 'Contact us', ...formContent(true) }], }; interface SeedRow { type: string; name: string; state: string; body: Record; packageId?: string } @@ -218,6 +234,29 @@ async function switchMarker(dbFile: string): Promise { } } +/** + * The served boot's verdict on `dbFile`, as `os serve`'s guard reaches it, from + * a boot that holds its DDL back: it creates nothing, so the guard cannot read + * the store as created from empty and decides on the marker alone. `null` when + * the database would be served, the refusal when it would not. + */ +async function guardRefusal(dbFile: string): Promise { + const stack = await bootSchemaStack({ + jsonOutput: false, + databaseUrl: `file:${dbFile}`, + deferSchemaDdl: true, + readOnlyProbe: true, + composeHostStack: true, + projectRoot: dir, + }); + try { + const engine = (stack.kernel as { getService: (name: string) => unknown }).getService('objectql'); + return await assertFormTypeSwitched(engine as never).then(() => null, (error: unknown) => error); + } finally { + await stack.shutdown(); + } +} + describe('os migrate protocol --to 19', () => { it('previews by default: lists the move, says it can switch, writes nothing, exits 0', async () => { const db = caseDb(templateDb); @@ -250,10 +289,17 @@ describe('os migrate protocol --to 19', () => { expect(applied.payload.refusal).toContain('Nothing was written'); expect(await storeSnapshot(db)).toBe(before); expect(await switchMarker(db)).toBeUndefined(); + // A held switch records nothing, so the served boot still refuses this database. + const refusal = await guardRefusal(db); + expect(isFormTypeSwitchBootRefusal(refusal), String(refusal)).toBe(true); }, CASE_TIMEOUT_MS); it('--apply on a deployment that can switch moves the row, checks again, and records the verified switch marker', async () => { const db = caseDb(templateDb); + // Before the switch the served boot refuses this database, naming this command. + const before = await guardRefusal(db); + expect(isFormTypeSwitchBootRefusal(before), String(before)).toBe(true); + expect((before as Error).message).toContain("'os migrate protocol --to 19 --apply --yes'"); const { payload, exitCode } = await runJson(['--to', '19', '--apply', '--yes', '--database-url', `file:${db}`, '--json']); expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); expect(exitCode).toBe(0); @@ -270,7 +316,11 @@ describe('os migrate protocol --to 19', () => { const marker = await switchMarker(db); expect(marker?.verified_at).toBeTruthy(); expect(marker?.blocking).toBe(0); + // The ceremony ran here: the record says so. + expect(marker?.applied_at).toBeTruthy(); expect(JSON.parse(marker.details).ceremony.removed[0].form).toBe(CREATE); + // The record is what the served boot reads: it admits the database now. + expect(await guardRefusal(db)).toBeNull(); // A second run finds nothing to move, and re-verifies. const again = await runJson(['--to', '19', '--apply', '--yes', '--database-url', `file:${db}`, '--json']); expect(again.exitCode).toBe(0); @@ -278,6 +328,24 @@ describe('os migrate protocol --to 19', () => { expect(again.payload.ceremony.removed).toEqual([]); }, CASE_TIMEOUT_MS); + it('a database with no sys_metadata table stores no form: --apply records the switch on the census alone, and claims no ceremony', async () => { + // A file that does not exist yet: no table at all, the marker's included. + const db = join(dir, 'cases', 'no-tables.db'); + mkdirSync(dirname(db), { recursive: true }); + const { payload, exitCode } = await runJson(['--to', '19', '--apply', '--yes', '--database-url', `file:${db}`, '--json']); + expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined(); + expect(exitCode).toBe(0); + expect(payload).toMatchObject({ switched: true, canSwitch: true }); + expect(payload.counts).toMatchObject({ keep: 0, move: 0, remove: 0, hold: 0 }); + expect(payload.ceremony).toMatchObject({ written: [], removed: [], rowsChanged: [] }); + const marker = await switchMarker(db); + expect(marker?.verified_at).toBeTruthy(); + expect(marker?.blocking).toBe(0); + // `applied_at` says the ceremony ran, and here it was never asked. + expect(marker?.applied_at).toBeNull(); + expect(await guardRefusal(db)).toBeNull(); + }, CASE_TIMEOUT_MS); + it('refuses a major it does not switch to', async () => { const db = caseDb(emptyDb); const { exitCode } = await runJson(['--to', '18', '--database-url', `file:${db}`, '--json']); diff --git a/packages/cli/src/commands/migrate/protocol.ts b/packages/cli/src/commands/migrate/protocol.ts index 215c4fd4dc7..135e51f7da6 100644 --- a/packages/cli/src/commands/migrate/protocol.ts +++ b/packages/cli/src/commands/migrate/protocol.ts @@ -103,8 +103,22 @@ async function confirm(question: string): Promise { * * ⛔ No write precedes the switch verdict: a held precheck writes no form row, * no pair and no marker; a database whose driver cannot roll back a - * transaction is refused before the ceremony is asked. The marker is the - * switch's record; no boot reads it in this release. + * transaction is refused before the ceremony is asked. + * + * The marker is the switch's record, and the served boot reads it: `os serve` + * refuses to start on a database without it and names this command + * (`FormTypeSwitchBootGuardPlugin`, `@objectstack/runtime`). A database a + * protocol-19 boot created from empty carries it from birth, so a new project + * never runs this command. + * + * ## A database with no `sys_metadata` table + * + * It stores no metadata row, so no form in any shape: there is no ceremony to + * run. Step 1 is skipped, the census of steps 2 and 3 is the empty one, and + * the marker is recorded verified with `applied_at` left unset, because this + * run moved nothing. Where the marker's own table is not there either, the + * run performs the DDL its boot held back before it writes the row: the one + * DDL this command ever performs, and only after the verdict. * * ## The refusal * @@ -208,7 +222,9 @@ export default class MigrateProtocol extends Command { composeHostStack: true, composeAuthGatedSecurity: true, serveFlags: { dev: flags.dev === true, ...(flags.preset ? { preset: flags.preset } : {}) }, - // The switch writes metadata rows and one `sys_migration` row, never DDL. + // The boot holds its DDL back: the switch writes metadata rows and one + // `sys_migration` row. Its only DDL is the flush below, after the + // verdict, on a database that has no table for that row yet. deferSchemaDdl: true, ...(apply ? {} : { readOnlyProbe: true }), }); @@ -369,7 +385,9 @@ export default class MigrateProtocol extends Command { passed: true, blocking: 0, advisory: 0, - applied: true, + // `applied_at` says the ceremony ran. With no `sys_metadata` table it + // was never asked: the row is the census's verdict alone. + applied: !noMetadataTable, details: { protocol: to, counts: after.precheck.counts, ceremony: ceremonyJson(result) }, }); if (typeof flagEngine.invalidateDataMigrationFlags === 'function') flagEngine.invalidateDataMigrationFlags(); diff --git a/packages/cli/src/commands/migrate/stored-forms.integration.test.ts b/packages/cli/src/commands/migrate/stored-forms.integration.test.ts index 39648eaec7d..6c3fd72ff4a 100644 --- a/packages/cli/src/commands/migrate/stored-forms.integration.test.ts +++ b/packages/cli/src/commands/migrate/stored-forms.integration.test.ts @@ -7,8 +7,9 @@ * ## The fixture * * A compiled artifact (`dist/objectstack.json`) whose package ships an object - * and a linked public form in an old shape (`formViews.contact`), over a - * database an older release left behind with, bound to no package: + * and a linked public form as a `forms:` item named `OBJECT.contact` (the + * shape a package authors a form in from protocol 19), over a database an + * older release left behind with, bound to no package: * * - a `viewKind: 'form'` row of the package's form that switches it off * (moves into the package's pair as a declared override); @@ -51,6 +52,7 @@ const OBJECT = 'm37111_inquiry'; const FORM = `${OBJECT}.contact`; const BROKEN = `${OBJECT}.broken`; const SLUG = 'contact-m37111'; +/** The form body an older release stored under a view row's `config`: the old shape, kept as written. */ const formBody = (enabled: boolean) => ({ type: 'simple', sections: [{ fields: ['name'] }], @@ -65,7 +67,16 @@ const ARTIFACT = { sharingModel: 'private', fields: { name: { name: 'name', label: 'Name', type: 'text' } }, }], - views: [{ object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }, formViews: { contact: formBody(true) } }], + views: [{ object: OBJECT, list: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }], + // The package's form as authored at protocol 19: a `forms:` item, bound by + // `object`. The old-shape data this command reads is the stored rows below. + forms: [{ + name: FORM, + object: OBJECT, + type: 'simple', + sections: [{ fields: ['name'] }], + sharing: { publicLink: `/forms/${SLUG}`, enabled: true, allowAnonymous: true }, + }], }; interface SeedRow { type: string; name: string; state: string; body: Record; packageId?: string } diff --git a/packages/cli/src/commands/migrate/stored-forms.ts b/packages/cli/src/commands/migrate/stored-forms.ts index 51a30db2db7..53262aef1e0 100644 --- a/packages/cli/src/commands/migrate/stored-forms.ts +++ b/packages/cli/src/commands/migrate/stored-forms.ts @@ -147,7 +147,7 @@ function holdText(hold: StoredFormHold): string { /** * `os migrate stored-forms` — the read-only run of the stored-form ceremony - * (ADR-0159 D7, card ⑤a): what the upgrade to the next protocol major does with + * (ADR-0159 D7, card ⑤a): what the upgrade to protocol 19 does with * every stored row that holds a form in an old shape (a `view` container's * `form`, a `formViews` entry, a `viewKind: 'form'` item), and the precheck — * whether that upgrade may switch. @@ -187,7 +187,7 @@ function holdText(hold: StoredFormHold): string { */ export default class MigrateStoredForms extends Command { static override description = - 'List what the upgrade to the next protocol major does with the stored rows that hold a form in an old shape ' + 'List what the upgrade to protocol 19 does with the stored rows that hold a form in an old shape ' + '(a view container\'s form, a formViews entry, a viewKind: \'form\' item), and whether it can switch: the rows ' + 'it moves, folds and removes, and the rows that hold it, with the action for each (ADR-0159 D7). Read-only.'; diff --git a/packages/cli/src/commands/serve-form-type-switch-refusal.integration.test.ts b/packages/cli/src/commands/serve-form-type-switch-refusal.integration.test.ts new file mode 100644 index 00000000000..7324d376ded --- /dev/null +++ b/packages/cli/src/commands/serve-form-type-switch-refusal.integration.test.ts @@ -0,0 +1,267 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { spawn, spawnSync, type ChildProcessByStdio } from 'node:child_process'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import type { Readable } from 'node:stream'; +import { fileURLToPath } from 'node:url'; +import Database from 'better-sqlite3'; +import { FORM_TYPE_SWITCH_MIGRATION_ID } from '@objectstack/spec/system'; + +/** + * [ADR-0159 D7] A real `os serve` boot serves a database only once the + * protocol-19 switch is recorded on it. + * + * The guard's own decisions are pinned on a real kernel in + * `@objectstack/runtime` (`form-type-switch-boot-guard.kernel.test.ts`), and + * the upgrade sequence on the showcase in + * `form-type-switch-boot-refusal.dogfood.test.ts`. Both compose the guard + * themselves. What is pinned HERE is the wiring only `serve.ts` owns, on the + * shipped entrypoint in production posture, one boot per shape: + * + * 1. a database this boot creates is served, and carries the switch record + * from birth (`details.birth`); + * 2. the same database with that record gone, which is how a database an + * earlier release created reads, is refused: the process exits non-zero + * before its ready banner and names `os migrate protocol --to 19`, + * without printing the auth secret it ran with; + * 3. a stack plugin registered under the guard's own name does not take its + * place (a later registration under one name replaces the earlier one): + * the boot is refused, naming the plugin name. Shapes 1 and 2 are its + * control: the same stack with that plugin under a name of its own; + * 4. the named command, through the same binary, records the switch, and the + * next boot is served. + * + * ## Why `bin/run.js` with `NODE_ENV` unset + * + * Production posture, which `bin/run-dev.js` cannot reach; `NODE_ENV` unset is + * also what makes oclif resolve the command from `dist/`, so this file needs a + * built CLI (CI declares it: `@objectstack/cli#test` dependsOn `build`). + * `src/` cannot import `test/helpers/serve-process.ts`, so the few helpers it + * needs are local, as in `serve-no-server-banner.integration.test.ts`. + */ + +const HERE = dirname(fileURLToPath(import.meta.url)); +/** `bin/run.js` — the SHIPPED entrypoint. See the header for why this one. */ +const CLI = resolve(HERE, '../../bin/run.js'); +/** What one build emits for every command; its absence means "never built". */ +const BUILT_SERVE = resolve(HERE, '../../dist/commands/serve.js'); + +/** The complete banner — keyed on its LAST line, so the whole block is on the stream. */ +const READY_BANNER_TAIL = /Press Ctrl\+C to stop/; + +const AUTH_SECRET = 'os-37112-auth-secret-not-a-real-credential'; +const SECRET_KEY = '0e2e'.repeat(16); +const GUARD_NAME = 'com.objectstack.form-type-switch-boot-guard'; + +const OBJECT = `{ name: 'fx_task', label: 'Task', pluralLabel: 'Tasks', fields: { title: { type: 'text', label: 'Title' } } }`; +const MANIFEST = `{ id: 'com.example.fx37112', namespace: 'fx', version: '1.0.0', type: 'app', name: 'Fx' }`; +/** An instantiated plugin, which is what makes this a HOST config. */ +const hostPlugin = (name: string) => `{ name: '${name}', version: '1.0.0', init: async () => {}, start: async () => {} }`; + +/** What `spawn(…, { stdio: ['ignore', 'pipe', 'pipe'] })` returns — no `stdin`. */ +type BootChild = ChildProcessByStdio; + +const children: BootChild[] = []; +let root: string; +/** One object and a host plugin under a name of its own. */ +let plainDir: string; +/** The same, the host plugin registered under the guard's name. */ +let impostorDir: string; + +/** The root of an installed dependency of this package, found through `node_modules`. */ +function packageRoot(specifier: string): string { + let dir = dirname(createRequire(import.meta.url).resolve(specifier)); + while (!existsSync(join(dir, 'package.json'))) { + if (dirname(dir) === dir) throw new Error(`${specifier} resolved to no package root`); + dir = dirname(dir); + } + return dir; +} + +function writeFixture(dir: string, pluginName: string): void { + mkdirSync(join(dir, 'node_modules', '@objectstack'), { recursive: true }); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'fx-37112', private: true, type: 'module' })); + writeFileSync( + join(dir, 'objectstack.config.ts'), + `import { defineStack } from '@objectstack/spec';\n` + + `export default defineStack({ manifest: ${MANIFEST}, objects: [${OBJECT}], plugins: [${hostPlugin(pluginName)}] });\n`, + ); + symlinkSync(packageRoot('@objectstack/spec'), join(dir, 'node_modules', '@objectstack', 'spec'), 'dir'); +} + +/** + * This process's environment for a child, minus the vitest worker family and + * every input that would point the boot at another store. An `undefined` + * entry unsets a variable. + */ +function childEnv(cwd: string, database: string): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key === 'TEST' || key === 'VITEST' || key.startsWith('VITEST_') || key === 'NODE_PATH') continue; + env[key] = value; + } + return { + ...env, + NO_COLOR: '1', + OS_LOG_LEVEL: '', + OS_DISABLE_CONSOLE: '1', + OS_CLOUD_URL: 'off', + OS_HOME: join(cwd, '.os-home'), + OS_SECRET_KEY: SECRET_KEY, + OS_DATABASE_URL: `file:${database}`, + DATABASE_URL: undefined, + OS_DATABASE_DRIVER: undefined, + OS_AUTH_SECRET: AUTH_SECRET, + OS_TENANCY_POSTURE: undefined, + OS_MULTI_ORG_ENABLED: undefined, + OS_AUTH_URL: undefined, + BETTER_AUTH_URL: undefined, + OS_BASE_URL: undefined, + // Truly unset: production posture, and oclif resolves the command from `dist/`. + NODE_ENV: undefined, + }; +} + +interface Outcome { + /** True when the complete ready banner printed (the child was then stopped). */ + served: boolean; + /** The exit code of a child that exited before its banner; null when it was served. */ + code: number | null; + output: string; +} + +/** + * Spawn `os serve --no-server` over `database` and resolve on whichever comes + * first: the complete ready banner (the child is then stopped and awaited, so + * the file is closed before the caller reads it) or the child's own exit. + */ +function serve(cwd: string, database: string): Promise { + const child = spawn(process.execPath, [CLI, 'serve', 'objectstack.config.ts', '--no-server'], { + cwd, + stdio: ['ignore', 'pipe', 'pipe'], + env: childEnv(cwd, database), + }) as BootChild; + children.push(child); + + let output = ''; + return new Promise((done, fail) => { + let served = false; + const timer = setTimeout(() => { + child.kill('SIGKILL'); + fail(new Error(`serve neither printed its complete banner nor exited\n--- output ---\n${output}`)); + }, 150_000); + const onData = (d: unknown) => { + output += String(d); + if (!served && READY_BANNER_TAIL.test(output)) { + served = true; + child.kill('SIGTERM'); + } + }; + child.stdout.on('data', onData); + child.stderr.on('data', onData); + child.on('exit', (code) => { + clearTimeout(timer); + done({ served, code: served ? null : code, output }); + }); + }); +} + +interface MarkerRow { verified_at: unknown; applied_at: unknown; blocking: unknown; details: unknown } + +/** The switch record of `database`, read on a connection of our own; undefined when there is none. */ +function switchMarker(database: string): MarkerRow | undefined { + const db = new Database(database, { readonly: true }); + try { + return db.prepare('SELECT verified_at, applied_at, blocking, details FROM sys_migration WHERE id = ?') + .get(FORM_TYPE_SWITCH_MIGRATION_ID) as MarkerRow | undefined; + } finally { + db.close(); + } +} + +let born: string; +let unswitched: string; + +beforeAll(() => { + if (!existsSync(BUILT_SERVE)) { + throw new Error( + `packages/cli is not built: ${BUILT_SERVE} does not exist. This file spawns bin/run.js with NODE_ENV unset, ` + + 'which resolves the command from dist/. Run: pnpm exec turbo run build --filter=@objectstack/cli', + ); + } + root = mkdtempSync(join(tmpdir(), 'os-serve-form-type-switch-')); + plainDir = join(root, 'plain'); + writeFixture(plainDir, 'com.example.fx37112.host-plugin'); + impostorDir = join(root, 'impostor'); + writeFixture(impostorDir, GUARD_NAME); + born = join(root, 'born.db'); + unswitched = join(root, 'unswitched.db'); +}); + +afterAll(() => { + for (const child of children) { + try { child.kill('SIGTERM'); } catch { /* already gone */ } + } + if (root) rmSync(root, { recursive: true, force: true }); +}); + +describe('os serve — a database is served only once the protocol-19 switch is recorded on it (ADR-0159 D7)', () => { + it('1. a database this boot creates is served, and carries the switch record from birth', async () => { + const outcome = await serve(plainDir, born); + expect(outcome.served, `not served\n--- output ---\n${outcome.output}`).toBe(true); + const marker = switchMarker(born); + expect(marker?.verified_at, 'the birth marker is a verified record').toBeTruthy(); + expect(Number(marker?.blocking)).toBe(0); + expect(marker?.applied_at ?? null, 'no ceremony ran, and the record claims none').toBeNull(); + expect(JSON.parse(String(marker?.details)).birth.protocol).toBe(19); + }, 240_000); + + it('2. the same database with no switch record is refused before the banner, naming the command and no credential', async () => { + // Every table of the served database, and no switch record: how a + // database an earlier release created reads to this boot. + copyFileSync(born, unswitched); + const db = new Database(unswitched); + try { + expect(db.prepare('DELETE FROM sys_migration WHERE id = ?').run(FORM_TYPE_SWITCH_MIGRATION_ID).changes).toBe(1); + } finally { + db.close(); + } + + const outcome = await serve(plainDir, unswitched); + const seen = `\n--- output ---\n${outcome.output}`; + expect(outcome.served, `an unswitched database was served${seen}`).toBe(false); + expect(outcome.code, `the refused boot exited 0${seen}`).not.toBe(0); + expect(outcome.output, `the refusal does not name the command${seen}`).toContain('os migrate protocol --to 19'); + expect(outcome.output, seen).toContain('--apply --yes'); + expect(outcome.output, `the refusal printed the auth secret${seen}`).not.toContain(AUTH_SECRET); + expect(switchMarker(unswitched), 'a refused boot records nothing').toBeUndefined(); + }, 240_000); + + it('3. a stack plugin under the guard\'s name does not take its place: the boot is refused, naming that name', async () => { + const database = join(root, 'impostor.db'); + copyFileSync(unswitched, database); + const outcome = await serve(impostorDir, database); + const seen = `\n--- output ---\n${outcome.output}`; + expect(outcome.served, `the database was served behind a plugin that took the guard's name${seen}`).toBe(false); + expect(outcome.code, `the refused boot exited 0${seen}`).not.toBe(0); + expect(outcome.output, `the refusal does not name the plugin name${seen}`).toContain(`'${GUARD_NAME}'`); + expect(switchMarker(database), 'a refused boot records nothing').toBeUndefined(); + }, 240_000); + + it('4. the named command records the switch through the same binary, and the next boot is served', async () => { + const database = join(root, 'switched.db'); + copyFileSync(unswitched, database); + const run = spawnSync(process.execPath, [CLI, 'migrate', 'protocol', '--to', '19', '--apply', '--yes'], { + cwd: plainDir, encoding: 'utf8', timeout: 200_000, env: childEnv(plainDir, database) as NodeJS.ProcessEnv, + }); + expect(run.status, `${run.stdout}\n${run.stderr}`).toBe(0); + expect(switchMarker(database)?.verified_at, 'the command verified its record').toBeTruthy(); + + const outcome = await serve(plainDir, database); + expect(outcome.served, `not served after the switch\n--- output ---\n${outcome.output}`).toBe(true); + }, 480_000); +}); diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index 93e7c7aa40c..45cc2582518 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -4496,6 +4496,32 @@ export default class Serve extends Command { trackPlugin('OrganizationOwnershipBootGuard'); } + // 5c-quater. [ADR-0159 D7; ruling record 7303149461] The protocol-19 + // boot refusal, beside the ownership one and judged after it: it + // refuses to start a database whose switch (`os migrate protocol --to + // 19`) is not recorded, naming the command, and writes the switch + // record as a birth marker on a store this boot creates from empty + // (ruling record 7308112533). Composed HERE, ahead of the auth family + // and the stack's own plugins, on served kernels only: + // ⛔ never in `createStandaloneStack`, which the switch command's own + // boot shares. ⛔ Always this command's own instance, and nothing skips + // it: a stack plugin that carries its name would replace it, and is + // refused before `runtime.start()` below. + const { FormTypeSwitchBootGuardPlugin, assertFormTypeSwitchGuardNotReplaced } = await import('@objectstack/runtime'); + // The refusal names the command as this boot was started (`--dev`, + // `--preset`, the database and the connection its parent's flags chose), + // so run verbatim it switches the database that was refused. + const switchDatabase = readCeremonyDatabaseChannel(process.env); + const formTypeSwitchGuard = new FormTypeSwitchBootGuardPlugin({ + dev: isDev, + ...(flags.preset ? { preset: flags.preset } : {}), + authSecretFile: readAuthSecretFileChannel(process.env), + ...(switchDatabase ? { databaseUrl: switchDatabase } : {}), + ...readCeremonyConnectionChannel(process.env), + }); + await kernel.use(formTypeSwitchGuard); + trackPlugin('FormTypeSwitchBootGuard'); + // The ONE secret crypto provider, built below (`createHostCryptoProvider`, // after the stack's plugins are checked) and declared here, because the // AuditPlugin of 5d is composed before it exists and reads it when its @@ -6073,6 +6099,10 @@ export default class Serve extends Command { // refused by the kernel itself when it happens. refuseTwoCryptoProviderPlugins([...stackMountedPlugins, ...resolverMounted]); + // [ADR-0159 D7] The protocol-19 boot guard stays this command's own + // instance: see `assertFormTypeSwitchGuardNotReplaced`. + assertFormTypeSwitchGuardNotReplaced(formTypeSwitchGuard, [...stackMountedPlugins, ...resolverMounted]); + // Boot the runtime await runtime.start(); @@ -6511,17 +6541,23 @@ export default class Serve extends Command { // so the kernel hands it on as the `cause` of its own start-failure // error: the refusal is looked for down the chain, and its own text is // what this boot prints. - const { isOrganizationOwnershipBootRefusal } = await import('@objectstack/runtime'); + // + // [ADR-0159 D7] The protocol-19 guard refuses the same way, and its own + // text is printed the same way. It has no development exception: a + // development database an earlier release created runs the command once. + const { isOrganizationOwnershipBootRefusal, isFormTypeSwitchBootRefusal } = await import('@objectstack/runtime'); let ownershipRefusal: { tables: readonly string[]; message: string } | undefined; - for (let cause: unknown = error, depth = 0; !ownershipRefusal && cause && typeof cause === 'object' && depth < 8; depth++) { + let switchRefusal: { message: string } | undefined; + for (let cause: unknown = error, depth = 0; !ownershipRefusal && !switchRefusal && cause && typeof cause === 'object' && depth < 8; depth++) { if (isOrganizationOwnershipBootRefusal(cause)) ownershipRefusal = cause; + else if (isFormTypeSwitchBootRefusal(cause)) switchRefusal = cause; cause = (cause as { cause?: unknown }).cause; } if (ownershipRefusal && isDev && typeof process.send === 'function') { const sent = await announceOrganizationOwnershipRequired([...ownershipRefusal.tables]); if (sent) this.exit(1); } - printError(ownershipRefusal?.message || error.message || String(error)); + printError(ownershipRefusal?.message || switchRefusal?.message || error.message || String(error)); // A boot that died is when its warnings matter most, and the banner that // would normally carry them never printed (#4012). const diagnostics = collectBootDiagnostics(); diff --git a/packages/cli/src/utils/organization-ownership-apply.declared-rule-mirrors.test.ts b/packages/cli/src/utils/organization-ownership-apply.declared-rule-mirrors.test.ts index bc68b8c32fa..1f2b2bfd781 100644 --- a/packages/cli/src/utils/organization-ownership-apply.declared-rule-mirrors.test.ts +++ b/packages/cli/src/utils/organization-ownership-apply.declared-rule-mirrors.test.ts @@ -60,6 +60,17 @@ import { mergeHostFateSupplement, type InventoryEntry } from './organization-own // Loaded at module top: the plugin's first load is paid here, not inside a clocked test. import { translateDeclaredSharingRule } from '@objectstack/plugin-sharing'; +// Pay the first load of what the source under test reaches through dynamic +// `import()`s at MODULE LOAD, outside the clocked cases. +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/runtime'; +import '@objectstack/service-datasource'; + /** * The seeding-release case answers as a release whose boot still seeds them * (`runs: true`); every other case reads the shipped constant, through the @@ -176,7 +187,7 @@ async function apply( }, }, templates: { async find() { return undefined; } }, - views: { async list() { return []; } }, + forms: { async list() { return []; } }, lock: { async verdict() { return { editable: true }; } }, columnDrops, ledger: l, diff --git a/packages/cli/src/utils/organization-ownership-apply.generation-1.test.ts b/packages/cli/src/utils/organization-ownership-apply.generation-1.test.ts index 4424afa3395..2f206dee751 100644 --- a/packages/cli/src/utils/organization-ownership-apply.generation-1.test.ts +++ b/packages/cli/src/utils/organization-ownership-apply.generation-1.test.ts @@ -157,7 +157,7 @@ async function apply( }, }, templates: { async find() { return undefined; } }, - views: { async list() { return []; } }, + forms: { async list() { return []; } }, lock: { async verdict() { return { editable: true }; } }, columnDrops, ledger: l, diff --git a/packages/cli/src/utils/organization-ownership-apply.not-null-resume.test.ts b/packages/cli/src/utils/organization-ownership-apply.not-null-resume.test.ts index 50cef939245..df584676099 100644 --- a/packages/cli/src/utils/organization-ownership-apply.not-null-resume.test.ts +++ b/packages/cli/src/utils/organization-ownership-apply.not-null-resume.test.ts @@ -144,7 +144,7 @@ async function apply( }, }, templates: { async find() { return undefined; } }, - views: { async list() { return []; } }, + forms: { async list() { return []; } }, lock: { async verdict() { return { editable: true }; } }, columnDrops: { async drop(columns) { return columns.map((c) => ({ ...c, outcome: 'dropped' as const })); } }, ledger: l, diff --git a/packages/cli/src/utils/organization-ownership-apply.served-catalog.integration.test.ts b/packages/cli/src/utils/organization-ownership-apply.served-catalog.integration.test.ts index cdbce401a72..811ed827d91 100644 --- a/packages/cli/src/utils/organization-ownership-apply.served-catalog.integration.test.ts +++ b/packages/cli/src/utils/organization-ownership-apply.served-catalog.integration.test.ts @@ -61,6 +61,13 @@ import '@objectstack/metadata-protocol'; import '@objectstack/platform-objects/plugin'; import '@objectstack/plugin-security'; +// Pay the first load of what the source under test reaches through dynamic +// `import()`s at MODULE LOAD, outside the clocked cases. +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/rest'; +import '@objectstack/service-datasource'; + const CASE_TIMEOUT_MS = 180_000; const PACKAGE_ID = 'com.example.ownership-catalog'; const ENV_KEYS = ['OS_ARTIFACT_PATH', 'OS_DATABASE_URL', 'DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', 'NODE_ENV', @@ -148,8 +155,8 @@ async function ceremony(posture: string, db: Database.Database): Promise [] }, + // No form is served here: the form-withdrawal carry has nothing to judge. + forms: { list: async () => [] }, // The save door's own verdict, as the command reads it: the item read's `editable`. lock: { verdict: async (type, name, packageId) => { diff --git a/packages/cli/src/utils/organization-ownership-apply.siblings.test.ts b/packages/cli/src/utils/organization-ownership-apply.siblings.test.ts index 63c4bb43a8d..56ae47b3e7b 100644 --- a/packages/cli/src/utils/organization-ownership-apply.siblings.test.ts +++ b/packages/cli/src/utils/organization-ownership-apply.siblings.test.ts @@ -31,6 +31,17 @@ import { type OrganizationOwnershipApplyReport, } from './organization-ownership-apply.js'; +// Pay the first load of what the source under test reaches through dynamic +// `import()`s at MODULE LOAD, outside the clocked cases. +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/runtime'; +import '@objectstack/service-datasource'; + let dir: string; let primary: Database.Database; let telemetry: Database.Database; @@ -115,7 +126,7 @@ async function apply(warnings: string[] = []): Promise>; /** Environment `view` saves, in order, with the package each was saved into. */ viewSaves: Array<{ name: string; body: Record; packageId: string | null }>; + /** Environment `form` saves (the withdrawal carry), in order, with the package each was saved into. */ + formSaves: Array<{ name: string; body: Record; packageId: string | null }>; boot(): void; } { const declared = new Map>([ @@ -108,10 +121,12 @@ function catalog(opts: { adminSetDeclared?: boolean } = {}): CatalogPort & Metad ]); let hydrated = new Map>(); const viewSaves: Array<{ name: string; body: Record; packageId: string | null }> = []; + const formSaves: Array<{ name: string; body: Record; packageId: string | null }> = []; return { saved, templates, viewSaves, + formSaves, async find(name, locale) { const own = templates.get(`${name}|${locale}`); if (own) return { definition: own, environment: true }; @@ -130,6 +145,10 @@ function catalog(opts: { adminSetDeclared?: boolean } = {}): CatalogPort & Metad viewSaves.push({ name, body, packageId: target?.packageId ?? null }); return; } + if (type === 'form') { + formSaves.push({ name, body, packageId: target?.packageId ?? null }); + return; + } if (type === 'email_template') { if (!/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/.test(name)) throw new Error(`VALIDATION_ERROR: ${name} is not dotted snake_case`); templates.set(`${name}|${String(body.locale)}`, body); @@ -141,7 +160,10 @@ function catalog(opts: { adminSetDeclared?: boolean } = {}): CatalogPort & Metad }; } -/** A form view the code package `pkg_a` ships, open to anonymous intake at `/forms/lead-intake`. */ +/** + * A stored 17.x form view, open to anonymous intake at `/forms/lead-intake`: + * the old-shape body an organization's row (and an environment row) holds. + */ const formView = (open: boolean, label = 'Lead intake'): Record => ({ name: 'crm_lead.intake', label, @@ -151,11 +173,40 @@ const formView = (open: boolean, label = 'Lead intake'): Record }); /** - * The env-wide view list as the anonymous doors read it: the code package's - * items, replaced per (name, package) by the active environment rows of - * `sys_metadata` and then by the door's saves this run. + * [ADR-0159 D7] The `form` item the code package `pkg_a` ships since protocol + * 19, open to anonymous intake at the same link: a form is its own item, its + * `sharing` at the top level. */ -function servedViews(c: ReturnType, code: Array> = [{ ...formView(true), _packageId: 'pkg_a' }]): ServedViewsPort { +const formItem = (open: boolean, label = 'Lead intake'): Record => ({ + name: 'crm_lead.intake', + label, + object: 'crm_lead', + sharing: { enabled: open, allowAnonymous: true, publicLink: '/forms/lead-intake' }, +}); + +/** Whether `sys_metadata` still carries the organization column (column-drops has not run). */ +const metadataScoped = (): boolean => rows(`SELECT name FROM pragma_table_info('sys_metadata') WHERE name = 'organization_id'`).length > 0; +const hasMetadataTable = (): boolean => rows(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sys_metadata'`).length > 0; + +/** The active environment rows of `type`, as stored; once column-drops has run, every row left is the environment's. */ +function environmentBodies(type: 'view' | 'form'): Array<{ body: Record; pkg: string | null }> { + if (!hasMetadataTable()) return []; + return rows(`SELECT * FROM sys_metadata WHERE type = '${type}' AND state = 'active'${metadataScoped() ? ' AND organization_id IS NULL' : ''}`) + .map((row) => ({ body: JSON.parse(String(row.metadata)) as Record, pkg: (row.package_id as string | null) ?? null })); +} + +/** + * The env-wide `form` list the anonymous doors offer their candidates from: + * the code package's `form` items, replaced per (name, package) by the active + * environment `form` rows of `sys_metadata` and then by the door's `form` + * saves this run. `saves: false` leaves the door's saves out, to read what the + * stored rows alone serve. + */ +function servedForms( + c: ReturnType, + code: Array> = [{ ...formItem(true), _packageId: 'pkg_a' }], + opts: { saves?: boolean } = {}, +): ServedFormsPort { return { async list() { const slots = new Map>(); @@ -163,15 +214,8 @@ function servedViews(c: ReturnType, code: Array 0; - if (hasTable) { - // Once column-drops has run, every row left is the environment's. - const scoped = rows(`SELECT name FROM pragma_table_info('sys_metadata') WHERE name = 'organization_id'`).length > 0; - for (const row of rows(`SELECT * FROM sys_metadata WHERE type = 'view' AND state = 'active'${scoped ? ' AND organization_id IS NULL' : ''}`)) { - put(JSON.parse(String(row.metadata)) as Record, (row.package_id as string | null) ?? null); - } - } - for (const save of c.viewSaves) put(save.body, save.packageId); + for (const { body, pkg } of environmentBodies('form')) put(body, pkg); + if (opts.saves !== false) for (const save of c.formSaves) put(save.body, save.packageId); return [...slots.values()]; }, }; @@ -196,7 +240,7 @@ function storingDoor(c: ReturnType): ReturnType async save(type, name, body, target) { await c.save(type, name, body, target); // The catalog conversion and the template promotion keep the catalog double's own store. - if (!['view', 'dashboard', 'report', 'translation'].includes(type)) return; + if (!['view', 'form', 'dashboard', 'report', 'translation'].includes(type)) return; const pkg = target?.packageId ?? null; let version = 1; if (has('sys_metadata_history')) { @@ -240,15 +284,29 @@ function storingDoor(c: ReturnType): ReturnType }; } -/** What the anonymous doors serve for a slug, by their own judgement over the env-wide list. */ -async function doorsServe(views: ServedViewsPort, slug: string): Promise { - const list = await views.list(); +/** + * The anonymous doors' withdrawal layer over what they read (ADR-0159 D6): + * the served `form` items and the stored environment `view` rows, raw (a + * 17.x old-shape row's withdrawal closes the form of its name). + */ +async function doorsLayer(forms: ServedFormsPort) { + return formIntakeLayer({ forms: await forms.list(), views: environmentBodies('view').map((v) => v.body) }); +} + +/** What the anonymous doors serve for a slug, by their own judgement: each served form the layer leaves open there. */ +async function doorsServe(forms: ServedFormsPort, slug: string): Promise { + const list = await forms.list(); + const layer = await doorsLayer(forms); return list - .filter((v) => anonymousFormIntakeCandidates(v).some((cand) => cand.slug === slug && !anonymousFormIntakeWithdrawnIn(list, v, cand))) - .map((v) => `${String(v.name)}|${String(v._packageId ?? '')}`) + .filter((f) => openFormAt([f], layer, slug) !== null) + .map((f) => `${String(f.name)}|${String(f._packageId ?? '')}`) .sort(); } +/** Whether the stored environment `view` rows alone withdraw the form `name` at the doors. */ +const storedRowsWithdraw = (name: string): boolean => + formIntakeLayer({ forms: [], views: environmentBodies('view').map((v) => v.body) }).withdrawn.has(name); + function ledger(): CeremonyLedgerPort & { checkpoint: CeremonyCheckpoint | null; verdicts: Array<{ complete: boolean; blocking: number; advisory: number }> } { const state = { checkpoint: null as CeremonyCheckpoint | null, @@ -459,7 +517,7 @@ const apply = ( executor?: ApplyExecutor; templateChoices?: string[]; metadataChoices?: string[]; - views?: ServedViewsPort; + forms?: ServedFormsPort; columnDrops?: ColumnDropPort; reviewed?: Partial; lock?: MetadataLockPort; @@ -472,7 +530,7 @@ const apply = ( ): Promise => { c.boot(); return reviewedConflictsNow(opts.posture ?? 'single').then((conflicts) => applyOrganizationOwnership({ - views: opts.views ?? servedViews(c), + forms: opts.forms ?? servedForms(c), lock: opts.lock ?? { verdict: async () => ({ editable: true }) }, // The plan the operator reviewed: by default, the one a plan run computes // over the database as it stands, conflict groups included. @@ -1219,47 +1277,58 @@ describe('ADR-0131 D10 --apply — organization customizations and form withdraw // The organization withdrew the package-less copy; package pkg_a serves its own copy, open. metadataTable(md('md_org', 'org_default', 'view', 'crm_lead.intake', formView(false, 'Org copy'))); const c = catalog(); - const views = servedViews(c); - expect(await doorsServe(views, 'lead-intake')).toEqual(['crm_lead.intake|pkg_a']); + const forms = servedForms(c); + expect(await doorsServe(forms, 'lead-intake')).toEqual(['crm_lead.intake|pkg_a']); - const report = await apply(c, ledger(), { posture, views }); + const report = await apply(c, ledger(), { posture, forms }); expect(step(report).status).toBe('done'); expect(step(report).summary.withdrawalsCarried).toBe(1); - // Carried onto pkg_a's own copy, through the door, into its own package. - expect(c.viewSaves.map((v) => [v.name, v.packageId, (v.body.config as any).sharing.enabled])).toEqual([ + // Carried onto pkg_a's own `form`, through the door, into its own package. + expect(c.formSaves.map((v) => [v.name, v.packageId, (v.body.sharing as any).enabled])).toEqual([ ['crm_lead.intake', 'pkg_a', false], ]); - expect(await doorsServe(views, 'lead-intake')).toEqual([]); + expect(c.viewSaves).toEqual([]); + expect(await doorsServe(forms, 'lead-intake')).toEqual([]); // Idempotent: a second run (no checkpoint) carries nothing more. - const again = await apply(c, ledger(), { posture, views }); + const again = await apply(c, ledger(), { posture, forms }); expect(step(again).summary.withdrawalsCarried).toBe(0); - expect(c.viewSaves).toHaveLength(1); + expect(c.formSaves).toHaveLength(1); }); } it('⭐ under single, a withdrawal the organization holds on the key it alone holds travels with the promoted row', async () => { metadataTable(md('md_org', 'org_default', 'view', 'crm_lead.intake', formView(false, 'Org copy'), 'pkg_a')); const c = catalog(); - const views = servedViews(c); + const forms = servedForms(c); + expect(storedRowsWithdraw('crm_lead.intake')).toBe(false); - const report = await apply(c, ledger(), { views }); + const report = await apply(c, ledger(), { forms }); - expect(step(report).summary).toMatchObject({ promoted: 1, withdrawalsCarried: 0 }); + // The promoted row is the environment's, its body as stored: no view is + // saved over it, and on its own it withdraws the form at the doors (the + // stored old-shape row is in their layer). The served `form` is a + // different key, so the carry closes it too, fail-closed. + expect(step(report).summary).toMatchObject({ promoted: 1, withdrawalsCarried: 1 }); expect(c.viewSaves).toEqual([]); expect(owners()).toEqual([['md_org', null]]); - expect(await doorsServe(views, 'lead-intake')).toEqual([]); + expect(storedRowsWithdraw('crm_lead.intake')).toBe(true); + expect(await doorsServe(servedForms(c, undefined, { saves: false }), 'lead-intake')).toEqual([]); + expect(await doorsServe(forms, 'lead-intake')).toEqual([]); }); it('control: an organization row that withdraws nothing carries nothing, and the form stays served', async () => { metadataTable(md('md_org', 'org_default', 'view', 'crm_lead.intake', formView(true, 'Org copy'))); const c = catalog(); - const views = servedViews(c); - const report = await apply(c, ledger(), { views }); + const forms = servedForms(c); + const report = await apply(c, ledger(), { forms }); expect(step(report).summary.withdrawalsCarried).toBe(0); expect(c.viewSaves).toEqual([]); - expect(await doorsServe(views, 'lead-intake')).toEqual(['crm_lead.intake|', 'crm_lead.intake|pkg_a']); + expect(c.formSaves).toEqual([]); + // The promoted row withdraws nothing; the served `form` stays open. + expect(storedRowsWithdraw('crm_lead.intake')).toBe(false); + expect(await doorsServe(forms, 'lead-intake')).toEqual(['crm_lead.intake|pkg_a']); }); it('a door that refuses the carry blocks the step, naming the form and the remedy', async () => { @@ -1268,16 +1337,16 @@ describe('ADR-0131 D10 --apply — organization customizations and form withdraw const refusing: ReturnType = { ...c, async save(type, name, body, target) { - if (type === 'view') throw new Error('NOT_OVERRIDABLE: the view is sealed'); + if (type === 'form') throw new Error('NOT_OVERRIDABLE: the form is sealed'); return c.save(type, name, body, target); }, }; - const report = await apply(refusing, ledger(), { views: servedViews(c) }); + const report = await apply(refusing, ledger(), { forms: servedForms(c) }); expect(step(report).status).toBe('blocked'); - expect(step(report).blockers.join('\n')).toMatch(/lead-intake of the view crm_lead\.intake \(package pkg_a\).*NOT_OVERRIDABLE.*sharing\.enabled false/); + expect(step(report).blockers.join('\n')).toMatch(/lead-intake of the form crm_lead\.intake \(package pkg_a\).*NOT_OVERRIDABLE.*sharing\.enabled false/); }); - describe('[ADR-0146 D1, D2, D3] a read-only package\'s view takes the withdrawal in its .custom pair', () => { + describe('[ADR-0146 D1, D2, D3] a read-only package\'s form takes the withdrawal in its .custom pair', () => { /** The pair doors: `readOnly` names the read-only packages; the ensure door answers `.custom` at version 2.1.0. */ const pairsOf = (readOnly: readonly string[], refuseEnsure?: string): CustomizationPairPort & { ensured: string[] } => { const ensured: string[] = []; @@ -1296,8 +1365,8 @@ describe('ADR-0131 D10 --apply — organization customizations and form withdraw * save declaring the override of its base is served at the base's slot, * over the base's own document. */ - const servedOverPairs = (c: ReturnType): ServedViewsPort => { - const plain = servedViews(c); + const servedOverPairs = (c: ReturnType): ServedFormsPort => { + const plain = servedForms(c); return { async list() { const slots = new Map((await plain.list()).map((v) => [`${String(v.name)}|${String(v._packageId ?? '')}`, v])); @@ -1312,35 +1381,35 @@ describe('ADR-0131 D10 --apply — organization customizations and form withdraw }; }; const saved = (c: ReturnType) => - c.viewSaves.map((v) => [v.name, v.packageId, (v.body.config as any).sharing.enabled, v.body.overrides]); + c.formSaves.map((v) => [v.name, v.packageId, (v.body.sharing as any).enabled, v.body.overrides]); it('⭐ carried into the pair, declared at the base\'s version; the doors serve it withdrawn; a re-run carries nothing', async () => { metadataTable(md('md_org', 'org_default', 'view', 'crm_lead.intake', formView(false, 'Org copy'))); const c = catalog(); - const views = servedOverPairs(c); + const forms = servedOverPairs(c); const pairs = pairsOf(['pkg_a']); const progress: string[] = []; - expect(await doorsServe(views, 'lead-intake')).toEqual(['crm_lead.intake|pkg_a']); + expect(await doorsServe(forms, 'lead-intake')).toEqual(['crm_lead.intake|pkg_a']); - const report = await apply(c, ledger(), { views, pairs, onProgress: (m) => progress.push(m) }); + const report = await apply(c, ledger(), { posture: 'isolated', forms, pairs, onProgress: (m) => progress.push(m) }); expect(step(report)).toMatchObject({ status: 'done', summary: { withdrawalsCarried: 1 } }); expect(pairs.ensured).toEqual(['pkg_a']); // ⛔ Nothing saved naming the read-only base itself. expect(saved(c)).toEqual([['crm_lead.intake', 'pkg_a.custom', false, { package: 'pkg_a', basedOn: '2.1.0' }]]); expect(progress.filter((m) => m.includes('pkg_a.custom'))).toHaveLength(1); - expect(await doorsServe(views, 'lead-intake')).toEqual([]); + expect(await doorsServe(forms, 'lead-intake')).toEqual([]); - const again = await apply(c, ledger(), { views, pairs }); + const again = await apply(c, ledger(), { posture: 'isolated', forms, pairs }); expect(step(again).summary.withdrawalsCarried).toBe(0); - expect(c.viewSaves).toHaveLength(1); + expect(c.formSaves).toHaveLength(1); }); - it('a writable package\'s view is saved in place, as before; no pair is ensured', async () => { + it('a writable package\'s form is saved in place, as before; no pair is ensured', async () => { metadataTable(md('md_org', 'org_default', 'view', 'crm_lead.intake', formView(false, 'Org copy'))); const c = catalog(); const pairs = pairsOf([]); - const report = await apply(c, ledger(), { views: servedViews(c), pairs }); + const report = await apply(c, ledger(), { forms: servedForms(c), pairs }); expect(step(report)).toMatchObject({ status: 'done', summary: { withdrawalsCarried: 1 } }); expect(saved(c)).toEqual([['crm_lead.intake', 'pkg_a', false, undefined]]); expect(pairs.ensured).toEqual([]); @@ -1352,16 +1421,16 @@ describe('ADR-0131 D10 --apply — organization customizations and form withdraw const refusing: ReturnType = { ...c, async save(type, name, body, target) { - if (type === 'view') throw new Error('NOT_OVERRIDABLE: the read-only base takes no customization'); + if (type === 'form') throw new Error('NOT_OVERRIDABLE: the read-only base takes no customization'); return c.save(type, name, body, target); }, }; - const report = await apply(refusing, ledger(), { views: servedViews(c), pairs: pairsOf(['pkg_a'], 'NAMESPACE_CONFLICT: the pair namespace is held') }); + const report = await apply(refusing, ledger(), { forms: servedForms(c), pairs: pairsOf(['pkg_a'], 'NAMESPACE_CONFLICT: the pair namespace is held') }); expect(step(report).status).toBe('blocked'); const blocker = step(report).blockers.join('\n'); - expect(blocker).toMatch(/lead-intake of the view crm_lead\.intake \(package pkg_a\).*NOT_OVERRIDABLE/); + expect(blocker).toMatch(/lead-intake of the form crm_lead\.intake \(package pkg_a\).*NOT_OVERRIDABLE/); expect(blocker).toMatch(/customization package of pkg_a could not be ensured: NAMESPACE_CONFLICT/); - expect(c.viewSaves).toEqual([]); + expect(c.formSaves).toEqual([]); }); it('a door that refuses the declared save into the pair keeps the blocker too, naming that refusal', async () => { @@ -1370,20 +1439,20 @@ describe('ADR-0131 D10 --apply — organization customizations and form withdraw const refusing: ReturnType = { ...c, async save(type, name, body, target) { - if (type === 'view') throw new Error(`NOT_OVERRIDABLE: refused in ${String(target?.packageId)}`); + if (type === 'form') throw new Error(`NOT_OVERRIDABLE: refused in ${String(target?.packageId)}`); return c.save(type, name, body, target); }, }; - const report = await apply(refusing, ledger(), { views: servedViews(c), pairs: pairsOf(['pkg_a']) }); + const report = await apply(refusing, ledger(), { forms: servedForms(c), pairs: pairsOf(['pkg_a']) }); expect(step(report).status).toBe('blocked'); expect(step(report).blockers.join('\n')).toMatch(/refused in pkg_a\. Nor could its customization package take it: the metadata door refused the save into pkg_a\.custom: NOT_OVERRIDABLE: refused in pkg_a\.custom/); - expect(c.viewSaves).toEqual([]); + expect(c.formSaves).toEqual([]); }); it('control: where the pair cannot take it and the door admits the save naming the package, that save carries it, as before', async () => { metadataTable(md('md_org', 'org_default', 'view', 'crm_lead.intake', formView(false))); const c = catalog(); - const report = await apply(c, ledger(), { views: servedViews(c), pairs: pairsOf(['pkg_a'], 'the base declares no namespace') }); + const report = await apply(c, ledger(), { forms: servedForms(c), pairs: pairsOf(['pkg_a'], 'the base declares no namespace') }); expect(step(report)).toMatchObject({ status: 'done', summary: { withdrawalsCarried: 1 } }); expect(saved(c)).toEqual([['crm_lead.intake', 'pkg_a', false, undefined]]); }); @@ -1450,7 +1519,7 @@ describe('ADR-0131 D10 --apply — a customization conflict resolved by --metada return base.save(type, name, body, { packageId: 'pkg_a' }); }, }; - const report = await apply(packaged, ledger(), { views: servedViews(base, []), metadataChoices: ['md_org'] }); + const report = await apply(packaged, ledger(), { forms: servedForms(base, []), metadataChoices: ['md_org'] }); expect(step(report)).toMatchObject({ status: 'done', summary: { chosen: 1, organizationRowsDeleted: 1 } }); // The key's own environment row holds the chosen body, with the environment row's withdrawal kept. expect(labelOf('md_env')).toBe('Org copy'); @@ -1524,12 +1593,13 @@ describe('ADR-0131 D10 --apply — a customization conflict resolved by --metada md('md_env', null, 'view', 'crm_lead.intake', formView(true, 'Env copy')), ].join(', ')); const c = storingDoor(catalog()); - const views = servedViews(c, []); - const report = await apply(c, ledger(), { views, metadataChoices: ['md_env'] }); + // The environment row serves the form open at the doors before the run. + expect(storedRowsWithdraw('crm_lead.intake')).toBe(false); + const report = await apply(c, ledger(), { forms: servedForms(c, []), metadataChoices: ['md_env'] }); expect(step(report).status).toBe('done'); expect(owners()).toEqual([['md_env', null]]); expect((JSON.parse(String(rows(`SELECT metadata FROM sys_metadata WHERE id = 'md_env'`)[0]!.metadata)) as any).config.sharing.enabled).toBe(false); - expect(await doorsServe(views, 'lead-intake')).toEqual([]); + expect(storedRowsWithdraw('crm_lead.intake')).toBe(true); }); it('a door that refuses the chosen body blocks the conflict, and no organization row is deleted', async () => { @@ -1545,7 +1615,7 @@ describe('ADR-0131 D10 --apply — a customization conflict resolved by --metada return c.save(type, name, body, target); }, }; - const report = await apply(refusing, ledger(), { views: servedViews(c, []), metadataChoices: ['md_env'] }); + const report = await apply(refusing, ledger(), { forms: servedForms(c, []), metadataChoices: ['md_env'] }); expect(step(report).status).toBe('blocked'); expect(step(report).blockers.join('\n')).toMatch(/Nothing was deleted; fix the cause, then re-run/); expect(deletes()).toEqual([]); @@ -1632,7 +1702,7 @@ describe('ADR-0131 D10 --apply — a customization conflict resolved by --metada md('md_env', null, 'view', 'crm_lead.intake', { ...formView(true, 'Env copy'), _lock: 'customize' }), ].join(', ')); const c = storingDoor(catalog()); - const report = await apply(c, ledger(), { views: servedViews(c, []), metadataChoices: ['md_org'] }); + const report = await apply(c, ledger(), { forms: servedForms(c, []), metadataChoices: ['md_org'] }); expect(step(report).status).toBe('done'); expect(c.viewSaves.at(-1)!.body).toMatchObject({ label: 'Org copy', _lock: 'customize' }); expect((c.viewSaves.at(-1)!.body.config as any).sharing.enabled).toBe(false); @@ -1949,10 +2019,10 @@ describe('ADR-0131 D10 --apply — history renumbering (seat answers 6162538253, ); const c = storingDoor(catalog()); - const report = await apply(c, ledger(), { views: servedViews(c), columnDrops: keepColumn }); + const report = await apply(c, ledger(), { forms: servedForms(c), columnDrops: keepColumn }); expect(report.steps.find((s) => s.step === 'metadata-promotion')!.summary).toMatchObject({ withdrawalsCarried: 1, promoted: 1 }); - expect(rows(`SELECT COUNT(*) AS n FROM sys_metadata_history WHERE id LIKE 'h_save_%' AND type = 'view'`)).toEqual([{ n: 1 }]); + expect(rows(`SELECT COUNT(*) AS n FROM sys_metadata_history WHERE id LIKE 'h_save_%' AND type = 'form'`)).toEqual([{ n: 1 }]); expect(duplicates()).toEqual([]); // The promoted row took its history with it, and still names its own snapshot. expect(rows(`SELECT organization_id FROM sys_metadata_history WHERE id IN ('h_org1', 'h_org2')`)).toEqual([{ organization_id: null }, { organization_id: null }]); @@ -1961,7 +2031,7 @@ describe('ADR-0131 D10 --apply — history renumbering (seat answers 6162538253, }); it('⭐ an item with only an organization history: no environment save, during the run or after it, lands on its numbers', async () => { - // F2: no environment lineage at all. The package's code view is carried + // F2: no environment lineage at all. The package's code form is carried // onto (another key), the package-less organization row is promoted. viewWithHistory( `('md_org', 'org_default', 'view', 'crm_lead.intake', 'active', NULL, NULL, 2, '${withdrawn}')`, @@ -1969,7 +2039,7 @@ describe('ADR-0131 D10 --apply — history renumbering (seat answers 6162538253, ); const c = storingDoor(catalog()); - await apply(c, ledger(), { views: servedViews(c), columnDrops: keepColumn }); + await apply(c, ledger(), { forms: servedForms(c), columnDrops: keepColumn }); expect(duplicates()).toEqual([]); expect(snapshotOf('md_org')).toEqual(['o2']); @@ -1986,7 +2056,7 @@ describe('ADR-0131 D10 --apply — history renumbering (seat answers 6162538253, ); const c = storingDoor(catalog()); - const report = await apply(c, ledger(), { posture: 'isolated', views: servedViews(c), columnDrops: keepColumn }); + const report = await apply(c, ledger(), { posture: 'isolated', forms: servedForms(c), columnDrops: keepColumn }); expect(report.steps.find((s) => s.step === 'metadata-promotion')!.summary).toMatchObject({ withdrawalsCarried: 1, promoted: 0 }); expect(duplicates()).toEqual([]); @@ -2004,7 +2074,7 @@ describe('ADR-0131 D10 --apply — history renumbering (seat answers 6162538253, ); const c = storingDoor(catalog()); - const report = await apply(c, ledger(), { views: servedViews(c, []), metadataChoices: ['md_b'], columnDrops: keepColumn }); + const report = await apply(c, ledger(), { forms: servedForms(c, []), metadataChoices: ['md_b'], columnDrops: keepColumn }); expect(report.steps.find((s) => s.step === 'metadata-promotion')!.summary).toMatchObject({ chosen: 1, organizationRowsDeleted: 1 }); expect(duplicates()).toEqual([]); @@ -2026,9 +2096,9 @@ describe('ADR-0131 D10 --apply — history renumbering (seat answers 6162538253, ); const c = storingDoor(catalog()); // A crash right after the first fold's event move, then the rerun. - await expect(apply(c, ledger(), { views: servedViews(c, []), columnDrops: keepColumn, executor: executor({ failOnceOn: /^UPDATE "sys_metadata_history" SET "organization_id" = NULL/ }) })) + await expect(apply(c, ledger(), { forms: servedForms(c, []), columnDrops: keepColumn, executor: executor({ failOnceOn: /^UPDATE "sys_metadata_history" SET "organization_id" = NULL/ }) })) .rejects.toThrow(/killed mid-step/); - const report = await apply(c, ledger(), { views: servedViews(c, []), columnDrops: keepColumn }); + const report = await apply(c, ledger(), { forms: servedForms(c, []), columnDrops: keepColumn }); expect(report.steps.find((s) => s.step === 'metadata-promotion')!.summary).toMatchObject({ promoted: 2 }); expect(duplicates()).toEqual([]); expect(snapshotOf('md_a')).toEqual(['a2']); diff --git a/packages/cli/src/utils/organization-ownership-apply.ts b/packages/cli/src/utils/organization-ownership-apply.ts index eff971a8c00..7d7cba9a4d7 100644 --- a/packages/cli/src/utils/organization-ownership-apply.ts +++ b/packages/cli/src/utils/organization-ownership-apply.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'; import { ORGANIZATION_OWNERSHIP_MIGRATION_ID, ORGANIZATION_OWNERSHIP_SHAPE_GENERATION } from '@objectstack/spec/system'; +import { anonymousFormIntakeSlug, formIntakeLayer } from '@objectstack/spec/ui'; import { convertPositionBindingRows, permissionSetDefinitionFromRow, @@ -74,10 +75,9 @@ import type { DeclaredSharingRuleSkip } from '@objectstack/plugin-sharing'; * 2a. `metadata-promotion` — rulings A on #22011 and #22008 (records * 6020163868, 6020151485): first every public-form withdrawal an * organization saved is carried onto the environment, fail-closed (any - * organization's withdrawal wins), by writing it onto each active - * environment `view` of that name that still serves the form open, - * through the metadata door; the same predicate the anonymous doors - * judge by (`anonymousFormIntakeWithdrawnIn`) decides. A view a + * organization's withdrawal wins), by writing it onto each served `form` + * of that name that is still open, through the metadata door; the + * anonymous doors' own layer (`formIntakeLayer`) decides. A form a * read-only package ships takes it in that package's `.custom` pair, * declared as the override of the base (ADR-0146 D1, D2, D3: * {@link CustomizationPairPort}). Then, under @@ -267,7 +267,7 @@ export interface CatalogPort { /** The metadata door: an environment metadata save. Throws when the door refuses. */ export interface MetadataDoorPort { save( - type: 'position' | 'permission' | 'email_template' | 'view' | 'dashboard' | 'report' | 'translation', + type: 'position' | 'permission' | 'email_template' | 'view' | 'form' | 'dashboard' | 'report' | 'translation', name: string, body: Record, target?: { packageId: string | null }, @@ -317,8 +317,13 @@ export function protocolCustomizationPairs(deps: { }; } -/** The env-wide `view` list the anonymous form doors read (every package's item of a name). */ -export interface ServedViewsPort { +/** + * [ADR-0159 D6, D7] The env-wide `form` list the anonymous form doors offer + * their candidates from (every package's item of a name, a declared override + * served for its base's name). Since protocol 19 a form is its own `form` + * item: the served `view` list holds lists only. + */ +export interface ServedFormsPort { list(): Promise>>>; } @@ -688,10 +693,13 @@ export interface ApplyOptions { declaredWebhooks?: DeclaredWebhooksPort; /** [18.x step 5d] The schema door the NOT NULL step applies through. Absent, it applies nothing and says so. */ notNull?: NotNullPort; - /** The served views, for carrying form withdrawals. */ - views: ServedViewsPort; /** - * The customization pair a withdrawal onto a read-only package's view is + * [ADR-0159 D7] The served `form` items, for carrying form withdrawals: since + * protocol 19 a form is its own item and no served view holds one. + */ + forms: ServedFormsPort; + /** + * The customization pair a withdrawal onto a read-only package's form is * carried into. Absent, the carry saves naming the served package, and the * door's refusal of that save blocks. */ @@ -1609,25 +1617,26 @@ const authoredBodyOf = (item: Readonly>): Record `${r.name}\u0000${r.packageId ?? ''}`)); - for (const served of await run.opts.views.list()) { + // [ADR-0159 D6, D7] The served `form` items, judged by the doors' own layer + // over the organization rows (their stored old-shape bodies, projected). + const withdrawn = formIntakeLayer({ forms: [], views: [...layerOf.values()].flat() }).withdrawn; + if (withdrawn.size === 0) return; + for (const served of await run.opts.forms.list()) { const name = typeof served.name === 'string' ? served.name : undefined; - const layer = name === undefined ? undefined : layerOf.get(name); - if (!name || !layer) continue; - const packageId = servedPackageOf(served); - if (run.opts.posture === 'single' && heldByOrganization.has(`${name}\u0000${packageId ?? ''}`)) continue; + if (!name || !withdrawn.has(name)) continue; + const slug = anonymousFormIntakeSlug(served.sharing); + if (slug === null) continue; const body = authoredBodyOf(served); - const closing = anonymousFormIntakeCandidates(body).filter((c) => anonymousFormIntakeWithdrawnIn(layer, body, c)); - if (closing.length === 0) continue; - for (const candidate of closing) { - candidate.form.sharing = { ...(candidate.form.sharing as Record), enabled: false }; - } - let pairRefusal: string | undefined; - if (packageId !== null && run.opts.pairs) { - const outcome = await carryIntoPair(run, run.opts.pairs, name, packageId, body); - if (outcome.carried) { - summary.withdrawalsCarried += closing.length; - run.opts.onProgress?.( - `carried ${closing.length} public-form withdrawal(s) onto the view ${name} through the customization package ` + - `${outcome.pair}, declared as the override of ${packageId} at ${outcome.basedOn}`, - ); - continue; - } - pairRefusal = outcome.refusal; - } - try { - await run.opts.door.save('view', name, body, { packageId }); - summary.withdrawalsCarried += closing.length; - run.opts.onProgress?.(`carried ${closing.length} public-form withdrawal(s) onto the environment view ${name}`); - } catch (error) { - blockers.push( - `An organization withdrew the public form(s) ${closing.map((c) => c.slug).join(', ')} of the view ${name}` + - `${packageId ? ` (package ${packageId})` : ''}, and the metadata door refused to carry that withdrawal onto ` + - `the environment: ${messageOf(error)}.${pairRefusal ? ` Nor could its customization package take it: ${pairRefusal}.` : ''} ` + - 'Withdraw the form there (sharing.enabled false), then re-run. An upgrade never reopens a withdrawn form ' + - '(ruling record 6020151485).', + body.sharing = { ...(body.sharing as Record), enabled: false }; + await carryClosing(run, 'form', name, servedPackageOf(served), body, [slug], summary, blockers); + } +} + +/** + * Save one served `type` item `name` with its withdrawn form(s) closed + * (`slugs`): into the read-only base's pair ({@link carryIntoPair}), else + * naming the served package, whose refusal blocks, the pair's refusal named + * beside it. + */ +async function carryClosing( + run: Run, + type: 'form', + name: string, + packageId: string | null, + body: Record, + slugs: readonly string[], + summary: Record, + blockers: string[], +): Promise { + let pairRefusal: string | undefined; + if (packageId !== null && run.opts.pairs) { + const outcome = await carryIntoPair(run, run.opts.pairs, type, name, packageId, body); + if (outcome.carried) { + summary.withdrawalsCarried += slugs.length; + run.opts.onProgress?.( + `carried ${slugs.length} public-form withdrawal(s) onto the ${type} ${name} through the customization package ` + + `${outcome.pair}, declared as the override of ${packageId} at ${outcome.basedOn}`, ); + return; } + pairRefusal = outcome.refusal; + } + try { + await run.opts.door.save(type, name, body, { packageId }); + summary.withdrawalsCarried += slugs.length; + run.opts.onProgress?.(`carried ${slugs.length} public-form withdrawal(s) onto the environment ${type} ${name}`); + } catch (error) { + blockers.push( + `An organization withdrew the public form(s) ${slugs.join(', ')} of the ${type} ${name}` + + `${packageId ? ` (package ${packageId})` : ''}, and the metadata door refused to carry that withdrawal onto ` + + `the environment: ${messageOf(error)}.${pairRefusal ? ` Nor could its customization package take it: ${pairRefusal}.` : ''} ` + + 'Withdraw the form there (sharing.enabled false), then re-run. An upgrade never reopens a withdrawn form ' + + '(ruling record 6020151485).', + ); } } /** - * [ADR-0146 D1, D2, D3] Carry a withdrawal onto `base`'s view `name` into the + * [ADR-0146 D1, D2, D3] Carry a withdrawal onto `base`'s `type` item `name` into the * base's `.custom` pair, when `base` is read-only: the pair ensured through * the ensure door, then `body` saved into it through the metadata door, * declaring `overrides: { package: base, basedOn }` (a body that already * declares the base, the pair's own override as served, keeps its * declaration). `carried: false` with no refusal: `base` is writable, and its - * view is saved in place. With one: the pair could not take it, in the + * item is saved in place. With one: the pair could not take it, in the * door's or the ensure door's own words. */ async function carryIntoPair( run: Run, pairs: CustomizationPairPort, + type: 'form', name: string, base: string, body: Record, @@ -1728,7 +1755,7 @@ async function carryIntoPair( ? { package: base, basedOn: own.basedOn } : { package: base, basedOn: pair.basedOn }; try { - await run.opts.door.save('view', name, { ...body, overrides }, { packageId: pair.packageId }); + await run.opts.door.save(type, name, { ...body, overrides }, { packageId: pair.packageId }); } catch (error) { return { carried: false, refusal: `the metadata door refused the save into ${pair.packageId}: ${messageOf(error)}` }; } diff --git a/packages/cli/src/utils/organization-ownership-apply.underivable-activity.test.ts b/packages/cli/src/utils/organization-ownership-apply.underivable-activity.test.ts index d33c78340fb..b9ca787deba 100644 --- a/packages/cli/src/utils/organization-ownership-apply.underivable-activity.test.ts +++ b/packages/cli/src/utils/organization-ownership-apply.underivable-activity.test.ts @@ -36,6 +36,17 @@ import { type OrganizationOwnershipApplyReport, } from './organization-ownership-apply.js'; +// Pay the first load of what the source under test reaches through dynamic +// `import()`s at MODULE LOAD, outside the clocked cases. +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/runtime'; +import '@objectstack/service-datasource'; + let dir: string; let db: Database.Database; /** Every write statement the ceremony issued, in order. */ @@ -103,7 +114,7 @@ async function apply(posture: string, l = ledger()): Promise { + it('a switch birth marker that cannot be written fails the flush, naming the row, the cause and the command', async () => { + const cause = new Error('SQLITE_READONLY: attempt to write a readonly database'); + const recordBirth = vi.fn(async () => { throw cause; }); + const failure = await recordBirthOfFlushedStore(kernelWith(engine), recordBirth, undefined, formTypeSwitchBirthFailure).then( + () => null, + (error: unknown) => error as Error, + ); + expect(failure).toBeInstanceOf(Error); + expect(failure!.cause).toBe(cause); + expect(failure!.message).toContain(FORM_TYPE_SWITCH_MIGRATION_ID); + expect(failure!.message).toContain(cause.message); + expect(failure!.message).toContain('os migrate protocol --to 19 --apply --yes'); + // Its own sentence, not the ownership ceremony's. + for (const step of CEREMONY_STEPS) expect(failure!.message).not.toContain(step); + }); + + it('resolves when the birth half does, handing it the engine and the logger', async () => { + const logger = { info: vi.fn() }; + const recordBirth = vi.fn(async () => null); + await expect(recordBirthOfFlushedStore(kernelWith(engine), recordBirth, logger, formTypeSwitchBirthFailure)).resolves.toBeUndefined(); + expect(recordBirth).toHaveBeenCalledWith(engine, logger); + }); +}); diff --git a/packages/cli/src/utils/schema-migrate.ts b/packages/cli/src/utils/schema-migrate.ts index a8ef1b0ec73..534cc5a9a7d 100644 --- a/packages/cli/src/utils/schema-migrate.ts +++ b/packages/cli/src/utils/schema-migrate.ts @@ -56,7 +56,7 @@ import type { PendingSchemaWork, } from '@objectstack/driver-sql'; import type { IObjectQLEngine } from '@objectstack/spec/contracts'; -import { ORGANIZATION_OWNERSHIP_MIGRATION_ID, StorageNameMapping } from '@objectstack/spec/system'; +import { FORM_TYPE_SWITCH_MIGRATION_ID, ORGANIZATION_OWNERSHIP_MIGRATION_ID, StorageNameMapping } from '@objectstack/spec/system'; import { isDevelopmentBoot, isFederatedObject } from '@objectstack/core'; import { doctorNodeEnv, @@ -648,13 +648,21 @@ type BirthLogger = Parameters[1]; * first `os serve` would refuse this database, and the command must not end * reporting success. The ceremony certifies such a database. * + * [ADR-0159 D7; ruling record 7308112533] The protocol-19 switch has the same + * birth half (`recordFormTypeSwitchBirth`), run through here on the same + * counts with its own failure sentence ({@link formTypeSwitchBirthFailure}): + * a store this flush created from empty holds no stored form, so its switch + * record is written as a birth marker and its first `os serve` is not refused. + * * Exported for its unit pin (`schema-migrate.birth-after-flush.test.ts`), which * holds the failed-write refusal without booting a kernel. */ -export async function recordBirthOfFlushedStore( +export async function recordBirthOfFlushedStore( kernel: { getService?: (name: string) => unknown }, - recordBirth: RecordOrganizationOwnershipBirth, + recordBirth: (engine: E, logger?: BirthLogger) => Promise, logger: BirthLogger | undefined, + /** What the thrown failure says, given the write's own message. The organization-ownership sentence when unset. */ + describeFailure: (cause: string) => string = organizationOwnershipBirthFailure, ): Promise { let engine: unknown; try { @@ -664,20 +672,38 @@ export async function recordBirthOfFlushedStore( } if (!engine || typeof (engine as { getDriverForObject?: unknown }).getDriverForObject !== 'function') return; try { - await recordBirth(engine as Parameters[0], logger); + await recordBirth(engine as E, logger); } catch (error) { - throw new Error( - `This run created the database from empty, and its organization-ownership birth marker (sys_migration ` + - `'${ORGANIZATION_OWNERSHIP_MIGRATION_ID}') could not be written ` + - `(${error instanceof Error ? error.message : String(error)}). Without it the first 'os serve' takes this ` + - `database for one an earlier release created and refuses it. Fix the write, then run 'os migrate ` + - `organization-ownership --out PLAN' and 'os migrate organization-ownership --apply --plan-file PLAN ` + - `--backup-taken', which certifies it.`, - { cause: error }, - ); + throw new Error(describeFailure(error instanceof Error ? error.message : String(error)), { cause: error }); } } +/** The failure of the organization-ownership birth half after a flush: what was not written, and the ceremony that certifies the database. */ +function organizationOwnershipBirthFailure(cause: string): string { + return ( + `This run created the database from empty, and its organization-ownership birth marker (sys_migration ` + + `'${ORGANIZATION_OWNERSHIP_MIGRATION_ID}') could not be written ` + + `(${cause}). Without it the first 'os serve' takes this ` + + `database for one an earlier release created and refuses it. Fix the write, then run 'os migrate ` + + `organization-ownership --out PLAN' and 'os migrate organization-ownership --apply --plan-file PLAN ` + + `--backup-taken', which certifies it.` + ); +} + +/** + * [ADR-0159 D7] The failure of the protocol-19 birth half after a flush: what + * was not written, and the command that records the switch on such a database. + * Exported for the same unit pin. + */ +export function formTypeSwitchBirthFailure(cause: string): string { + return ( + `This run created the database from empty, and its protocol 19 birth marker (sys_migration ` + + `'${FORM_TYPE_SWITCH_MIGRATION_ID}') could not be written (${cause}). Without it the first 'os serve' takes ` + + `this database for one an earlier release created and refuses it. Fix the write, then run 'os migrate protocol ` + + `--to 19 --apply --yes', which records the switch.` + ); +} + /** * [#23816] The engine's DEFAULT driver — the primary datasource's — read * through the accessors the engine makes public, or `null` when the engine @@ -1298,8 +1324,9 @@ export async function bootSchemaStack( const projectRoot = opts.projectRoot ?? process.cwd(); const envLoad = loadProjectEnvFiles(projectRoot, { dev: opts.serveFlags?.dev === true }); - const { createStandaloneStack, Runtime, resolveStandaloneDatabase, recordOrganizationOwnershipBirth } = - await import('@objectstack/runtime'); + const { + createStandaloneStack, Runtime, resolveStandaloneDatabase, recordOrganizationOwnershipBirth, recordFormTypeSwitchBirth, + } = await import('@objectstack/runtime'); // The inputs the database is resolved from — by `createStandaloneStack` // below, the occupancy probe before it, and the telemetry sibling's key. @@ -1692,6 +1719,8 @@ export async function bootSchemaStack( // [ADR-0131 D10] The birth half the deferred boot could not run: only a // deferred boot holds DDL back, so only it can have created the store here. if (deferral) await recordBirthOfFlushedStore(kernel, recordOrganizationOwnershipBirth, deferral.logger); + // [ADR-0159 D7] …and the protocol-19 switch's, on the same counts. + if (deferral) await recordBirthOfFlushedStore(kernel, recordFormTypeSwitchBirth, deferral.logger, formTypeSwitchBirthFailure); return sortPendingSchemaWork(performed); }, composition, diff --git a/packages/cli/test/dev-host-config-artifact-source.integration.test.ts b/packages/cli/test/dev-host-config-artifact-source.integration.test.ts index b5538f215aa..b33c0044bdb 100644 --- a/packages/cli/test/dev-host-config-artifact-source.integration.test.ts +++ b/packages/cli/test/dev-host-config-artifact-source.integration.test.ts @@ -97,7 +97,7 @@ function configSource(copy: Copy, host: boolean): string { const c = copyOf(copy); return `import { writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { defineStack } from '@objectstack/spec'; +import { defineStack, defineForm } from '@objectstack/spec'; export const onEnable = async (): Promise => { writeFileSync(join(process.cwd(), '${ON_ENABLE_MARKER}'), 'ran'); @@ -122,13 +122,15 @@ export default defineStack({ data: { provider: 'object', object: '${OBJECT}' }, columns: [{ field: 'name' }, { field: 'score' }], }, - form: { - type: 'simple', - data: { provider: 'object', object: '${OBJECT}' }, - sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], - sharing: { enabled: ${c.formOpen}, allowAnonymous: true, publicLink: '/forms/${SLUG}' }, - }, }], + // [ADR-0159] The public form is a \`forms:\` item from protocol 19, bound by \`object\`. + forms: [defineForm({ + name: '${OBJECT}.form', + object: '${OBJECT}', + type: 'simple', + sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], + sharing: { enabled: ${c.formOpen}, allowAnonymous: true, publicLink: '/forms/${SLUG}' }, + })], hooks: [{ name: 'hx_lead_score', object: '${OBJECT}', diff --git a/packages/cli/test/getting-started-build-with-claude-code.e2e.test.ts b/packages/cli/test/getting-started-build-with-claude-code.e2e.test.ts index 51be08a893b..5c56ce74ba4 100644 --- a/packages/cli/test/getting-started-build-with-claude-code.e2e.test.ts +++ b/packages/cli/test/getting-started-build-with-claude-code.e2e.test.ts @@ -34,8 +34,8 @@ * shows, in its own directory's `index.ts` (the page's rule that metadata * exists only if its barrel exports it). Exit statuses and count lines are * asserted; prose is not pinned. Two advisories are asserted absent, by rule - * id: `form-view-internal-not-loaded` (the page's files declare no internal - * create/edit form, which the platform does not load) and `field-no-consumers` + * id: `form-consumer-less` (the page's files declare no form that nothing + * reaches: its create and edit forms are the object's field groups) and `field-no-consumers` * on the ticket's `description` (the page says its field group is the * consumer that names it). * @@ -226,8 +226,8 @@ describe('the page, followed verbatim in a fresh `blank` scaffold', () => { for (const line of countLines) expect(printed, out(validate)).toContain(line); }); - it('prints no `form-view-internal-not-loaded`: the page declares no internal create/edit form', () => { - expect(out(validate)).not.toContain('form-view-internal-not-loaded'); + it('prints no `form-consumer-less`: the page declares no form that nothing reaches', () => { + expect(out(validate)).not.toContain('form-consumer-less'); }); it("prints no `field-no-consumers` for the ticket's `description`: its field group names it", () => { diff --git a/packages/cli/test/i18n-form-section-entry-coverage.test.ts b/packages/cli/test/i18n-form-section-entry-coverage.test.ts index b5210a9b72c..70d6fb87d87 100644 --- a/packages/cli/test/i18n-form-section-entry-coverage.test.ts +++ b/packages/cli/test/i18n-form-section-entry-coverage.test.ts @@ -2,27 +2,42 @@ // // A form section entry's override copy — the `label`, `placeholder` and // `helpText` an entry object authors over the object field it renders — is -// translated through `objects.._sections.
.fields.` -// (`translateView` overlays it onto the served section's entries). The walker -// emits that slot for every authored string of a form view's named sections, -// so `os i18n extract` scaffolds it and the coverage gate reports a locale -// that leaves one untranslated. +// translated at the form's own node, +// `forms..sections.
.fields.`, and at the +// object-level default `objects.._sections.
.fields.` +// for each key that node lacks (ADR-0159 D8). The walker emits the form's slot +// for every authored string of a `forms[]` item's named sections, with the +// object-level slot as its fallback, so `os i18n extract` scaffolds it and the +// coverage gate reports a locale that leaves one untranslated at both. +// +// Under protocol 18 the form was held in a view and the walker emitted the +// object-level slot alone. A view holds lists only now, and the walker reads +// no form out of one. import { describe, it, expect } from 'vitest'; import { collectExpectedEntries, extractTranslations } from '../src/utils/i18n-bundle-extract'; import { computeI18nCoverage } from '../src/utils/i18n-coverage'; -import { ObjectTranslationDataSchema } from '@objectstack/spec/system'; +import { ObjectTranslationDataSchema, TranslationDataSchema } from '@objectstack/spec/system'; const entryKeys = (config: any) => collectExpectedEntries(config) .map((e) => e.path.join('.')) - .filter((p) => p.includes('._sections.') && p.includes('.fields.')); + .filter((p) => (p.includes('._sections.') || p.startsWith('forms.')) && p.includes('.fields.')); -const caseForm = (sections: unknown[]) => ({ - type: 'simple', - data: { provider: 'object', object: 'crm_case' }, - sections, -}); +const FORM = 'crm_case.support'; +const supportSections = [ + { + name: 'submitter', + label: 'About you', + fields: [ + { field: 'contact_name', label: 'Your name', placeholder: 'Jane Doe', helpText: 'As on your ID' }, + { field: 'contact_email', label: 'Your email' }, + 'subject', + ], + }, + // No `name`: its entries have no address. + { label: 'Details', fields: [{ field: 'subject', label: 'What happened' }] }, +]; const config = (translations: unknown[] = []) => ({ i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'] }, @@ -38,23 +53,9 @@ const config = (translations: unknown[] = []) => ({ views: [ { list: { type: 'grid', name: 'all_cases', label: 'All Cases', data: { provider: 'object', object: 'crm_case' } }, - formViews: { - support: caseForm([ - { - name: 'submitter', - label: 'About you', - fields: [ - { field: 'contact_name', label: 'Your name', placeholder: 'Jane Doe', helpText: 'As on your ID' }, - { field: 'contact_email', label: 'Your email' }, - 'subject', - ], - }, - // No `name`: its entries have no address. - { label: 'Details', fields: [{ field: 'subject', label: 'What happened' }] }, - ]), - }, }, ], + forms: [{ name: FORM, object: 'crm_case', type: 'simple', sections: supportSections }], pages: [{ name: 'case_record', type: 'record', @@ -70,37 +71,59 @@ const config = (translations: unknown[] = []) => ({ translations, }); -describe('i18n walker — a form section entry\'s copy, `_sections.
.fields.`', () => { - it('emits one slot per AUTHORED entry string of a named form-view section', () => { +describe('i18n walker — a form section entry\'s copy, `forms..sections.
.fields.`', () => { + it('emits one slot per AUTHORED entry string of a named form section', () => { expect(entryKeys(config()).sort()).toEqual([ - 'objects.crm_case._sections.submitter.fields.contact_email.label', - 'objects.crm_case._sections.submitter.fields.contact_name.helpText', - 'objects.crm_case._sections.submitter.fields.contact_name.label', - 'objects.crm_case._sections.submitter.fields.contact_name.placeholder', + `forms.${FORM}.sections.submitter.fields.contact_email.label`, + `forms.${FORM}.sections.submitter.fields.contact_name.helpText`, + `forms.${FORM}.sections.submitter.fields.contact_name.label`, + `forms.${FORM}.sections.submitter.fields.contact_name.placeholder`, ]); }); - it('seeds each slot with the authored string, under the `section` bucket', () => { + it('seeds each slot with the authored string, with the object-level slot as its fallback', () => { const at = (p: string) => collectExpectedEntries(config()).find((e) => e.path.join('.') === p); - expect(at('objects.crm_case._sections.submitter.fields.contact_name.placeholder')) - .toMatchObject({ sourceValue: 'Jane Doe', inline: 'Jane Doe', source: 'section', objectName: 'crm_case' }); + const slot = at(`forms.${FORM}.sections.submitter.fields.contact_name.placeholder`); + expect(slot).toMatchObject({ sourceValue: 'Jane Doe', inline: 'Jane Doe', objectName: 'crm_case' }); + expect(slot?.fallbackPath?.join('.')).toBe('objects.crm_case._sections.submitter.fields.contact_name.placeholder'); + }); + + it('a form held in a view (the protocol-18 shape) emits no entry slot under either address', () => { + // The parse refuses the container's `formViews` slot at its own key; the + // walker reads no form out of it. + const old = { + ...config(), + forms: [], + views: [{ + list: { type: 'grid', name: 'all_cases', label: 'All Cases', data: { provider: 'object', object: 'crm_case' } }, + formViews: { support: { type: 'simple', data: { provider: 'object', object: 'crm_case' }, sections: supportSections } }, + }], + }; + expect(entryKeys(old)).toEqual([]); }); it('`os i18n extract` writes a skeleton the translation schema accepts', () => { - const node: any = extractTranslations(config(), { locales: ['en'] }).bundles.en?.objects?.crm_case; - expect(node?._sections?.submitter?.fields?.contact_name).toEqual({ + const bundle: any = extractTranslations(config(), { locales: ['en'] }).bundles.en; + expect(bundle?.forms?.[FORM]?.sections?.submitter?.fields?.contact_name).toEqual({ label: 'Your name', placeholder: 'Jane Doe', helpText: 'As on your ID', }); - const parsed = ObjectTranslationDataSchema.safeParse(node); + const object = ObjectTranslationDataSchema.safeParse(bundle?.objects?.crm_case); + expect(object.success, JSON.stringify(object.error?.issues)).toBe(true); + const parsed = TranslationDataSchema.safeParse(bundle); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); }); it('the coverage gate reports an authored entry string a supported locale leaves untranslated', () => { + const entryIssue = (i: { locale: string; key: string }) => + i.locale === 'zh-CN' && i.key.includes('.fields.') && (i.key.includes('._sections.') || i.key.startsWith('forms.')); const missing = computeI18nCoverage(config([{ 'zh-CN': { objects: { crm_case: { label: '工单' } } } }])) - .issues.filter((i) => i.locale === 'zh-CN' && i.key.includes('.fields.') && i.key.includes('._sections.')) + .issues.filter(entryIssue) .map((i) => i.key) .sort(); + expect(missing).toHaveLength(4); expect(missing).toEqual(entryKeys(config()).sort()); + // Translated at the object-level default, the address the same copy had + // under protocol 18: the form's slot counts as covered. const covered = computeI18nCoverage(config([{ 'zh-CN': { objects: { @@ -117,7 +140,7 @@ describe('i18n walker — a form section entry\'s copy, `_sections.
.fie }, }, }, - }])).issues.filter((i) => i.locale === 'zh-CN' && i.key.includes('.fields.') && i.key.includes('._sections.')); + }])).issues.filter(entryIssue); expect(covered).toEqual([]); }); }); diff --git a/packages/cli/test/i18n-form-thank-you-coverage.test.ts b/packages/cli/test/i18n-form-thank-you-coverage.test.ts index 177ff7488ad..1f21efdb149 100644 --- a/packages/cli/test/i18n-form-thank-you-coverage.test.ts +++ b/packages/cli/test/i18n-form-thank-you-coverage.test.ts @@ -1,27 +1,32 @@ // Copyright (c) 2026 ObjectStack contributors. Apache-2.0 license. // -// A form view's thank-you panel (the `title` / `message` of a -// `kind: 'thank-you'` `FormViewSchema.submitBehavior`) is translated through -// `objects.._views..submitBehavior.{title,message}` -// (`translateView` overlays it onto the served form item's -// `config.submitBehavior`). The walker emits both slots for every form a view -// container serves and for a form item, keyed by the composer's runtime -// identity, so `os i18n extract` scaffolds them and the coverage gate reports -// a locale that leaves an authored panel untranslated. +// A form's thank-you panel (the `title` / `message` of a `kind: 'thank-you'` +// `submitBehavior`) is translated through +// `forms..submitBehavior.{title,message}` (ADR-0159 D8): a form is +// its own item from protocol 19, and the translator reads its panel at the +// form's own node. The walker emits both slots for every `forms[]` item, so +// `os i18n extract` scaffolds them and the coverage gate reports a locale that +// leaves an authored panel untranslated. +// +// Under protocol 18 the same panel was keyed +// `objects.._views..submitBehavior`, by the runtime identity of +// a form held in a view. That tail is retired with the forms a view held: the +// translation schema refuses it by name, and the walker emits it for nothing. import { describe, it, expect } from 'vitest'; import { collectExpectedEntries, extractTranslations } from '../src/utils/i18n-bundle-extract'; import { computeI18nCoverage } from '../src/utils/i18n-coverage'; -import { ObjectTranslationDataSchema } from '@objectstack/spec/system'; +import { ObjectTranslationDataSchema, TranslationDataSchema } from '@objectstack/spec/system'; const panelKeys = (config: any) => collectExpectedEntries(config) .map((e) => e.path.join('.')) .filter((p) => p.includes('.submitBehavior.')); -const leadForm = (extra: Record = {}) => ({ +const leadForm = (key: string, extra: Record = {}) => ({ + name: `crm_lead.${key}`, + object: 'crm_lead', type: 'simple', - data: { provider: 'object', object: 'crm_lead' }, sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], ...extra, }); @@ -32,58 +37,74 @@ const config = (translations: unknown[] = []) => ({ views: [ { list: { type: 'grid', name: 'all_leads', label: 'All Leads', data: { provider: 'object', object: 'crm_lead' } }, - form: leadForm({ submitBehavior: { kind: 'thank-you', title: 'Saved' } }), - formViews: { - web_to_lead: leadForm({ submitBehavior: { kind: 'thank-you', title: 'Thanks!', message: 'We will reach out shortly.' } }), - redirect: leadForm({ submitBehavior: { kind: 'redirect', url: '/thanks' } }), - }, - }, - { - name: 'referral', - object: 'crm_lead', - viewKind: 'form', - config: leadForm({ submitBehavior: { kind: 'thank-you', message: 'Thank you for the referral.' } }), }, ], + forms: [ + leadForm('form', { submitBehavior: { kind: 'thank-you', title: 'Saved' } }), + leadForm('web_to_lead', { submitBehavior: { kind: 'thank-you', title: 'Thanks!', message: 'We will reach out shortly.' } }), + leadForm('redirect', { submitBehavior: { kind: 'redirect', url: '/thanks' } }), + leadForm('referral', { submitBehavior: { kind: 'thank-you', message: 'Thank you for the referral.' } }), + ], translations, }); -describe('i18n walker — a form view\'s thank-you panel, `_views..submitBehavior`', () => { - it('emits both slots for each form a container serves and for a form item, keyed by the runtime identity', () => { +describe('i18n walker — a form\'s thank-you panel, `forms..submitBehavior`', () => { + it('emits both slots for each form item, keyed by the form\'s name', () => { expect(panelKeys(config()).sort()).toEqual([ - 'objects.crm_lead._views.form.submitBehavior.message', - 'objects.crm_lead._views.form.submitBehavior.title', - 'objects.crm_lead._views.redirect.submitBehavior.message', - 'objects.crm_lead._views.redirect.submitBehavior.title', - 'objects.crm_lead._views.referral.submitBehavior.message', - 'objects.crm_lead._views.referral.submitBehavior.title', - 'objects.crm_lead._views.web_to_lead.submitBehavior.message', - 'objects.crm_lead._views.web_to_lead.submitBehavior.title', + 'forms.crm_lead.form.submitBehavior.message', + 'forms.crm_lead.form.submitBehavior.title', + 'forms.crm_lead.redirect.submitBehavior.message', + 'forms.crm_lead.redirect.submitBehavior.title', + 'forms.crm_lead.referral.submitBehavior.message', + 'forms.crm_lead.referral.submitBehavior.title', + 'forms.crm_lead.web_to_lead.submitBehavior.message', + 'forms.crm_lead.web_to_lead.submitBehavior.title', ]); }); it('seeds authored panel copy and leaves unauthored copy — and every non-thank-you kind — unseeded', () => { const entries = collectExpectedEntries(config()); const at = (p: string) => entries.find((e) => e.path.join('.') === p); - expect(at('objects.crm_lead._views.web_to_lead.submitBehavior.title')).toMatchObject({ sourceValue: 'Thanks!', inline: 'Thanks!' }); - expect(at('objects.crm_lead._views.web_to_lead.submitBehavior.message')).toMatchObject({ sourceValue: 'We will reach out shortly.' }); - expect(at('objects.crm_lead._views.form.submitBehavior.title')).toMatchObject({ sourceValue: 'Saved' }); - expect(at('objects.crm_lead._views.form.submitBehavior.message')?.inline).toBeUndefined(); - expect(at('objects.crm_lead._views.referral.submitBehavior.message')).toMatchObject({ sourceValue: 'Thank you for the referral.' }); - expect(at('objects.crm_lead._views.redirect.submitBehavior.title')?.inline).toBeUndefined(); - expect(at('objects.crm_lead._views.redirect.submitBehavior.message')?.inline).toBeUndefined(); + expect(at('forms.crm_lead.web_to_lead.submitBehavior.title')).toMatchObject({ sourceValue: 'Thanks!', inline: 'Thanks!' }); + expect(at('forms.crm_lead.web_to_lead.submitBehavior.message')).toMatchObject({ sourceValue: 'We will reach out shortly.' }); + expect(at('forms.crm_lead.form.submitBehavior.title')).toMatchObject({ sourceValue: 'Saved' }); + expect(at('forms.crm_lead.form.submitBehavior.message')?.inline).toBeUndefined(); + expect(at('forms.crm_lead.referral.submitBehavior.message')).toMatchObject({ sourceValue: 'Thank you for the referral.' }); + expect(at('forms.crm_lead.redirect.submitBehavior.title')?.inline).toBeUndefined(); + expect(at('forms.crm_lead.redirect.submitBehavior.message')?.inline).toBeUndefined(); }); - it('CONTROL: the list view emits no panel slot', () => { + it('CONTROL: the list view emits no panel slot, and no form emits one under `_views`', () => { const paths = collectExpectedEntries(config()).map((e) => e.path.join('.')); expect(paths).toContain('objects.crm_lead._views.all_leads.label'); - expect(paths.filter((p) => p.startsWith('objects.crm_lead._views.all_leads.submitBehavior'))).toEqual([]); + expect(paths.filter((p) => p.startsWith('objects.crm_lead._views.') && p.includes('.submitBehavior'))).toEqual([]); + }); + + it('a form held in a view (the protocol-18 shape) emits no panel slot under either address', () => { + // The parse refuses the container's `form` / `formViews` slots and the + // form-kind view item at their own keys; the walker reads no form out of + // them, so `os i18n extract` scaffolds no key the translation schema + // refuses. + const held = { type: 'simple', data: { provider: 'object', object: 'crm_lead' }, submitBehavior: { kind: 'thank-you', title: 'Saved' } }; + const old = { + ...config(), + forms: [], + views: [ + { list: { type: 'grid', name: 'all_leads', label: 'All Leads', data: { provider: 'object', object: 'crm_lead' } }, form: held, formViews: { web_to_lead: held } }, + { name: 'referral', object: 'crm_lead', viewKind: 'form', config: held }, + ], + }; + expect(panelKeys(old)).toEqual([]); }); it('`os i18n extract` writes a skeleton the translation schema accepts', () => { - const lead: any = extractTranslations(config(), { locales: ['en'] }).bundles.en?.objects?.crm_lead; - expect(lead?._views?.web_to_lead?.submitBehavior).toEqual({ title: 'Thanks!', message: 'We will reach out shortly.' }); - const parsed = ObjectTranslationDataSchema.safeParse(lead); + const bundle: any = extractTranslations(config(), { locales: ['en'] }).bundles.en; + expect(bundle?.forms?.['crm_lead.web_to_lead']?.submitBehavior).toEqual({ title: 'Thanks!', message: 'We will reach out shortly.' }); + // The object node carries no panel: the `_views` tail is retired. + expect(JSON.stringify(bundle?.objects?.crm_lead ?? {})).not.toContain('submitBehavior'); + const object = ObjectTranslationDataSchema.safeParse(bundle?.objects?.crm_lead); + expect(object.success, JSON.stringify(object.error?.issues)).toBe(true); + const parsed = TranslationDataSchema.safeParse(bundle); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); }); @@ -93,22 +114,18 @@ describe('i18n walker — a form view\'s thank-you panel, `_views..submitB .map((i) => i.key) .sort(); expect(missing).toEqual([ - 'objects.crm_lead._views.form.submitBehavior.title', - 'objects.crm_lead._views.referral.submitBehavior.message', - 'objects.crm_lead._views.web_to_lead.submitBehavior.message', - 'objects.crm_lead._views.web_to_lead.submitBehavior.title', + 'forms.crm_lead.form.submitBehavior.title', + 'forms.crm_lead.referral.submitBehavior.message', + 'forms.crm_lead.web_to_lead.submitBehavior.message', + 'forms.crm_lead.web_to_lead.submitBehavior.title', ]); const covered = computeI18nCoverage(config([{ 'zh-CN': { - objects: { - crm_lead: { - label: '线索', - _views: { - web_to_lead: { submitBehavior: { title: '感谢您!', message: '我们会尽快与您联系。' } }, - form: { submitBehavior: { title: '已保存' } }, - referral: { submitBehavior: { message: '感谢您的推荐。' } }, - }, - }, + objects: { crm_lead: { label: '线索' } }, + forms: { + 'crm_lead.web_to_lead': { submitBehavior: { title: '感谢您!', message: '我们会尽快与您联系。' } }, + 'crm_lead.form': { submitBehavior: { title: '已保存' } }, + 'crm_lead.referral': { submitBehavior: { message: '感谢您的推荐。' } }, }, }, }])).issues.filter((i) => i.locale === 'zh-CN' && i.key.includes('.submitBehavior.')); diff --git a/packages/cli/test/i18n-form-title-coverage.test.ts b/packages/cli/test/i18n-form-title-coverage.test.ts index 51fe7aa6ca2..29d0aea8b32 100644 --- a/packages/cli/test/i18n-form-title-coverage.test.ts +++ b/packages/cli/test/i18n-form-title-coverage.test.ts @@ -1,27 +1,33 @@ // Copyright (c) 2026 ObjectStack contributors. Apache-2.0 license. // -// A form view's title (`FormViewSchema.title`) is translated through -// `objects.._views..title` (`translateView` overlays it onto the -// served form item's `config.title`). The walker emits that slot for every -// form a view container serves, keyed by the composer's runtime identity, so -// `os i18n extract` scaffolds it and the coverage gate reports a locale that -// leaves an authored title untranslated. +// A form's title is translated through `forms..title` (ADR-0159 +// D8): a form is its own item from protocol 19, and the translator reads its +// heading at the form's own node. The walker emits that slot for every +// `forms[]` item, so `os i18n extract` scaffolds it and +// the coverage gate reports a locale that leaves an authored title +// untranslated. +// +// Under protocol 18 the same heading was keyed +// `objects.._views..title`, by the runtime identity of a form +// held in a view. That tail is retired with the forms a view held: the +// translation schema refuses it by name, and the walker emits it for nothing. import { describe, it, expect } from 'vitest'; import { collectExpectedEntries, extractTranslations } from '../src/utils/i18n-bundle-extract'; import { computeI18nCoverage } from '../src/utils/i18n-coverage'; -import { ObjectTranslationDataSchema } from '@objectstack/spec/system'; +import { ObjectTranslationDataSchema, TranslationDataSchema } from '@objectstack/spec/system'; const titleKeys = (config: any) => collectExpectedEntries(config) .map((e) => e.path.join('.')) - // The view node's own `title` — not the thank-you panel's + // The form node's own `title` — not the thank-you panel's // `submitBehavior.title` one level down (`i18n-form-thank-you-coverage`). - .filter((p) => /\._views\.[^.]+\.title$/.test(p)); + .filter((p) => p.endsWith('.title') && !p.includes('.submitBehavior.')); -const leadForm = (extra: Record = {}) => ({ +const leadForm = (key: string, extra: Record = {}) => ({ + name: `crm_lead.${key}`, + object: 'crm_lead', type: 'simple', - data: { provider: 'object', object: 'crm_lead' }, sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], ...extra, }); @@ -32,74 +38,94 @@ const config = (translations: unknown[] = []) => ({ views: [ { list: { type: 'grid', name: 'all_leads', label: 'All Leads', data: { provider: 'object', object: 'crm_lead' } }, - form: leadForm({ title: 'New lead' }), - formViews: { - web_to_lead: leadForm({ title: 'Contact us' }), - quick: leadForm(), - }, - }, - { - name: 'referral', - object: 'crm_lead', - viewKind: 'form', - config: leadForm({ title: 'Refer a friend' }), }, ], + forms: [ + leadForm('form', { title: 'New lead' }), + leadForm('web_to_lead', { title: 'Contact us' }), + leadForm('quick'), + leadForm('referral', { title: 'Refer a friend' }), + ], translations, }); -describe('i18n walker — a form view\'s title, `_views..title`', () => { - it('emits the slot for each form a container serves and for a form item, keyed by the runtime identity', () => { +describe('i18n walker — a form\'s title, `forms..title`', () => { + it('emits the slot for each form item, keyed by the form\'s name', () => { expect(titleKeys(config()).sort()).toEqual([ - 'objects.crm_lead._views.form.title', - 'objects.crm_lead._views.quick.title', - 'objects.crm_lead._views.referral.title', - 'objects.crm_lead._views.web_to_lead.title', + 'forms.crm_lead.form.title', + 'forms.crm_lead.quick.title', + 'forms.crm_lead.referral.title', + 'forms.crm_lead.web_to_lead.title', ]); }); it('seeds an authored title and leaves a form without one unseeded', () => { const entries = collectExpectedEntries(config()); const at = (p: string) => entries.find((e) => e.path.join('.') === p); - expect(at('objects.crm_lead._views.web_to_lead.title')).toMatchObject({ sourceValue: 'Contact us', inline: 'Contact us' }); - expect(at('objects.crm_lead._views.form.title')).toMatchObject({ sourceValue: 'New lead' }); - expect(at('objects.crm_lead._views.quick.title')?.inline).toBeUndefined(); + expect(at('forms.crm_lead.web_to_lead.title')).toMatchObject({ sourceValue: 'Contact us', inline: 'Contact us' }); + expect(at('forms.crm_lead.form.title')).toMatchObject({ sourceValue: 'New lead' }); + expect(at('forms.crm_lead.quick.title')?.inline).toBeUndefined(); }); - it('CONTROL: the list view emits no title slot, and the container forms emit no `label` slot', () => { + it('CONTROL: the list view emits no title slot, and no form emits a slot under `_views`', () => { const paths = collectExpectedEntries(config()).map((e) => e.path.join('.')); expect(paths).toContain('objects.crm_lead._views.all_leads.label'); expect(paths).not.toContain('objects.crm_lead._views.all_leads.title'); - expect(paths).not.toContain('objects.crm_lead._views.web_to_lead.label'); + expect(paths.filter((p) => /^objects\.crm_lead\._views\.(form|web_to_lead|quick|referral)\./.test(p))).toEqual([]); + }); + + it('a form held in a view (the protocol-18 shape) emits no title slot under either address', () => { + // The parse refuses the container's `form` / `formViews` slots and the + // form-kind view item at their own keys; the walker reads no form out of + // them, so `os i18n extract` scaffolds no key the translation schema + // refuses. + const held = (title: string) => ({ type: 'simple', data: { provider: 'object', object: 'crm_lead' }, title }); + const old = { + ...config(), + forms: [], + views: [ + { + list: { type: 'grid', name: 'all_leads', label: 'All Leads', data: { provider: 'object', object: 'crm_lead' } }, + form: held('New lead'), + formViews: { web_to_lead: held('Contact us') }, + }, + { name: 'referral', object: 'crm_lead', viewKind: 'form', config: held('Refer a friend') }, + ], + }; + expect(titleKeys(old)).toEqual([]); }); it('`os i18n extract` writes a skeleton the translation schema accepts', () => { - const lead: any = extractTranslations(config(), { locales: ['en'] }).bundles.en?.objects?.crm_lead; - expect(lead?._views?.web_to_lead?.title).toBe('Contact us'); - const parsed = ObjectTranslationDataSchema.safeParse(lead); + const bundle: any = extractTranslations(config(), { locales: ['en'] }).bundles.en; + expect(bundle?.forms?.['crm_lead.web_to_lead']?.title).toBe('Contact us'); + const object = ObjectTranslationDataSchema.safeParse(bundle?.objects?.crm_lead); + expect(object.success, JSON.stringify(object.error?.issues)).toBe(true); + const parsed = TranslationDataSchema.safeParse(bundle); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); }); it('the coverage gate reports an authored title a supported locale leaves untranslated', () => { + const titles = (i: { locale: string; key: string }) => + i.locale === 'zh-CN' && i.key.endsWith('.title') && !i.key.includes('.submitBehavior.'); const missing = computeI18nCoverage(config([{ 'zh-CN': { objects: { crm_lead: { label: '线索' } } } }])) - .issues.filter((i) => i.locale === 'zh-CN' && i.key.endsWith('.title')) + .issues.filter(titles) .map((i) => i.key) .sort(); expect(missing).toEqual([ - 'objects.crm_lead._views.form.title', - 'objects.crm_lead._views.referral.title', - 'objects.crm_lead._views.web_to_lead.title', + 'forms.crm_lead.form.title', + 'forms.crm_lead.referral.title', + 'forms.crm_lead.web_to_lead.title', ]); const covered = computeI18nCoverage(config([{ 'zh-CN': { - objects: { - crm_lead: { - label: '线索', - _views: { web_to_lead: { title: '联系我们' }, form: { title: '新建线索' }, referral: { title: '推荐朋友' } }, - }, + objects: { crm_lead: { label: '线索' } }, + forms: { + 'crm_lead.web_to_lead': { title: '联系我们' }, + 'crm_lead.form': { title: '新建线索' }, + 'crm_lead.referral': { title: '推荐朋友' }, }, }, - }])).issues.filter((i) => i.locale === 'zh-CN' && i.key.endsWith('.title')); + }])).issues.filter(titles); expect(covered).toEqual([]); }); }); diff --git a/packages/cli/test/i18n-section-coverage.test.ts b/packages/cli/test/i18n-section-coverage.test.ts index e6f3cee9455..dde8c02e2ec 100644 --- a/packages/cli/test/i18n-section-coverage.test.ts +++ b/packages/cli/test/i18n-section-coverage.test.ts @@ -148,44 +148,72 @@ describe('field-group sections', () => { // ── (b) authored sections on form views and record pages ─────────────── describe('authored form-view sections', () => { + // [ADR-0159 D8/D9] A form is a `forms[]` item from protocol 19. Its named + // sections are keyed at the form's own node, + // `forms..sections.
`, with the object-level + // `objects.._sections.
` slot as the fallback the translator + // reads for each key that node lacks. Under protocol 18 the forms were held + // in the view container below and the walker emitted the object-level slot. + const formSections = { + form: [ + { name: 'contact', label: 'Contact', fields: ['name'] }, + { name: 'work', label: 'Work', fields: ['company'] }, + ], + create: [ + { name: 'who', label: 'Who is this?', fields: ['name'] }, + // No `name` → `ObjectForm`'s `tSec` falls straight through to + // `s.label`; the lookup can never fire, so no expected key. + { label: 'Anything else?', fields: ['notes'] }, + ], + }; const config = { views: [ { list: { type: 'grid', data: { object: 'crm_contact' } }, - form: { - type: 'simple', - data: { object: 'crm_contact' }, - sections: [ - { name: 'contact', label: 'Contact', fields: ['name'] }, - { name: 'work', label: 'Work', fields: ['company'] }, - ], - }, - formViews: { - create: { - type: 'simple', - data: { object: 'crm_contact' }, - sections: [ - { name: 'who', label: 'Who is this?', fields: ['name'] }, - // No `name` → `ObjectForm`'s `tSec` falls straight through to - // `s.label`; the lookup can never fire, so no expected key. - { label: 'Anything else?', fields: ['notes'] }, - ], - }, - }, }, ], + forms: [ + { name: 'crm_contact.form', object: 'crm_contact', type: 'simple', sections: formSections.form }, + { name: 'crm_contact.create', object: 'crm_contact', type: 'simple', sections: formSections.create }, + ], }; - - it('covers the container default form AND its named overrides', () => { - expect(sectionKeys(config).sort()).toEqual([ + const formSectionEntries = (c: any) => + // The heading slot: a section also has an optional `description` slot beside it. + collectExpectedEntries(c).filter((e) => e.path[0] === 'forms' && e.path[2] === 'sections' && e.path[4] === 'label'); + + it('covers each form item\'s named sections, with the object-level slot as the fallback', () => { + expect(formSectionEntries(config).map((e) => e.path.join('.')).sort()).toEqual([ + 'forms.crm_contact.create.sections.who.label', + 'forms.crm_contact.form.sections.contact.label', + 'forms.crm_contact.form.sections.work.label', + ]); + expect(formSectionEntries(config).map((e) => e.fallbackPath?.join('.')).sort()).toEqual([ 'objects.crm_contact._sections.contact.label', 'objects.crm_contact._sections.who.label', 'objects.crm_contact._sections.work.label', ]); }); + it('a form held in the view container (the protocol-18 shape) emits no section slot', () => { + // The parse refuses the container's `form` / `formViews` slots at their + // own keys; the walker reads no form out of them. + const held = { + views: [ + { + list: { type: 'grid', data: { object: 'crm_contact' } }, + form: { type: 'simple', data: { object: 'crm_contact' }, sections: formSections.form }, + formViews: { create: { type: 'simple', data: { object: 'crm_contact' }, sections: formSections.create } }, + }, + ], + }; + expect(sectionKeys(held)).toEqual([]); + expect(collectExpectedEntries(held).filter((e) => e.path[0] === 'forms')).toEqual([]); + }); + it('skips a section with no `name` — every renderer guards the lookup on it', () => { - expect(sectionKeys(config)).not.toContain('objects.crm_contact._sections.anything_else.label'); + const keys = collectExpectedEntries(config).map((e) => e.path.join('.')); + expect(keys).not.toContain('objects.crm_contact._sections.anything_else.label'); + expect(keys.filter((k) => k.includes('anything_else'))).toEqual([]); }); }); diff --git a/packages/lint/src/authoring-rule-input-tier.test.ts b/packages/lint/src/authoring-rule-input-tier.test.ts index 20e05cffdaf..d6c0f074063 100644 --- a/packages/lint/src/authoring-rule-input-tier.test.ts +++ b/packages/lint/src/authoring-rule-input-tier.test.ts @@ -242,20 +242,29 @@ describe('premise 3 (FALSE): "the `visibleOn` alias survives until the parse"', // (`runAuthoringRules('lint', …)` over the normalized tier). There a // predicate under a retired key is nobody's verdict, by design — pinned // below as that door's reading, beside a canonical control. + // + // [ADR-0159 D9] The two form sites are a `forms[]` item's section and its + // field entry: a form is its own item from protocol 19, and the container + // slots these sites stood on under 18 (`form`, `formViews.`) are + // refused by the parse at their own keys, before any alias key is read. /** The three alias sites, each carrying `predicate` under its RETIRED key. */ const aliasSitesWith = (predicate: string): Array<[string, AnyRec]> => [ - ['views[].form.sections[]', { + ['forms[].sections[]', { manifest, - views: [{ - name: 'tier_form', - form: { type: 'simple', sections: [{ label: 'S', visibleOn: predicate, fields: [{ field: 'name' }] }] }, + forms: [{ + name: 'tier_task.intake', + object: 'tier_task', + type: 'simple', + sections: [{ label: 'S', visibleOn: predicate, fields: [{ field: 'name' }] }], }], }], - ['views[].formViews.edit.sections[]', { + ['forms[].sections[].fields[]', { manifest, - views: [{ - name: 'tier_form2', - formViews: { edit: { type: 'simple', sections: [{ label: 'S', visibleOn: predicate, fields: [{ field: 'name' }] }] } }, + forms: [{ + name: 'tier_task.edit', + object: 'tier_task', + type: 'simple', + sections: [{ label: 'S', fields: [{ field: 'name', visibleOn: predicate }] }], }], }], ['pages[].regions[].components[]', { @@ -323,9 +332,16 @@ describe('premise 3 (FALSE): "the `visibleOn` alias survives until the parse"', // says so from the far side of the retirement. const bare = { manifest, - views: [{ - name: 'tier_form3', - form: { type: 'simple', sections: [{ label: 'S', visibleWhen: "status == 'active'", fields: [{ field: 'name' }] }] }, + objects: [{ + name: 'tier_task', + label: 'Task', + fields: { name: { type: 'text', label: 'Name' }, status: { type: 'text', label: 'Status' } }, + }], + forms: [{ + name: 'tier_task.review', + object: 'tier_task', + type: 'simple', + sections: [{ label: 'S', visibleWhen: "status == 'active'", fields: [{ field: 'name' }] }], }], }; const cli = quietly(() => cliTierFor(structuredClone(bare))); diff --git a/packages/lint/src/authoring-rule-wiring.test.ts b/packages/lint/src/authoring-rule-wiring.test.ts index 26f87e48073..f398d8bf76b 100644 --- a/packages/lint/src/authoring-rule-wiring.test.ts +++ b/packages/lint/src/authoring-rule-wiring.test.ts @@ -499,25 +499,32 @@ describe('authoring-rule registry wiring (#4409)', () => { expect( typeSets.size, `the family's members declare different runtimeTypes (${[...typeSets].join(' vs ')}) — ` - + `a view write would reach some of them and not others`, + + `a form write would reach some of them and not others`, ).toBe(1); - // Non-vacuous, and the record of where #7220 left this: both are wired, - // for `view`. Flipping the family back to CLI-only is a legal edit that - // must go through this line rather than around it. + // Non-vacuous, and the record of where #7220 left this: both are wired. + // Flipping the family back to CLI-only is a legal edit that must go + // through this line rather than around it. expect(wired.map((e) => e.name)).toEqual(FAMILY); - // `view` writes also dispatch `validatePresetComparands` (#8793) — a - // different judgement (filter comparands, not predicates), registered - // ahead of the family — and `validateReferenceIntegrity` (#9313), whose - // suite runs exactly its two list-view FIELD members on a view snapshot - // (`runtime-gate.view-writes.test.ts` pins that member surface). Both - // are named here rather than folded into the family. + // [ADR-0159 D9] The family is wired for `form`, where a form's predicates + // are authored from protocol 19; a view holds lists only, so a `view` + // write reaches none of it. + expect(typeSets).toEqual(new Set(['app,form,page'])); + // `view` writes dispatch `validatePresetComparands` (#8793) — filter + // comparands, not predicates — and `validateReferenceIntegrity` (#9313), + // whose suite runs exactly its two list-view FIELD members on a view + // snapshot (`runtime-gate.view-writes.test.ts` pins that member surface). // `validateStackExpressions` (#24798) runs ONE pass on a view write — // the bulk `confirmText` template slots — registered ahead of the rest. expect(runtimeAuthoringRulesFor('view').map((r) => r.name)).toEqual([ 'validateStackExpressions', 'validatePresetComparands', 'validateReferenceIntegrity', + ]); + // The form-only rules moved with the form. This is the whole `form` + // dispatch, in registry order, so a rule joining or leaving it goes + // through this line. + expect(runtimeAuthoringRulesFor('form').map((r) => r.name)).toEqual([ // #29309 — a form section naming an unknown field or field group. 'validateFormLayout', // #25650 — a form open to anonymous intake declaring a file field. diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 7e71759c93a..eeb877ad9bc 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -135,7 +135,6 @@ import { validateRecordPageHeader } from './validate-record-page-header.js'; import { validateFieldConsumers } from './validate-field-consumers.js'; import { validateSemanticRoles } from './validate-semantic-roles.js'; import { validateFormLayout } from './validate-form-layout.js'; -import { validateInternalFormViews } from './validate-internal-form-views.js'; import { validatePublicFormFileFields } from './validate-public-form-file-fields.js'; import { validateFormConsumers, validateFormPublicAddresses } from './validate-form-items.js'; import { validateThankYouRecordFields } from './validate-thank-you-record-fields.js'; @@ -1933,9 +1932,11 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // Pure structured-metadata walk (no lazy dependency), so wiring it to all // three costs nothing measurable. // - // [#29309] Runtime publish gate: a `view` write's snapshot carries `objects` - // as context, and the rule reads nothing else beside the written view — the - // bound object's fields and its `fieldGroups`. Measured at the two doors + // [#29309; ADR-0159 D9] Runtime publish gate: from protocol 19 a form is a + // `form` item, so the rule runs on a `form` write, in place of the `view` + // write it ran on while a view held forms. A `form` write's snapshot carries + // `objects` as context, and the rule reads nothing else beside the written + // form — the bound object's fields and its `fieldGroups`. Measured at the two doors // that run this registry (an active save, a publish): the universe is the // registry's merged objects (`getAllObjects`, the overlay and every extender // folded on, the shape `getObject` serves) with the stored rows folded on by @@ -1953,27 +1954,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ commands: ALL, source: 'packages/lint/src/validate-form-layout.ts', surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['view'], + runtimeTypes: ['form'], run: (stack) => validateFormLayout(stack), }, - // #36425 — an internal create / edit form view the app still declares: the - // Console's create and edit surfaces no longer load one (they lay out by the - // object's field groups), so it installs, runs and steers nothing. Advisory, - // once per form. `normalized`: it reads only the authored `views[]` shapes, - // so `os lint`, which never parses, runs it too. - { - name: 'validateInternalFormViews', - tier: 'advisory', - input: 'normalized', - commands: ALL, - source: 'packages/lint/src/validate-internal-form-views.ts', - surfaces: CLI_ONLY, - surfaceReason: - 'Advisory-tier retirement notice for the app author at the check tools (`os lint`, `os validate`, ' + - '`os build`): an internal form view still installs and runs, inert, so the runtime door has nothing ' + - 'to refuse, and the Studio no longer offers internal form views to save.', - run: (stack) => validateInternalFormViews(stack), - }, // [ADR-0159 ruled question 3 = A] An authored `form` left open on a public // address another form of the stack holds (authored or projected out of an // old `view` shape). Gating. The runtime half is the save door's own @@ -1991,8 +1974,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ '`409 FORM_ADDRESS_TAKEN`): a per-write snapshot carries no other form, so the gate would judge nothing.', run: (stack) => validateFormPublicAddresses(stack), }, - // [ADR-0159 D1] An authored `form` no link and no action reaches: the - // successor of `form-view-internal-not-loaded` for `form` items. Advisory. + // [ADR-0159 D1] An authored `form` no link and no action reaches. Advisory. + // It succeeds `form-view-internal-not-loaded`, retired with protocol 19: a + // `view` holds no form there, so that rule had nothing left to read. { name: 'validateFormConsumers', tier: 'advisory', @@ -2011,10 +1995,12 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // filled. The prescription is the ruled route: register and sign in, then // fill a form that is not public. Gating, so all three commands run it. // - // Runtime publish gate: a `view` write's snapshot carries `objects` as - // context, which is every input this rule reads, so the view's publish is - // refused at the key. `object` is deliberately not declared: an object - // write's snapshot carries no views, so the rule would judge nothing there. + // Runtime publish gate ([ADR-0159 D9]: on a `form` write, in place of the + // `view` write it ran on while a view held forms): a `form` write's snapshot + // carries `objects` as context, which is every input this rule reads, so the + // form's publish is refused at the key. `object` is deliberately not + // declared: an object write's snapshot carries no forms, so the rule would + // judge nothing there. { name: 'validatePublicFormFileFields', tier: 'gating', @@ -2022,7 +2008,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ commands: ALL, source: 'packages/lint/src/validate-public-form-file-fields.ts', surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['view'], + runtimeTypes: ['form'], run: (stack) => validatePublicFormFileFields(stack), }, // Ruling B on #28005 — a form's `thank-you` panel may name, as @@ -2031,8 +2017,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // the anonymous form grant cannot read, and the public submit answer never // carries it. Gating, so all three commands run it. // - // Runtime publish gate: a `view` or `page` write's snapshot carries - // `objects` as context, which is every input this rule reads. `object` is + // Runtime publish gate: a `form` or `page` write's snapshot carries + // `objects` as context, which is every input this rule reads ([ADR-0159 D9]: + // `form` in place of `view`, which holds no form from protocol 19). `object` is // not declared, for the reason the file-field rule above gives. { name: 'validateThankYouRecordFields', @@ -2041,7 +2028,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ commands: ALL, source: 'packages/lint/src/validate-thank-you-record-fields.ts', surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['view', 'page'], + runtimeTypes: ['form', 'page'], run: (stack) => validateThankYouRecordFields(stack), }, // ADR-0078 Phase 3 (Tier-A `action-locations`) — an action that declares no @@ -2338,6 +2325,17 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // declares `app` with it for the one-wall reason above and judges nothing // there. Stored apps keep loading and serving; only the next save of an app // with such a predicate is refused, with the fix. + // + // ─── …and on `form` writes, in place of `view` (ADR-0159 D9) ─── + // + // From protocol 19 a form is a `form` item and a view holds lists only, so + // the half that judged a view's form sections judges a `forms:` item's, and + // the family declares `form` where it declared `view`. `form` maps to + // `forms`, and a form snapshot holds the item as `forms: [item]`. A `view` + // write carries no form section to judge. `validatePredicatePathRefs` reads + // schema-bound metadata forms only and gains no `forms:` arm; it declares + // `form` with its sibling for the one-wall reason above and judges nothing + // there. { name: 'validateVisibilityPredicates', tier: 'gating', @@ -2345,7 +2343,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ commands: ALL, source: 'packages/lint/src/validate-visibility-predicates.ts', surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['view', 'page', 'app'], + runtimeTypes: ['form', 'page', 'app'], run: (stack) => validateVisibilityPredicates(stack), }, // #7010 — the same predicate surface, one question further in. The three @@ -2387,7 +2385,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // it at either door. `app` likewise (#28663): declared with its sibling, // judging nothing on an app write. surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['view', 'page', 'app'], + runtimeTypes: ['form', 'page', 'app'], run: (stack) => validatePredicatePathRefs(stack), }, // #24953 — the CEL slots INSIDE a page component's `properties` bag (a diff --git a/packages/lint/src/finding-user-text.connector-permission-form.test.ts b/packages/lint/src/finding-user-text.connector-permission-form.test.ts index f9de69a8d5c..3edea471e9c 100644 --- a/packages/lint/src/finding-user-text.connector-permission-form.test.ts +++ b/packages/lint/src/finding-user-text.connector-permission-form.test.ts @@ -91,14 +91,16 @@ const permissionSet = (key: 'allowRestore' | 'allowPurge') => ({ objects: { acme_ticket: { allowRead: true, allowEdit: true, [key]: false } }, }); -/** A schema-bound form view: its predicates resolve against `FieldSchema`. */ +/** + * A schema-bound form view: its predicates resolve against `FieldSchema`. It is + * the entry itself — the one rung the predicate-path rule walks from protocol + * 19, where a view container holds no form (ADR-0159 D7). + */ const formView = (visibleWhen: string) => ({ name: 'acme_field_editor', label: 'Field editor', - form: { - data: { provider: 'schema', schemaId: 'field' }, - sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }], - }, + data: { provider: 'schema', schemaId: 'field' }, + sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }], }); type Finding = { rule: string; severity: string; userTextParams?: Record }; @@ -338,10 +340,27 @@ describe('connector, permission and form advisories user text · from the runtim expect(issue.userMessage).toContain('権限セット「acme_support_agent」は、オブジェクト「acme_ticket」に対してまだ「allowPurge: false」'); }); - it('a view write\'s unquoted-word advisory renders a valid userMessage', () => { - const result = runRuntimeAuthoringRules({ type: 'view', item: formView('data.type == active'), context: { objects: [] } }); - const advisory = result.advisories.find((f) => f.rule === PREDICATE_RHS_PATH_SHAPED); - expect(advisory, JSON.stringify(result.advisories)).toBeDefined(); + it('the unquoted-word advisory renders a valid userMessage; no write door returns it from protocol 19', () => { + // Under protocol 18 a `view` write carried a schema-bound form in its + // container slot and the gate returned this advisory. A view holds lists + // only now (the parse refuses a `views[]` entry's root `sections` and the + // retired slots alike), and a `form` item binds an object, never a schema, + // so the rule judges nothing either door hands it (ADR-0159 D7, D9). + const onView = runRuntimeAuthoringRules({ type: 'view', item: formView('data.type == active'), context: { objects: [] } }); + const onForm = runRuntimeAuthoringRules({ + type: 'form', + item: { name: 'acme_field.editor', object: 'acme_field', sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen: 'data.type == active' }] }] }, + context: { objects: [] }, + }); + for (const result of [onView, onForm]) { + expect([...result.advisories, ...result.errors].filter((f) => f.rule === PREDICATE_RHS_PATH_SHAPED)).toEqual([]); + } + + // The sentence itself still renders, from the finding the check commands + // report on a source that carries the schema-bound form view. + const advisory = validatePredicatePathRefs({ views: [formView('data.type == active')] }) + .find((f) => f.rule === PREDICATE_RHS_PATH_SHAPED); + expect(advisory).toBeDefined(); expect(advisory!.userTextParams).toEqual({ view: 'acme_field_editor', word: 'active', op: '==' }); const issue = issueOf(advisory!, ['fr-FR']); diff --git a/packages/lint/src/finding-user-text.pages-forms.test.ts b/packages/lint/src/finding-user-text.pages-forms.test.ts index 3115366272e..55060a38d1d 100644 --- a/packages/lint/src/finding-user-text.pages-forms.test.ts +++ b/packages/lint/src/finding-user-text.pages-forms.test.ts @@ -63,13 +63,14 @@ const EXTERNAL = { fields: { name: { type: 'text' }, email: { type: 'text' } }, }; -const formStack = (view: AnyRec): AnyRec => ({ objects: [CONTRACT], views: [view] }); +// [ADR-0159 D9] A form is a `forms[]` item from protocol 19, bound by `object`. +const formStack = (form: AnyRec): AnyRec => ({ objects: [CONTRACT], forms: [form] }); const simpleForm = (form: AnyRec): AnyRec => - ({ name: 'contract_form', type: 'simple', data: { provider: 'object', object: 'contract' }, ...form }); + ({ name: 'contract.intake', object: 'contract', type: 'simple', ...form }); const RUNTIME_RULE = "data.status == 'open'"; const visibilityStack = (extra: AnyRec): AnyRec => ({ objects: [CONTRACT], ...extra }); -const runtimeView = (section: AnyRec): AnyRec => ({ name: 'contract_view', object: 'contract', form: { sections: [section] } }); +const runtimeForm = (section: AnyRec): AnyRec => ({ name: 'contract.review', object: 'contract', sections: [section] }); const sortPage = (page: AnyRec): AnyRec => ({ objects: [EXTERNAL], pages: [{ name: 'customer_page', ...page }] }); const UNSTORED_SORT = [{ field: 'created_at' }]; @@ -83,8 +84,8 @@ type Case = { run: (stack: AnyRec) => readonly Finding[]; }; -const formCase = (label: string, rule: string, view: AnyRec, params: Record): Case => - ({ label, rule, stack: formStack(view), params, run: (s) => validateFormLayout(s as never) }); +const formCase = (label: string, rule: string, form: AnyRec, params: Record): Case => + ({ label, rule, stack: formStack(form), params, run: (s) => validateFormLayout(s as never) }); const visibilityCase = (label: string, stack: AnyRec, params: Record): Case => ({ label, rule: VISIBILITY_ROOT_MISLAYERED, stack, params, run: (s) => validateVisibilityPredicates(s as never) }); const sortCase = (label: string, page: AnyRec): Case => @@ -92,40 +93,48 @@ const sortCase = (label: string, page: AnyRec): Case => /** * One stack per advisory push site the publish door reaches, and per way into - * it: both of the form rule's sites (and both section buckets, and the Studio - * form item's `config` rung), the visibility site from a view section, a view - * field, a page component and a metadata-editing form, and the page-sort site - * from each of its five callers. + * it: both of the form rule's sites (and both section buckets, and the bare + * form view entry a raw source carries), the visibility site from a form + * section, a form field, a page component and a metadata-editing form, and the + * page-sort site from each of its five callers. */ const CASES: readonly Case[] = [ formCase('section field the object does not have', FORM_FIELD_UNKNOWN, simpleForm({ sections: [{ label: 'Main', fields: ['name', 'ghost_field'] }] }), - { view: 'contract_form', object: 'contract', field: 'ghost_field' }), - formCase('field in a Studio form item\'s config', FORM_FIELD_UNKNOWN, - { name: 'contract_entry', object: 'contract', viewKind: 'form', config: { sections: [{ label: 'Main', fields: ['ghost_field'] }] } }, - { view: 'contract_entry', object: 'contract', field: 'ghost_field' }), + { form: 'contract.intake', object: 'contract', field: 'ghost_field' }), + { + // The second way into the same push site: a `views[]` entry that is a bare + // form view. Under protocol 18 this case stood on the Studio form item's + // `config` rung, which is retired with the form-kind view item. + label: 'field in a bare form view entry', + rule: FORM_FIELD_UNKNOWN, + stack: { objects: [CONTRACT], views: [{ name: 'contract_entry', object: 'contract', sections: [{ label: 'Main', fields: ['ghost_field'] }] }] }, + params: { form: 'contract_entry', object: 'contract', field: 'ghost_field' }, + run: (s) => validateFormLayout(s as never), + }, formCase('section group the object does not declare', FORM_SECTION_GROUP_UNKNOWN, simpleForm({ sections: [{ label: 'Money', group: 'money' }] }), - { view: 'contract_form', object: 'contract', group: 'money' }), + { form: 'contract.intake', object: 'contract', group: 'money' }), formCase('legacy groups bucket naming an undeclared group', FORM_SECTION_GROUP_UNKNOWN, simpleForm({ groups: [{ label: 'Money', group: 'money' }] }), - { view: 'contract_form', object: 'contract', group: 'money' }), - visibilityCase('data-rooted rule on a view section', - visibilityStack({ views: [runtimeView({ label: 'Main', visibleWhen: RUNTIME_RULE, fields: [] })] }), - { surface: 'view', name: 'contract_view', root: 'data' }), - visibilityCase('data-rooted rule on a view field', - visibilityStack({ views: [runtimeView({ label: 'Main', fields: [{ field: 'name', visibleWhen: RUNTIME_RULE }] })] }), - { surface: 'view', name: 'contract_view', root: 'data' }), + { form: 'contract.intake', object: 'contract', group: 'money' }), + visibilityCase('data-rooted rule on a form section', + visibilityStack({ forms: [runtimeForm({ label: 'Main', visibleWhen: RUNTIME_RULE, fields: [] })] }), + { surface: 'form', name: 'contract.review', root: 'data' }), + visibilityCase('data-rooted rule on a form field', + visibilityStack({ forms: [runtimeForm({ label: 'Main', fields: [{ field: 'name', visibleWhen: RUNTIME_RULE }] })] }), + { surface: 'form', name: 'contract.review', root: 'data' }), visibilityCase('data-rooted rule on a page component', visibilityStack({ pages: [{ name: 'contract_page', type: 'record', object: 'contract', regions: [{ name: 'main', components: [ { type: 'record:details', visibleWhen: RUNTIME_RULE, properties: {} }, ] }] }] }), { surface: 'page', name: 'contract_page', root: 'data' }), visibilityCase('record-rooted rule on a metadata-editing form', - visibilityStack({ views: [{ name: 'field_editor', form: { + visibilityStack({ views: [{ + name: 'field_editor', data: { provider: 'schema', schemaId: 'field' }, sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen: "record.type == 'grid'" }] }], - } }] }), + }] }), { surface: 'view', name: 'field_editor', root: 'record' }), sortCase('list page sort', { type: 'list', object: 'showcase_ext_customer', interfaceConfig: { sort: UNSTORED_SORT } }), sortCase('app page record sort', { type: 'app', record: { object: 'showcase_ext_customer', sort: UNSTORED_SORT } }), @@ -220,32 +229,38 @@ describe('form, visibility and page-sort advisories user text · rendered from t }); it('tells a runtime surface to use record. and a metadata-editing form to use data., in every locale', () => { - const [runtime, metadata] = ['data-rooted rule on a view section', 'record-rooted rule on a metadata-editing form'] + const [runtime, metadata] = ['data-rooted rule on a form section', 'record-rooted rule on a metadata-editing form'] .map((label) => findingOf(CASES.find((c) => c.label === label)!)); expect(findingUserMessage(runtime!, ['en'])).toContain('Start the rule with "record."'); expect(findingUserMessage(metadata!, ['en'])).toContain('Start the rule with "data."'); for (const tag of PLATFORM_LOCALE_TAGS) { - // Same name, so only `root` tells the two apart. + // Same name and surface, so only `root` tells the two apart. const texts = [runtime!, metadata!].map((f) => - findingUserMessage({ ...f, userTextParams: { ...f.userTextParams!, name: 'n' } }, [tag])); + findingUserMessage({ ...f, userTextParams: { ...f.userTextParams!, name: 'n', surface: 'form' } }, [tag])); expect(new Set(texts).size, tag).toBe(2); } }); - it('names a view as a view and a page as a page, in every locale', () => { - const [view, page] = ['data-rooted rule on a view section', 'data-rooted rule on a page component'] + it('names a form as a form, a view as a view and a page as a page, in every locale', () => { + const [form, page] = ['data-rooted rule on a form section', 'data-rooted rule on a page component'] .map((label) => findingOf(CASES.find((c) => c.label === label)!)); + expect(form!.userTextParams!.surface).toBe('form'); + expect(page!.userTextParams!.surface).toBe('page'); for (const tag of PLATFORM_LOCALE_TAGS) { - const texts = [view!, page!].map((f) => + const texts = [form!, page!].map((f) => findingUserMessage({ ...f, userTextParams: { ...f.userTextParams!, name: 'n' } }, [tag])); expect(new Set(texts).size, tag).toBe(2); + // The same finding under each of the three nouns, so only the noun differs. + const nouns = ['form', 'view', 'page'].map((surface) => + findingUserMessage({ ...form!, userTextParams: { ...form!.userTextParams!, name: 'n', surface } }, [tag])); + expect(new Set(nouns).size, tag).toBe(3); } }); - it('renders the form sentence in zh-Hans and en with the view, object and field names', () => { + it('renders the form sentence in zh-Hans and en with the form, object and field names', () => { const finding = findingOf(CASES[0]!); - expect(findingUserMessage(finding, ['zh-CN'])).toContain('视图“contract_form”的表单列出了字段“ghost_field”'); - expect(findingUserMessage(finding, ['en-US'])).toContain('The form in view "contract_form" lists the field "ghost_field"'); + expect(findingUserMessage(finding, ['zh-CN'])).toContain('表单“contract.intake”列出了字段“ghost_field”'); + expect(findingUserMessage(finding, ['en-US'])).toContain('The form "contract.intake" lists the field "ghost_field"'); }); it('gives no sentence where the id is not advice the door returns', () => { @@ -269,7 +284,7 @@ describe('form, visibility and page-sort advisories user text · rendered from t for (const f of nav) expect((f as Finding).userTextParams, f.rule).toBeUndefined(); // A gating visibility verdict is an error with its own English message. const syntax = validateVisibilityPredicates( - visibilityStack({ views: [runtimeView({ label: 'Main', visibleWhen: "record.status === 'open'", fields: [] })] }) as never); + visibilityStack({ forms: [runtimeForm({ label: 'Main', visibleWhen: "record.status === 'open'", fields: [] })] }) as never); expect(syntax.map((f) => f.severity)).toEqual(['error']); expect(syntax[0]!.userTextParams).toBeUndefined(); }); @@ -288,12 +303,12 @@ describe('form, visibility and page-sort advisories user text · from the runtim userMessage: findingUserMessage(advisory, locales), }); - it('a view write\'s section-group advisory carries the call-site params out of the gate', () => { - const view = simpleForm({ sections: [{ label: 'Money', group: 'money' }] }); - const result = runRuntimeAuthoringRules({ type: 'view', item: view, context: { objects: [CONTRACT] } }); + it('a form write\'s section-group advisory carries the call-site params out of the gate', () => { + const form = simpleForm({ sections: [{ label: 'Money', group: 'money' }] }); + const result = runRuntimeAuthoringRules({ type: 'form', item: form, context: { objects: [CONTRACT] } }); const advisory = result.advisories.find((f) => f.rule === FORM_SECTION_GROUP_UNKNOWN); expect(advisory, 'the gate returns the section-group advisory for this write').toBeDefined(); - expect(advisory!.userTextParams).toEqual({ view: 'contract_form', object: 'contract', group: 'money' }); + expect(advisory!.userTextParams).toEqual({ form: 'contract.intake', object: 'contract', group: 'money' }); const issue = issueOf(advisory!, ['de-DE', 'en']); expect(issue.rule).toBe('form-section-group-unknown'); @@ -301,12 +316,12 @@ describe('form, visibility and page-sort advisories user text · from the runtim expect(issue.message).toBe(advisory!.message); }); - it('a view write\'s unknown-field advisory renders a valid userMessage', () => { - const view = simpleForm({ sections: [{ label: 'Main', fields: ['ghost_field'] }] }); - const result = runRuntimeAuthoringRules({ type: 'view', item: view, context: { objects: [CONTRACT] } }); + it('a form write\'s unknown-field advisory renders a valid userMessage', () => { + const form = simpleForm({ sections: [{ label: 'Main', fields: ['ghost_field'] }] }); + const result = runRuntimeAuthoringRules({ type: 'form', item: form, context: { objects: [CONTRACT] } }); const advisory = result.advisories.find((f) => f.rule === FORM_FIELD_UNKNOWN); - expect(advisory!.userTextParams).toEqual({ view: 'contract_form', object: 'contract', field: 'ghost_field' }); - expect(issueOf(advisory!, ['ja-JP']).userMessage).toContain('ビュー「contract_form」のフォーム'); + expect(advisory!.userTextParams).toEqual({ form: 'contract.intake', object: 'contract', field: 'ghost_field' }); + expect(issueOf(advisory!, ['ja-JP']).userMessage).toContain('フォーム「contract.intake」'); }); it('a page write\'s mislayered root and unstored sort carry their params out of the gate', () => { diff --git a/packages/lint/src/form-view-internal-not-loaded-retired.test.ts b/packages/lint/src/form-view-internal-not-loaded-retired.test.ts new file mode 100644 index 00000000000..fd48ebe6b9f --- /dev/null +++ b/packages/lint/src/form-view-internal-not-loaded-retired.test.ts @@ -0,0 +1,123 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `form-view-internal-not-loaded` is RETIRED with protocol 19 (ADR-0159 D7). + * + * The rule (#36425) named an internal create / edit form an app still declared + * inside a `view`: a container's default `form`, its `formViews.default` and + * `formViews.create`, and a `viewKind: 'form'` item that is the default or is + * named `OBJECT.create`. From protocol 19 a `view` holds lists only and the + * spec refuses each of those shapes at the parse, with a prescription naming + * `forms:`, so the rule had nothing left to read. Its successor on `form` + * items, `form-consumer-less` (ADR-0159 D1), stays. + * + * What this file pins, on the shapes the rule used to read: + * + * - the registry runs no rule under its name, on any check command, and + * `os explain` no longer answers its id; + * - `os lint`, which never parses, reports nothing under the id on a source + * that still authors the old shapes; + * - the parse refuses each old shape at its own key, which is what an author + * hears in the rule's place; + * - the successor reports a `form` item nothing reaches, and stays silent on + * one an action of type `form` opens or a public link names. + * + * This file authors the retired `view` keys as keys on purpose. + */ + +import { describe, expect, it } from 'vitest'; +import { ViewSchema } from '@objectstack/spec/ui'; + +import { AUTHORING_COMMANDS, AUTHORING_RULES, runAuthoringRules } from './authoring-rules.js'; +import { explainRule, RULE_EXPLANATIONS } from './rule-explanations.js'; +import { FORM_CONSUMER_LESS, validateFormConsumers } from './validate-form-items.js'; + +type AnyRec = Record; + +const RETIRED_RULE = 'form-view-internal-not-loaded'; +const RETIRED_RUNNER = 'validateInternalFormViews'; + +const sections = [{ label: 'Main', fields: ['name'] }]; +const account = { name: 'account', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } }; + +/** Every shape the retired rule used to name, in one protocol-18 source. */ +const oldShapeStack = (): AnyRec => ({ + objects: [account], + views: [ + { + name: 'account', + object: 'account', + form: { type: 'simple', sections }, + formViews: { create: { type: 'simple', sections }, default: { type: 'tabbed', sections } }, + }, + { name: 'account.form', object: 'account', viewKind: 'form', isDefault: true, config: { sections } }, + { name: 'account.create', object: 'account', viewKind: 'form', config: { sections } }, + ], +}); + +describe('form-view-internal-not-loaded is retired with protocol 19', () => { + it('no registry rule runs under its name and `os explain` does not answer its id', () => { + expect(AUTHORING_RULES.find((r) => r.name === RETIRED_RUNNER)).toBeUndefined(); + expect(AUTHORING_RULES.filter((r) => r.source.endsWith('validate-internal-form-views.ts'))).toEqual([]); + expect(explainRule(RETIRED_RULE)).toBeUndefined(); + expect(Object.keys(RULE_EXPLANATIONS)).not.toContain(RETIRED_RULE); + }); + + it('no check command reports the id on a source that still authors the old shapes', () => { + for (const command of AUTHORING_COMMANDS) { + const findings = runAuthoringRules(command, { normalized: oldShapeStack() }); + expect(findings.filter((f) => f.rule === RETIRED_RULE), command).toEqual([]); + } + }); + + it('the parse refuses a container that holds a form, at the key that holds it', () => { + const container = (oldShapeStack().views as AnyRec[])[0]!; + const result = ViewSchema.safeParse({ + ...container, + list: { type: 'grid', data: { provider: 'object', object: 'account' }, columns: ['name'] }, + }); + expect(result.success).toBe(false); + const refused = (result.error?.issues ?? []).map((issue) => issue.path.join('.')); + expect(refused).toEqual(expect.arrayContaining(['form', 'formViews'])); + }); + + it('lit control: the same container with its lists alone parses', () => { + const result = ViewSchema.safeParse({ + name: 'account', + object: 'account', + list: { type: 'grid', data: { provider: 'object', object: 'account' }, columns: ['name'] }, + }); + expect(result.success, JSON.stringify(result.error?.issues)).toBe(true); + }); +}); + +describe('its successor on `form` items stays (form-consumer-less, ADR-0159 D1)', () => { + const form = (extra: AnyRec = {}): AnyRec => ({ name: 'account.intake', object: 'account', type: 'simple', sections, ...extra }); + + it('a `form` item no link and no action reaches is reported once, as a warning', () => { + const findings = validateFormConsumers({ objects: [account], forms: [form()] }); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ rule: FORM_CONSUMER_LESS, severity: 'warning', path: 'forms[0]' }); + }); + + it('a `form` item an action of type `form` opens by name, or a public link names, is not reported', () => { + const opened = validateFormConsumers({ + objects: [account], + forms: [form()], + actions: [{ name: 'open_intake', type: 'form', target: 'account.intake' }], + }); + expect(opened).toEqual([]); + const linked = validateFormConsumers({ + objects: [account], + forms: [form({ sharing: { enabled: false, publicLink: '/forms/intake' } })], + }); + expect(linked).toEqual([]); + }); + + it('is registered as an advisory rule on every check command, and `os explain` knows it', () => { + const entry = AUTHORING_RULES.find((r) => r.name === 'validateFormConsumers'); + expect(entry?.tier).toBe('advisory'); + expect(entry?.commands).toEqual(AUTHORING_COMMANDS); + expect(explainRule(FORM_CONSUMER_LESS)?.rule).toBe(FORM_CONSUMER_LESS); + }); +}); diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 0413dc9a81e..277a60b6069 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -76,8 +76,6 @@ * objects.._views..label * objects.._views..description * objects.._views..emptyState.title / .message - * objects.._views..title - * objects.._views..submitBehavior.title / .message * objects.._views..bulkActions..label / .confirmText * / .confirmLabel * objects.._views..bulkActions..params..label @@ -316,18 +314,17 @@ export interface ExpectedEntry { /** * The object a view binds to. * - * The last two arms cover the aggregated View CONTAINER (`{ list, listViews, - * formViews }`), which per spec carries no object of its own and is keyed - * implicitly by its inner data source — the same fallback chain objectql's - * `resolveMetadataItemName` uses to register it. + * The last arm covers the aggregated View CONTAINER (`{ list, listViews }`), + * which per spec carries no object of its own and is keyed implicitly by its + * inner data source — the fallback objectql's `resolveMetadataItemName` uses + * to register it. */ function viewObjectName(view: any): string | undefined { return ( view?.objectName ?? view?.object ?? view?.data?.object ?? - view?.list?.data?.object ?? - view?.form?.data?.object + view?.list?.data?.object ); } @@ -419,57 +416,10 @@ function pushViewEntries(out: ExpectedEntry[], objectName: string, viewName: str pushBulkActionDefs(out, root, view, objectName); } -/** - * Emit `_views..title` for every FORM view a view container serves — - * each `formViews.` entry and the default `form` — the key - * `translateView` overlays a form's `title` (`FormViewSchema.title`) from. - * - * **The key is the composer's, asked, never re-derived.** A container form is - * served as the item `expandViewContainer` expands it to, and `translateView` - * keys its title by that item's registry name with the object prefix - * stripped: `formViews.` is `` (renamed on a collision, e.g. - * `default_2` beside a default list), the default `form` is its `name` or - * `form`. Reading the expanded items is the same discipline - * {@link defaultListViewKey} keeps for the default list, so the key written - * here is the key the runtime reads. - * - * **Title and thank-you panel only** ({@link pushFormViewCopy}). The other - * `_views` tails stay unemitted for a form: a container's form entry carries - * no `label`, and its `description` is not overlaid by anything a form - * renders. A form that authors no title still records the key - * (`pushOptional`), so the coverage gate notices a bundle that translates one - * the source never wrote. - */ -function pushContainerFormTitles(out: ExpectedEntry[], containerObject: string, container: any): void { - if (!container?.form && !container?.formViews) return; - const prefix = `${containerObject}.`; - for (const item of expandViewContainer(containerObject, container)) { - if (item.viewKind !== 'form') continue; - const key = item.name.startsWith(prefix) ? item.name.slice(prefix.length) : item.name; - pushFormViewCopy(out, containerObject, key, item.config); - } -} - -/** - * Emit the `_views` tails ONE served form view carries: its heading - * (`_views..title`, `config.title`) and its thank-you panel - * (`_views..submitBehavior.title` / `.message`, the `title` / `message` - * of a `kind: 'thank-you'` `config.submitBehavior`) — the strings - * `translateView` overlays. A panel of another kind authors no copy, so its - * two keys are recorded unauthored (`pushOptional`), exactly as an untitled - * form's `title` is. - */ -function pushFormViewCopy(out: ExpectedEntry[], objectName: string, key: string, config: unknown): void { - const form = config && typeof config === 'object' ? config as { title?: unknown; submitBehavior?: any } : undefined; - const root = ['objects', objectName, '_views', key]; - pushOptional(out, [...root, 'title'], form?.title, 'view', { objectName }); - pushThankYouPanel(out, root, form?.submitBehavior, 'view', { objectName }); -} - /** * Emit `.submitBehavior.title` / `.message` for one form's * `submitBehavior` — the panel's two slots, under whichever address its - * carrier has: a form view's `_views.` ({@link pushFormViewCopy}) or a + * carrier has: a `form` item's `forms.` ({@link walkForms}) or a * page `object-form` component's `pages..components.` * ({@link emitPageComponentCopy}). Only a `kind: 'thank-you'` panel authors * copy; any other kind records both keys unauthored (`pushOptional`), so the @@ -1283,25 +1233,13 @@ function walkObjectSections(config: any, out: ExpectedEntry[]): void { } } - // (b) authored form-view sections. + // (b) authored sections of a `views[]` entry that is a bare form view. A + // container holds lists only and carries none. const views: any[] = Array.isArray(config?.views) ? config.views : []; for (const view of views) { const containerObject = viewObjectName(view); addSectionList(index, view?.sections, containerObject); addSectionEntries(entries, view?.sections, containerObject); - if (view?.form && typeof view.form === 'object') { - const formObject = viewObjectName(view.form) ?? containerObject; - addSectionList(index, view.form.sections, formObject); - addSectionEntries(entries, view.form.sections, formObject); - } - if (view?.formViews && typeof view.formViews === 'object') { - for (const form of Object.values(view.formViews)) { - if (!form || typeof form !== 'object') continue; - const formObject = viewObjectName(form) ?? containerObject; - addSectionList(index, form.sections, formObject); - addSectionEntries(entries, form.sections, formObject); - } - } } // (b) [ADR-0159 D8] An authored `form` item's sections are NOT walked here: @@ -1744,7 +1682,7 @@ export function collectExpectedEntries( // object via `object`. // // 2. The aggregated View CONTAINER `defineView()` emits: - // `{ list, listViews, formViews }`. Per spec (`view.zod.ts`) it has NO + // `{ list, listViews }`. Per spec (`view.zod.ts`) it has NO // top-level `name` — it is keyed implicitly by its target object, which // lives at `list.data.object` (objectql's `resolveMetadataItemName` // says the same). @@ -1756,12 +1694,10 @@ export function collectExpectedEntries( // `i18n/missing-view` had zero producers repo-wide while the ratchet // reported green (#4123). // - // A container's form views (`formViews.*`, the default `form`) emit the - // `_views` tails `translateView` overlays — the form heading `title` and the - // thank-you panel's `submitBehavior.title` / `.message` (see - // `pushFormViewCopy`). Their `label` / `description` stay - // unemitted: a container form entry carries no label, and nothing a form - // renders reads a `_views` description. + // [ADR-0159 D8] A view holds lists only, so no `_views` key is emitted for a + // form: a form's heading and its thank-you panel are keyed at the form's own + // node, `forms.` ({@link walkForms}), and the `_views` form tails are + // refused by the translation schema. const views: any[] = Array.isArray(config?.views) ? config.views : []; for (const view of views) { const containerObject = viewObjectName(view); @@ -1769,16 +1705,9 @@ export function collectExpectedEntries( if (view.name) { pushViewEntries(out, containerObject, view.name, view); - // A `viewKind: 'form'` item carries its form under `config`, title and - // thank-you panel included. - if (view.viewKind === 'form' && view.config && typeof view.config === 'object') { - pushFormViewCopy(out, containerObject, view.name, view.config); - } continue; } - pushContainerFormTitles(out, containerObject, view); - // The container's default list, keyed exactly as the runtime registry keys // it — see `defaultListViewKey`. `undefined` means the container declares // no default list; a key the container's own `listViews` also declares @@ -2331,10 +2260,9 @@ function walkPackages(config: any, out: ExpectedEntry[]): void { /** * [ADR-0159 D8] Emit `forms..{label, description, title}` and its * thank-you panel's `forms..submitBehavior.{title, message}` for each - * authored `form` item — the address `translateForm` reads first. ⛔ No - * `objects.._views.` tail is emitted for an authored `form`: that - * address is the old shapes' fallback, read, never scaffolded for the new - * type. + * authored `form` item — the address `translateForm` reads. ⛔ No + * `objects.._views.` tail is emitted for a form: the translation + * schema refuses the form tails there from protocol 19. * * Section copy is the form's own too: `forms..sections.
.{label, * description}` and `.fields..{label, placeholder, helpText}`, for a diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index f6e1c0467ec..38b9e9dd671 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -324,13 +324,6 @@ export { FORM_SECTION_GROUP_UNKNOWN, } from './validate-form-layout.js'; export type { FormLayoutFinding, FormLayoutSeverity } from './validate-form-layout.js'; -// #36425 — an app still declaring an internal create / edit form, which the -// Console no longer loads. Advisory. -export { - validateInternalFormViews, - FORM_VIEW_INTERNAL_NOT_LOADED, -} from './validate-internal-form-views.js'; -export type { InternalFormViewFinding } from './validate-internal-form-views.js'; // [ADR-0159 card ②] The `form` type's authoring rules: the public-address // refusal (gating), the consumer-less advisory and the object binding. export { diff --git a/packages/lint/src/lint-liveness-properties.test.ts b/packages/lint/src/lint-liveness-properties.test.ts index 39f2cdf693d..70e4b855d36 100644 --- a/packages/lint/src/lint-liveness-properties.test.ts +++ b/packages/lint/src/lint-liveness-properties.test.ts @@ -291,17 +291,22 @@ describe('lintLivenessProperties', () => { // (the strict parse refuses them as unknown keys). The 17.x list tombstones // (`filterableFields`, `pageName`, `tabs`) still carry `dead` rows, so one of // them is the positive this case keeps. + // + // [ADR-0159 D7] Protocol 19 refuses a form a view holds at parse, so the form + // half rides as the `form` item it became under `forms:` (its `data` binding + // lifted to `object`); the pin below holds the 18 spelling to its refusal. it('retired view keys are graded dead while their tombstone stands; the corrected live key stays silent', () => { const findings = lintLivenessProperties({ views: [{ object: 'task', list: { type: 'grid', responsive: { breakpoint: 'md' }, filterableFields: ['title'] }, - form: { - type: 'wizard', - sections: [{ fields: ['title'] }], - data: { provider: 'object', object: 'task' }, - defaultSort: [{ field: 'created_at' }], - }, + }], + forms: [{ + name: 'task.form', + object: 'task', + type: 'wizard', + sections: [{ fields: ['title'] }], + defaultSort: [{ field: 'created_at' }], }], }); expect(ruleOf(findings, 'list.filterableFields')).toBe(LIVENESS_DEAD_PROPERTY); @@ -310,6 +315,31 @@ describe('lintLivenessProperties', () => { expect(paths(findings).some((m) => m.includes('form.data'))).toBe(false); }); + // [ADR-0159 D7] The 18 spelling of the case above, the form held by the + // view: the parse refuses it with a prescription naming `forms:`, and handed + // an unparsed stack the rule grades the retired `form` member dead as a + // whole (its row carries no children, so no `form.*` key is graded). + it('a form held by the view is refused at parse, the prescription naming `forms:`; the rule grades the member dead', () => { + const view = { + object: 'task', + list: { type: 'grid', columns: ['title'] }, + form: { + type: 'wizard', + sections: [{ fields: ['title'] }], + data: { provider: 'object', object: 'task' }, + defaultSort: [{ field: 'created_at' }], + }, + }; + const parsed = ViewSchema.safeParse(view); + expect(parsed.success).toBe(false); + const refusal = parsed.error?.issues.find((issue) => issue.path.join('.') === 'form'); + expect(refusal?.message, JSON.stringify(parsed.error?.issues)).toContain('forms:'); + const findings = lintLivenessProperties({ views: [view] }); + expect(ruleOf(findings, 'form')).toBe(LIVENESS_DEAD_PROPERTY); + expect(ruleOf(findings, 'form.defaultSort')).toBeUndefined(); + expect(paths(findings).some((m) => m.includes('form.data'))).toBe(false); + }); + // list.striped / list.bordered / list.virtualScroll left the surface with // the #7176 retirement (pass-through-only; keys REMOVED, the strict parse // refuses them). Their ledger rows are dead WITHOUT authorWarn, which kept diff --git a/packages/lint/src/lint-view-refs.test.ts b/packages/lint/src/lint-view-refs.test.ts index 6b408e28d43..1955a254c9b 100644 --- a/packages/lint/src/lint-view-refs.test.ts +++ b/packages/lint/src/lint-view-refs.test.ts @@ -36,11 +36,26 @@ const formView = (object: string) => ({ data: { provider: 'object', object }, sections: [], }); +/** [ADR-0159] A `forms[]` item: served under its exact name `OBJECT.KEY`, bound by `object`. */ +const formOf = (object: string, key: string) => ({ + name: `${object}.${key}`, + object, + type: 'simple', + sections: [], +}); +/** A second list config, distinct from `listView` so the expander does not dedupe it into the default. */ +const otherListView = (object: string) => ({ + type: 'grid', + label: 'Other', + columns: ['status'], + data: { provider: 'object', object }, +}); describe('lintViewRefs — clean paths', () => { - it('passes a container whose form key does not collide, with a correct form target', () => { + it('passes a list container beside a form of its object, with a correct form target', () => { const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { edit: formView('task') } }], + views: [{ name: 'task', list: listView('task') }], + forms: [formOf('task', 'edit')], actions: [{ name: 'log_time', type: 'form', target: 'task.edit' }], }; expect(lintViewRefs(stack)).toEqual([]); @@ -59,7 +74,8 @@ describe('lintViewRefs — clean paths', () => { it('skips dynamic (interpolated) and non-qualified targets', () => { const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { edit: formView('task') } }], + views: [{ name: 'task', list: listView('task') }], + forms: [formOf('task', 'edit')], actions: [ { name: 'a', type: 'form', target: 'task.${param.view}' }, { name: 'b', type: 'form', target: 'bare_key_no_dot' }, @@ -77,15 +93,25 @@ describe('lintViewRefs — object name derivation (real defineView shape)', () = // app-showcase). it('indexes a name-less container via list.data.object and accepts a good target', () => { const stack = { - views: [{ list: listView('showcase_task'), formViews: { edit: formView('showcase_task') } }], + views: [{ list: listView('showcase_task') }], + forms: [formOf('showcase_task', 'edit')], actions: [{ name: 'log_time', type: 'form', target: 'showcase_task.edit' }], }; expect(lintViewRefs(stack)).toEqual([]); + // What proves the container WAS indexed under the derived object: a form + // target naming its default list is told the name is a list's, which a + // container that dropped out of the index could only answer as a miss. + const atList = lintViewRefs({ + ...stack, + actions: [{ name: 'log_time', type: 'form', target: 'showcase_task.default' }], + }); + expect(atList.map((f) => f.rule)).toEqual([VIEW_REF_FORM_TARGET_KIND]); }); it('still flags a genuinely missing target on a name-less container', () => { const stack = { - views: [{ list: listView('showcase_task'), formViews: { edit: formView('showcase_task') } }], + views: [{ list: listView('showcase_task') }], + forms: [formOf('showcase_task', 'edit')], actions: [{ name: 'x', type: 'form', target: 'showcase_task.nope' }], }; expect(lintViewRefs(stack).some((f) => f.rule === VIEW_REF_FORM_TARGET_MISSING)).toBe(true); @@ -93,9 +119,9 @@ describe('lintViewRefs — object name derivation (real defineView shape)', () = }); describe('lintViewRefs — view-key collisions (#2554)', () => { - it('warns (does NOT fail the build) when formViews.default collides with the implicit default list', () => { + it('warns (does NOT fail the build) when listViews.default collides with the implicit default list', () => { const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { default: formView('task') } }], + views: [{ name: 'task', list: listView('task'), listViews: { default: otherListView('task') } }], }; const out = lintViewRefs(stack); const collision = out.find((f) => f.rule === VIEW_KEY_COLLISION); @@ -106,23 +132,40 @@ describe('lintViewRefs — view-key collisions (#2554)', () => { expect(collision!.message).toContain("'task.default_2'"); }); - it('detects the collision in object-nested listViews/formViews too', () => { + it('detects the collision in an object-nested list / listViews container too', () => { const stack = { objects: [ { name: 'task', - listViews: { mine: listView('task') }, - formViews: { mine: formView('task') }, + list: listView('task'), + listViews: { default: otherListView('task') }, }, ], }; const out = lintViewRefs(stack); - expect(out.some((f) => f.rule === VIEW_KEY_COLLISION && f.message.includes("'task.mine'"))).toBe(true); + expect(out.some((f) => f.rule === VIEW_KEY_COLLISION && f.message.includes("'task.default'"))).toBe(true); + }); + + it('a retired `formViews` slot is no collision: a form is its own item and takes no view key (ADR-0159 D7)', () => { + // Under protocol 18 `formViews.default` beside a nameless default list was + // the commonest collision. The parse refuses the slot now, and the form it + // held is served as no form, so its key renames nothing a reference reads. + const retired = lintViewRefs({ + views: [{ name: 'task', list: listView('task'), formViews: { default: formView('task') } }], + objects: [{ name: 'job', listViews: { mine: listView('job') }, formViews: { mine: formView('job') } }], + }); + expect(retired.filter((f) => f.rule === VIEW_KEY_COLLISION)).toEqual([]); + // A form item named like the default list is no collision either. + const item = lintViewRefs({ + views: [{ name: 'task', list: listView('task') }], + forms: [formOf('task', 'default')], + }); + expect(item.filter((f) => f.rule === VIEW_KEY_COLLISION)).toEqual([]); }); it('a collision-only stack yields NO error-severity finding — build is not blocked', () => { const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { default: formView('task') } }], + views: [{ name: 'task', list: listView('task'), listViews: { default: otherListView('task') } }], }; const out = lintViewRefs(stack); expect(out.some((f) => f.rule === VIEW_KEY_COLLISION)).toBe(true); // collision surfaced… @@ -132,22 +175,25 @@ describe('lintViewRefs — view-key collisions (#2554)', () => { describe('lintViewRefs — form action target resolution', () => { it('errors when a form target names a LIST view (the #2554 runtime symptom)', () => { - // `default` is the list; the form collides to `default_2`, so `task.default` - // resolves to the list — exactly what opened a blank form at runtime. + // `task.default` is the default list and no form item carries that name, + // so the target resolves to the list — exactly what opened a blank form at + // runtime. const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { default: formView('task') } }], + views: [{ name: 'task', list: listView('task') }], + forms: [formOf('task', 'edit')], actions: [{ name: 'log_time', type: 'form', target: 'task.default' }], }; const out = lintViewRefs(stack); const kindErr = out.find((f) => f.rule === VIEW_REF_FORM_TARGET_KIND); expect(kindErr).toBeDefined(); expect(kindErr!.severity).toBe('error'); - expect(kindErr!.message).toContain('list view, not a form view'); + expect(kindErr!.message).toContain('list view, not a form'); }); - it('warns (possible false positive, does NOT fail) when a form target resolves to no view at all', () => { + it('warns (possible false positive, does NOT fail) when a form target resolves to no form at all', () => { const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { edit: formView('task') } }], + views: [{ name: 'task', list: listView('task') }], + forms: [formOf('task', 'edit')], actions: [{ name: 'log_time', type: 'form', target: 'task.nope' }], }; const out = lintViewRefs(stack); @@ -157,32 +203,45 @@ describe('lintViewRefs — form action target resolution', () => { expect(missWarn!.severity).toBe('warning'); }); - it('accepts a form target that resolves to an actual form view', () => { + it('accepts a form target that resolves to an actual form', () => { const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { edit: formView('task') } }], + views: [{ name: 'task', list: listView('task') }], + forms: [formOf('task', 'edit')], actions: [{ name: 'log_time', type: 'form', target: 'task.edit' }], }; expect(lintViewRefs(stack).filter((f) => f.rule.startsWith('view-ref'))).toEqual([]); }); - it('validates object-nested actions against object-nested form views', () => { + it('a form held in a retired container slot answers no target (ADR-0159 D7)', () => { + // The same target, with the form where protocol 18 held it: the parse + // refuses the slot, and nothing serves a form out of it. const stack = { + views: [{ name: 'task', list: listView('task'), formViews: { edit: formView('task') } }], + actions: [{ name: 'log_time', type: 'form', target: 'task.edit' }], + }; + expect(lintViewRefs(stack).map((f) => [f.rule, f.severity])).toEqual([[VIEW_REF_FORM_TARGET_MISSING, 'warning']]); + }); + + it('validates object-nested actions against the stack\'s forms', () => { + const stack = (target: string) => ({ + forms: [formOf('task', 'edit')], objects: [ { name: 'task', - formViews: { edit: formView('task') }, - actions: [{ name: 'nested_form', type: 'form', target: 'task.missing' }], + actions: [{ name: 'nested_form', type: 'form', target }], }, ], - }; - const out = lintViewRefs(stack); + }); + const out = lintViewRefs(stack('task.missing')); expect(out.some((f) => f.rule === VIEW_REF_FORM_TARGET_MISSING && f.where.includes("object 'task'"))).toBe(true); + expect(lintViewRefs(stack('task.edit'))).toEqual([]); }); it('reports a shared (top-level + object-nested) action only once', () => { const shared = { name: 'log_time', type: 'form', target: 'task.missing' }; const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { edit: formView('task') } }], + views: [{ name: 'task', list: listView('task') }], + forms: [formOf('task', 'edit')], actions: [shared], objects: [{ name: 'task', actions: [shared] }], }; @@ -229,9 +288,9 @@ describe('[ADR-0159] lintViewRefs — a form action targeting an authored `forms expect(targetFindings(stack)).toEqual([]); }); - it('CONTROL: a target that is neither a form view nor a form item still warns', () => { + it('CONTROL: a target that is neither a view nor a form item still warns', () => { const stack = { - views: [{ name: 'task', list: listView('task'), formViews: { edit: formView('task') } }], + views: [{ name: 'task', list: listView('task') }], forms: [formItem('task.quick')], actions: [{ name: 'quick_edit', type: 'form', target: 'task.quik' }], }; @@ -262,11 +321,12 @@ const NAV_OBJECT = { schedule: navListView('duly_task', 'Schedule', 'due_at'), board: navListView('duly_task', 'Board', 'status'), }, - formViews: { edit: formView('duly_task') }, }; const navStack = (nav: Record, appExtra: Record = {}) => ({ objects: [NAV_OBJECT], + // [ADR-0159] The object's one form, as the item it is from protocol 19. + forms: [formOf('duly_task', 'edit')], apps: [{ name: 'duly', label: 'Duly', navigation: [nav], ...appExtra }], }); @@ -336,10 +396,10 @@ describe('lintViewRefs — navigation viewName resolution (#14108)', () => { expect(navFindings(stack)).toEqual([]); }); - it('names the form-view case explicitly rather than reporting a bare miss', () => { + it('names the form case explicitly rather than reporting a bare miss', () => { const out = navFindings(navStack({ id: 'n', type: 'object', objectName: 'duly_task', viewName: 'edit', label: 'E' })); expect(out).toHaveLength(1); - expect(out[0].message).toContain('resolves to a FORM view'); + expect(out[0].message).toContain('resolves to a FORM)'); expect(out[0].hint).toContain("type:'form' action target"); }); @@ -478,8 +538,8 @@ describe('[#22161] one-line verdicts — view-ref-nav-view-missing, view-key-col // The coverage control first: both ids fired, and the nav id on both arms. expect([...new Set(converted.map((f) => f.rule))].sort()).toEqual([...CONVERTED].sort()); const nav = converted.filter((f) => f.rule === VIEW_REF_NAV_VIEW_MISSING); - expect(nav.some((f) => f.message.includes('resolves to a FORM view'))).toBe(true); - expect(nav.some((f) => !f.message.includes('resolves to a FORM view'))).toBe(true); + expect(nav.some((f) => f.message.includes('resolves to a FORM)'))).toBe(true); + expect(nav.some((f) => !f.message.includes('resolves to a FORM)'))).toBe(true); for (const f of converted) { expect(f.message, f.rule).not.toContain('\n'); expect(f.message.length, `${f.rule}: ${f.message}`).toBeLessThanOrEqual(200); @@ -497,14 +557,14 @@ describe('[#22161] one-line verdicts — view-ref-nav-view-missing, view-key-col const [form] = navFindings(navStack({ id: 'n', type: 'object', objectName: 'duly_task', viewName: 'edit', label: 'E' })); expect(form!.message).toBe( "Navigation entry opens view 'edit' on object 'duly_task', which has no such list view (the name " + - 'resolves to a FORM view), so it silently opens the default view. List views: board, default, ' + + 'resolves to a FORM), so it silently opens the default view. List views: board, default, ' + 'schedule', ); const [collision] = lintViewRefs({ - views: [{ name: 'task', list: listView('task'), formViews: { default: formView('task') } }], + views: [{ name: 'task', list: listView('task'), listViews: { default: otherListView('task') } }], }).filter((f) => f.rule === VIEW_KEY_COLLISION); expect(collision!.message).toBe( - "View key collision: the form view 'task.default' was renamed to 'task.default_2', so every " + + "View key collision: the list view 'task.default' was renamed to 'task.default_2', so every " + "reference to 'task.default' resolves to the OTHER view", ); }); diff --git a/packages/lint/src/lint-view-refs.ts b/packages/lint/src/lint-view-refs.ts index 9b2898057d2..36b69b625ff 100644 --- a/packages/lint/src/lint-view-refs.ts +++ b/packages/lint/src/lint-view-refs.ts @@ -17,23 +17,26 @@ * the concrete #2554 breakage and is high-confidence, so it fails the build. * * view-key-collision (#2554) — WARNING - * List and form views share one `.` namespace during expansion, + * A container's views share one `.` namespace during expansion, * and the default `list` implicitly claims `.default`. A colliding * key is renamed (`.` → `._2`) so the registry key * stays unique. The rename alone is only *fragile* — it breaks something only * if that name is referenced — so it warns rather than failing the build. * * view-ref-form-target-missing — WARNING - * A `type:'form'` target that resolves to no view is probably a typo, but it - * may also be a view this lint failed to collect (a non-standard container - * shape), so it warns rather than risk a false-positive build failure. + * A `type:'form'` target that resolves to no form is probably a typo, but it + * may also be a form another package ships, so it warns rather than risk a + * false-positive build failure. * * A target equal to the `name` of an authored `forms:` item (ADR-0159) * resolves, and neither rule above fires on it: the console's form page * reads `/meta/form/` by that exact name, and the by-name `form` * read (ADR-0159 D5) answers it from the item, whatever views share the * name. The items are read through `stackForms`, the one walk every - * `form` rule shares; a target that is neither still warns. + * `form` rule shares; a target that is neither still warns. From protocol 19 + * a `forms:` item is the ONLY form a target can open: a view holds lists + * only, so a form a container still carries (the parse refuses it) satisfies + * no target here. * * view-ref-nav-view-missing — ERROR (fails the build) * An app navigation entry whose `viewName` resolves to no list view on its @@ -41,7 +44,7 @@ * `listViews` namespace the two rules above guard, and the more travelled one. * * Deliberately conservative to keep false positives near zero: only `type:'form'` - * targets are checked (the one type that unambiguously names a form view), + * targets are checked (the one type that unambiguously names a form), * interpolated targets (`${…}`) are skipped as non-static, and non-qualified * targets (no `.`) are treated as opaque handler/modal refs rather than view * references. @@ -200,12 +203,13 @@ export function lintViewRefs(stack: AnyRec): ViewRefFinding[] { const containers: Array<{ object: string; container: AnyRec }> = []; for (const v of recordsOf(stack.views)) { if (v.viewKind) { - // Already an independent, expanded ViewItem — index it directly. - const kind = v.viewKind === 'form' ? 'form' : 'list'; - if (typeof v.name === 'string') { - indexKind(v.name, kind); + // Already an independent, expanded ViewItem — index it directly. [ADR-0159 + // D7] A `viewKind: 'form'` item is a retired shape the parse refuses; it + // is no view a navigation entry can open and no form a target can. + if (v.viewKind !== 'form' && typeof v.name === 'string') { + indexKind(v.name, 'list'); const owner = independentViewObject(v); - if (owner) indexForObject(owner, v.name, kind); + if (owner) indexForObject(owner, v.name, 'list'); } continue; } @@ -225,13 +229,21 @@ export function lintViewRefs(stack: AnyRec): ViewRefFinding[] { for (const { object, container } of containers) { const { items, collisions } = expandViewContainerWithDiagnostics(object, container); for (const it of items) { - indexKind(it.name, it.viewKind); + // [ADR-0159 D7] The expander still reads a form out of a container that + // carries one (a retired slot the parse refuses). It is served as no + // form from protocol 19, so it is indexed as neither kind. + if (it.viewKind !== 'list') continue; + indexKind(it.name, 'list'); // Index under the item's OWN object (`it.object`), not the container's — // they are the same here, but the expander is the authority on which // object a produced item belongs to. - indexForObject(it.object ?? object, it.name, it.viewKind); + indexForObject(it.object ?? object, it.name, 'list'); } for (const col of collisions) { + // [ADR-0159 D7] Only a list view's rename moves a reference: the form the + // expander reads out of a retired container slot is served as no form + // from protocol 19, so nothing resolves through the name it lost. + if (col.viewKind !== 'list') continue; findings.push({ where: `object '${object}' · view key '${col.key}'`, // [#22161] One verdict; the shared namespace and which references @@ -254,7 +266,14 @@ export function lintViewRefs(stack: AnyRec): ViewRefFinding[] { const seenFormTargets = new Set(); // [ADR-0159 D1/D5] The names the authored `form` items are served under — // the exact name a form target must equal for the console's form page. - const formItemNames = new Set(stackForms(stack).filter((f) => f.definedIn === 'form').map((f) => f.name)); + const formItems = stackForms(stack).filter((f) => f.definedIn === 'form'); + const formItemNames = new Set(formItems.map((f) => f.name)); + // The same items under their own object: what tells a navigation entry that + // the name it carries is a form's, not a list view's. + for (const form of formItems) { + indexKind(form.name, 'form'); + if (form.object) indexForObject(form.object, form.name, 'form'); + } const checkAction = (action: AnyRec, ownerObject?: string) => { if (!action || action.type !== 'form') return; const target = action.target; @@ -274,11 +293,11 @@ export function lintViewRefs(stack: AnyRec): ViewRefFinding[] { findings.push({ where, message: - `Form action target '${target}' does not resolve to any view or form. A type:'form' action must point at ` + - `an existing form view or \`forms:\` item; at runtime this opens a blank/broken form.`, + `Form action target '${target}' does not resolve to any form. A type:'form' action must point at ` + + `an existing \`forms:\` item; at runtime this opens a blank/broken form.`, hint: - `Check for a typo, or a form view renamed by a key collision. Expected a form view named ` + - `'.', or the exact name of a \`forms:\` item.`, + `Check for a typo. Expected the exact name of a \`forms:\` item ('.'); a view holds ` + + `lists only, so a form is never named through one.`, rule: VIEW_REF_FORM_TARGET_MISSING, severity: 'warning', }); @@ -289,11 +308,10 @@ export function lintViewRefs(stack: AnyRec): ViewRefFinding[] { findings.push({ where, message: - `Form action target '${target}' resolves to a ${actual} view, not a form view. Opening a ${actual} ` + + `Form action target '${target}' resolves to a ${actual} view, not a form. Opening a ${actual} ` + `view through a form action renders an empty form (and a submit can silently no-op) at runtime.`, hint: - `Point target at a form view (viewKind 'form'). If the form view was renamed by a key collision, ` + - `fix the colliding key so '${target}' names the form again.`, + `Point target at a form: the exact name of a \`forms:\` item ('.').`, rule: VIEW_REF_FORM_TARGET_KIND, severity: 'error', }); @@ -355,13 +373,13 @@ export function lintViewRefs(stack: AnyRec): ViewRefFinding[] { // silent are `os explain` text. The list views stay: they are the fix. message: `Navigation entry opens view '${viewName}' on object '${objectName}', which has no such list view` + - (isFormView ? ` (the name resolves to a FORM view)` : '') + + (isFormView ? ` (the name resolves to a FORM)` : '') + `, so it silently opens the default view. List views: ${viewRoster(available)}`, hint: `Correct the name, declare '${viewName}' in the object's \`listViews\`, or drop \`viewName\` ` + `to open the default view.` + (isFormView - ? ` A form view is reachable from a type:'form' action target, not from navigation.` + ? ` A form is reachable from a type:'form' action target, not from navigation.` : '') + suggestName(viewName, available), rule: VIEW_REF_NAV_VIEW_MISSING, diff --git a/packages/lint/src/object-graph.test.ts b/packages/lint/src/object-graph.test.ts index f8720dceb36..becd424bae9 100644 --- a/packages/lint/src/object-graph.test.ts +++ b/packages/lint/src/object-graph.test.ts @@ -637,12 +637,11 @@ describe('[#30383] the field-path rules read the objects as served', () => { permissions: [{ name: 's', label: 'S', rowLevelSecurity: [{ name: 'p', object: 'xs_deal', operation: 'select', using: `record.${f} == 'x'` }] }], })], ['validate-thank-you-record-fields', THANK_YOU_RECORD_FIELD, validateThankYouRecordFields, (f) => ({ - views: [{ - name: 'vv', - form: { - type: 'simple', data: { provider: 'object', object: 'xs_deal' }, sections: [{ name: 'a', fields: ['name'] }], - submitBehavior: { kind: 'thank-you', title: 'T', message: `Ref {{record.${f}}}` }, - }, + // [ADR-0159 D9] A form is a `forms[]` item from protocol 19. + forms: [{ + name: 'xs_deal.vv', object: 'xs_deal', + type: 'simple', sections: [{ name: 'a', fields: ['name'] }], + submitBehavior: { kind: 'thank-you', title: 'T', message: `Ref {{record.${f}}}` }, }], })], ['validate-mapping-target-fields', MAPPING_TARGET_FIELD_UNKNOWN, validateMappingTargetFields, (f) => ({ @@ -813,12 +812,10 @@ describe('[#30383] the field-path rules read the objects as served', () => { it('is admitted on a thank-you panel only when every tied definition is engine-generated', () => { const panel = (stack: Rec) => ({ ...stack, - views: [{ - name: 'vv', - form: { - type: 'simple', data: { provider: 'object', object: 'xs_deal' }, sections: [{ name: 'a', fields: ['name'] }], - submitBehavior: { kind: 'thank-you', title: 'T', message: 'Ref {{record.ref_no}}' }, - }, + forms: [{ + name: 'xs_deal.vv', object: 'xs_deal', + type: 'simple', sections: [{ name: 'a', fields: ['name'] }], + submitBehavior: { kind: 'thank-you', title: 'T', message: 'Ref {{record.ref_no}}' }, }], }); expect(ids(validateThankYouRecordFields, panel(tie({ ref_no: { type: 'autonumber' } }, { ref_no: { type: 'autonumber' } })))).toEqual([]); @@ -1209,13 +1206,12 @@ describe('[#30608] the remaining field indexes read the objects as served', () = }; const verdicts = (run: Run, stack: Rec) => run(stack).map((f) => [f.rule, f.severity]); + // [ADR-0159 D9] A form is a `forms[]` item from protocol 19. const form = (field: string, sharing?: Rec): Rec => ({ - views: [{ - name: 'vf', - form: { - type: 'simple', data: { provider: 'object', object: 'xs_deal' }, sections: [{ name: 's', fields: ['name', field] }], - ...(sharing ? { sharing } : {}), - }, + forms: [{ + name: 'xs_deal.vf', object: 'xs_deal', + type: 'simple', sections: [{ name: 's', fields: ['name', field] }], + ...(sharing ? { sharing } : {}), }], }); const publicForm = (field: string) => form(field, { enabled: true, allowAnonymous: true, publicLink: 'intake' }); diff --git a/packages/lint/src/reference-integrity-suite.test.ts b/packages/lint/src/reference-integrity-suite.test.ts index 5f009f8b504..5402e73ed45 100644 --- a/packages/lint/src/reference-integrity-suite.test.ts +++ b/packages/lint/src/reference-integrity-suite.test.ts @@ -224,15 +224,19 @@ describe('reference-integrity suite — every member actually runs', () => { // validateActionNameRefs: no such action. rowActions: ['mass_update'], }, - // validateTranslatableSections (#5417): a form section authored with a - // `label` and no `name`. `_sections` is keyed by name, so this heading - // has no key any bundle can carry — and crm_lead IS translated below, - // which is what opens the rule's opt-in gate. - form: { - type: 'simple', - data: { provider: 'object', object: 'crm_lead' }, - sections: [{ label: 'Qualification', columns: 2, fields: ['name'] }], - }, + }, + ], + // validateTranslatableSections (#5417): a form section authored with a + // `label` and no `name`. `_sections` is keyed by name, so this heading + // has no key any bundle can carry — and crm_lead IS translated below, + // which is what opens the rule's opt-in gate. [ADR-0159 D9] The form is a + // `forms[]` item from protocol 19. + forms: [ + { + name: 'crm_lead.intake', + object: 'crm_lead', + type: 'simple', + sections: [{ label: 'Qualification', columns: 2, fields: ['name'] }], }, ], pages: [ diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 8bf90e4f6e9..49523b776e5 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -323,7 +323,6 @@ import { PAGE_FIELD_UNPROVISIONED_EXPLANATION, PAGE_SECTION_GROUP_UNKNOWN_EXPLANATION, FORM_SECTION_GROUP_UNKNOWN_EXPLANATION, - FORM_VIEW_INTERNAL_NOT_LOADED_EXPLANATION, } from './rule-explanations/page-field-bindings.js'; import { FORM_PUBLIC_ADDRESS_TAKEN_EXPLANATION, @@ -646,7 +645,6 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [PAGE_FIELD_UNPROVISIONED_EXPLANATION.rule]: PAGE_FIELD_UNPROVISIONED_EXPLANATION, [PAGE_SECTION_GROUP_UNKNOWN_EXPLANATION.rule]: PAGE_SECTION_GROUP_UNKNOWN_EXPLANATION, [FORM_SECTION_GROUP_UNKNOWN_EXPLANATION.rule]: FORM_SECTION_GROUP_UNKNOWN_EXPLANATION, - [FORM_VIEW_INTERNAL_NOT_LOADED_EXPLANATION.rule]: FORM_VIEW_INTERNAL_NOT_LOADED_EXPLANATION, [FORM_PUBLIC_ADDRESS_TAKEN_EXPLANATION.rule]: FORM_PUBLIC_ADDRESS_TAKEN_EXPLANATION, [FORM_CONSUMER_LESS_EXPLANATION.rule]: FORM_CONSUMER_LESS_EXPLANATION, [FORM_OBJECT_OUTSIDE_CLOSURE_EXPLANATION.rule]: FORM_OBJECT_OUTSIDE_CLOSURE_EXPLANATION, diff --git a/packages/lint/src/rule-explanations/page-field-bindings.ts b/packages/lint/src/rule-explanations/page-field-bindings.ts index 1f45f32007b..c69712f81b8 100644 --- a/packages/lint/src/rule-explanations/page-field-bindings.ts +++ b/packages/lint/src/rule-explanations/page-field-bindings.ts @@ -87,31 +87,8 @@ export const FORM_SECTION_GROUP_UNKNOWN_EXPLANATION: RuleExplanation = { covers: 'how a form section inherits a field group', paragraphs: [ ...SECTION_GROUP_REFERENCE, - 'On a form view the reference is a section\'s `group`, in `sections` and in the legacy `groups` ' + - 'alias alike, resolved against the object the form binds (its own `objectName`, `object` or ' + - '`data.object`, else its container\'s, else the container\'s list binding).', - ], -}; - -export const FORM_VIEW_INTERNAL_NOT_LOADED_EXPLANATION: RuleExplanation = { - rule: 'form-view-internal-not-loaded', - covers: 'why an internal create or edit form no longer loads', - paragraphs: [ - 'The Console\'s record create and edit surfaces — the create dialog, the full-page create, a create ' + - 'or edit an action opens, and the edit dialog — lay a record out by its object\'s field groups ' + - '(`fieldGroups`) and follow the rules declared on its fields: `required`, `requiredWhen`, ' + - '`visibleWhen`, `readonlyWhen`, and `showOnCreate` for a field a create should not ask for. They no ' + - 'longer load an object\'s internal form view, so its sections, tabs, wizard steps, subforms, ' + - '`modalSize`, `buttons`, `layout` and `defaults` steer nothing.', - 'The forms reported are the ones those surfaces used to load: a view container\'s default `form`, ' + - 'its `formViews.default` and `formViews.create`, and a stored form view item that is the default ' + - '(`isDefault`) or is named `.create`. A form shared publicly (`sharing.enabled: true`) keeps ' + - 'loading at its own link and is never reported; neither is a form view under any other name, which ' + - 'an action of type `form` opens by that name. Nor is a default or create form that an action of type ' + - '`form` opens by name: its `target` equals the name the form is served under (`.form` for a ' + - 'container\'s default form, `.create` for its `formViews.create`), so it keeps loading there.', - 'The rule is a warning: the declared form still parses, installs and runs, and changes nothing. To ' + - 'clear it, move the sections into the object\'s field groups, put each required and show/hide rule ' + - 'on its field (a create-time default goes on the field\'s `defaultValue`), and delete the form.', + 'On a form the reference is a section\'s `group`, in `sections` and in the legacy `groups` ' + + 'alias alike, resolved against the object the form binds: a `forms:` item\'s own `object` ' + + '(or `objectName` / `data.object`).', ], }; diff --git a/packages/lint/src/rule-explanations/predicate-path-refs.ts b/packages/lint/src/rule-explanations/predicate-path-refs.ts index 87abe716f9b..1dd594b0590 100644 --- a/packages/lint/src/rule-explanations/predicate-path-refs.ts +++ b/packages/lint/src/rule-explanations/predicate-path-refs.ts @@ -9,7 +9,7 @@ import type { RuleExplanation } from '../rule-explanations.js'; /** Which predicates the three ids judge, and the oracle they ask (all three). */ const PREDICATE_FORM_SCOPE = 'Judged: the `visibleWhen` predicates on a metadata-editing form — a `views[]` ' + - 'form, its default `form` or a `formViews` entry whose data source is `{ provider: \'schema\', ' + + 'entry that is itself a form whose data source is `{ provider: \'schema\', ' + 'schemaId }` — on its sections and fields, nested repeater rows included, where `data` is rebound ' + 'to the ROW. A path is resolved against the Zod schema of the metadata type the form edits ' + '(`getMetadataTypeSchema(schemaId)`, the entry `saveMetaItem` validates the saved row against), ' + diff --git a/packages/lint/src/rule-explanations/translations.ts b/packages/lint/src/rule-explanations/translations.ts index d5d7fc9bc8c..e6739a15425 100644 --- a/packages/lint/src/rule-explanations/translations.ts +++ b/packages/lint/src/rule-explanations/translations.ts @@ -122,8 +122,8 @@ export const TRANSLATION_SECTION_NAME_MISSING_EXPLANATION: RuleExplanation = { 'Judged only on an object that some `stack.translations` bundle carries a node for (a ' + 'monolingual stack owes nobody a section name), and only on the array form of `sections`: a ' + 'name-keyed map supplies the name from its key, and a `fieldGroups` section is keyed by ' + - '`fieldGroups[].key`. Surfaces: a view container\'s `sections`, its default `form` and every ' + - '`listViews.*` / `formViews.*` sub-container, on stack views and on views embedded in an ' + + '`fieldGroups[].key`. Surfaces: a `forms:` item\'s `sections`, a view container\'s own ' + + '`sections` and every `listViews.*` sub-container, on stack views and on views embedded in an ' + 'object, and `record:details` sections anywhere in a page\'s component tree.', ], }; diff --git a/packages/lint/src/rule-explanations/view-containers.ts b/packages/lint/src/rule-explanations/view-containers.ts index f54f2b36cb9..58e29eccf9f 100644 --- a/packages/lint/src/rule-explanations/view-containers.ts +++ b/packages/lint/src/rule-explanations/view-containers.ts @@ -8,10 +8,12 @@ export const VIEW_CONTAINER_SHAPE_EXPLANATION: RuleExplanation = { rule: 'view-container-shape', covers: 'what the stack views collection carries', paragraphs: [ - 'The stack\'s `views:` collection carries view CONTAINERS (`defineView`): `{ list, form, ' + - 'listViews, formViews }`, every slot optional. A container with none of them set is ' + - 'schema-valid, the loader expands no view from it, and the Console renders nothing for it ' + - '(no switcher entry).', + 'The stack\'s `views:` collection carries view CONTAINERS (`defineView`): `{ list, listViews }`, ' + + 'both slots optional. A container with neither set is schema-valid, the loader expands no ' + + 'view from it, and the Console renders nothing for it (no switcher entry). A view holds lists ' + + 'only: a form is its own item under the stack\'s `forms:` (`defineForm`), and a container ' + + 'that still holds a `form` or `formViews` slot is refused by the parse at that key, not ' + + 'reported here as empty.', 'A flat list-view object (`{ name, type, columns, data }` where the slots belong) and a ViewItem ' + 'record (`viewKind` with `config`) are single views, not containers. `ViewSchema` is strict, ' + 'so `defineStack` refuses either by name, and the registration loop refuses them too ' + diff --git a/packages/lint/src/rule-explanations/view-refs.ts b/packages/lint/src/rule-explanations/view-refs.ts index f8ca85911e3..4fcc2881fd5 100644 --- a/packages/lint/src/rule-explanations/view-refs.ts +++ b/packages/lint/src/rule-explanations/view-refs.ts @@ -32,10 +32,13 @@ export const VIEW_KEY_COLLISION_EXPLANATION: RuleExplanation = { rule: 'view-key-collision', covers: 'what a renamed view key does to its references', paragraphs: [ - 'List and form views share one `OBJECT.KEY` namespace when a view container is expanded. A ' + - 'colliding key is renamed — `OBJECT.KEY` becomes `OBJECT.KEY_2` — so the registry key stays ' + - 'unique, and every reference to the requested name resolves to the OTHER view: a ' + - '`type: \'form\'` action target and a navigation `viewName` alike.', + 'The list views of a view container share one `OBJECT.KEY` namespace when it is expanded, and ' + + 'the default `list` claims `OBJECT.default`. A colliding key is renamed — `OBJECT.KEY` becomes ' + + '`OBJECT.KEY_2` — so the registry key stays unique, and every reference to the requested name ' + + 'resolves to the OTHER view: a navigation `viewName`, or a `type: \'form\'` action target that ' + + 'names the list by mistake.', + 'A view holds lists only from protocol 19: a form is a `form` item under `forms:`, keyed by its ' + + 'own `name`, so no form takes part in this namespace and no rename here moves a form.', 'A warning, not an error: the rename alone breaks something only when the name is referenced, ' + 'and a reference that lands on the wrong kind of view is reported on its own, by ' + '`view-ref-form-target-kind` or `view-ref-nav-view-missing`.', diff --git a/packages/lint/src/runtime-gate.page-visibility-predicate-writes.test.ts b/packages/lint/src/runtime-gate.page-visibility-predicate-writes.test.ts index 435f390e1d5..a7293fd3630 100644 --- a/packages/lint/src/runtime-gate.page-visibility-predicate-writes.test.ts +++ b/packages/lint/src/runtime-gate.page-visibility-predicate-writes.test.ts @@ -17,7 +17,8 @@ * * Ruling of record 6161173492 on #23388 (letter B) moved the two page component * rules to this door on one principle: a page with a finding is fixed, then - * saved. The family follows it, so both entries declare `['view', 'page']`. + * saved. The family follows it, so both entries declare `page` beside the + * type a form is written as (`view` then; `form` from protocol 19, ADR-0159 D9). * No gate change: `page` already maps to `pages`, and the page snapshot holds * the item as `pages: [item]`. * @@ -204,38 +205,55 @@ describe('#24491 — the page door gives the build\'s visibility-predicate verdi expect(family(result.advisories)).toEqual(buildFindings(body)); }); - it('the `view` control: a view write is judged exactly as before', () => { - // `validateStackExpressions` joined for its bulk `confirmText` pass alone - // (#24798) — no visibility predicate is judged by it on a view write. + it('the `form` control: a form write is judged as a view write was before protocol 19', () => { + // [ADR-0159 D9] A view holds lists only, so the family left the `view` + // door with the forms it judged there and stands on the `form` door. + // `validateStackExpressions` joined the view door for its bulk + // `confirmText` pass alone (#24798) — no visibility predicate is judged by + // it on a view write. expect(runtimeAuthoringRulesFor('view').map((r) => r.name)).toEqual([ 'validateStackExpressions', 'validatePresetComparands', 'validateReferenceIntegrity', + ]); + const onForm = runtimeAuthoringRulesFor('form').map((r) => r.name); + expect(onForm).toEqual(expect.arrayContaining([ 'validateFormLayout', 'validatePublicFormFileFields', 'validateThankYouRecordFields', ...FAMILY, - ]); - const view = (visibleWhen: string, data?: unknown) => ({ - name: 'field_editor', + ])); + const form = (visibleWhen: string) => ({ + name: 'field.editor', + object: 'field', label: 'Field editor', - form: { - ...(data ? { data } : {}), - sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }], - }, + sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }], }); - const gateView = (item: unknown) => runRuntimeAuthoringRules({ type: 'view', item, context: { objects: [] } }); + const gateForm = (item: unknown) => runRuntimeAuthoringRules({ type: 'form', item, context: { objects: [] } }); - const fn = family(gateView(view('totallyBogusFn(1)')).errors); + const fn = family(gateForm(form('totallyBogusFn(1)')).errors); expect(fn.map((f) => [f.rule, f.path])).toEqual([ - [VISIBILITY_PREDICATE_UNKNOWN_FUNCTION, 'views[0].form.sections[0].fields[0]'], + [VISIBILITY_PREDICATE_UNKNOWN_FUNCTION, 'forms[0].sections[0].fields[0]'], ]); - // [#25281] The `has()` argument arm reaches the view door the same way. - expect(family(gateView(view('has(status)')).errors).map((f) => [f.rule, f.path])).toEqual([ - [VISIBILITY_PREDICATE_HAS_ARGUMENT, 'views[0].form.sections[0].fields[0]'], + // [#25281] The `has()` argument arm reaches the form door the same way. + expect(family(gateForm(form('has(status)')).errors).map((f) => [f.rule, f.path])).toEqual([ + [VISIBILITY_PREDICATE_HAS_ARGUMENT, 'forms[0].sections[0].fields[0]'], ]); - // The path half is live on the view surface it was built for. - const path = family(gateView(view("data.tpye == 'text'", { provider: 'schema', schemaId: 'field' })).errors); - expect(path.map((f) => f.rule)).toContain(PREDICATE_PATH_UNRESOLVED); + // The path half is declared on the form door with its sibling and judges + // nothing there: its oracle is a schema-bound form's `schemaId`, and a + // form item binds an object, never a schema. The same wrong path on a form + // is the visibility rule's verdict, as it is on a page. + const wrongPath = gateForm(form("data.tpye == 'text'")); + expect(wrongPath.rulesRun).toContain('validatePredicatePathRefs'); + expect(family(wrongPath.errors).map((f) => f.rule)).not.toContain(PREDICATE_PATH_UNRESOLVED); + expect(family(wrongPath.advisories).map((f) => f.rule)).toEqual([VISIBILITY_ROOT_MISLAYERED]); + // A view write carrying the same predicate where protocol 18 held a form + // draws nothing from the family: the parse refuses the slot at its own key. + const onView = runRuntimeAuthoringRules({ + type: 'view', + item: { name: 'field_editor', form: { sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen: 'totallyBogusFn(1)' }] }] } }, + context: { objects: [] }, + }); + expect(family([...onView.errors, ...onView.advisories])).toEqual([]); }); }); diff --git a/packages/lint/src/runtime-gate.test.ts b/packages/lint/src/runtime-gate.test.ts index d651f0995ae..92ce124103b 100644 --- a/packages/lint/src/runtime-gate.test.ts +++ b/packages/lint/src/runtime-gate.test.ts @@ -316,70 +316,123 @@ describe('runtime publish gate (#4463)', () => { // unresolvable predicate PATH while a predicate that does not parse at all walks // through — is exactly what #7214's implementer built, measured and reverted. -/** A plain runtime view: `record` / `current_user` are the bound roots. */ -const runtimeView = (visibleWhen: string) => ({ - name: 'account_form', +// +// [ADR-0159 D9] From protocol 19 a form is its own metadata type, so the body +// such an author saves is a `form` item and the family stands on the `form` +// door. A view holds lists only: a `view` write reaches none of the family. + +/** A plain runtime form item: `record` / `current_user` are the bound roots. */ +const runtimeForm = (visibleWhen: string) => ({ + name: 'account.intake', label: 'Account', object: 'account', - form: { sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }] }, + sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }], }); /** - * A schema-bound metadata FORM published as a view — `data` is the bound root. + * A schema-bound metadata FORM — `data` is the bound root. * `validatePredicatePathRefs` judges only this shape (`#7010`: the `record.*` * layer's addressable path set is not closed), so the family's path half needs * it to be non-vacuous. + * + * [ADR-0159 D7] No write carries one from protocol 19. Under 18 it was + * published as a view, in the container's `form` slot; that slot is refused by + * the parse, and a `form` item binds an object by `object` and declares no + * `data`. The shape that still carries one is the entry itself, in a source + * the check commands read, so the family's verdicts on it are pinned through + * `checkSchemaBound` below, and the door's silence on it is pinned beside them. */ const schemaBoundForm = (visibleWhen: string) => ({ name: 'field_editor', label: 'Field editor', - form: { - data: { provider: 'schema', schemaId: 'field' }, - sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }], - }, + data: { provider: 'schema', schemaId: 'field' }, + sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }], }); /** A predicate that is flawless CEL and overruns `DEFAULT_LIMITS.maxAstNodes`. */ const overBudget = Array.from({ length: 120 }, (_, i) => `record.name == 'n${i}'`).join(' || '); +const gateForm = (item: unknown) => + runRuntimeAuthoringRules({ type: 'form', item, context: { objects: [] } }); + const gateView = (item: unknown) => runRuntimeAuthoringRules({ type: 'view', item, context: { objects: [] } }); +/** + * The family's verdict on a schema-bound form: the two rule functions over the + * stack that carries it, split the way the gate splits a result. This is the + * reading `os validate` / `os build` / `os lint` reach. + */ +const checkSchemaBound = (item: unknown) => { + const stack = { views: [item] }; + const findings: AuthoringFinding[] = [...validateVisibilityPredicates(stack), ...validatePredicatePathRefs(stack)]; + return { + errors: findings.filter((f) => f.severity === 'error'), + advisories: findings.filter((f) => f.severity !== 'error'), + }; +}; + describe('the views[] visibility-predicate family at the runtime publish gate (#7220)', () => { - it('dispatches `view` writes to both family rules, from the shared table', () => { + it('dispatches `form` writes to both family rules, from the shared table', () => { + expect(runtimeGatedTypes()).toContain('form'); + expect(stackKeyForType('form')).toBe('forms'); + expect(runtimeAuthoringRulesFor('form').map((r) => r.name)).toEqual([ + // #29309 — a form section naming an unknown field or field group; + // advisory, against the same `objects` context. + 'validateFormLayout', + // #25650 — a form open to anonymous intake declaring a file field; + // the snapshot's `objects` context carries the field types it reads. + 'validatePublicFormFileFields', + // #28005 — a thank-you panel naming a field the engine does not + // generate; the same `objects` context carries the types it reads. + 'validateThankYouRecordFields', + 'validateVisibilityPredicates', + 'validatePredicatePathRefs', + ]); + // A view holds lists only, so a `view` write keeps the list rules alone. expect(runtimeGatedTypes()).toContain('view'); expect(stackKeyForType('view')).toBe('views'); expect(runtimeAuthoringRulesFor('view').map((r) => r.name)).toEqual([ // #24798 — the expression rule runs ONE pass on a view write: the bulk // `confirmText` template slots, errors since #25205. 'validateStackExpressions', - // #8793 — filter comparands, not predicates; registered ahead of the - // family and dispatched for `view` because list-view filter rules are - // one of the three shapes it judges. + // #8793 — filter comparands, not predicates; dispatched for `view` + // because list-view filter rules are one of the three shapes it judges. 'validatePresetComparands', // #9313 — the reference-integrity suite's entry dispatches for `view`; // the suite then runs only its two list-view field members // (`validateSearchableFields` / `validateSortableFields`) on the // per-write snapshot — see `runtime-gate.view-writes.test.ts`. 'validateReferenceIntegrity', - // #29309 — a form section naming an unknown field or field group; - // advisory, against the same `objects` context. - 'validateFormLayout', - // #25650 — a form open to anonymous intake declaring a file field; - // the snapshot's `objects` context carries the field types it reads. - 'validatePublicFormFileFields', - // #28005 — a thank-you panel naming a field the engine does not - // generate; the same `objects` context carries the types it reads. - 'validateThankYouRecordFields', - 'validateVisibilityPredicates', - 'validatePredicatePathRefs', ]); }); + it('no write carries a schema-bound form from protocol 19: neither door draws a family verdict for one', () => { + // The path half's whole population at the door was the schema-bound form a + // `view` write held. Each input below draws a family verdict from the check + // commands (the `checkSchemaBound` cases in this file) and none from either + // write door: on a `view` write the family does not run, and on a `form` + // write the item is a form bound to an object, which names no schema. + for (const predicate of ["data.tpye == 'text'", "type == 'text'", 'data.type == data.label', 'data.type == active']) { + const family = (fs: readonly AuthoringFinding[]) => + fs.filter((f) => f.rule.startsWith('predicate-')); + const asView = gateView(schemaBoundForm(predicate)); + expect(family([...asView.errors, ...asView.advisories]), predicate).toEqual([]); + expect(asView.rulesRun).not.toContain('validatePredicatePathRefs'); + const { data: _data, ...body } = schemaBoundForm(predicate); + const asForm = gateForm({ ...body, name: 'field.editor', object: 'field' }); + expect(asForm.rulesRun).toContain('validatePredicatePathRefs'); + expect(family([...asForm.errors, ...asForm.advisories]), predicate).toEqual([]); + // Lit control: the same predicate is a family verdict where a source carries the form. + const checked = checkSchemaBound(schemaBoundForm(predicate)); + expect(family([...checked.errors, ...checked.advisories]).length, predicate).toBeGreaterThan(0); + } + }); + // ── fires: the four defects the card names, at the door they bypassed ── it('REFUSES a predicate that does not parse as CEL', () => { - const { errors } = gateView(runtimeView("record.status === 'open'")); + const { errors } = gateForm(runtimeForm("record.status === 'open'")); const f = errors.find((e) => e.rule === 'visibility-predicate-syntax'); expect( f, @@ -390,23 +443,23 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // `err.issues` verbatim, so a finding without them is a refusal an author // cannot act on. expect(f!.severity).toBe('error'); - expect(f!.path).toBe('views[0].form.sections[0].fields[0]'); + expect(f!.path).toBe('forms[0].sections[0].fields[0]'); expect(f!.where.length).toBeGreaterThan(0); expect(f!.message).toMatch(/not valid CEL/); expect(f!.hint).toMatch(/==/); }); it('REFUSES a bare identifier no binding root resolves', () => { - const { errors } = gateView(runtimeView("status == 'open'")); + const { errors } = gateForm(runtimeForm("status == 'open'")); const f = errors.find((e) => e.rule === 'visibility-bare-identifier'); expect(f, '`status` instead of `record.status` resolves nowhere on any layer').toBeDefined(); expect(f!.severity).toBe('error'); - expect(f!.path).toBe('views[0].form.sections[0].fields[0]'); + expect(f!.path).toBe('forms[0].sections[0].fields[0]'); expect(f!.hint).toMatch(/record\.status/); }); it('REFUSES a predicate that overruns the CEL parse budget', () => { - const { errors } = gateView(runtimeView(overBudget)); + const { errors } = gateForm(runtimeForm(overBudget)); const f = errors.find((e) => e.rule === 'visibility-predicate-over-budget'); expect(f, 'same refusal as a syntax fault, different edit (#7217)').toBeDefined(); expect(f!.severity).toBe('error'); @@ -424,11 +477,11 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // registered receiver method now. `canApprove` carries the same shape and is // still invented; the case below is the other half, and the two together are // what says the gate narrowed by exactly one name. - const { errors } = gateView(runtimeView('current_user.canApprove(object, verb)')); + const { errors } = gateForm(runtimeForm('current_user.canApprove(object, verb)')); const f = errors.find((e) => e.rule === 'visibility-predicate-unknown-function'); expect(f, 'the publish door must refuse an unresolvable call, not just the validator').toBeDefined(); expect(f!.severity).toBe('error'); - expect(f!.path).toBe('views[0].form.sections[0].fields[0]'); + expect(f!.path).toBe('forms[0].sections[0].fields[0]'); expect(f!.message).toMatch(/`canApprove`/); expect(f!.message).toMatch(/found no matching overload/); }); @@ -440,31 +493,31 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // that accepted it while nothing could evaluate it was the defect. Both ends // moved together — `@objectstack/formula` registers `can` receiver-only and // answers it from `EvalContext.permissions`. - const { errors } = gateView(runtimeView('current_user.can(object, verb)')); + const { errors } = gateForm(runtimeForm('current_user.can(object, verb)')); expect(errors.map((e) => e.rule)).not.toContain('visibility-predicate-unknown-function'); }); it('ACCEPTS a predicate whose functions all resolve — the control for the arm above', () => { // Same door, same shape, a registered function. Without this the test above // would still pass if the arm had started refusing every call. - const { errors } = gateView(runtimeView("upper(record.name) == 'X'")); + const { errors } = gateForm(runtimeForm("upper(record.name) == 'X'")); expect(errors.map((e) => e.rule)).not.toContain('visibility-predicate-unknown-function'); }); it('REFUSES a predicate path the target schema does not declare', () => { - const { errors } = gateView(schemaBoundForm("data.tpye == 'text'")); + const { errors } = checkSchemaBound(schemaBoundForm("data.tpye == 'text'")); const f = errors.find((e) => e.rule === 'predicate-path-unresolved'); expect( f, 'this is the rule whose SOLO wiring #7214 reverted — it is here because its siblings are', ).toBeDefined(); expect(f!.severity).toBe('error'); - expect(f!.path).toBe('views[0].form.sections[0].fields[0].visibleWhen'); + expect(f!.path).toBe('views[0].sections[0].fields[0].visibleWhen'); expect(f!.message).toMatch(/data\.tpye/); }); it('REFUSES a schema key written without its binding root', () => { - const { errors } = gateView(schemaBoundForm("type == 'text'")); + const { errors } = checkSchemaBound(schemaBoundForm("type == 'text'")); expect(errors.map((e) => e.rule)).toContain('predicate-path-unrooted'); }); @@ -474,7 +527,7 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // silent here BY CONSTRUCTION. The renderer resolves only the left side and // parses the right as a literal, so this compares against the string // "data.label" and is false on every row. - const { errors } = gateView(schemaBoundForm('data.type == data.label')); + const { errors } = checkSchemaBound(schemaBoundForm('data.type == data.label')); const f = errors.find((e) => e.rule === 'predicate-rhs-path-shaped'); expect(f, 'the right-hand position never evaluates a path').toBeDefined(); expect(f!.severity).toBe('error'); @@ -496,7 +549,7 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // asked for is a path on the RIGHT, which this same gate refuses at `error` // (the test below measures it). So the root-prescribing rules stand down // for this position and the advisory carries both readings. - const result = gateView(schemaBoundForm('data.type == active')); + const result = checkSchemaBound(schemaBoundForm('data.type == active')); const f = result.advisories.find((a) => a.rule === 'predicate-rhs-path-shaped'); expect(f, 'the subset boundary must still reach the author').toBeDefined(); expect(f!.severity).toBe('warning'); @@ -518,7 +571,7 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // author to root the word in place; both rootings of that exact predicate // are a dotted chain on the RIGHT, and the gate refuses them at `error`. for (const root of ['data', 'record']) { - const { errors } = gateView(schemaBoundForm(`data.type == ${root}.active`)); + const { errors } = checkSchemaBound(schemaBoundForm(`data.type == ${root}.active`)); expect( errors.map((e) => e.rule), `\`== ${root}.active\` is the spelling the old error asked for`, @@ -531,15 +584,15 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // stand-down is per-IDENTIFIER and per-SURFACE, so three neighbours of the // reconciled case keep their refusal unchanged. expect( - gateView(schemaBoundForm('status == active')).errors.map((e) => e.rule), + checkSchemaBound(schemaBoundForm('status == active')).errors.map((e) => e.rule), 'a bare word on the LEFT is a genuine dropped root, whatever sits on the right', ).toContain('visibility-bare-identifier'); expect( - gateView(schemaBoundForm('data.name == active && active')).errors.map((e) => e.rule), + checkSchemaBound(schemaBoundForm('data.name == active && active')).errors.map((e) => e.rule), 'the word also occurs outside a right-hand slot — not a literal position', ).toContain('visibility-bare-identifier'); expect( - gateView(runtimeView('record.status == active')).errors.map((e) => e.rule), + gateForm(runtimeForm('record.status == active')).errors.map((e) => e.rule), 'a runtime surface goes to real CEL, where a path on the right is legal and a bare word ' + 'there really is a dropped root — nothing about it was reconciled', ).toContain('visibility-bare-identifier'); @@ -553,7 +606,7 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // this gate exists for can actually read it. That channel landing is why // this move was allowed to happen at all rather than running rules and // discarding their verdicts (#4463's own shape, one notch quieter). - const result = gateView(runtimeView("data.status == 'open'")); + const result = gateForm(runtimeForm("data.status == 'open'")); expect(result.errors).toEqual([]); const f = result.advisories.find((a) => a.rule === 'visibility-root-mislayered'); expect(f, 'a wrong-layer paste must still reach the author').toBeDefined(); @@ -562,15 +615,12 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // ── stays quiet ─────────────────────────────────────────────────────── - it('a valid view still publishes, with the rules having RUN', () => { - const result = gateView(runtimeView("record.status == 'open'")); + it('a valid form still publishes, with the rules having RUN', () => { + const result = gateForm(runtimeForm("record.status == 'open'")); expect(result.errors, JSON.stringify(result.errors)).toEqual([]); expect(result.advisories, JSON.stringify(result.advisories)).toEqual([]); // "clean" and "nothing ran" must stay distinguishable. expect(result.rulesRun).toEqual([ - 'validateStackExpressions', // #24798 — its bulk `confirmText` pass alone, clean here - 'validatePresetComparands', // #8793 — dispatched for `view`, clean here - 'validateReferenceIntegrity', // #9313 — its two list-view field members, clean here 'validateFormLayout', // #29309 — a form's field and group references, clean here 'validatePublicFormFileFields', // #25650 — a public form's file fields, clean here 'validateThankYouRecordFields', // #28005 — a thank-you panel's named fields, clean here @@ -579,12 +629,12 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# ]); }); - it('does not blame a `view` write for a pre-existing violation elsewhere', () => { + it('does not blame a `form` write for a pre-existing violation elsewhere', () => { // The D4 subtraction, on the newly gated type: a stored object carrying a // broken predicate is not this write's to answer for. const result = runRuntimeAuthoringRules({ - type: 'view', - item: runtimeView("record.status == 'open'"), + type: 'form', + item: runtimeForm("record.status == 'open'"), context: { objects: [ { name: 'account', fields: { name: { type: 'text', visibleWhen: 'broken ===' } } }, @@ -606,16 +656,19 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // // Asserted by set equality, not by "both are non-empty": a half-wired wall // is precisely the state where both sides are non-empty and disagree. + // + // [ADR-0159 D9] The corpus is every family input a write can carry: a + // form item's predicates. The schema-bound half left the door with the + // shape that held it (the case above pins that both doors are silent on + // it), so it is no input on which the door and the build can disagree. const corpus = [ - runtimeView("record.status === 'open'"), // syntax - runtimeView("status == 'open'"), // bare identifier - runtimeView("data.status == 'open'"), // mislayered root - runtimeView(overBudget), // over budget - runtimeView("record.status == 'open'"), // clean - schemaBoundForm("data.tpye == 'text'"), // unresolvable path - schemaBoundForm("type == 'text'"), // unrooted schema key - schemaBoundForm("data.type == 'text'"), // resolvable path - schemaBoundForm('data.type == active'), // bare word on the RIGHT (#7696) + runtimeForm("record.status === 'open'"), // syntax + runtimeForm("status == 'open'"), // bare identifier + runtimeForm("data.status == 'open'"), // mislayered root + runtimeForm(overBudget), // over budget + runtimeForm("record.status == 'open'"), // clean + runtimeForm('current_user.canApprove(object, verb)'), // unregistered function + runtimeForm('record.status == active'), // bare word on the RIGHT, runtime surface ]; const fingerprints = (fs: readonly AuthoringFinding[]) => @@ -625,11 +678,11 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# let sawAdvisory = false; for (const item of corpus) { - const gate = gateView(item); + const gate = gateForm(item); sawError ||= gate.errors.length > 0; sawAdvisory ||= gate.advisories.length > 0; - const stack = { views: [item] }; + const stack = { forms: [item] }; const cli = [...validateVisibilityPredicates(stack), ...validatePredicatePathRefs(stack)]; expect( @@ -653,6 +706,10 @@ describe('the views[] visibility-predicate family at the runtime publish gate (# // above (#7576 serialization): nothing in that suite is touched. // ───────────────────────────────────────────────────────────────────── +// [ADR-0159 D7] The schema-bound form left the publish gate with the view slot +// that held it; these cases hold the same layer derivation where it is still +// reached, the check commands' reading of a source that carries the form +// (`checkSchemaBound`). The runtime control beside them stays on the gate. describe('the publish gate judges a schema-bound form at its own layer (#7815)', () => { it('a correctly `data.`-rooted form is SILENT — no advisory, no refusal', () => { // The finding. `authoring-rules.ts` calls `validateVisibilityPredicates(stack)` @@ -661,30 +718,25 @@ describe('the publish gate judges a schema-bound form at its own layer (#7815)', // its author to write `record.`, on a surface that binds no `record` at all. // Nothing went red then and nothing goes red now; the difference is only // what the author is told, which is the whole harm of the class. - const result = gateView(schemaBoundForm("data.type == 'text'")); + const result = checkSchemaBound(schemaBoundForm("data.type == 'text'")); expect(result.errors, JSON.stringify(result.errors)).toEqual([]); expect(result.advisories, JSON.stringify(result.advisories)).toEqual([]); - // "clean" and "nothing ran" must stay distinguishable. - expect(result.rulesRun).toEqual([ - 'validateStackExpressions', // #24798 — its bulk `confirmText` pass alone, clean here - 'validatePresetComparands', // #8793 — dispatched for `view`, clean here - 'validateReferenceIntegrity', // #9313 — its two list-view field members, clean here - 'validateFormLayout', // #29309 — a form's field and group references, clean here - 'validatePublicFormFileFields', // #25650 — a public form's file fields, clean here - 'validateThankYouRecordFields', // #28005 — a thank-you panel's named fields, clean here - 'validateVisibilityPredicates', - 'validatePredicatePathRefs', - ]); + // "clean" and "nothing ran" must stay distinguishable: the same site, one + // letter off, is a verdict of each family member. + expect(checkSchemaBound(schemaBoundForm("data.tpye == 'text'")).errors.map((e) => e.rule)) + .toEqual(['predicate-path-unresolved']); + expect(checkSchemaBound(schemaBoundForm("record.type == 'text'")).advisories.map((a) => a.rule)) + .toEqual(['visibility-root-mislayered']); }); - it('the runtime view one fixture-line away still draws it — the rule is live', () => { + it('the runtime form one fixture-line away still draws it — the rule is live', () => { // The negative control. Standing an advisory down and going blind look // identical from the inside, so the case above is only worth its ink beside // one that still fires: same predicate root, same gate, opposite verdict, // decided by the `data:` source alone. - const f = gateView(runtimeView("data.status == 'open'")) + const f = gateForm(runtimeForm("data.status == 'open'")) .advisories.find((a) => a.rule === 'visibility-root-mislayered'); - expect(f, 'a wrong-layer paste on a RUNTIME view is still a wrong-layer paste').toBeDefined(); + expect(f, 'a wrong-layer paste on a RUNTIME form is still a wrong-layer paste').toBeDefined(); expect(f!.severity).toBe('warning'); }); @@ -693,7 +745,7 @@ describe('the publish gate judges a schema-bound form at its own layer (#7815)', // `'runtime'`, the rule forbids `data.` and has nothing to say about // `record.`, so a form predicate that can never match published in silence. // Not new behaviour — the rule's existing metadata arm, finally addressed. - const result = gateView(schemaBoundForm("record.type == 'text'")); + const result = checkSchemaBound(schemaBoundForm("record.type == 'text'")); expect(result.errors, 'still advisory-only: acceptance is untouched').toEqual([]); const f = result.advisories.find((a) => a.rule === 'visibility-root-mislayered'); expect(f, 'a predicate that never matches must reach the author').toBeDefined(); @@ -707,7 +759,7 @@ describe('the publish gate judges a schema-bound form at its own layer (#7815)', // on this surface — the one that BLOCKS the publish — told the author to // write `record.status` on a form that binds `data`. Same id, same // severity, same input: only the prescription moved. - const f = gateView(schemaBoundForm('status == active')) + const f = checkSchemaBound(schemaBoundForm('status == active')) .errors.find((e) => e.rule === 'visibility-bare-identifier'); expect(f, 'a bare word on the LEFT is still refused').toBeDefined(); expect(f!.severity).toBe('error'); @@ -736,7 +788,7 @@ describe('the publish gate judges a schema-bound form at its own layer (#7815)', ]; for (const [predicate, expected] of cases) { expect( - gateView(schemaBoundForm(predicate)).errors.map((e) => e.rule).sort(), + checkSchemaBound(schemaBoundForm(predicate)).errors.map((e) => e.rule).sort(), `the refusal set for \`${predicate}\` changed — the #7815 layer derivation is ` + `advisory-only by construction, so anything moving here is a scope breach`, ).toEqual([...expected].sort()); diff --git a/packages/lint/src/runtime-gate.view-writes.test.ts b/packages/lint/src/runtime-gate.view-writes.test.ts index 094936135e6..5da6e4d1d27 100644 --- a/packages/lint/src/runtime-gate.view-writes.test.ts +++ b/packages/lint/src/runtime-gate.view-writes.test.ts @@ -26,6 +26,7 @@ import { describe, it, expect } from 'vitest'; import { runRuntimeAuthoringRules } from './runtime-gate.js'; +import { ViewItemWireSchema } from '@objectstack/spec/ui'; import { REFERENCE_INTEGRITY_RULES } from './reference-integrity-suite.js'; import { SORT_FIELD_UNKNOWN, SORT_FIELD_UNSORTABLE } from './validate-sortable-fields.js'; import { SEARCHABLE_FIELD_UNKNOWN } from './validate-searchable-fields.js'; @@ -361,12 +362,34 @@ describe('a flattened list overlay at the runtime publish gate (#9313)', () => { // wire union's own arms: a `form` record carries `FormViewSchema` config, // which has no `sort` / `searchableFields` — a stray one riding in the // stored body must not be judged by a list-view rule. - const { errors } = gate({ + // + // [ADR-0159 D7] Protocol 19 refuses `viewKind: 'form'` on a `view` write + // at parse, the prescription naming `forms:`: the form is written as a + // `form` item, which no list-view rule judges. The 18 record, refused at + // the door, is still not judged when a stored row hands it over unparsed. + const form = runRuntimeAuthoringRules({ + type: 'form', + item: { + name: 'crm_case.edit', + object: 'crm_case', + type: 'simple', + sections: [{ name: 'main', label: 'Main', fields: ['name'] }], + sort: [{ field: 'amout', order: 'desc' }], + }, + context: { objects }, + }); + expect(form.errors, JSON.stringify(form.errors)).toEqual([]); + + const record = { name: 'crm_case.edit', object: 'crm_case', viewKind: 'form', config: { type: 'simple', fields: ['name'], sort: [{ field: 'amout', order: 'desc' }] }, - }); + }; + const parsed = ViewItemWireSchema.safeParse(record); + expect(parsed.success).toBe(false); + expect(parsed.error?.issues.map((issue) => issue.message).join('\n')).toContain('forms:'); + const { errors } = gate(record); expect(errors, JSON.stringify(errors)).toEqual([]); }); diff --git a/packages/lint/src/showcase-shape.fixtures.ts b/packages/lint/src/showcase-shape.fixtures.ts index 4fa831a57e9..a0722eca23f 100644 --- a/packages/lint/src/showcase-shape.fixtures.ts +++ b/packages/lint/src/showcase-shape.fixtures.ts @@ -81,13 +81,22 @@ * — which sections carry a `name` — is untouched, and no finding depends on a * form's `type`. * + * A second one, for the same reason: protocol 19 made a form its own metadata + * item and a view lists only (ADR-0159), so a container that holds a `form` or + * `formViews` slot stopped parsing. Each form is lifted out of its container + * as a `defineForm` item named `OBJECT.KEY` (the name it was served under), + * body verbatim but for its `data` binding, which the item states as `object`, + * as the major's own source conversion moves it. The specimen + * is untouched again: the same sections carry a `name`, and the same three do + * not. + * * Nothing else failed to survive the lift. `Field.lookup('showcase_account')` on * the contact object still points at an object this stack does not declare — * that is unchanged from the live-import tests, which composed the same partial * stack (`objects: [Contact]`), and no assertion here reads it. */ -import { defineView, P } from '@objectstack/spec'; +import { defineForm, defineView, P } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; const taskData = { provider: 'object' as const, object: 'showcase_task' }; @@ -97,12 +106,13 @@ const taskData = { provider: 'object' as const, object: 'showcase_task' }; * * The container names itself nowhere — it binds through `list.data.object`, which * is the rung that attaches every finding below to `showcase_task` and the reason - * their `where` lines carry no `view "…"` part. Its five form views are the - * specimen: `tabbed` / `wizard` / `split` name every section they declare, while - * `edit` ("Task") and `quick` ("Quick Edit") name none. The thirteen `listViews` - * are carried in full precisely because they declare NO sections — an exhaustive - * assertion over this container's findings is only exhaustive if the list layer - * that must stay silent is really present. + * their `where` lines carry no `view "…"` part. Its five forms + * ({@link SnapshotTaskForms}) are the specimen: `tabbed` / `wizard` / `split` + * name every section they declare, while `edit` ("Task") and `quick` + * ("Quick Edit") name none. The thirteen `listViews` are carried in full + * precisely because they declare NO sections — an exhaustive assertion over + * this stack's findings is only exhaustive if the list layer that must stay + * silent is really present. */ export const SnapshotTaskViews = defineView({ list: { @@ -288,68 +298,79 @@ export const SnapshotTaskViews = defineView({ }, }, }, +}); - formViews: { - // ⛔ SPECIMEN — `edit`'s single section declares a label and NO `name`. - edit: { - type: 'simple', - data: taskData, - sections: [ - { - label: 'Task', - columns: 2, - fields: [ - { field: 'title', required: true }, - { field: 'project', required: true }, - { field: 'assignee' }, - { field: 'status', required: true }, - { field: 'priority' }, - { field: 'due_date' }, - { field: 'notes', visibleWhen: P`record.priority == 'urgent'`, span: 'full' }, - ], - }, - ], - }, +/** + * The five forms of the shipped task container, each a `form` item (ADR-0159: + * from protocol 19 a form is its own item, served under `OBJECT.KEY`, and a view + * holds lists only). Their bodies are the snapshot's, verbatim; the key each + * sat under in the container is the last segment of its name. + */ +export const SnapshotTaskForms = [ + // ⛔ SPECIMEN — `edit`'s single section declares a label and NO `name`. + defineForm({ + name: 'showcase_task.edit', + object: 'showcase_task', + type: 'simple', + sections: [ + { + label: 'Task', + columns: 2, + fields: [ + { field: 'title', required: true }, + { field: 'project', required: true }, + { field: 'assignee' }, + { field: 'status', required: true }, + { field: 'priority' }, + { field: 'due_date' }, + { field: 'notes', visibleWhen: P`record.priority == 'urgent'`, span: 'full' }, + ], + }, + ], + }), - // The named siblings — the contrast that makes the two specimens legible: - // one container, the same author, some sections addressable and some not. - tabbed: { - type: 'tabbed', - data: taskData, - sections: [ - { name: 'overview', label: 'Overview', columns: 2, fields: ['title', 'project', 'assignee', 'status'] }, - { name: 'schedule', label: 'Schedule', columns: 2, fields: ['start_date', 'end_date', 'due_date', 'progress'] }, - { name: 'details', label: 'Details', columns: 1, fields: ['estimate_hours', 'labels', 'location', 'notes'] }, - ], - }, + // The named siblings — the contrast that makes the two specimens legible: + // one container, the same author, some sections addressable and some not. + defineForm({ + name: 'showcase_task.tabbed', + object: 'showcase_task', + type: 'tabbed', + sections: [ + { name: 'overview', label: 'Overview', columns: 2, fields: ['title', 'project', 'assignee', 'status'] }, + { name: 'schedule', label: 'Schedule', columns: 2, fields: ['start_date', 'end_date', 'due_date', 'progress'] }, + { name: 'details', label: 'Details', columns: 1, fields: ['estimate_hours', 'labels', 'location', 'notes'] }, + ], + }), - wizard: { - type: 'wizard', - data: taskData, - sections: [ - { name: 'step_basics', label: 'Basics', columns: 1, fields: ['title', 'project'] }, - { name: 'step_assign', label: 'Assignment', columns: 1, fields: ['assignee', 'priority'] }, - { name: 'step_schedule', label: 'Schedule', columns: 2, fields: ['start_date', 'end_date', 'due_date'] }, - ], - }, + defineForm({ + name: 'showcase_task.wizard', + object: 'showcase_task', + type: 'wizard', + sections: [ + { name: 'step_basics', label: 'Basics', columns: 1, fields: ['title', 'project'] }, + { name: 'step_assign', label: 'Assignment', columns: 1, fields: ['assignee', 'priority'] }, + { name: 'step_schedule', label: 'Schedule', columns: 2, fields: ['start_date', 'end_date', 'due_date'] }, + ], + }), - split: { - type: 'tabbed', - data: taskData, - sections: [ - { name: 'split_task', label: 'Task', columns: 1, fields: ['title', 'status', 'assignee'] }, - { name: 'split_schedule', label: 'Schedule', columns: 1, fields: ['start_date', 'due_date', 'progress'] }, - ], - }, + defineForm({ + name: 'showcase_task.split', + object: 'showcase_task', + type: 'tabbed', + sections: [ + { name: 'split_task', label: 'Task', columns: 1, fields: ['title', 'status', 'assignee'] }, + { name: 'split_schedule', label: 'Schedule', columns: 1, fields: ['start_date', 'due_date', 'progress'] }, + ], + }), - // ⛔ SPECIMEN — `quick`'s single section declares a label and NO `name`. - quick: { - type: 'simple', - data: taskData, - sections: [{ label: 'Quick Edit', columns: 1, fields: ['status', 'priority', 'progress'] }], - }, - }, -}); + // ⛔ SPECIMEN — `quick`'s single section declares a label and NO `name`. + defineForm({ + name: 'showcase_task.quick', + object: 'showcase_task', + type: 'simple', + sections: [{ label: 'Quick Edit', columns: 1, fields: ['status', 'priority', 'progress'] }], + }), +]; const contactData = { provider: 'object' as const, object: 'showcase_contact' }; @@ -400,11 +421,11 @@ export const SnapshotContact = ObjectSchema.create({ /** * Snapshot of `examples/app-showcase/src/ui/views/contact.view.ts`. * - * The contrast this container carries in ONE file is the reason it was pinned: - * the default `form` names all four of its sections (addressable, translatable, - * and accepted by `validateTranslationReferences`), while the sparse - * `formViews.create` override names none. One rule has to be silent about the - * first and loud about the second. + * The contrast its forms ({@link SnapshotContactForms}) carry in ONE file is + * the reason it was pinned: the default form names all four of its sections + * (addressable, translatable, and accepted by `validateTranslationReferences`), + * while the sparse `create` form names none. One rule has to be silent about + * the first and loud about the second. */ export const SnapshotContactViews = defineView({ list: { @@ -419,35 +440,41 @@ export const SnapshotContactViews = defineView({ ], addRecord: { enabled: true }, }, +}); - form: { +/** + * The two forms of the shipped contact container, each a `form` item: the + * default form (served as `showcase_contact.form`), whose four sections are + * all named, and the sparse `create` form, whose one section is not. + */ +export const SnapshotContactForms = [ + defineForm({ + name: 'showcase_contact.form', + object: 'showcase_contact', type: 'simple', - data: contactData, sections: [ { name: 'contact', label: 'Contact', columns: 2, fields: ['name', 'email', 'phone'] }, { name: 'work', label: 'Work', columns: 2, fields: ['company', 'title', 'account'] }, { name: 'status', label: 'Status', columns: 2, fields: ['stage', 'lead_score'] }, { name: 'notes', label: 'Notes', columns: 1, fields: ['notes'] }, ], - }, - - formViews: { - // ⛔ SPECIMEN — `create`'s single section declares a label and NO `name`. - create: { - type: 'simple', - data: contactData, - title: 'New contact', - sections: [ - { - label: 'Who is this?', - columns: 1, - fields: ['name', 'email', 'phone', 'company'], - }, - ], - submitBehavior: { kind: 'thank-you', title: 'Contact created', message: 'You can fill in the rest on the record.' }, - }, - }, -}); + }), + // ⛔ SPECIMEN — `create`'s single section declares a label and NO `name`. + defineForm({ + name: 'showcase_contact.create', + object: 'showcase_contact', + type: 'simple', + title: 'New contact', + sections: [ + { + label: 'Who is this?', + columns: 1, + fields: ['name', 'email', 'phone', 'company'], + }, + ], + submitBehavior: { kind: 'thank-you', title: 'Contact created', message: 'You can fill in the rest on the record.' }, + }), +]; /** * Snapshot of the `showcase_task` and `showcase_contact` nodes of @@ -626,7 +653,7 @@ export const SnapshotTranslationBundle = { default: { label: '联系人' }, }, // The four NAMED headings of the default form — and nothing for - // `formViews.create`'s "Who is this?", which has no name to key on. + // the `create` form's "Who is this?", which has no name to key on. _sections: { contact: { label: '联系方式' }, work: { label: '工作信息' }, diff --git a/packages/lint/src/validate-field-consumers.test.ts b/packages/lint/src/validate-field-consumers.test.ts index c27e83a5926..4c7ffc3cbda 100644 --- a/packages/lint/src/validate-field-consumers.test.ts +++ b/packages/lint/src/validate-field-consumers.test.ts @@ -69,6 +69,26 @@ function placeInlineEdited(stack: AnyRec): AnyRec { }; } +/** + * [ADR-0159 D7] Protocol 19 refuses a form a view container holds (`form`, + * `formViews`) at parse: a form is its own `form` item under `forms:`, bound + * by `object`. The suites below keep the form bodies they always judged and + * lay each out as that item, the way the 19 conversion moves it: named + * `OBJECT.KEY` after the slot that held it (the default slot is `form`, as + * the parse's prescription names it), its `data` binding lifted to `object`. + */ +function formItems(object: string, slots: { form?: AnyRec; formViews?: Record } = {}): AnyRec { + const item = (key: string, body: AnyRec): AnyRec => { + const { data: _binding, ...rest } = body; + return { name: `${object}.${key}`, object, ...rest }; + }; + const forms = [ + ...(slots.form ? [item('form', slots.form)] : []), + ...Object.entries(slots.formViews ?? {}).map(([key, body]) => item(key, body)), + ]; + return forms.length > 0 ? { forms } : {}; +} + /** * The HotCRM shape, reduced: two objects sharing a field NAME (`tax_rate`), * consumed on one and merely carried on the other, plus one field of every @@ -370,8 +390,8 @@ describe('validateFieldConsumers (#15922)', () => { ...extra, }).map((f) => `${f.object}.${f.field}`); - it('a form section field on the view bound to the object', () => { - expect(one({ views: [{ object: 'o', form: { data: { object: 'o' }, sections: [{ fields: ['x'] }] } }, { list: { data: { object: 'other' }, columns: [{ field: 'x' }] } }] })).toEqual([]); + it('a form section field on the `form` item bound to the object', () => { + expect(one(formItems('o', { form: { data: { object: 'o' }, sections: [{ fields: ['x'] }] } }))).toEqual([]); }); it('a page component binding through the page object', () => { @@ -720,7 +740,7 @@ describe('[#20929] validateFieldConsumers — an inline grid column names a fiel const data = { provider: 'object', object: 'inv' }; const columns = [{ name: 'qty' }]; - const stack = (relationship: AnyRec, view: AnyRec = {}, extra: AnyRec = {}): AnyRec => placeInlineEdited({ + const stack = (relationship: AnyRec, slots: Parameters[1] = {}, extra: AnyRec = {}): AnyRec => placeInlineEdited({ objects: [ { name: 'inv', fields: { name: { type: 'text' }, qty: { type: 'number' } } }, { @@ -733,7 +753,8 @@ describe('[#20929] validateFieldConsumers — an inline grid column names a fiel }, }, ], - views: [{ list: { type: 'grid', data, columns: [{ field: 'name' }] }, ...view }], + views: [{ list: { type: 'grid', data, columns: [{ field: 'name' }] } }], + ...formItems('inv', slots), ...extra, }); @@ -752,12 +773,12 @@ describe('[#20929] validateFieldConsumers — an inline grid column names a fiel expect(verdicts(stack({ inlineEdit: 'grid', inlineColumns: columns }))).toEqual(CREDITED); }); - it("a form view's `subforms[].columns`: the child is the entry's `childObject`, not the view's object", () => { + it("a `form` item's `subforms[].columns`: the child is the entry's `childObject`, not the form's object", () => { const form = { type: 'simple', data, subforms: [{ childObject: 'line', columns }] }; expect(verdicts(stack({}, { form }))).toEqual(CREDITED); }); - it("each `formViews` entry's `subforms[].columns`, the same way", () => { + it("a `form` item under any other key (an 18 `formViews` entry), `subforms[].columns` the same way", () => { const edit = { type: 'simple', data, subforms: [{ childObject: 'line', columns }] }; expect(verdicts(stack({}, { formViews: { edit } }))).toEqual(CREDITED); }); @@ -828,12 +849,13 @@ describe('[#20951] validateFieldConsumers — a child collection credits its chi const data = { provider: 'object', object: 'inv' }; const MASTER_DETAIL = { type: 'master_detail', reference: 'inv' }; - const stack = (lineFields: AnyRec, view: AnyRec = {}, invoice: AnyRec = MASTER_DETAIL): AnyRec => placeInlineEdited({ + const stack = (lineFields: AnyRec, slots: Parameters[1] = {}, invoice: AnyRec = MASTER_DETAIL): AnyRec => placeInlineEdited({ objects: [ { name: 'inv', fields: { name: { type: 'text' }, total: { type: 'number' }, line_total: { type: 'number' } } }, { name: 'line', fields: { name: { type: 'text' }, invoice, ...lineFields } }, ], - views: [{ list: { type: 'grid', data, columns: [{ field: 'name' }] }, ...view }], + views: [{ list: { type: 'grid', data, columns: [{ field: 'name' }] } }], + ...formItems('inv', slots), }); /** `object.field` → verdict, for every field the rule reports. */ @@ -855,6 +877,15 @@ describe('[#20951] validateFieldConsumers — a child collection credits its chi }); }); + it('[ADR-0159 D7] the fixture is a `form` item the spec accepts, every child-collection key included', () => { + const laidOut = formItems('inv', { + form: { type: 'simple', data, subforms: [entry({ amountField: 'line_total', totalField: 'total', relationshipField: 'link' })] }, + }); + const [item] = laidOut.forms as AnyRec[]; + const parsed = FormSchema.safeParse(item); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + }); + it("`amountField` credits the CHILD's field, `totalField` the PARENT's — each same-named counterpart stays reported", () => { const form = { type: 'simple', data, subforms: [entry({ amountField: 'line_total', totalField: 'total' })] }; expect(verdicts(stack(lineFields, { form }))).toEqual({ @@ -864,7 +895,7 @@ describe('[#20951] validateFieldConsumers — a child collection credits its chi }); }); - it('each `formViews` entry, the same way', () => { + it('a `form` item under any other key (an 18 `formViews` entry), the same way', () => { const edit = { type: 'simple', data, subforms: [entry({ amountField: 'line_total', totalField: 'total' })] }; expect(verdicts(stack(lineFields, { formViews: { edit } }))).toEqual({ 'inv.line_total': 'inert', @@ -1103,7 +1134,8 @@ describe('[#21091] validateFieldConsumers — an inline collection reads its joi { name: 'ord', fields: { name: { type: 'text' }, notes: { type: 'textarea' } } }, { name: 'itm', fields: { ...ITEM_FIELDS, ord: relationship } }, ], - views: [{ list: { type: 'grid', data, columns: [{ field: 'name' }] }, ...(extra.form ? { form: extra.form } : {}) }], + views: [{ list: { type: 'grid', data, columns: [{ field: 'name' }] } }], + ...formItems('ord', { form: extra.form }), ...(extra.details ? { pages: [{ @@ -1717,9 +1749,9 @@ describe('[#32256] validateFieldConsumers — an inline grid reads its line-posi expect(reported(stack({ ...LOOKUP, inlineEdit: 'grid' }))).toEqual(['sort_order']); }); - it('a form view `subforms` entry reads it on its `childObject`', () => { + it('a `form` item `subforms` entry reads it on its `childObject`', () => { const entry = { childObject: 'lin', relationshipField: 'ord', columns: [{ name: 'qty' }] }; - const s = stack(LOOKUP, { views: [{ list: { type: 'grid', data, columns: [{ field: 'name' }] }, form: { type: 'simple', data, subforms: [entry] } }] }); + const s = stack(LOOKUP, formItems('ord', { form: { type: 'simple', data, subforms: [entry] } })); expect(reported(s)).toEqual(['sort_order']); }); diff --git a/packages/lint/src/validate-field-consumers.ts b/packages/lint/src/validate-field-consumers.ts index 1b501cfb161..60d6ff9b052 100644 --- a/packages/lint/src/validate-field-consumers.ts +++ b/packages/lint/src/validate-field-consumers.ts @@ -545,8 +545,8 @@ const WRITE_KEYS: ReadonlySet = new Set([ /** * [#20929] Keys whose array entries are INLINE CHILD COLLECTIONS: each entry * names its child object in `childObject` and the child's grid in `columns`. - * That is a form view's `subforms` (`FormViewSchema.subforms`, on a view - * container's `form` and on every `formViews` entry) and, since #20928, an + * That is a form's `subforms` (`FormViewSchema.subforms`, on a `forms:` + * item) and, since #20928, an * `object-master-detail-form` page block's `details` * (`ComponentPropsMap['object-master-detail-form']`). On both, `columns` is the * same `InlineGridColumnSchema` a relationship field's `inlineColumns` takes, diff --git a/packages/lint/src/validate-form-items.ts b/packages/lint/src/validate-form-items.ts index 9ee00efd5d9..cbf1311c657 100644 --- a/packages/lint/src/validate-form-items.ts +++ b/packages/lint/src/validate-form-items.ts @@ -13,15 +13,15 @@ * `sharing.publicLink` names it, switched on or off. A refusal on the new * type only: two old-shape forms on one slug keep today's first-match * behaviour, and a closed authored form is never refused. - * - `form-consumer-less` (advisory, D1; the successor of - * `form-view-internal-not-loaded` for `form` items): an authored `form` - * with no public link that no `type: 'form'` action targets steers + * - `form-consumer-less` (advisory, D1; it succeeds + * `form-view-internal-not-loaded`, retired with protocol 19): an authored + * `form` with no public link that no `type: 'form'` action targets steers * nothing. ⛔ Not raised for an item that declares `overrides`: an * override with no link over a base form that has a consumer is what keeps * that address closed, and a warning that it steers nothing would invite * its removal (the base is not in the stack, so its consumers cannot be * read here; the rule stays silent rather than guess). ⛔ No advisory for - * an old shape: `form-view-internal-not-loaded` stays the only one (D5). + * an old shape: the spec refuses one at the parse, with its prescription. * - `form-object-outside-closure` / `form-object-unknown` (gating, D2): a * `form`'s `object` judged where a list view's object is judged * (`validateListViewFieldRefs`): under a stated package closure, or diff --git a/packages/lint/src/validate-form-layout.test.ts b/packages/lint/src/validate-form-layout.test.ts index 73bff11663e..581742bb5eb 100644 --- a/packages/lint/src/validate-form-layout.test.ts +++ b/packages/lint/src/validate-form-layout.test.ts @@ -276,42 +276,61 @@ describe('#13855 — dangling `section.group` references', () => { }); // ─────────────────────────────────────────────────────────────────────────── -// #6251 — `views[]` is a view CONTAINER, and both rules above were unreachable -// on the shape real apps actually ship. +// #6251 — both rules above were unreachable on the shape real apps ship. // -// The measurement that opened the issue: one broken form, three placements. +// The measurement that opened the issue: one broken form, several placements. // Only the placement the strict schema REFUSES was being read, so an app whose -// forms all live under `form` / `formViews.` — i.e. every app — got a -// clean report from a rule that had read nothing at all. That is the ghost -// check #4984 / #5009 name: green because nothing was inspected. +// forms all lived where apps author them got a clean report from a rule that +// had read nothing at all. That is the ghost check #4984 / #5009 name: green +// because nothing was inspected. +// +// [ADR-0159 D9] From protocol 19 the place an app authors a form is a +// `forms[]` item, so that is the rung these cases stand on. A view container +// holds lists only: its retired `form` / `formViews` slots are no rung, and +// each case that used to stand on one now stands on the form item instead. // ─────────────────────────────────────────────────────────────────────────── -/** The one broken form, reused verbatim in every placement below. */ +/** The one broken form body, reused verbatim in every placement below. */ +const brokenSections = [{ columns: 2, fields: ['name', 'ghost_field'] }]; +/** The same body as a `views[]` entry that is a bare form view (raw source). */ const brokenForm = { data: { provider: 'object', object: 'contract' }, - sections: [{ columns: 2, fields: ['name', 'ghost_field'] }], + sections: brokenSections, }; +/** The same body as a `forms[]` item, bound by its own `object`. */ +const brokenFormItem = (key: string): AnyRec => ({ + name: `contract.${key}`, + object: 'contract', + sections: brokenSections, +}); -describe('#6251 — the view CONTAINER ladder', () => { - it('reports the SAME broken form in all three placements', () => { - const at = (view: AnyRec) => - validateFormLayout({ objects, views: [view] }).map((f) => `${f.rule}@${f.path}`); +describe('#6251 — the form item rung', () => { + it('reports the SAME broken form in both placements a form is read at', () => { + const at = (stack: AnyRec) => + validateFormLayout({ objects, ...stack }).map((f) => `${f.rule}@${f.path}`); - // (1) the entry IS a bare form view — the only shape read before #6251. - expect(at({ name: 'contract_form', ...brokenForm })).toEqual([ + // (1) a `views[]` entry that IS a bare form view — the only shape read before #6251. + expect(at({ views: [{ name: 'contract_form', ...brokenForm }] })).toEqual([ `${FORM_FIELD_UNKNOWN}@views[0].sections[0].fields[1]`, ]); - // (2) the container's DEFAULT form. - expect(at({ name: 'contract_views', object: 'contract', form: brokenForm })).toEqual([ - `${FORM_FIELD_UNKNOWN}@views[0].form.sections[0].fields[1]`, + // (2) a `forms[]` item — where an app authors a form from protocol 19. + expect(at({ forms: [brokenFormItem('edit')] })).toEqual([ + `${FORM_FIELD_UNKNOWN}@forms[0].sections[0].fields[1]`, ]); - // (3) a NAMED form view — where `os build` on app-showcase actually puts them. - expect(at({ name: 'contract_views', object: 'contract', formViews: { edit: brokenForm } })).toEqual([ - `${FORM_FIELD_UNKNOWN}@views[0].formViews.edit.sections[0].fields[1]`, + // (3) beside a list-only container of the same object: the item is still + // the one site, and the container adds none. + expect(at({ + views: [{ name: 'contract_views', object: 'contract', list: { type: 'grid', columns: ['name'] } }], + forms: [brokenFormItem('edit')], + })).toEqual([ + `${FORM_FIELD_UNKNOWN}@forms[0].sections[0].fields[1]`, ]); }); - it('names the sub-container in `where`, so two forms under one view are distinguishable', () => { + it('a container\'s retired `form` and `formViews` slots are no rung (ADR-0159 D7)', () => { + // The parse refuses both keys by name with a prescription naming `forms:`, + // which is what an author hears. Paired with the item on the same stack, so + // the silence on the slots is a verdict about the slots and not an unread stack. const findings = validateFormLayout({ objects, views: [{ @@ -320,38 +339,42 @@ describe('#6251 — the view CONTAINER ladder', () => { form: brokenForm, formViews: { edit: brokenForm, create: brokenForm }, }], + forms: [brokenFormItem('edit')], + }); + expect(findings.map((f) => f.path)).toEqual(['forms[0].sections[0].fields[1]']); + }); + + it('names the form in `where`, so two forms of one object are distinguishable', () => { + const findings = validateFormLayout({ + objects, + forms: [brokenFormItem('intake'), brokenFormItem('edit'), brokenFormItem('create')], }); expect(findings.map((f) => f.where)).toEqual([ - 'view "contract_views" · form', - 'view "contract_views" · formViews.edit', - 'view "contract_views" · formViews.create', + 'form "contract.intake"', + 'form "contract.edit"', + 'form "contract.create"', ]); }); - it('a sub-container INHERITS the container binding when it declares none', () => { - // The canonical container carries `object`; a `formViews.` entry that - // omits its own `data.object` still renders against that object, so a - // dangling field reference there is as real as anywhere else. + it('a form item is judged against its own `object` — it declares no `data` binding', () => { + // A form item carries `object` and no `data.object`; a dangling field + // reference there is as real as anywhere else. const findings = validateFormLayout({ objects, - views: [{ - name: 'contract_views', - object: 'contract', - formViews: { edit: { sections: [{ fields: ['ghost_inherited'] }] } }, - }], + forms: [{ name: 'contract.edit', object: 'contract', sections: [{ fields: ['ghost_inherited'] }] }], }); expect(findings.map((f) => f.rule)).toEqual([FORM_FIELD_UNKNOWN]); expect(findings[0].message).toContain('ghost_inherited'); expect(findings[0].message).toContain('"contract"'); }); - it('reads the legacy `groups` bucket too — measured NOT folded into `sections` at parse', () => { + it('reads the legacy `groups` bucket too — `os lint` hands the rule the source before the parse folds it', () => { const findings = validateFormLayout({ objects, - views: [{ - name: 'contract_views', + forms: [{ + name: 'contract.edit', object: 'contract', - form: { data: { object: 'contract' }, groups: [{ fields: ['name', { field: 'ghost_g', colSpan: 3 }] }] }, + groups: [{ fields: ['name', { field: 'ghost_g', colSpan: 3 }] }], }], }); // [#17328] RE-JUDGED: the second row was the withdrawn @@ -359,16 +382,21 @@ describe('#6251 — the view CONTAINER ladder', () => { // is deliberately LEFT on the fixture — it is what proves the entry object // shape is read here at all — but it no longer earns a row. expect(findings.map((f) => `${f.rule}@${f.path}`)).toEqual([ - `${FORM_FIELD_UNKNOWN}@views[0].form.groups[0].fields[1]`, + `${FORM_FIELD_UNKNOWN}@forms[0].groups[0].fields[1]`, ]); }); - it('reports a map-shaped `views` at the key it sits at, not a synthetic index', () => { - const findings = validateFormLayout({ + it('reports a map-shaped collection at the key it sits at, not a synthetic index', () => { + const formsMap = validateFormLayout({ + objects, + forms: { contract_edit: { object: 'contract', sections: brokenSections } }, + }); + expect(formsMap.map((f) => f.path)).toEqual(['forms.contract_edit.sections[0].fields[1]']); + const viewsMap = validateFormLayout({ objects, - views: { contract_views: { object: 'contract', formViews: { edit: brokenForm } } }, + views: { contract_form: brokenForm }, }); - expect(findings.map((f) => f.path)).toEqual(['views.contract_views.formViews.edit.sections[0].fields[1]']); + expect(viewsMap.map((f) => f.path)).toEqual(['views.contract_form.sections[0].fields[1]']); }); // NEGATIVE polarity — this one cannot go red when the traversal is reverted @@ -424,9 +452,10 @@ describe('#6251 — reachable on a REAL parsed app stack', () => { const data = { provider: 'object' as const, object: 'fl_contact' }; /** - * The container ladder copied from `examples/app-showcase/src/ui/views/ - * contact.view.ts` — default `form` grouped into sections, plus a sparse - * `formViews.create` override — with one dangling field planted in each. + * The protocol-19 shape of `examples/app-showcase`'s contact surfaces: a + * list-only view container, and the two forms as `forms[]` items — a form + * grouped into sections and a sparser one with its own title — with one + * dangling field planted in each. */ const appShape: AnyRec = { manifest, @@ -443,44 +472,58 @@ describe('#6251 — reachable on a REAL parsed app stack', () => { name: 'fl_contact', object: 'fl_contact', list: { label: 'Contacts', type: 'grid', data, columns: [{ field: 'name' }] }, - form: { + }], + forms: [ + { + name: 'fl_contact.intake', + object: 'fl_contact', type: 'simple', - data, sections: [{ name: 'contact', label: 'Contact', columns: 2, fields: ['name', 'email', 'ghost_default'] }], }, - formViews: { - create: { - type: 'simple', - data, - title: 'New contact', - sections: [{ label: 'Who is this?', columns: 1, fields: ['name', { field: 'ghost_named', colSpan: 2 }] }], - }, + { + name: 'fl_contact.create', + object: 'fl_contact', + type: 'simple', + title: 'New contact', + sections: [{ label: 'Who is this?', columns: 1, fields: ['name', { field: 'ghost_named', colSpan: 2 }] }], }, - }], + ], }; it('the fixture is a shape the strict schema ACCEPTS (so the pin is not testing a rejected stack)', () => { const { error, value } = quietly(() => cliTierFor(structuredClone(appShape))); expect(error).toBeUndefined(); - // And it really is the container shape: no `sections` at the entry root. + // And it really is the protocol-19 shape: the container holds its list + // alone, and the forms are items of their own. const view = (value!.views as AnyRec[])[0]; - expect(Object.keys(view).sort()).toEqual(['form', 'formViews', 'list', 'name', 'object']); + expect(Object.keys(view).sort()).toEqual(['list', 'name', 'object']); expect(view.sections).toBeUndefined(); + expect((value!.forms as AnyRec[]).map((f) => f.name)).toEqual(['fl_contact.intake', 'fl_contact.create']); + }); + + it('the same forms held in the container are REFUSED by the parse — the shape the rule no longer reads', () => { + const held = structuredClone(appShape); + const [intake, create] = held.forms as AnyRec[]; + delete held.forms; + const body = ({ name: _name, object: _object, ...rest }: AnyRec) => ({ ...rest, data }); + Object.assign((held.views as AnyRec[])[0], { form: body(intake), formViews: { create: body(create) } }); + const { error } = quietly(() => cliTierFor(held)); + expect(error).toBeDefined(); }); it('reports every planted defect on that stack — this is the assertion #6251 exists for', () => { const { value } = quietly(() => cliTierFor(structuredClone(appShape))); // [#17328] RE-JUDGED: the third row was the withdrawn colSpan finding on // the `ghost_named` entry. The other two rows are the ones #6251 exists for - // — one per container rung — and both still fire, so the traversal - // assertion this test carries is undiminished. + // — one per form — and both still fire, so the traversal assertion this + // test carries is undiminished. expect(validateFormLayout(value!).map((f) => `${f.rule}@${f.path}`)).toEqual([ - `${FORM_FIELD_UNKNOWN}@views[0].form.sections[0].fields[2]`, - `${FORM_FIELD_UNKNOWN}@views[0].formViews.create.sections[0].fields[1]`, + `${FORM_FIELD_UNKNOWN}@forms[0].sections[0].fields[2]`, + `${FORM_FIELD_UNKNOWN}@forms[1].sections[0].fields[1]`, ]); }); - // EMPTY-GREEN, declared. Revert the container ladder and this test still + // EMPTY-GREEN, declared. Revert the form item walk and this test still // passes — because nothing was read, not because nothing is wrong. It is kept // (a false-positive guard is worth having) but it is only meaningful PAIRED // with the test above, which proves on the same fixture family that the @@ -488,12 +531,9 @@ describe('#6251 — reachable on a REAL parsed app stack', () => { // stops guarding anything; do not treat it as independent cover. it('a CLEAN app stack of the same shape reports nothing — the fix adds no false positives', () => { const clean = structuredClone(appShape); - const view = (clean.views as AnyRec[])[0]; - (view.form as AnyRec).sections = [{ name: 'contact', label: 'Contact', columns: 2, fields: ['name', 'email', 'phone'] }]; - (view.formViews as AnyRec).create = { - type: 'simple', data, title: 'New contact', - sections: [{ label: 'Who is this?', columns: 1, fields: ['name', { field: 'email', span: 'full' }] }], - }; + const forms = clean.forms as AnyRec[]; + forms[0].sections = [{ name: 'contact', label: 'Contact', columns: 2, fields: ['name', 'email', 'phone'] }]; + forms[1].sections = [{ label: 'Who is this?', columns: 1, fields: ['name', { field: 'email', span: 'full' }] }]; const { error, value } = quietly(() => cliTierFor(clean)); expect(error).toBeUndefined(); expect(validateFormLayout(value!)).toEqual([]); @@ -503,85 +543,109 @@ describe('#6251 — reachable on a REAL parsed app stack', () => { // ─────────────────────────────────────────────────────────────────────────── // #16168 — a container that binds its object only through `list.data.object` // (HotCRM's own shape, 14/14 views) had NO `object` / `objectName` / -// `data.object` of its own, so `containerObject` — and every site under it, -// including the container's own default `form` — resolved to `undefined` and -// `form-field-unknown` / `form-section-group-unknown` never fired there. -// Fix: fall back to `viewObjectName(view.list)`, the same third rung -// `validate-translatable-sections.ts:178-179` already carries for its sites. +// `data.object` of its own, so every form site under it resolved to +// `undefined` and `form-field-unknown` / `form-section-group-unknown` never +// fired there. +// +// [ADR-0159 D9] At protocol 19 the form is a `forms[]` item with its own +// `object`, so it needs no fallback and the container beside it — list-bound or +// not — changes nothing about its verdict. Those are the cases below. The +// list-binding fallback itself stays for the one `views[]` rung left, a raw +// entry that carries root `sections` beside its `list`, and is pinned on it. // ─────────────────────────────────────────────────────────────────────────── -describe('#16168 — falls back to the container list binding', () => { +describe('#16168 — a form beside a list-bound container', () => { /** A container that binds ONLY through `list.data.object` — no `object` / `objectName` at the container root. */ - const listBoundContainer = (form: AnyRec) => ({ + const listBoundContainer = (patch: AnyRec = {}) => ({ name: 'contract_views', list: { label: 'Contracts', type: 'grid', data: { provider: 'object', object: 'contract' }, columns: [{ field: 'name' }] }, - form, + ...patch, }); + const formItem = (sections: unknown[]): AnyRec => ({ name: 'contract.intake', object: 'contract', sections }); - it('P1 — flags a dangling field in the default `form` of a list-bound container', () => { + it('P1 — flags a dangling field in the form beside a list-bound container', () => { const findings = validateFormLayout({ objects, - views: [listBoundContainer({ sections: [{ columns: 2, fields: ['name', 'ghost_field'] }] })], + views: [listBoundContainer()], + forms: [formItem([{ columns: 2, fields: ['name', 'ghost_field'] }])], }); expect(findings.map((f) => `${f.rule}@${f.path}`)).toEqual([ - `${FORM_FIELD_UNKNOWN}@views[0].form.sections[0].fields[1]`, + `${FORM_FIELD_UNKNOWN}@forms[0].sections[0].fields[1]`, ]); expect(findings[0].message).toContain('"contract"'); }); - it('P2 — flags an undeclared `group` in the default `form` of a list-bound container', () => { + it('P2 — flags an undeclared `group` in the form beside a list-bound container', () => { const findings = validateFormLayout({ objects: groupedObjects, - views: [listBoundContainer({ sections: [{ group: 'contact_info' }] })], + views: [listBoundContainer()], + forms: [formItem([{ group: 'contact_info' }])], }); expect(findings.map((f) => `${f.rule}@${f.path}`)).toEqual([ - `${FORM_SECTION_GROUP_UNKNOWN}@views[0].form.sections[0].group`, + `${FORM_SECTION_GROUP_UNKNOWN}@forms[0].sections[0].group`, ]); }); + it('P3 — the list-binding fallback still resolves a raw `views[]` entry carrying root `sections` beside its `list`', () => { + const findings = validateFormLayout({ + objects, + views: [listBoundContainer({ sections: [{ columns: 2, fields: ['name', 'ghost_field'] }] })], + }); + expect(findings.map((f) => ({ rule: f.rule, where: f.where, path: f.path }))).toEqual([ + { rule: FORM_FIELD_UNKNOWN, where: 'view "contract_views"', path: 'views[0].sections[0].fields[1]' }, + ]); + expect(findings[0].message).toContain('"contract"'); + }); + it('N1 — positive control: the same defects with `object` also on the container produce the SAME findings (byte-identical where/path)', () => { - const withObject = (view: AnyRec) => ({ ...view, object: 'contract' }); const p1 = validateFormLayout({ objects, - views: [withObject(listBoundContainer({ sections: [{ columns: 2, fields: ['name', 'ghost_field'] }] }))], + views: [listBoundContainer({ object: 'contract' })], + forms: [formItem([{ columns: 2, fields: ['name', 'ghost_field'] }])], }); expect(p1.map((f) => ({ rule: f.rule, where: f.where, path: f.path }))).toEqual([ - { rule: FORM_FIELD_UNKNOWN, where: 'view "contract_views" · form', path: 'views[0].form.sections[0].fields[1]' }, + { rule: FORM_FIELD_UNKNOWN, where: 'form "contract.intake"', path: 'forms[0].sections[0].fields[1]' }, ]); const p2 = validateFormLayout({ objects: groupedObjects, - views: [withObject(listBoundContainer({ sections: [{ group: 'contact_info' }] }))], + views: [listBoundContainer({ object: 'contract' })], + forms: [formItem([{ group: 'contact_info' }])], }); expect(p2.map((f) => ({ rule: f.rule, where: f.where, path: f.path }))).toEqual([ - { rule: FORM_SECTION_GROUP_UNKNOWN, where: 'view "contract_views" · form', path: 'views[0].form.sections[0].group' }, + { rule: FORM_SECTION_GROUP_UNKNOWN, where: 'form "contract.intake"', path: 'forms[0].sections[0].group' }, ]); }); - it('N2 — a list-bound container whose form references only real fields is clean', () => { + it('N2 — a form beside a list-bound container that references only real fields is clean', () => { expect(validateFormLayout({ objects, - views: [listBoundContainer({ sections: [{ columns: 2, fields: ['name', 'amount'] }] })], + views: [listBoundContainer()], + forms: [formItem([{ columns: 2, fields: ['name', 'amount'] }])], })).toEqual([]); }); - it('N3 — a `formViews[]` entry with its own `objectName` resolves as today, independent of the container', () => { + it('N3 — a form item resolves through its own binding, independent of the container beside it', () => { const findings = validateFormLayout({ objects, views: [{ name: 'contract_views', - list: { data: { object: 'contract' } }, - formViews: { edit: { objectName: 'contract', sections: [{ fields: ['ghost_via_own_binding'] }] } }, + list: { data: { object: 'some_other_object' } }, }], + forms: [{ name: 'contract.edit', object: 'contract', sections: [{ fields: ['ghost_via_own_binding'] }] }], }); expect(findings.map((f) => `${f.rule}@${f.path}`)).toEqual([ - `${FORM_FIELD_UNKNOWN}@views[0].formViews.edit.sections[0].fields[0]`, + `${FORM_FIELD_UNKNOWN}@forms[0].sections[0].fields[0]`, ]); }); - it('N4 — a view with neither a container nor a list binding stays silent (unchanged: the rule cannot check what it cannot resolve)', () => { + it('N4 — a form whose object does not resolve stays silent (unchanged: the rule cannot check what it cannot resolve)', () => { expect(validateFormLayout({ objects, - views: [{ name: 'orphan_views', form: { sections: [{ fields: ['whatever'] }] } }], + views: [listBoundContainer()], + forms: [ + { name: 'orphan.intake', sections: [{ fields: ['whatever'] }] }, + { name: 'missing.intake', object: 'does_not_exist', sections: [{ fields: ['whatever'] }] }, + ], })).toEqual([]); }); @@ -590,21 +654,21 @@ describe('#16168 — falls back to the container list binding', () => { // needed only `entry.colSpan != null`, so it was never dead on HotCRM's // list-bound views and #16168 only ever fixed the two reference rules. That // rule is now withdrawn, so what the same fixture measures is the OTHER half - // of the same sentence: on a list-bound container a well-formed field with a - // `colSpan` is silent, while a dangling one is not — which is exactly the - // #16168 fix still holding, now with nothing riding alongside it. - it('[#17328] a list-bound container reports only its reference findings — the colSpan rule is gone', () => { + // of the same sentence: a well-formed field with a `colSpan` is silent, while + // a dangling one is not — with nothing riding alongside it. + it('[#17328] a form beside a list-bound container reports only its reference findings — the colSpan rule is gone', () => { expect(validateFormLayout({ objects, - views: [listBoundContainer({ sections: [{ columns: 2, fields: [{ field: 'name', colSpan: 2 }] }] })], + views: [listBoundContainer()], + forms: [formItem([{ columns: 2, fields: [{ field: 'name', colSpan: 2 }] }])], })).toEqual([]); - // POSITIVE CONTROL — the #16168 fix itself: the same list-bound rung, a - // dangling reference, still reported. Without this the line above would - // pass on a container the walk never descends into. + // POSITIVE CONTROL: the same form, a dangling reference, still reported. + // Without this the line above would pass on a form the walk never reads. expect(validateFormLayout({ objects, - views: [listBoundContainer({ sections: [{ columns: 2, fields: [{ field: 'ghost_lb', colSpan: 2 }] }] })], + views: [listBoundContainer()], + forms: [formItem([{ columns: 2, fields: [{ field: 'ghost_lb', colSpan: 2 }] }])], }).map((f) => f.rule)).toEqual([FORM_FIELD_UNKNOWN]); }); }); @@ -612,35 +676,36 @@ describe('#16168 — falls back to the container list binding', () => { // [#22161] Slice 21: the `fix:` line of `form-section-group-unknown` is one // remedy line. It names the nearest declared group ("Did you mean") instead of // echoing the object's whole group list, and how a section inherits a group's -// [#29309] A stored form ViewItem — `{ name, object, viewKind: 'form', config }`, -// the shape Studio saves through `PUT /meta/view` — keeps its form under -// `config`. The view walk read only the container rungs, so the runtime publish -// gate (which hands the rule the written body as authored) judged such a form -// not at all. Same two findings, located under `config`. -describe('#29309 — a form ViewItem\'s `config` rung', () => { - const formItem = (config: AnyRec, patch: AnyRec = {}) => ({ +// [#29309] The form Studio saves. Under protocol 18 that was a view item +// `{ name, object, viewKind: 'form', config }` written through the `view` door, +// its form under `config`; the runtime publish gate judged such a form not at +// all until the walk read that rung. [ADR-0159 D2] From protocol 19 Studio +// saves a `form` item through the `form` door, its body at the top level (no +// `config` wrapper), and the gate hands the rule that written body as authored. +// Same two findings, located on the item. +describe('#29309 — the form item a save writes', () => { + const formItem = (body: AnyRec, patch: AnyRec = {}) => ({ objects: groupedObjects, - views: [{ name: 'contract.edit', object: 'contract', viewKind: 'form', config, ...patch }], + forms: [{ name: 'contract.edit', object: 'contract', ...body, ...patch }], }); - it('flags an unknown field and an undeclared group in `config.sections`, at the `config` path', () => { + it('flags an unknown field and an undeclared group in the item\'s `sections`, at the item\'s path', () => { const findings = validateFormLayout(formItem({ type: 'simple', sections: [{ name: 'main', fields: ['name', 'no_such_field'] }, { group: 'no_such_group' }], })); expect(findings.map((f) => [f.rule, f.path, f.where])).toEqual([ - [FORM_SECTION_GROUP_UNKNOWN, 'views[0].config.sections[1].group', 'view "contract.edit" · config'], - [FORM_FIELD_UNKNOWN, 'views[0].config.sections[0].fields[1]', 'view "contract.edit" · config'], + [FORM_SECTION_GROUP_UNKNOWN, 'forms[0].sections[1].group', 'form "contract.edit"'], + [FORM_FIELD_UNKNOWN, 'forms[0].sections[0].fields[1]', 'form "contract.edit"'], ]); expect(findings.every((f) => f.severity === 'warning')).toBe(true); }); - it('honors the config\'s own `data.object` binding over the item\'s `object`', () => { - const findings = validateFormLayout(formItem( - { data: { provider: 'object', object: 'contract' }, sections: [{ fields: ['nope'] }] }, - { object: 'not_an_object' }, - )); - expect(findings.map((f) => f.rule)).toEqual([FORM_FIELD_UNKNOWN]); + it('judges the item against its own `object`, the one binding a form item has', () => { + const body = { sections: [{ fields: ['nope'] }] }; + expect(validateFormLayout(formItem(body)).map((f) => f.rule)).toEqual([FORM_FIELD_UNKNOWN]); + // An `object` naming nothing resolvable is not reference-checked. + expect(validateFormLayout(formItem(body, { object: 'not_an_object' }))).toEqual([]); }); it('control: a form item naming only real fields and a declared group is clean', () => { @@ -650,11 +715,20 @@ describe('#29309 — a form ViewItem\'s `config` rung', () => { }))).toEqual([]); }); - it('control: a LIST item\'s `config` is not a form and is not walked', () => { - expect(validateFormLayout(formItem( - { type: 'grid', sections: [{ fields: ['no_such_field'] }] }, - { viewKind: 'list' }, - ))).toEqual([]); + it('control: a view item\'s `config` is not a form and is not walked, whatever `viewKind` it carries', () => { + const viewItem = (viewKind: string) => ({ + objects: groupedObjects, + views: [{ + name: 'contract.edit', + object: 'contract', + viewKind, + config: { type: 'grid', sections: [{ fields: ['no_such_field'] }] }, + }], + }); + expect(validateFormLayout(viewItem('list'))).toEqual([]); + // The retired form-kind item: the parse refuses it by name, and no rule + // reads a form out of it. + expect(validateFormLayout(viewItem('form'))).toEqual([]); }); }); diff --git a/packages/lint/src/validate-form-layout.ts b/packages/lint/src/validate-form-layout.ts index d2fed7465a4..1d9e8cd25c5 100644 --- a/packages/lint/src/validate-form-layout.ts +++ b/packages/lint/src/validate-form-layout.ts @@ -46,14 +46,13 @@ * that actually misrenders, and a positive control proving the probe fires on * it. * - * Scope: every form view reachable from a `views[]` entry — the entry itself - * when it IS a bare form view, plus the container's default `form` and each - * `formViews.`, plus [#29309] a form ViewItem's `config`, through the - * shared `view-walk.ts` ladder (#6381; see - * {@link formViewSites} for why reading only the first shape left the rules - * reporting clean on real app metadata, #6251). Forms embedded inside page - * component trees are a follow-up — the walk deliberately stays shallow so it - * never guesses at an arbitrary component's object binding. + * Scope ([ADR-0159 D9]): every `forms[]` item, the one place an app authors a + * form from protocol 19, plus a `views[]` entry that IS a bare form view — + * both through the shared `view-walk.ts` walk ({@link formItemSites}, + * {@link formViewSites}). A view container holds lists only, so no form is + * read out of one. Forms embedded inside page component trees are a + * follow-up — the walk deliberately stays shallow so it never guesses at an + * arbitrary component's object binding. */ import { collectionEntries } from './collection-entries.js'; @@ -66,7 +65,7 @@ import { indexObjectFieldGroups, sectionGroupRefs, } from './object-field-groups.js'; -import { formViewSites, viewObjectName } from './view-walk.js'; +import { formItemName, formItemSites, formViewSites, viewObjectName } from './view-walk.js'; import { objectsAsServed, recordsOf } from './object-graph.js'; export const FORM_FIELD_UNKNOWN = 'form-field-unknown'; @@ -85,9 +84,9 @@ export interface FormLayoutFinding { severity: FormLayoutSeverity; /** Diagnostic rule id, e.g. `form-field-unknown`. */ rule: string; - /** Human-readable location, e.g. `view "contract_form" · formViews.create`. */ + /** Human-readable location, e.g. `form "contract.intake"`. */ where: string; - /** Config path, e.g. `views[2].formViews.create.sections[0].fields[3]`. */ + /** Config path, e.g. `forms[2].sections[0].fields[3]`. */ path: string; /** What is wrong. */ message: string; @@ -116,7 +115,7 @@ function strName(v: unknown): string | undefined { * the distinction is worth keeping straight where this rule reads it: strict * `ViewSchema` refuses a `views[]` entry carrying root `sections` — measured, * `unrecognized_keys` naming `sections` — so on a parsed `defineStack` config - * only the container rungs can fire. But this rule is registered + * only the `forms[]` items can fire. But this rule is registered * `input: 'parsed'`, and `os lint` never parses: `runAuthoringRules` hands * `parsed` rules the NORMALIZED stack, where a raw (non-`defineStack`) config's * root `sections` is still present and still the author's mistake to hear about. @@ -174,6 +173,18 @@ export function validateFormLayout(stack: AnyRec): FormLayoutFinding[] { // [#13855] object name → its declared field-group keys, for `section.group`. const objectFieldGroups = indexObjectFieldGroups(stack); + // One judged form: the record, where it is, the name findings call it by and + // the object it binds. + interface JudgedForm { view: AnyRec; path: string; name: string; where: string; objName: string | undefined } + const judged: JudgedForm[] = []; + + // [ADR-0159 D9] `forms[]` items: a form carries its own `object`, so its + // binding needs no fallback. + for (const site of formItemSites(stack)) { + const name = formItemName(site); + judged.push({ view: site.view, path: site.path, name, where: `form "${name}"`, objName: viewObjectName(site.view) }); + } + for (const { rec: view, path: viewPath } of collectionEntries(stack.views, 'views')) { // A container names itself with `name`, or binds with `object` — and an // artifact-emitted one may carry neither, so the path is the last resort. @@ -182,42 +193,33 @@ export function validateFormLayout(stack: AnyRec): FormLayoutFinding[] { // [#16168] A container whose object lives on the LIST block // (`list.data.object`, `list.object` or `list.objectName` — any anchor // `viewObjectName` reads) has no `object` / `objectName` / `data.object` of - // its own, so `containerObject` above is `undefined` and every site under it - // — including the container's own default `form` — was unreferenceable. - // Same third rung `validate-translatable-sections.ts:178-179` already - // carries for its own sites. + // its own, so `containerObject` above is `undefined`. Same third rung + // `validate-translatable-sections.ts` carries for its own sites. const listBinding = isRec(view.list) ? viewObjectName(view.list) ?? containerObject : undefined; - - // [#29309] A stored form ViewItem (`{ name, object, viewKind: 'form', - // config }`, the shape Studio saves through `PUT /meta/view`) keeps its form - // under `config`, a rung the shared container walk does not carry. Read - // here, beside the container rungs: the runtime publish gate hands this - // rule the written body as authored, so without this rung a Studio form was - // judged on no save and no publish. Keyed on `viewKind: 'form'` only — a - // list item's `config` is a list view and carries no sections. The rung is - // this rule's, not `view-walk.ts`'s: adding it there would change the - // verdicts of the other walkers, which a fix here may not do. - const sites: Array<{ view: AnyRec; path: string; surface: string }> = formViewSites(view, viewPath); - if (view.viewKind === 'form' && isRec(view.config)) { - sites.push({ view: view.config, path: `${viewPath}.config`, surface: 'config' }); + for (const site of formViewSites(view, viewPath)) { + judged.push({ + view: site.view, + path: site.path, + name: viewName, + where: site.surface ? `view "${viewName}" · ${site.surface}` : `view "${viewName}"`, + // The base rung is the shared `viewObjectName` (#6662); this FALLBACK + // is deliberately NOT folded into the shared walker, because the + // consumers compose it differently (see `view-walk.ts`). + objName: viewObjectName(site.view) ?? containerObject ?? listBinding, + }); } + } - for (const site of sites) { - // A sub-container declares its own binding (`form.data.object`) and - // otherwise inherits the container's, then the container's list-bound - // object as a last resort (#16168) — the resolution order every other - // view-walking rule in this package uses. The base rung is the shared - // `viewObjectName` (#6662); this FALLBACK is deliberately NOT folded into - // the shared walker, because the consumers compose it differently (see - // `view-walk.ts`) and a refactor that changes a verdict is a failed - // refactor. - const objName = viewObjectName(site.view) ?? containerObject ?? listBinding; + { + for (const site of judged) { + const viewName = site.name; + const objName = site.objName; + const where = site.where; // Only reference-check when the bound object resolves; otherwise we can't. const known = objName ? objectFields.get(objName) : undefined; - const where = site.surface ? `view "${viewName}" · ${site.surface}` : `view "${viewName}"`; - // `sections` (canonical) and `groups` (legacy alias → sections, - // `view.zod.ts:1624`) both hold FormSection objects. Reading both is what + // `sections` (canonical) and `groups` (legacy alias → sections) both + // hold FormSection objects. Reading both is what // #6248 does on this surface, for the same reason: a rule that judges only // the canonical spelling is silent on the legacy one, which is exactly the // half-coverage this issue is about. @@ -239,7 +241,7 @@ export function validateFormLayout(stack: AnyRec): FormLayoutFinding[] { ...checkSectionGroupRefs(groupRefs, objName, objectFieldGroups, where, FORM_SECTION_GROUP_UNKNOWN) .map((finding) => ({ ...finding, - userTextParams: { view: viewName, object: objName ?? '', group: groupAt.get(finding.path) ?? '' }, + userTextParams: { form: viewName, object: objName ?? '', group: groupAt.get(finding.path) ?? '' }, })), ); @@ -264,7 +266,7 @@ export function validateFormLayout(stack: AnyRec): FormLayoutFinding[] { hint: `Fix the field name, or add "${fname}" to ${objName}. Section field ` + `references must match the object's field names exactly.`, - userTextParams: { view: viewName, object: objName ?? '', field: fname }, + userTextParams: { form: viewName, object: objName ?? '', field: fname }, }); } } diff --git a/packages/lint/src/validate-form-layout.user-text.ts b/packages/lint/src/validate-form-layout.user-text.ts index 118f0d2d82d..1861a9836aa 100644 --- a/packages/lint/src/validate-form-layout.user-text.ts +++ b/packages/lint/src/validate-form-layout.user-text.ts @@ -7,30 +7,30 @@ * this file is the rule's own half of it, kept beside the rule so its wording * and its translations change together. * - * Who reads these: the person who saved a form view in Studio, in their own + * Who reads these: the person who saved a form in Studio, in their own * language, once the save door composes `RuntimeAuthoringIssueSchema.userMessage` * from them. So each sentence says what the form fails to show and the one - * change that fixes it, in the form designer's own words (view, form, section, + * change that fixes it, in the form designer's own words (form, section, * field, field group, object); the developer-facing detail stays in the * finding's `message`, `hint` and `os explain` entry. * * Both of the rule's ids are advisory and both reach the publish door, on a - * `view` write. Each entry reads the `userTextParams` its finding carries: + * `form` write. Each entry reads the `userTextParams` its finding carries: * * | rule id | params | set at | * |---|---|---| - * | `form-field-unknown` | `view`, `object`, `field` | the section-field push site | - * | `form-section-group-unknown` | `view`, `object`, `group` | the `checkSectionGroupRefs` call site | + * | `form-field-unknown` | `form`, `object`, `field` | the section-field push site | + * | `form-section-group-unknown` | `form`, `object`, `group` | the `checkSectionGroupRefs` call site | * * The group finding is built by the shared `object-field-groups.ts` helper, * so its params are added where this rule calls it, not in the helper: the * helper's other host (`validate-page-field-bindings`) emits its group id on * no write the door judges. * - * Names in a sentence are the API names the rule saw (`contract_form`, a + * Names in a sentence are the API names the rule saw (`contract.intake`, a * field's name), not labels, for the reason `validate-security-posture.user-text.ts` * gives: the rule is a pure function of the stack with no label lookup in the - * request's language. A view with no name shows the rule's own stand-in, as + * request's language. A form with no name shows the rule's own stand-in, as * its `message` does. * * `finding-user-text.pages-forms.test.ts` renders every entry from the rule's @@ -43,87 +43,87 @@ import { FORM_FIELD_UNKNOWN, FORM_SECTION_GROUP_UNKNOWN } from './validate-form- export const FORM_LAYOUT_USER_TEXT: UserTextCatalog = Object.freeze({ [FORM_FIELD_UNKNOWN]: { en: (p) => - `The form in view "${p.view}" lists the field "${p.field}", which object "${p.object}" does not have, so ` + + `The form "${p.form}" lists the field "${p.field}", which object "${p.object}" does not have, so ` + `it is skipped and never appears on the form. Correct the field name, or add the field to "${p.object}".`, 'zh-Hans': (p) => - `视图“${p.view}”的表单列出了字段“${p.field}”,但对象“${p.object}”没有这个字段,因此它会被跳过,` + + `表单“${p.form}”列出了字段“${p.field}”,但对象“${p.object}”没有这个字段,因此它会被跳过,` + `不会出现在表单上。请更正字段名称,或在“${p.object}”中添加该字段。`, 'zh-Hant': (p) => - `檢視「${p.view}」的表單列出了欄位「${p.field}」,但物件「${p.object}」沒有這個欄位,因此它會被略過,` + + `表單「${p.form}」列出了欄位「${p.field}」,但物件「${p.object}」沒有這個欄位,因此它會被略過,` + `不會出現在表單上。請更正欄位名稱,或在「${p.object}」中新增該欄位。`, es: (p) => - `El formulario de la vista "${p.view}" incluye el campo "${p.field}", que el objeto "${p.object}" no ` + + `El formulario "${p.form}" incluye el campo "${p.field}", que el objeto "${p.object}" no ` + `tiene, así que se omite y nunca aparece en el formulario. Corrija el nombre del campo o agregue el ` + `campo a "${p.object}".`, ar: (p) => - `يتضمن النموذج في طريقة العرض "${p.view}" الحقل "${p.field}"، وهو غير موجود في الكائن "${p.object}"، ` + + `يتضمن النموذج "${p.form}" الحقل "${p.field}"، وهو غير موجود في الكائن "${p.object}"، ` + `لذلك يتم تخطيه ولا يظهر في النموذج أبدًا. صحّح اسم الحقل، أو أضف الحقل إلى "${p.object}".`, fr: (p) => - `Le formulaire de la vue « ${p.view} » liste le champ « ${p.field} », que l'objet « ${p.object} » ne ` + + `Le formulaire « ${p.form} » liste le champ « ${p.field} », que l'objet « ${p.object} » ne ` + `possède pas : il est donc ignoré et n'apparaît jamais dans le formulaire. Corrigez le nom du champ, ou ` + `ajoutez ce champ à « ${p.object} ».`, 'pt-BR': (p) => - `O formulário da visualização "${p.view}" lista o campo "${p.field}", que o objeto "${p.object}" não ` + + `O formulário "${p.form}" lista o campo "${p.field}", que o objeto "${p.object}" não ` + `tem, então ele é ignorado e nunca aparece no formulário. Corrija o nome do campo ou adicione o campo a ` + `"${p.object}".`, ru: (p) => - `Форма в представлении «${p.view}» содержит поле «${p.field}», которого нет у объекта «${p.object}», ` + + `Форма «${p.form}» содержит поле «${p.field}», которого нет у объекта «${p.object}», ` + `поэтому оно пропускается и никогда не отображается в форме. Исправьте имя поля или добавьте это поле ` + `в «${p.object}».`, de: (p) => - `Das Formular in der Ansicht „${p.view}“ führt das Feld „${p.field}“ auf, das das Objekt „${p.object}“ ` + + `Das Formular „${p.form}“ führt das Feld „${p.field}“ auf, das das Objekt „${p.object}“ ` + `nicht hat. Es wird daher übersprungen und erscheint nie im Formular. Korrigieren Sie den Feldnamen, oder ` + `fügen Sie das Feld zu „${p.object}“ hinzu.`, ja: (p) => - `ビュー「${p.view}」のフォームには項目「${p.field}」が含まれていますが、オブジェクト「${p.object}」には` + + `フォーム「${p.form}」には項目「${p.field}」が含まれていますが、オブジェクト「${p.object}」には` + `この項目がないため、スキップされてフォームに表示されません。項目名を修正するか、「${p.object}」に` + `この項目を追加してください。`, ko: (p) => - `보기 "${p.view}"의 양식에 필드 "${p.field}"이(가) 있지만 개체 "${p.object}"에는 이 필드가 없으므로, ` + + `양식 "${p.form}"에 필드 "${p.field}"이(가) 있지만 개체 "${p.object}"에는 이 필드가 없으므로, ` + `건너뛰어지고 양식에 표시되지 않습니다. 필드 이름을 수정하거나 "${p.object}"에 이 필드를 추가하세요.`, }, [FORM_SECTION_GROUP_UNKNOWN]: { en: (p) => - `A section of the form in view "${p.view}" takes its fields from the field group "${p.group}", which ` + + `A section of the form "${p.form}" takes its fields from the field group "${p.group}", which ` + `object "${p.object}" does not declare, so the section has no fields and does not appear. Correct the ` + `group name, or add the group to "${p.object}" and assign fields to it.`, 'zh-Hans': (p) => - `视图“${p.view}”的表单中有一个分区从字段分组“${p.group}”获取字段,但对象“${p.object}”没有声明这个分组,` + + `表单“${p.form}”中有一个分区从字段分组“${p.group}”获取字段,但对象“${p.object}”没有声明这个分组,` + `因此该分区没有字段,也不会显示。请更正分组名称,或在“${p.object}”中添加该分组并为其分配字段。`, 'zh-Hant': (p) => - `檢視「${p.view}」的表單中有一個區段從欄位分組「${p.group}」取得欄位,但物件「${p.object}」沒有宣告這個分組,` + + `表單「${p.form}」中有一個區段從欄位分組「${p.group}」取得欄位,但物件「${p.object}」沒有宣告這個分組,` + `因此該區段沒有欄位,也不會顯示。請更正分組名稱,或在「${p.object}」中新增該分組並為其指派欄位。`, es: (p) => - `Una sección del formulario de la vista "${p.view}" toma sus campos del grupo de campos "${p.group}", que ` + + `Una sección del formulario "${p.form}" toma sus campos del grupo de campos "${p.group}", que ` + `el objeto "${p.object}" no declara, así que la sección no tiene campos y no aparece. Corrija el nombre ` + `del grupo, o agregue el grupo a "${p.object}" y asígnele campos.`, ar: (p) => - `يأخذ قسم في النموذج ضمن طريقة العرض "${p.view}" حقوله من مجموعة الحقول "${p.group}"، التي لا يعرّفها ` + + `يأخذ قسم في النموذج "${p.form}" حقوله من مجموعة الحقول "${p.group}"، التي لا يعرّفها ` + `الكائن "${p.object}"، لذلك لا يحتوي القسم على أي حقول ولا يظهر. صحّح اسم المجموعة، أو أضف المجموعة ` + `إلى "${p.object}" وعيّن لها حقولًا.`, fr: (p) => - `Une section du formulaire de la vue « ${p.view} » tire ses champs du groupe de champs « ${p.group} », ` + + `Une section du formulaire « ${p.form} » tire ses champs du groupe de champs « ${p.group} », ` + `que l'objet « ${p.object} » ne déclare pas : la section n'a donc aucun champ et ne s'affiche pas. ` + `Corrigez le nom du groupe, ou ajoutez ce groupe à « ${p.object} » et attribuez-lui des champs.`, 'pt-BR': (p) => - `Uma seção do formulário da visualização "${p.view}" obtém seus campos do grupo de campos "${p.group}", ` + + `Uma seção do formulário "${p.form}" obtém seus campos do grupo de campos "${p.group}", ` + `que o objeto "${p.object}" não declara, então a seção não tem campos e não aparece. Corrija o nome do ` + `grupo ou adicione o grupo a "${p.object}" e atribua campos a ele.`, ru: (p) => - `Раздел формы в представлении «${p.view}» берёт поля из группы полей «${p.group}», которую объект ` + + `Раздел формы «${p.form}» берёт поля из группы полей «${p.group}», которую объект ` + `«${p.object}» не объявляет, поэтому в разделе нет полей и он не отображается. Исправьте имя группы или ` + `добавьте эту группу в «${p.object}» и назначьте ей поля.`, de: (p) => - `Ein Abschnitt des Formulars in der Ansicht „${p.view}“ bezieht seine Felder aus der Feldgruppe ` + + `Ein Abschnitt des Formulars „${p.form}“ bezieht seine Felder aus der Feldgruppe ` + `„${p.group}“, die das Objekt „${p.object}“ nicht deklariert. Der Abschnitt hat daher keine Felder und ` + `wird nicht angezeigt. Korrigieren Sie den Gruppennamen, oder fügen Sie die Gruppe zu „${p.object}“ ` + `hinzu und ordnen Sie ihr Felder zu.`, ja: (p) => - `ビュー「${p.view}」のフォームのセクションが項目グループ「${p.group}」から項目を取得していますが、` + + `フォーム「${p.form}」のセクションが項目グループ「${p.group}」から項目を取得していますが、` + `オブジェクト「${p.object}」はこのグループを宣言していないため、セクションに項目がなく表示されません。` + `グループ名を修正するか、「${p.object}」にこのグループを追加して項目を割り当ててください。`, ko: (p) => - `보기 "${p.view}"의 양식에 있는 섹션이 필드 그룹 "${p.group}"에서 필드를 가져오지만, 개체 ` + + `양식 "${p.form}"에 있는 섹션이 필드 그룹 "${p.group}"에서 필드를 가져오지만, 개체 ` + `"${p.object}"은(는) 이 그룹을 선언하지 않으므로 섹션에 필드가 없고 표시되지 않습니다. 그룹 이름을 ` + `수정하거나 "${p.object}"에 이 그룹을 추가하고 필드를 할당하세요.`, }, diff --git a/packages/lint/src/validate-internal-form-views.test.ts b/packages/lint/src/validate-internal-form-views.test.ts deleted file mode 100644 index 0b2493cd350..00000000000 --- a/packages/lint/src/validate-internal-form-views.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * `form-view-internal-not-loaded` (#36425): an internal create / edit form the - * app still declares is reported once, as a warning; a public form and a named - * form are not, and neither is a default or create form a `type: 'form'` - * action opens by the name it is served under (#36545). - */ - -import { describe, expect, it } from 'vitest'; -import { FORM_VIEW_INTERNAL_NOT_LOADED, validateInternalFormViews } from './validate-internal-form-views.js'; -import { AUTHORING_RULES } from './authoring-rules.js'; -import { explainRule } from './rule-explanations.js'; - -const sections = [{ label: 'Main', fields: ['name'] }]; - -describe('form-view-internal-not-loaded', () => { - it('reports a container\'s default form, its formViews.create and formViews.default, each as a warning', () => { - const findings = validateInternalFormViews({ - views: [{ - name: 'account', - object: 'account', - form: { type: 'simple', sections }, - formViews: { create: { type: 'simple', sections }, default: { type: 'tabbed', sections } }, - }], - }); - expect(findings.map((f) => f.where)).toEqual([ - 'view "account" · form', - 'view "account" · formViews.create', - 'view "account" · formViews.default', - ]); - expect(findings.map((f) => f.path)).toEqual([ - 'views[0].form', - 'views[0].formViews.create', - 'views[0].formViews.default', - ]); - for (const f of findings) { - expect(f.rule).toBe(FORM_VIEW_INTERNAL_NOT_LOADED); - expect(f.severity).toBe('warning'); - expect(f.hint).toMatch(/^Internal forms are no longer loaded: use field groups/); - } - }); - - it('reports a stored form view item that is the default or the object\'s create form', () => { - const findings = validateInternalFormViews({ - views: [ - { name: 'account.form', object: 'account', viewKind: 'form', isDefault: true, config: { sections } }, - { name: 'account.create', object: 'account', viewKind: 'form', config: { sections } }, - ], - }); - expect(findings.map((f) => f.path)).toEqual(['views[0].config', 'views[1].config']); - }); - - it('CONTROL: a public form (sharing.enabled) is never reported, wherever it sits', () => { - const sharing = { enabled: true, publicLink: 'contact-us', allowAnonymous: true }; - expect(validateInternalFormViews({ - views: [ - { name: 'lead', object: 'lead', form: { type: 'simple', sections, sharing } }, - { name: 'lead.form', object: 'lead', viewKind: 'form', isDefault: true, config: { sections, sharing } }, - ], - })).toEqual([]); - }); - - it('CONTROL: a form view under any other name (opened by name by an action) is not reported', () => { - expect(validateInternalFormViews({ - views: [ - { name: 'lead', object: 'lead', formViews: { wizard: { type: 'wizard', sections } } }, - { name: 'lead.qualify', object: 'lead', viewKind: 'form', config: { sections } }, - ], - })).toEqual([]); - }); - - it('a nameless container is named by the object its form binds, not by its index', () => { - const findings = validateInternalFormViews({ - views: [ - { list: { type: 'grid', data: { provider: 'object', object: 'deal' } }, form: { data: { provider: 'object', object: 'deal' }, sections } }, - { list: { type: 'grid', data: { provider: 'object', object: 'lead' } }, form: { sections } }, - ], - }); - expect(findings.map((f) => f.where)).toEqual(['view "deal" · form', 'view "lead" · form']); - expect(findings.map((f) => f.path)).toEqual(['views[0].form', 'views[1].form']); - }); - - it('a form with sharing turned off is internal and reported', () => { - const findings = validateInternalFormViews({ - views: [{ name: 'lead', object: 'lead', form: { sections, sharing: { enabled: false } } }], - }); - expect(findings).toHaveLength(1); - }); - - it('is registered as an advisory rule on every check command, and `os explain` knows it', () => { - const entry = AUTHORING_RULES.find((r) => r.name === 'validateInternalFormViews'); - expect(entry?.tier).toBe('advisory'); - expect(explainRule(FORM_VIEW_INTERNAL_NOT_LOADED)?.rule).toBe(FORM_VIEW_INTERNAL_NOT_LOADED); - }); -}); - -describe('form-view-internal-not-loaded — a form an action opens by name keeps loading (#36545)', () => { - const container = { - name: 'account', - object: 'account', - list: { type: 'grid', columns: ['name'] }, - form: { type: 'simple', sections }, - formViews: { create: { type: 'simple', sections }, default: { type: 'tabbed', sections } }, - }; - - it('a registered or object-bound form action targeting the served name exempts that form, and only it', () => { - const findings = validateInternalFormViews({ - views: [container], - actions: [{ name: 'log_call', type: 'form', target: 'account.form' }], - objects: [{ name: 'account', actions: [{ name: 'new_account', type: 'form', target: 'account.create' }] }], - }); - expect(findings.map((f) => f.where)).toEqual(['view "account" · formViews.default']); - }); - - it('matches the name the spec expansion serves, collisions included, never a hand-built OBJECT.KEY', () => { - // The default `list` claims `account.default`, so `formViews.default` is - // served as `account.default_2`: a target of `account.default` opens the - // list, not this form. - const atList = validateInternalFormViews({ - views: [container], - actions: [{ name: 'a', type: 'form', target: 'account.default' }], - }); - expect(atList.map((f) => f.where)).toContain('view "account" · formViews.default'); - const atServed = validateInternalFormViews({ - views: [container], - actions: [{ name: 'a', type: 'form', target: 'account.default_2' }], - }); - expect(atServed.map((f) => f.where)).not.toContain('view "account" · formViews.default'); - // A container form with its own `name` is served under it. - const renamed = validateInternalFormViews({ - views: [{ object: 'deal', form: { name: 'quick', sections } }], - actions: [{ name: 'a', type: 'form', target: 'deal.quick' }], - }); - expect(renamed).toEqual([]); - }); - - it('a page component\'s inline form action exempts a stored default form it names', () => { - const findings = validateInternalFormViews({ - views: [{ name: 'task.form', object: 'task', viewKind: 'form', isDefault: true, config: { sections } }], - pages: [{ - name: 'home', - regions: [{ name: 'main', components: [ - { type: 'element:button', properties: { label: 'New', action: { name: 'new_task', type: 'form', target: 'task.form' } } }, - ] }], - }], - }); - expect(findings).toEqual([]); - }); - - it('CONTROL: a short or interpolated target, or a non-form action with the same target, exempts nothing', () => { - for (const action of [ - { name: 'a', type: 'form', target: 'form' }, - { name: 'a', type: 'form', target: '{record.form_name}' }, - { name: 'a', type: 'modal', target: 'account.form' }, - { name: 'a', type: 'url', target: '/forms/account.form' }, - ]) { - const findings = validateInternalFormViews({ views: [container], actions: [action] }); - expect(findings.map((f) => f.where), JSON.stringify(action)).toContain('view "account" · form'); - } - }); -}); diff --git a/packages/lint/src/validate-internal-form-views.ts b/packages/lint/src/validate-internal-form-views.ts deleted file mode 100644 index c2e22aa6642..00000000000 --- a/packages/lint/src/validate-internal-form-views.ts +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * `form-view-internal-not-loaded` — an app still declares an internal create or - * edit form (#36425). - * - * The Console's record create and edit surfaces (the create dialog, the - * full-page create, a create or edit an action opens, the edit dialog) no - * longer load an object's form view. They lay out by the object's - * `fieldGroups` and follow the rules on its fields (`visibleWhen`, - * `readonlyWhen`, `requiredWhen`, `required`, `showOnCreate`). A declared - * internal form still parses, installs and runs; it steers nothing. This rule - * says so, once per form, as a warning: nothing is broken, and the app keeps - * working. - * - * ## Which forms are internal create / edit forms - * - * The ones those surfaces used to load, and only those: - * - * - a view container's default `form`, and its `formViews.default` (the - * legacy container shape) — what create and edit opened; - * - its `formViews.create` — what a create opened when declared; - * - a stored form ViewItem (`{ name, object, viewKind: 'form', config }`) that - * carries `isDefault: true`, or is named `OBJECT.create`. - * - * A form shared publicly (`sharing.enabled: true`) is a public form, which - * keeps loading at its own link: never reported. That is the one test for a - * public form. A form view under any other name is a NAMED form, which an - * action of type `form` opens by its name and which keeps loading: never - * reported either. - * - * ## A default or create form an action opens by name (#36545) - * - * Seat ruling 5 on #36425: "A form an action opens by name (action type - * `form`, `/forms/:name`, `/apps/:app/forms/:name`) is not the object's create - * or edit form and keeps loading." So a default or `OBJECT.create` form that - * some `type: 'form'` action in the stack targets is not reported either. - * - * "By name" is matched the way the Console resolves it, and no looser: the - * action runner routes the target to `/forms/:name` and `FormPage` reads - * `/meta/view/:name` with that string, so the target must EQUAL the name the - * form is served under. A stored item is served under its own `name`; a - * container's form is served under the name the spec's own expansion gives it - * ({@link servedFormNames}: `expandViewContainer`, collisions included, on the - * object `deriveViewContainerObject` binds), never a hand-built - * `.`. An interpolated target names no form statically and - * exempts nothing. The actions read are the registered ones (`actions[]`, - * `objects[].actions[]`) and a page component's inline `properties.action`. - */ - -import { - deriveViewContainerObject, - expandViewContainer, - isAggregatedViewContainer, -} from '@objectstack/spec'; -import { collectionEntries } from './collection-entries.js'; -import { recordsOf } from './object-graph.js'; -import { walkPageComponents } from './page-walk.js'; -import { formViewSites, viewObjectName } from './view-walk.js'; - -export const FORM_VIEW_INTERNAL_NOT_LOADED = 'form-view-internal-not-loaded'; - -export interface InternalFormViewFinding { - /** Always `warning`: the form is inert, and nothing fails. */ - severity: 'warning'; - rule: typeof FORM_VIEW_INTERNAL_NOT_LOADED; - /** Human-readable location, e.g. `view "account" · form`. */ - where: string; - /** Config path of the form, e.g. `views[2].formViews.create`. */ - path: string; - message: string; - hint: string; -} - -type AnyRec = Record; - -function isRec(v: unknown): v is AnyRec { - return !!v && typeof v === 'object' && !Array.isArray(v); -} - -function strName(v: unknown): string | undefined { - return typeof v === 'string' && v.length > 0 ? v : undefined; -} - -/** The card's one test for a public form: `sharing.enabled === true`. */ -function isPublicForm(form: AnyRec): boolean { - return isRec(form.sharing) && form.sharing.enabled === true; -} - -/** - * The literal target of a `type: 'form'` action — the view name the Console - * opens — or `undefined` for any other action and for an interpolated target. - */ -function formActionTarget(action: unknown): string | undefined { - if (!isRec(action) || action.type !== 'form') return undefined; - const target = strName(action.target); - return target && !target.includes('{') ? target : undefined; -} - -/** - * Every view name a `type: 'form'` action in the stack opens: registered - * actions (top-level and object-bound) and the inline action a page component - * carries (`properties.action`, e.g. an `element:button`). - */ -function formNamesOpenedByAction(stack: AnyRec): Set { - const opened = new Set(); - const add = (action: unknown) => { - const target = formActionTarget(action); - if (target) opened.add(target); - }; - for (const action of recordsOf(stack.actions)) add(action); - for (const obj of recordsOf(stack.objects)) { - for (const action of recordsOf(obj.actions)) add(action); - } - const pages = recordsOf(stack.pages); - for (let i = 0; i < pages.length; i++) { - for (const { component } of walkPageComponents(pages[i], `pages[${i}]`)) { - if (isRec(component.properties)) add(component.properties.action); - } - } - return opened; -} - -/** - * The names a view container's forms are served under, keyed by the site's - * `surface` (`form`, `formViews.KEY`): the spec's own expansion, run on the - * object the registrars bind the container to. Empty when the container binds - * no object, which the runtime does not expand either. - */ -function servedFormNames(view: AnyRec): Map { - const names = new Map(); - if (!isAggregatedViewContainer(view)) return names; - const object = deriveViewContainerObject(view); - if (!object) return names; - const forms = expandViewContainer(object, view).filter((item) => item.viewKind === 'form'); - // The expansion serves each `formViews` entry that is an object, in key - // order (its own skip test, copied), then `form` (the one item flagged - // `isDefault`). - const named = forms.filter((item) => item.isDefault !== true); - const keys = view.formViews && typeof view.formViews === 'object' - ? Object.entries(view.formViews).filter(([, v]) => !!v && typeof v === 'object').map(([k]) => k) - : []; - keys.forEach((key, i) => { - if (named[i]) names.set(`formViews.${key}`, named[i].name); - }); - const defaultForm = forms.find((item) => item.isDefault === true); - if (defaultForm) names.set('form', defaultForm.name); - return names; -} - -/** What the author reads: the card's sentence, the same at every site. */ -const HINT = - 'Internal forms are no longer loaded: use field groups (`fieldGroups`) for sections, and put required ' + - 'and show/hide rules on the fields (`required`, `requiredWhen`, `visibleWhen`, `showOnCreate`). The ' + - 'form still installs and runs, and changes nothing. A form shared publicly (`sharing.enabled: true`) ' + - 'keeps loading.'; - -/** - * Report every internal create / edit form view the stack declares. Returns - * findings (empty = none). Advisory only: the caller must never fail on these. - */ -export function validateInternalFormViews(stack: AnyRec): InternalFormViewFinding[] { - const findings: InternalFormViewFinding[] = []; - const openedByAction = formNamesOpenedByAction(stack); - - for (const { rec: view, path: viewPath } of collectionEntries(stack.views, 'views')) { - // A container carries no name of its own: it is named by the object its - // default form or list binds, so a finding reads the same wherever the - // container sits in `views[]`. - const viewName = - strName(view.name) - ?? viewObjectName(view) - ?? (isRec(view.form) ? viewObjectName(view.form) : undefined) - ?? (isRec(view.list) ? viewObjectName(view.list) : undefined) - ?? viewPath; - // `served` is the name the Console opens the form under, when it has one. - const sites: Array<{ form: AnyRec; path: string; surface: string; served?: string }> = []; - const served = servedFormNames(view); - - for (const site of formViewSites(view, viewPath)) { - if (site.kind === 'form') { - sites.push({ form: site.view, path: site.path, surface: site.surface, served: served.get(site.surface) }); - } else if (site.kind === 'formView') { - const key = site.surface.slice('formViews.'.length); - if (key === 'create' || key === 'default') { - sites.push({ form: site.view, path: site.path, surface: site.surface, served: served.get(site.surface) }); - } - } - } - - // A stored form ViewItem: the default form (`isDefault`), or the object's - // `create` form, by the name the Console looked it up under. - if (view.viewKind === 'form') { - const object = viewObjectName(view); - const isCreate = !!object && view.name === `${object}.create`; - if (view.isDefault === true || isCreate) { - const form = isRec(view.config) ? view.config : view; - const path = isRec(view.config) ? `${viewPath}.config` : viewPath; - sites.push({ form, path, surface: isRec(view.config) ? 'config' : '', served: strName(view.name) }); - } - } - - for (const site of sites) { - if (isPublicForm(site.form)) continue; - // Opened by name by a `type: 'form'` action: it keeps loading (#36545). - if (site.served && openedByAction.has(site.served)) continue; - const where = site.surface ? `view "${viewName}" · ${site.surface}` : `view "${viewName}"`; - findings.push({ - severity: 'warning', - rule: FORM_VIEW_INTERNAL_NOT_LOADED, - where, - path: site.path, - message: - `${where}: this internal create/edit form is no longer loaded — create and edit lay the ` + - `object out by its field groups and follow the rules on its fields`, - hint: HINT, - }); - } - } - - return findings; -} diff --git a/packages/lint/src/validate-predicate-path-refs.test.ts b/packages/lint/src/validate-predicate-path-refs.test.ts index 3d24ecc9eca..9e5e0eb168f 100644 --- a/packages/lint/src/validate-predicate-path-refs.test.ts +++ b/packages/lint/src/validate-predicate-path-refs.test.ts @@ -249,28 +249,41 @@ describe('validatePredicatePathRefs — deliberate boundaries', () => { }); describe('validatePredicatePathRefs — traversal reach', () => { - it('reaches `formViews.` and the container `form` (#6381 ladder)', () => { + it('reaches the entry\'s own rung; a container\'s retired `form` and `formViews` slots are none (#6381 ladder, ADR-0159 D7)', () => { const bad = { fields: [{ field: 'x', visibleWhen: "data.tpye == 'a'" }] }; + const schemaBound = { data: { provider: 'schema', schemaId: 'demo' }, sections: [bad] }; const findings = validatePredicatePathRefs( { views: [ - { - name: 'demo', - form: { data: { provider: 'schema', schemaId: 'demo' }, sections: [bad] }, - formViews: { - edit: { data: { provider: 'schema', schemaId: 'demo' }, sections: [bad] }, - }, - }, + // The retired slots: refused by the parse at their own keys, and no + // rung of the walk. + { name: 'demo', form: schemaBound, formViews: { edit: schemaBound } }, + // The one rung left: the entry itself, a schema-bound form view. + { name: 'demo_form', ...schemaBound }, ], }, { resolveSchema }, ); expect(findings.map((f) => f.path)).toEqual([ - 'views[0].form.sections[0].fields[0].visibleWhen', - 'views[0].formViews.edit.sections[0].fields[0].visibleWhen', + 'views[1].sections[0].fields[0].visibleWhen', ]); }); + it('judges no `forms[]` item: a form item binds an object by `object`, never a schema', () => { + // A form item declares no `data` (the spec refuses the key by name), so it + // names no schema a `data.` path could be resolved against. Paired with the + // same section on a schema-bound form view, which is judged. + const bad = { fields: [{ field: 'x', visibleWhen: "data.tpye == 'a'" }] }; + const findings = validatePredicatePathRefs( + { + forms: [{ name: 'demo.intake', object: 'demo', sections: [bad] }], + views: [{ name: 'demo_form', data: { provider: 'schema', schemaId: 'demo' }, sections: [bad] }], + }, + { resolveSchema }, + ); + expect(findings.map((f) => f.path)).toEqual(['views[0].sections[0].fields[0].visibleWhen']); + }); + it('does not read the retired `visibleOn` key; the same value under `visibleWhen` is judged (#23543 F4)', () => { // The spec refuses the key by name before any door runs this rule. expect(run(form([{ fields: [{ field: 'x', visibleOn: "data.tpye == 'a'" }] }]))).toEqual([]); @@ -499,8 +512,11 @@ describe('registry wiring', () => { // page write draws nothing from it, and the declaration keeps the family on // one type set. #28663 — and `app`, for the same reason: the family's // sibling judges a nav entry's `visible`, this rule judges nothing there. + // [ADR-0159 D9] — and `form` in place of `view`: the sibling judges a form + // item's predicates, this rule judges no form item, and a view holds lists + // only, so neither has anything to judge on a view write. expect([...entry!.surfaces]).toEqual(['cli', 'runtime-publish']); - expect([...entry!.runtimeTypes!]).toEqual(['view', 'page', 'app']); + expect([...entry!.runtimeTypes!]).toEqual(['form', 'page', 'app']); expect(entry!.surfaceReason).toBeUndefined(); }); }); diff --git a/packages/lint/src/validate-predicate-path-refs.ts b/packages/lint/src/validate-predicate-path-refs.ts index e46a78c451c..25f79cc6e2e 100644 --- a/packages/lint/src/validate-predicate-path-refs.ts +++ b/packages/lint/src/validate-predicate-path-refs.ts @@ -795,8 +795,8 @@ function walkFields( * declare (#7010). * * Walks `views[]` through the shared {@link formViewSites} ladder — the entry - * itself (the bare `defineMetadataForm` shape every `*.metadata-form.ts` uses), the container's - * default `form`, and each `formViews.` — and judges only the sites whose + * itself, the bare `defineMetadataForm` shape every `*.metadata-form.ts` uses — + * and judges only the sites whose * data source is `{ provider: 'schema', schemaId }`, resolving `schemaId` * through `opts.resolveSchema` (the canonical metadata-type registry by * default). A site bound to an ObjectQL object, or naming a `schemaId` no schema diff --git a/packages/lint/src/validate-public-form-file-fields.test.ts b/packages/lint/src/validate-public-form-file-fields.test.ts index 911a594ee81..708e565f04f 100644 --- a/packages/lint/src/validate-public-form-file-fields.test.ts +++ b/packages/lint/src/validate-public-form-file-fields.test.ts @@ -4,8 +4,12 @@ // file field is refused at validate, compile and the publish gate, naming the // field. Pins both doors: the rule over a whole stack (what the three CLI // commands run through `authoring-rules.ts`), and the runtime publish gate on a -// `view` write (`runRuntimeAuthoringRules`, the function the metadata write +// `form` write (`runRuntimeAuthoringRules`, the function the metadata write // path calls) resolving the field's type against its `objects` context. +// +// [ADR-0159 D9] A form is a `forms[]` item from protocol 19, so that is the +// shape every case here authors. The shapes a view held a form in are refused +// by the parse at their own keys, and are pinned below as no site of this rule. import { readFileSync } from 'node:fs'; @@ -30,84 +34,96 @@ const supplier = { const OPEN = { enabled: true, allowAnonymous: true, publicLink: '/forms/apply' }; -const formOf = (fields: unknown[], sharing: Record = OPEN, bucket = 'sections') => ({ +const formOf = (fields: unknown[], sharing: Record = OPEN, bucket = 'sections'): Record => ({ + name: 'supplier_application.apply', + object: 'supplier_application', type: 'simple', - data: { provider: 'object', object: 'supplier_application' }, [bucket]: [{ name: 'about', fields }], sharing, }); -const stackOf = (view: Record, objects: unknown = [supplier]) => ({ objects, views: [view] }); +const stackOf = (form: Record, objects: unknown = [supplier]) => ({ objects, forms: [form] }); describe('validatePublicFormFileFields — the stack rule the CLI commands run', () => { - it('refuses a `{ field }` entry naming a file field on a public formViews entry', () => { - const findings = validatePublicFormFileFields(stackOf({ - name: 'supplier_views', - formViews: { apply: formOf([{ field: 'company' }, { field: 'certificate', required: true }]) }, - })); + it('refuses a `{ field }` entry naming a file field on a public form', () => { + const findings = validatePublicFormFileFields(stackOf( + formOf([{ field: 'company' }, { field: 'certificate', required: true }]), + )); expect(findings).toHaveLength(1); expect(findings[0]).toMatchObject({ severity: 'error', rule: PUBLIC_FORM_FILE_FIELD, - where: 'view "supplier_views" · formViews.apply', - path: 'views[0].formViews.apply.sections[0].fields[1]', + where: 'form "supplier_application.apply"', + path: 'forms[0].sections[0].fields[1]', }); expect(findings[0].message).toContain('"certificate"'); }); it('refuses a bare field name, and every file field in a section, each at its own entry', () => { - const findings = validatePublicFormFileFields(stackOf({ - name: 'supplier_views', - form: formOf(['logo', 'company', 'certificate']), - })); + const findings = validatePublicFormFileFields(stackOf( + formOf(['logo', 'company', 'certificate']), + )); expect(findings.map((f) => f.path)).toEqual([ - 'views[0].form.sections[0].fields[0]', - 'views[0].form.sections[0].fields[2]', + 'forms[0].sections[0].fields[0]', + 'forms[0].sections[0].fields[2]', ]); }); it('refuses a file field in a later section and in the legacy `groups` bucket', () => { const form = formOf(['company']); (form.sections as unknown[]).push({ name: 'documents', fields: [{ field: 'certificate' }] }); - expect(validatePublicFormFileFields(stackOf({ name: 'v', form })).map((f) => f.path)) - .toEqual(['views[0].form.sections[1].fields[0]']); - expect(validatePublicFormFileFields(stackOf({ name: 'v', form: formOf(['certificate'], OPEN, 'groups') })) - .map((f) => f.path)).toEqual(['views[0].form.groups[0].fields[0]']); + expect(validatePublicFormFileFields(stackOf(form)).map((f) => f.path)) + .toEqual(['forms[0].sections[1].fields[0]']); + expect(validatePublicFormFileFields(stackOf(formOf(['certificate'], OPEN, 'groups'))) + .map((f) => f.path)).toEqual(['forms[0].groups[0].fields[0]']); }); - it('refuses on the flattened `viewKind: form` item', () => { - const findings = validatePublicFormFileFields(stackOf({ - name: 'supplier_apply', - viewKind: 'form', - config: formOf(['certificate']), - })); - expect(findings.map((f) => f.path)).toEqual(['views[0].config.sections[0].fields[0]']); + it('refuses on the form item a save writes, and reads no form out of the shapes a view held one in', () => { + // [ADR-0159 D2] The item a save writes: the body at the top level, no + // `config` wrapper. Under protocol 18 this was the flattened + // `viewKind: 'form'` view item, its form under `config`. + const findings = validatePublicFormFileFields(stackOf(formOf(['certificate']))); + expect(findings.map((f) => f.path)).toEqual(['forms[0].sections[0].fields[0]']); + // [ADR-0159 D7] The retired shapes: each is refused by the parse at its own + // key, and none is a site of this rule. + const { name: _name, object: _object, ...body } = formOf(['certificate']); + const held = { ...body, data: { provider: 'object', object: 'supplier_application' } }; + expect(validatePublicFormFileFields({ + objects: [supplier], + views: [ + { name: 'supplier_apply', viewKind: 'form', config: held }, + { name: 'supplier_views', form: held, formViews: { apply: held } }, + ], + })).toEqual([]); }); it('refuses every FILE_REFERENCE_TYPES type, and only those', () => { for (const type of FILE_REFERENCE_TYPES) { const object = { name: 'supplier_application', fields: { attachment: { type } } }; - const findings = validatePublicFormFileFields(stackOf({ name: 'v', form: formOf(['attachment']) }, [object])); + const findings = validatePublicFormFileFields(stackOf(formOf(['attachment']), [object])); expect(findings, type).toHaveLength(1); } for (const type of ['text', 'textarea', 'url', 'json', 'lookup']) { const object = { name: 'supplier_application', fields: { attachment: { type } } }; - expect(validatePublicFormFileFields(stackOf({ name: 'v', form: formOf(['attachment']) }, [object])), type) + expect(validatePublicFormFileFields(stackOf(formOf(['attachment']), [object])), type) .toEqual([]); } }); it('reads an object whose fields are a list', () => { const object = { name: 'supplier_application', fields: [{ name: 'certificate', type: 'file' }] }; - expect(validatePublicFormFileFields(stackOf({ name: 'v', form: formOf(['certificate']) }, [object]))) + expect(validatePublicFormFileFields(stackOf(formOf(['certificate']), [object]))) .toHaveLength(1); }); - it('resolves the object from the view when the form names none', () => { - const form: Record = formOf(['certificate']); - delete form.data; - expect(validatePublicFormFileFields(stackOf({ name: 'v', object: 'supplier_application', formViews: { apply: form } }))) - .toHaveLength(1); + it('resolves the object from the item\'s own `object`, the one binding a form item has', () => { + // A form item declares no `data`; `object` alone names what it submits into. + const form = formOf(['certificate']); + expect(form.data).toBeUndefined(); + expect(validatePublicFormFileFields(stackOf(form))).toHaveLength(1); + // An item naming no object resolves no field type, so nothing is judged. + const { object: _object, ...unbound } = form; + expect(validatePublicFormFileFields(stackOf(unbound))).toEqual([]); }); it('passes a form that is not open to anonymous intake, whichever switch is off', () => { @@ -117,61 +133,59 @@ describe('validatePublicFormFileFields — the stack rule the CLI commands run', { enabled: true, allowAnonymous: true }, { allowAnonymous: true, publicLink: '/forms/apply' }, ]) { - expect(validatePublicFormFileFields(stackOf({ name: 'v', form: formOf(['certificate'], sharing) }))) + expect(validatePublicFormFileFields(stackOf(formOf(['certificate'], sharing)))) .toEqual([]); } }); it('passes a public form that declares no file field', () => { - expect(validatePublicFormFileFields(stackOf({ name: 'v', form: formOf(['company', { field: 'email' }]) }))) + expect(validatePublicFormFileFields(stackOf(formOf(['company', { field: 'email' }])))) .toEqual([]); }); it('does not judge a form whose object or field does not resolve', () => { - expect(validatePublicFormFileFields(stackOf({ name: 'v', form: formOf(['certificate']) }, []))).toEqual([]); - expect(validatePublicFormFileFields(stackOf({ name: 'v', form: formOf(['not_a_field']) }))).toEqual([]); + expect(validatePublicFormFileFields(stackOf(formOf(['certificate']), []))).toEqual([]); + expect(validatePublicFormFileFields(stackOf(formOf(['not_a_field'])))).toEqual([]); }); - it('is registered gating, on all three commands and on the publish gate for view writes', () => { + it('is registered gating, on all three commands and on the publish gate for form writes', () => { const entry = AUTHORING_RULES.find((r) => r.name === 'validatePublicFormFileFields'); expect(entry).toMatchObject({ tier: 'gating', commands: ['validate', 'build', 'lint'], surfaces: ['cli', 'runtime-publish'], - runtimeTypes: ['view'], + runtimeTypes: ['form'], }); }); }); -describe('the runtime publish gate on a view write', () => { +describe('the runtime publish gate on a form write', () => { const gate = (item: unknown) => - runRuntimeAuthoringRules({ type: 'view', item, context: { objects: [supplier] } }); + runRuntimeAuthoringRules({ type: 'form', item, context: { objects: [supplier] } }); it('refuses the publish as an error at the field entry, resolving the type from the objects context', () => { - const { errors } = gate({ - name: 'supplier_views', - formViews: { apply: formOf([{ field: 'company' }, { field: 'certificate' }]) }, - }); + const { errors } = gate(formOf([{ field: 'company' }, { field: 'certificate' }])); const finding = errors.find((e) => e.rule === PUBLIC_FORM_FILE_FIELD); expect(finding, JSON.stringify(errors)).toBeDefined(); - expect(finding!.path).toContain('formViews.apply.sections[0].fields[1]'); + expect(finding!.path).toContain('sections[0].fields[1]'); }); it('admits the same form once the file field is off it', () => { - const { errors } = gate({ - name: 'supplier_views', - formViews: { apply: formOf([{ field: 'company' }, { field: 'email' }]) }, - }); + const { errors } = gate(formOf([{ field: 'company' }, { field: 'email' }])); expect(errors.filter((e) => e.rule === PUBLIC_FORM_FILE_FIELD)).toEqual([]); }); }); -describe('the object a candidate submits into is the doors\' own function', () => { +describe('the object a form submits into is the item\'s own `object`', () => { const source = readFileSync(new URL('./validate-public-form-file-fields.ts', import.meta.url), 'utf8'); - it('imports anonymousFormObjectName from @objectstack/spec/ui and keeps no retyped rung order', () => { - expect(source).toMatch(/anonymousFormObjectName,[\s\S]*?\} from '@objectstack\/spec\/ui'/); + it('asks the doors\' own function whether a form is open, and keeps no retyped rung order', () => { + // Openness is `anonymousFormIntakeSlug`, the function the anonymous doors + // answer with. The object is `form.object`: a form item has one binding, so + // there is no rung order to retype and no view-held candidate to enumerate. + expect(source).toMatch(/anonymousFormIntakeSlug \} from '@objectstack\/spec\/ui'/); expect(source).not.toContain('candidateObjectName'); expect(source).not.toContain('viewObjectName'); + expect(source).not.toContain('anonymousFormIntakeCandidates'); }); }); diff --git a/packages/lint/src/validate-public-form-file-fields.ts b/packages/lint/src/validate-public-form-file-fields.ts index 86a03739c7e..ac129fb7dd9 100644 --- a/packages/lint/src/validate-public-form-file-fields.ts +++ b/packages/lint/src/validate-public-form-file-fields.ts @@ -5,12 +5,12 @@ * (ruling C on #25572: a guest form takes no attachment, and there is no guest * upload door). * - * A form view is open to anonymous intake when its `sharing` declares - * `enabled: true`, `allowAnonymous: true` and a `publicLink`. Which form - * candidates of a view that opens is ONE rule, `anonymousFormIntakeCandidates` - * (`@objectstack/spec/ui`), the same function both anonymous doors - * (`GET /forms/:slug`, `POST /forms/:slug/submit`) serve from, so this rule - * judges exactly the forms a visitor can reach and no other. + * A form is open to anonymous intake when its `sharing` declares + * `enabled: true`, `allowAnonymous: true` and a `publicLink`. That reading is + * ONE rule, `anonymousFormIntakeSlug` (`@objectstack/spec/ui`), the same + * function both anonymous doors (`GET /forms/:slug`, + * `POST /forms/:slug/submit`) admit a form by, so this rule judges exactly the + * forms a visitor can reach and no other. * * Such a form collects the fields its sections declare: a section field entry * is a bare field name or `{ field }`, and both doors read the same two @@ -26,15 +26,19 @@ * * ## Where it runs * - * A field's type lives on the object and the `sharing` on the view, so the + * A field's type lives on the object and the `sharing` on the form, so the * rule needs both. It is a stack-level authoring rule (`authoring-rules.ts`): * `os validate`, `os build` and `os lint` run it over the whole stack, and the - * runtime publish gate runs it on a `view` write, whose snapshot carries the + * runtime publish gate runs it on a `form` write, whose snapshot carries the * `objects` collection as resolution context (`runtime-gate.ts`). An `object` - * write's snapshot carries no views, so changing a field's type under a - * published public form is caught by the CLI commands and by that view's next + * write's snapshot carries no forms, so changing a field's type under a + * published public form is caught by the CLI commands and by that form's next * publish, not by the object's own write. * + * [ADR-0159 D9] The forms judged are the `forms[]` items: from protocol 19 a + * form is its own item and a view holds lists only, so no form is read out of + * a `views[]` entry. + * * Both section spellings are read, `sections` and the legacy `groups` alias * (folded onto `sections` at parse), because `os lint` hands this rule the * unparsed stack. A form whose bound object, or whose field, does not resolve @@ -44,12 +48,7 @@ */ import { FILE_REFERENCE_TYPES } from '@objectstack/spec/data'; -import { - anonymousFormIntakeCandidates, - anonymousFormIntakeSlug, - anonymousFormObjectName, - type AnonymousFormIntakeCandidate, -} from '@objectstack/spec/ui'; +import { anonymousFormIntakeSlug } from '@objectstack/spec/ui'; import { collectionEntries } from './collection-entries.js'; import { objectsAsServed, objectsWithoutTiedFields, recordsOf } from './object-graph.js'; @@ -60,9 +59,9 @@ export interface PublicFormFileFieldFinding { severity: 'error'; /** Diagnostic rule id: always {@link PUBLIC_FORM_FILE_FIELD}. */ rule: string; - /** Human-readable location, e.g. `view "supplier_intake" · formViews.apply`. */ + /** Human-readable location, e.g. `form "supplier.apply"`. */ where: string; - /** Config path of the section field entry, e.g. `views[0].formViews.apply.sections[1].fields[2]`. */ + /** Config path of the section field entry, e.g. `forms[0].sections[1].fields[2]`. */ path: string; message: string; hint: string; @@ -112,15 +111,6 @@ function indexFieldTypes(stack: AnyRec): Map> { return idx; } -/** Where a candidate sits in its view: `form`, `formViews.KEY` or `config`. */ -function candidateSlot(view: AnyRec, candidate: AnonymousFormIntakeCandidate): string { - if (candidate.form === view.form) return 'form'; - if (candidate.key !== undefined && isRec(view.formViews) && view.formViews[candidate.key] === candidate.form) { - return `formViews.${candidate.key}`; - } - return 'config'; -} - /** A section field entry is a bare field name or `{ field, … }`. */ function fieldNameOf(entry: unknown): string | undefined { if (typeof entry === 'string') return strName(entry); @@ -132,47 +122,8 @@ export function validatePublicFormFileFields(stack: AnyRec): PublicFormFileField const findings: PublicFormFileFieldFinding[] = []; const fieldTypes = indexFieldTypes(stack); - for (const { rec: view, path: viewPath } of collectionEntries(stack.views, 'views')) { - const viewName = strName(view.name) ?? strName(view.object) ?? viewPath; - for (const candidate of anonymousFormIntakeCandidates(view)) { - const objectName = anonymousFormObjectName(view, candidate.form); - const types = objectName ? fieldTypes.get(objectName) : undefined; - if (!types) continue; - const slot = candidateSlot(view, candidate); - const where = `view "${viewName}" · ${slot}`; - - for (const bucket of ['sections', 'groups'] as const) { - const sections = Array.isArray(candidate.form[bucket]) ? (candidate.form[bucket] as unknown[]) : []; - for (let s = 0; s < sections.length; s++) { - const section = sections[s]; - const entries = isRec(section) && Array.isArray(section.fields) ? (section.fields as unknown[]) : []; - for (let f = 0; f < entries.length; f++) { - const fieldName = fieldNameOf(entries[f]); - const type = fieldName ? types.get(fieldName) : undefined; - if (!fieldName || !type || !FILE_REFERENCE_TYPES.has(type)) continue; - findings.push({ - severity: 'error', - rule: PUBLIC_FORM_FILE_FIELD, - where, - path: `${viewPath}.${slot}.${bucket}[${s}].fields[${f}]`, - message: - `${viewName}: the form at ${slot} is open to anonymous intake (its sharing publishes ` + - `/forms/${candidate.slug} with allowAnonymous: true) and declares "${fieldName}", a ` + - `${type} field on object "${objectName}". A public form takes no attachment: an ` + - `anonymous visitor has no upload door, so this field can never be filled.`, - hint: - `Take "${fieldName}" off this public form. To collect a file from a visitor, have ` + - `them register and sign in, then fill a form that is not open to anonymous intake ` + - `and declares "${fieldName}".`, - }); - } - } - } - } - } - - // [ADR-0159] …and every authored `form` item open to anonymous intake, the - // same judgement at the form's own root. + // [ADR-0159 D9] Every `form` item open to anonymous intake, judged at the + // form's own root. for (const { rec: form, path: formPath } of collectionEntries(stack.forms, 'forms')) { const formName = strName(form.name) ?? formPath; const slug = anonymousFormIntakeSlug(form.sharing); diff --git a/packages/lint/src/validate-sortable-fields.test.ts b/packages/lint/src/validate-sortable-fields.test.ts index cde175f725c..760e497e7e4 100644 --- a/packages/lint/src/validate-sortable-fields.test.ts +++ b/packages/lint/src/validate-sortable-fields.test.ts @@ -20,7 +20,7 @@ import { indexObjectSortability, } from './validate-sortable-fields.js'; import { resolveObjectSortability } from '@objectstack/spec/api'; -import { COLUMN_SUMMARY_AGGREGATION, ComponentPropsMap } from '@objectstack/spec/ui'; +import { COLUMN_SUMMARY_AGGREGATION, ComponentPropsMap, ViewItemSchema } from '@objectstack/spec/ui'; import { LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED, validateListViewFieldRefs } from './validate-list-view-field-refs.js'; import { runRuntimeAuthoringRules } from './runtime-gate.js'; import { indexObjectSearchTargets } from './validate-searchable-fields.js'; @@ -435,18 +435,27 @@ describe('validateSortableFields — the surfaces it walks', () => { it('a FORM record\'s config is not judged — the rung keys on viewKind \'list\' (#10001)', () => { // `FormViewSchema` declares no `sort`; a stray one riding in the stored // body (the store keeps the original) must not be judged by a list rule. + // + // [ADR-0159 D7] Protocol 19 refuses `viewKind: 'form'` at parse, the + // prescription naming `forms:`; the record is authored as the `form` item + // it became, and the 18 record, refused, is still not judged when a stored + // row hands it over unparsed. const findings = validateSortableFields({ objects: [{ name: 'crm_lead', fields }], - views: [ - { - name: 'crm_lead.edit', - object: 'crm_lead', - viewKind: 'form', - config: { type: 'simple', sort: [{ field: 'score', order: 'desc' }] }, - }, - ], + forms: [{ name: 'crm_lead.edit', object: 'crm_lead', type: 'simple', sort: [{ field: 'score', order: 'desc' }] }], }); expect(findings).toEqual([]); + + const record = { + name: 'crm_lead.edit', + object: 'crm_lead', + viewKind: 'form', + config: { type: 'simple', sort: [{ field: 'score', order: 'desc' }] }, + }; + const parsed = ViewItemSchema.safeParse(record); + expect(parsed.success).toBe(false); + expect(parsed.error?.issues.map((issue) => issue.message).join('\n')).toContain('forms:'); + expect(validateSortableFields({ objects: [{ name: 'crm_lead', fields }], views: [record] })).toEqual([]); }); it('each list-view rung is judged exactly once — no rung double-judges another\'s shape (#10001)', () => { @@ -493,13 +502,21 @@ describe('validateSortableFields — the surfaces it walks', () => { it('a form overlay has no sort surface and is not judged (#9313)', () => { // `FormViewSchema` tombstones `sort` — a related list sorts by its own // list view's sort — so the rung keys on `viewKind: 'list'` alone. + // + // [ADR-0159 D7] Protocol 19 refuses the form overlay at parse, the + // prescription naming `forms:`; the form is authored as a `form` item, and + // the 18 overlay, refused, is still not judged when handed over unparsed. const findings = validateSortableFields({ objects: [{ name: 'crm_lead', fields }], - views: [ - { name: 'crm_lead.edit', object: 'crm_lead', viewKind: 'form', sort: 'score desc' }, - ], + forms: [{ name: 'crm_lead.edit', object: 'crm_lead', sort: 'score desc' }], }); expect(findings).toEqual([]); + + const overlay = { name: 'crm_lead.edit', object: 'crm_lead', viewKind: 'form', sort: 'score desc' }; + const parsed = ViewItemSchema.safeParse(overlay); + expect(parsed.success).toBe(false); + expect(parsed.error?.issues.map((issue) => issue.message).join('\n')).toContain('forms:'); + expect(validateSortableFields({ objects: [{ name: 'crm_lead', fields }], views: [overlay] })).toEqual([]); }); }); diff --git a/packages/lint/src/validate-thank-you-record-fields.test.ts b/packages/lint/src/validate-thank-you-record-fields.test.ts index 479d50660e6..fe03383e165 100644 --- a/packages/lint/src/validate-thank-you-record-fields.test.ts +++ b/packages/lint/src/validate-thank-you-record-fields.test.ts @@ -3,7 +3,7 @@ // Ruling B on #28005: a form's thank-you panel may name, as // `{{record.field_name}}`, only a field the engine generates on insert // (`RUNTIME_OWNED_FIELD_TYPES`). Pins the stack rule the three CLI commands run, -// the runtime publish gate on `view` and `page` writes, and that the admitted +// the runtime publish gate on `form` and `page` writes, and that the admitted // set is the spec's one set and no list of this rule's own. import { readFileSync } from 'node:fs'; @@ -28,34 +28,34 @@ const support = { const panel = (message: string) => ({ kind: 'thank-you', title: 'Thank you', message }); -const formOf = (message: string) => ({ +/** [ADR-0159 D2] A `forms[]` item: bound by its own `object`, its body at the top level. */ +const formOf = (message: string, key = 'intake'): Record => ({ + name: `support_case.${key}`, + object: 'support_case', type: 'simple', - data: { provider: 'object', object: 'support_case' }, sections: [{ name: 'about', fields: ['subject'] }], submitBehavior: panel(message), }); -const stackOf = (view: Record, objects: unknown = [support]) => ({ objects, views: [view] }); +const stackOf = (form: Record, objects: unknown = [support]) => ({ objects, forms: [form] }); describe('validateThankYouRecordFields — the stack rule the CLI commands run', () => { it('admits an autonumber field', () => { - expect(validateThankYouRecordFields(stackOf({ - name: 'case_views', - form: formOf('Your case number is {{record.case_number}}.'), - }))).toEqual([]); + expect(validateThankYouRecordFields(stackOf( + formOf('Your case number is {{record.case_number}}.'), + ))).toEqual([]); }); it('refuses a text field, naming the field, its type and the reason', () => { - const findings = validateThankYouRecordFields(stackOf({ - name: 'case_views', - formViews: { intake: formOf('We got {{record.subject}} as {{record.case_number}}') }, - })); + const findings = validateThankYouRecordFields(stackOf( + formOf('We got {{record.subject}} as {{record.case_number}}'), + )); expect(findings).toHaveLength(1); expect(findings[0]).toMatchObject({ severity: 'error', rule: THANK_YOU_RECORD_FIELD, - where: 'view "case_views" · formViews.intake', - path: 'views[0].formViews.intake.submitBehavior', + where: 'form "support_case.intake"', + path: 'forms[0].submitBehavior', }); expect(findings[0].message).toContain('{{record.subject}}'); expect(findings[0].message).toContain('a text field'); @@ -63,17 +63,16 @@ describe('validateThankYouRecordFields — the stack rule the CLI commands run', }); it('refuses a formula field the same way', () => { - const findings = validateThankYouRecordFields(stackOf({ name: 'v', form: formOf('{{record.priority_score}}') })); + const findings = validateThankYouRecordFields(stackOf(formOf('{{record.priority_score}}'))); expect(findings).toHaveLength(1); expect(findings[0].message).toContain('{{record.priority_score}}'); expect(findings[0].message).toContain('a formula field'); }); it('refuses a name the object does not declare, and an injected system column', () => { - const findings = validateThankYouRecordFields(stackOf({ - name: 'v', - form: formOf('{{record.no_such_field}} {{record.created_at}} {{record.id}}'), - })); + const findings = validateThankYouRecordFields(stackOf( + formOf('{{record.no_such_field}} {{record.created_at}} {{record.id}}'), + )); expect(findings.map((f) => f.message.match(/is (.*?)\. A thank-you/)?.[1])).toEqual([ 'not a field the object declares', expect.stringContaining('a system column'), @@ -84,36 +83,51 @@ describe('validateThankYouRecordFields — the stack rule the CLI commands run', it('reads the title as well as the message, each name once', () => { const form = formOf('{{record.subject}}'); (form.submitBehavior as Record).title = 'Re: {{record.subject}}'; - expect(validateThankYouRecordFields(stackOf({ name: 'v', form }))).toHaveLength(1); + expect(validateThankYouRecordFields(stackOf(form))).toHaveLength(1); }); - it('judges every form shape a view carries, public or not', () => { + it('judges every shape a form is written in, public or not', () => { const bad = formOf('{{record.subject}}'); - expect(validateThankYouRecordFields(stackOf({ name: 'v', viewKind: 'form', config: bad })).map((f) => f.path)) - .toEqual(['views[0].config.submitBehavior']); - expect(validateThankYouRecordFields(stackOf({ name: 'v', ...bad })).map((f) => f.path)) + // A `forms[]` item, where an app authors a form from protocol 19. + expect(validateThankYouRecordFields(stackOf(bad)).map((f) => f.path)) + .toEqual(['forms[0].submitBehavior']); + // A `views[]` entry that is a bare form view (a raw source `os lint` reads). + const { name: _name, object: _object, ...body } = bad; + const bare = { name: 'v', data: { provider: 'object', object: 'support_case' }, ...body }; + expect(validateThankYouRecordFields({ objects: [support], views: [bare] }).map((f) => f.path)) .toEqual(['views[0].submitBehavior']); const open = { ...bad, sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/case' } }; - expect(validateThankYouRecordFields(stackOf({ name: 'v', form: open }))).toHaveLength(1); - }); - - it('resolves the object from the view when the form names none', () => { - const form: Record = formOf('{{record.subject}}'); - delete form.data; - expect(validateThankYouRecordFields(stackOf({ name: 'v', object: 'support_case', form }))).toHaveLength(1); + expect(validateThankYouRecordFields(stackOf(open))).toHaveLength(1); + // [ADR-0159 D7] The shapes a view held a form in are no site: the parse + // refuses each at its own key. + expect(validateThankYouRecordFields({ + objects: [support], + views: [ + { name: 'v', viewKind: 'form', config: { ...body, data: bare.data } }, + { name: 'case_views', form: { ...body, data: bare.data }, formViews: { intake: { ...body, data: bare.data } } }, + ], + })).toEqual([]); + }); + + it('resolves the object from the record\'s own `object` when the form names no `data`', () => { + // A form item declares no `data` at all: `object` is its one binding. + expect(validateThankYouRecordFields(stackOf(formOf('{{record.subject}}')))).toHaveLength(1); + // The bare form view resolves the same way when it carries no `data`. + const { name: _name, ...body } = formOf('{{record.subject}}'); + expect(validateThankYouRecordFields({ objects: [support], views: [{ name: 'v', ...body }] })).toHaveLength(1); }); it('reads an object whose fields are a list', () => { const object = { name: 'support_case', fields: [{ name: 'subject', type: 'text' }] }; - expect(validateThankYouRecordFields(stackOf({ name: 'v', form: formOf('{{record.subject}}') }, [object]))) + expect(validateThankYouRecordFields(stackOf(formOf('{{record.subject}}'), [object]))) .toHaveLength(1); }); it('does not judge a panel with no token, another kind, or an object outside the stack', () => { - expect(validateThankYouRecordFields(stackOf({ name: 'v', form: formOf('Thanks!') }))).toEqual([]); + expect(validateThankYouRecordFields(stackOf(formOf('Thanks!')))).toEqual([]); const redirect = { ...formOf(''), submitBehavior: { kind: 'redirect', url: '/t/{{record.subject}}' } }; - expect(validateThankYouRecordFields(stackOf({ name: 'v', form: redirect }))).toEqual([]); - expect(validateThankYouRecordFields(stackOf({ name: 'v', form: formOf('{{record.subject}}') }, []))).toEqual([]); + expect(validateThankYouRecordFields(stackOf(redirect))).toEqual([]); + expect(validateThankYouRecordFields(stackOf(formOf('{{record.subject}}'), []))).toEqual([]); }); it('judges a page object-form panel against its objectName', () => { @@ -140,13 +154,13 @@ describe('validateThankYouRecordFields — the stack rule the CLI commands run', expect(validateThankYouRecordFields({ objects: [support], pages: [ok] })).toEqual([]); }); - it('is registered gating, on all three commands and on the publish gate for view and page writes', () => { + it('is registered gating, on all three commands and on the publish gate for form and page writes', () => { const entry = AUTHORING_RULES.find((r) => r.name === 'validateThankYouRecordFields'); expect(entry).toMatchObject({ tier: 'gating', commands: ['validate', 'build', 'lint'], surfaces: ['cli', 'runtime-publish'], - runtimeTypes: ['view', 'page'], + runtimeTypes: ['form', 'page'], }); }); }); @@ -154,12 +168,12 @@ describe('validateThankYouRecordFields — the stack rule the CLI commands run', describe('the admitted set is RUNTIME_OWNED_FIELD_TYPES, the one source', () => { it('in production it is the spec set itself', () => { expect([...RUNTIME_OWNED_FIELD_TYPES]).toContain('autonumber'); - const stack = stackOf({ name: 'v', form: formOf('{{record.case_number}}') }); + const stack = stackOf(formOf('{{record.case_number}}')); expect(validateThankYouRecordFields(stack)).toEqual(validateThankYouRecordFields(stack, RUNTIME_OWNED_FIELD_TYPES)); }); it('widening the set (a test double) admits the new type with no other edit', () => { - const stack = stackOf({ name: 'v', form: formOf('{{record.priority_score}}') }); + const stack = stackOf(formOf('{{record.priority_score}}')); expect(validateThankYouRecordFields(stack)).toHaveLength(1); const widened = new Set([...RUNTIME_OWNED_FIELD_TYPES, 'formula']); expect(validateThankYouRecordFields(stack, widened)).toEqual([]); @@ -174,21 +188,21 @@ describe('the admitted set is RUNTIME_OWNED_FIELD_TYPES, the one source', () => }); describe('the runtime publish gate', () => { - it('refuses a view write naming a text field, resolving the type from the objects context', () => { + it('refuses a form write naming a text field, resolving the type from the objects context', () => { const { errors } = runRuntimeAuthoringRules({ - type: 'view', - item: { name: 'case_views', form: formOf('{{record.subject}}') }, + type: 'form', + item: formOf('{{record.subject}}'), context: { objects: [support] }, }); const finding = errors.find((e) => e.rule === THANK_YOU_RECORD_FIELD); expect(finding, JSON.stringify(errors)).toBeDefined(); - expect(finding!.path).toContain('form.submitBehavior'); + expect(finding!.path).toContain('submitBehavior'); }); - it('admits the same view naming the autonumber field', () => { + it('admits the same form naming the autonumber field', () => { const { errors } = runRuntimeAuthoringRules({ - type: 'view', - item: { name: 'case_views', form: formOf('{{record.case_number}}') }, + type: 'form', + item: formOf('{{record.case_number}}'), context: { objects: [support] }, }); expect(errors.filter((e) => e.rule === THANK_YOU_RECORD_FIELD)).toEqual([]); diff --git a/packages/lint/src/validate-thank-you-record-fields.ts b/packages/lint/src/validate-thank-you-record-fields.ts index 3e049365af8..71bec20a8c8 100644 --- a/packages/lint/src/validate-thank-you-record-fields.ts +++ b/packages/lint/src/validate-thank-you-record-fields.ts @@ -31,10 +31,11 @@ * flipping its `sharing`, which is a write this rule would otherwise never see * again. * - * - A `views[]` entry's forms: the bare form-view shape itself, the nested - * `form`, every `formViews` entry and the flattened `config` of a - * `viewKind: 'form'` item. The object is the one `anonymousFormObjectName` - * resolves, the rung order both anonymous doors submit by. + * - A `forms[]` item ([ADR-0159 D9]: from protocol 19 a form is its own item). + * Its object is the one it names itself (`object`). + * - A `views[]` entry that is a bare form view (the entry itself carries the + * panel). The object is the one `anonymousFormObjectName` resolves. A view + * container holds lists only, so no form is read out of one. * - A page `object-form` component (`properties.submitBehavior`, the form * view's own block by reference). Its object is its `properties.objectName`, * else the binding the page walk resolves. @@ -47,7 +48,7 @@ * * A stack-level authoring rule (`authoring-rules.ts`): `os validate`, * `os build` and `os lint` run it over the whole stack, and the runtime publish - * gate runs it on a `view` or `page` write, whose snapshot carries the + * gate runs it on a `form` or `page` write, whose snapshot carries the * `objects` collection as resolution context. An `object` write's snapshot * carries no views or pages, so retyping a named field under a published panel * is caught by the CLI commands and by the form's next publish. @@ -71,9 +72,9 @@ export interface ThankYouRecordFieldFinding { severity: 'error'; /** Diagnostic rule id: always {@link THANK_YOU_RECORD_FIELD}. */ rule: string; - /** Human-readable location, e.g. `view "case_intake" · form`. */ + /** Human-readable location, e.g. `form "case.intake"`. */ where: string; - /** Config path of the panel, e.g. `views[0].form.submitBehavior`. */ + /** Config path of the panel, e.g. `forms[0].submitBehavior`. */ path: string; message: string; hint: string; @@ -98,39 +99,36 @@ interface PanelSite { objectName: string | undefined; where: string; path: string; - /** Who reads the refusal: `view "x" · form`, `page "y" · component …`. */ + /** Who reads the refusal: `form "x.intake"`, `page "y" · component …`. */ owner: string; } -/** Every form a `views[]` entry carries, in scan order, with its slot. */ -function viewForms(view: AnyRec): Array<{ form: AnyRec; slot: string }> { - const forms: Array<{ form: AnyRec; slot: string }> = []; - if ('submitBehavior' in view) forms.push({ form: view, slot: '' }); - if (isRec(view.form)) forms.push({ form: view.form, slot: 'form' }); - if (isRec(view.formViews)) { - for (const [key, fv] of Object.entries(view.formViews)) { - if (isRec(fv)) forms.push({ form: fv, slot: `formViews.${key}` }); - } - } - if (view.viewKind === 'form' && isRec(view.config)) forms.push({ form: view.config, slot: 'config' }); - return forms; -} - function panelSites(stack: AnyRec): PanelSite[] { const sites: PanelSite[] = []; + // [ADR-0159 D9] `forms[]` items: the panel sits at the form's own root, and + // the form names its object itself. + for (const { rec: form, path: formPath } of collectionEntries(stack.forms, 'forms')) { + if (form.submitBehavior === undefined) continue; + const owner = `form "${strName(form.name) ?? formPath}"`; + sites.push({ + submitBehavior: form.submitBehavior, + objectName: strName(form.object), + where: owner, + path: `${formPath}.submitBehavior`, + owner, + }); + } + // A `views[]` entry that is a bare form view carries the panel itself. for (const { rec: view, path: viewPath } of collectionEntries(stack.views, 'views')) { - const viewName = strName(view.name) ?? strName(view.object) ?? viewPath; - for (const { form, slot } of viewForms(view)) { - if (form.submitBehavior === undefined) continue; - const owner = `view "${viewName}"${slot ? ` · ${slot}` : ''}`; - sites.push({ - submitBehavior: form.submitBehavior, - objectName: anonymousFormObjectName(view, form), - where: owner, - path: `${viewPath}${slot ? `.${slot}` : ''}.submitBehavior`, - owner, - }); - } + if (!('submitBehavior' in view) || view.submitBehavior === undefined) continue; + const owner = `view "${strName(view.name) ?? strName(view.object) ?? viewPath}"`; + sites.push({ + submitBehavior: view.submitBehavior, + objectName: anonymousFormObjectName(view, view), + where: owner, + path: `${viewPath}.submitBehavior`, + owner, + }); } for (const { rec: page, path: pagePath } of collectionEntries(stack.pages, 'pages')) { const pageName = strName(page.name) ?? pagePath; diff --git a/packages/lint/src/validate-translatable-sections.test.ts b/packages/lint/src/validate-translatable-sections.test.ts index c7d262a4480..7a28a4f9fc3 100644 --- a/packages/lint/src/validate-translatable-sections.test.ts +++ b/packages/lint/src/validate-translatable-sections.test.ts @@ -17,7 +17,9 @@ import { ShowcaseTranslationBundle } from '../../../examples/app-showcase/src/sy // the shipped app gets RIGHT, which no fix to the app can pull out from under. import { SnapshotContact, + SnapshotContactForms, SnapshotContactViews, + SnapshotTaskForms, SnapshotTaskViews, SnapshotTranslationBundle, } from './showcase-shape.fixtures.js'; @@ -72,18 +74,20 @@ describe('validateTranslatableSections — the HotCRM shape (#5417)', () => { { name: 'case_views', list: { name: 'all', type: 'grid', data }, - formViews: { edit: { type: 'simple', data, sections: hotcrmSections } }, }, ], + // [ADR-0159 D9] The form is a `forms[]` item from protocol 19; the + // container beside it holds its list alone. + forms: [{ name: 'crm_case.edit', object: 'crm_case', type: 'simple', sections: hotcrmSections }], translations: caseTranslated, }; it('warns once per nameless labelled section, in authoring order', () => { const findings = validateTranslatableSections(stack); expect(findings.map((f) => f.path)).toEqual([ - 'views[0].formViews.edit.sections[0]', - 'views[0].formViews.edit.sections[1]', - 'views[0].formViews.edit.sections[2]', + 'forms[0].sections[0]', + 'forms[0].sections[1]', + 'forms[0].sections[2]', ]); expect(findings.map((f) => f.rule)).toEqual([ TRANSLATION_SECTION_NAME_MISSING, @@ -100,7 +104,7 @@ describe('validateTranslatableSections — the HotCRM shape (#5417)', () => { it('names the heading, the object, and the key that can never exist', () => { const [first] = validateTranslatableSections(stack); - expect(first.where).toBe('object "crm_case" · view "case_views" · formViews.edit · section "Case"'); + expect(first.where).toBe('object "crm_case" · form "crm_case.edit" · section "Case"'); expect(first.message).toContain('Section "Case" declares a label but no `name`'); expect(first.message).toContain('objects.crm_case._sections..label'); // The coverage half of the invisibility, said out loud: #5405's walker is @@ -128,17 +132,12 @@ describe('validateTranslatableSections — the HotCRM shape (#5417)', () => { it('says nothing once the sections carry names', () => { const named = { ...stack, - views: [ + forms: [ { - name: 'case_views', - list: { name: 'all', type: 'grid', data }, - formViews: { - edit: { - type: 'simple', - data, - sections: hotcrmSections.map((s, i) => ({ ...s, name: ['case', 'sla', 'resolution'][i] })), - }, - }, + name: 'crm_case.edit', + object: 'crm_case', + type: 'simple', + sections: hotcrmSections.map((s, i) => ({ ...s, name: ['case', 'sla', 'resolution'][i] })), }, ], }; @@ -149,7 +148,7 @@ describe('validateTranslatableSections — the HotCRM shape (#5417)', () => { describe('validateTranslatableSections — the opt-in gate', () => { const nameless = { objects: [crmCase], - views: [{ name: 'case_views', form: { type: 'simple', data, sections: hotcrmSections } }], + forms: [{ name: 'crm_case.intake', object: 'crm_case', type: 'simple', sections: hotcrmSections }], }; it('says nothing on a monolingual stack (no bundles at all)', () => { @@ -203,15 +202,16 @@ describe('validateTranslatableSections — the section face', () => { const anchors: Array<[string, (sections: unknown[]) => Record, string]> = [ [ - "a container's default `form` (#5415)", - (sections) => ({ objects: [crmCase], views: [{ name: 'v', form: { type: 'simple', data, sections } }] }), + 'a `forms[]` item (#5415)', + (sections) => ({ objects: [crmCase], forms: [{ name: 'crm_case.intake', object: 'crm_case', type: 'simple', sections }] }), 'form_section', ], [ - 'a named `formViews.*` entry', + 'a `forms[]` item beside a list-only container of its object', (sections) => ({ objects: [crmCase], - views: [{ name: 'v', list: { name: 'all', data }, formViews: { create: { type: 'simple', sections } } }], + views: [{ name: 'v', list: { name: 'all', data } }], + forms: [{ name: 'crm_case.create', object: 'crm_case', type: 'simple', sections }], }), 'create_section', ], @@ -231,7 +231,7 @@ describe('validateTranslatableSections — the section face', () => { [ 'a view embedded on the object', (sections) => ({ - objects: [{ ...crmCase, views: [{ name: 'inner', form: { type: 'simple', sections } }] }], + objects: [{ ...crmCase, views: [{ name: 'inner', sections }] }], }), 'inner_section', ], @@ -317,7 +317,7 @@ describe('validateTranslatableSections — what it deliberately leaves alone', ( it('ignores a name-keyed `sections` MAP (the key supplies the name)', () => { const findings = validateTranslatableSections({ objects: [crmCase], - views: [{ name: 'v', form: { type: 'simple', data, sections: { intro: { label: 'Intro' } } } }], + forms: [{ name: 'crm_case.intake', object: 'crm_case', type: 'simple', sections: { intro: { label: 'Intro' } } }], translations: caseTranslated, }); expect(findings).toEqual([]); @@ -326,7 +326,7 @@ describe('validateTranslatableSections — what it deliberately leaves alone', ( it('ignores a section with no heading at all — that is `required/label`\'s question', () => { const findings = validateTranslatableSections({ objects: [crmCase], - views: [{ name: 'v', form: { type: 'simple', data, sections: [{ fields: ['subject'] }] } }], + forms: [{ name: 'crm_case.intake', object: 'crm_case', type: 'simple', sections: [{ fields: ['subject'] }] }], translations: caseTranslated, }); expect(findings).toEqual([]); @@ -337,10 +337,18 @@ describe('validateTranslatableSections — what it deliberately leaves alone', ( // describe — and guessing an owner is how a rule reports the wrong one. const findings = validateTranslatableSections({ objects: [crmCase], - views: [{ name: 'v', form: { type: 'simple', sections: hotcrmSections } }], + views: [{ name: 'v', sections: hotcrmSections }], + forms: [{ name: 'intake', type: 'simple', sections: hotcrmSections }], translations: caseTranslated, }); expect(findings).toEqual([]); + // Lit control: the same two records, each bound, report every heading. + expect(validateTranslatableSections({ + objects: [crmCase], + views: [{ name: 'v', object: 'crm_case', sections: hotcrmSections }], + forms: [{ name: 'crm_case.intake', object: 'crm_case', type: 'simple', sections: hotcrmSections }], + translations: caseTranslated, + })).toHaveLength(6); }); // #5730: `label` is the only heading spelling `RecordDetailsProps.sections[]` @@ -434,14 +442,15 @@ describe('validateTranslatableSections — what it deliberately leaves alone', ( * still exited 0, because they are `warning` findings and only `error` gates.) */ describe('validateTranslatableSections — the snapshotted showcase task views', () => { - it('reports both nameless headings the shipped task container declares', () => { + it('reports both nameless headings the shipped task forms declare', () => { const findings = validateTranslatableSections({ views: [SnapshotTaskViews], + forms: SnapshotTaskForms, translations: [SnapshotTranslationBundle], }); expect(findings.map((f) => f.where)).toEqual([ - 'object "showcase_task" · formViews.edit · section "Task"', - 'object "showcase_task" · formViews.quick · section "Quick Edit"', + 'object "showcase_task" · form "showcase_task.edit" · section "Task"', + 'object "showcase_task" · form "showcase_task.quick" · section "Quick Edit"', ]); for (const finding of findings) { expect(finding.rule).toBe(TRANSLATION_SECTION_NAME_MISSING); @@ -453,31 +462,32 @@ describe('validateTranslatableSections — the snapshotted showcase task views', /** * The other half of the showcase evidence, on the surface #5415 pinned. * - * `ContactViews` is exported from the views barrel but not listed in the - * showcase's `views:` array, so it is composed here exactly as #5415's sibling - * test composes it — object + container. What makes it worth pinning is the - * CONTRAST it carries in one file: the default `form` names all four of its - * sections (and #5415 pins that the reference validator accepts bundles for - * exactly those four), while the sparse `formViews.create` override names none. - * One rule must therefore be silent about the first and loud about the second, - * or the two rules would tell an author opposite things about one surface. + * What makes this surface worth pinning is the CONTRAST it carries: the four + * sections of the contact record form are named (and #5415 pins that the + * reference validator accepts bundles for exactly those four), while the sparse + * create form names none. One rule must therefore be silent about the first + * and loud about the second, or the two rules would tell an author opposite + * things about one surface. * * ⚠️ The two cases below read the same surface from DIFFERENT places, and the * split is the point of #8515 rather than an oversight: * - * - the NAMELESS half — `formViews.create`'s "Who is this?" — is the defect + * - the NAMELESS half — the create form's "Who is this?" — is the defect * #8231 is fixing, so pinning it against the live app made the rule's - * coverage depend on the app staying broken. It reads the frozen snapshot. - * - the NAMED half — the four sections of the default `form` — is what the - * shipped app gets RIGHT. Nothing about fixing the create override can - * remove it, so it stays pinned against the metadata that really ships, and - * the rule keeps one live real-metadata anchor. + * coverage depend on the app staying broken. It reads the frozen snapshot, + * where the two contact forms are `forms[]` items (ADR-0159 D9). + * - the NAMED half — the four names the shipped app gets RIGHT. From + * protocol 19 the contact record form is the object's own `fieldGroups` + * (ADR-0159 D1), whose keys are those four names, so it stays pinned + * against the metadata that really ships and the rule keeps one live + * real-metadata anchor. */ describe('validateTranslatableSections — the showcase contact surface (#5415)', () => { /** The frozen snapshot (#8515) — the nameless-section half. */ const snapshotContactStack = { objects: [SnapshotContact], views: [SnapshotContactViews], + forms: SnapshotContactForms, translations: [SnapshotTranslationBundle], }; @@ -488,23 +498,22 @@ describe('validateTranslatableSections — the showcase contact surface (#5415)' translations: [ShowcaseTranslationBundle], }; - it('reports the sparse create override and nothing from the named default form', () => { + it('reports the sparse create form and nothing from the form that names its sections', () => { const findings = validateTranslatableSections(snapshotContactStack); expect(findings).toHaveLength(1); expect(findings[0].rule).toBe(TRANSLATION_SECTION_NAME_MISSING); - expect(findings[0].path).toBe('views[0].formViews.create.sections[0]'); + expect(findings[0].path).toBe('forms[1].sections[0]'); expect(findings[0].where).toBe( - 'object "showcase_contact" · formViews.create · section "Who is this?"', + 'object "showcase_contact" · form "showcase_contact.create" · section "Who is this?"', ); expect(findings[0].severity).toBe('warning'); expect(findings[0].hint).toContain('objects.showcase_contact._sections.who_is_this.label'); }, 60_000); - it('agrees with #5415 about the four sections the default form names', () => { + it('agrees with #5415 about the four sections the contact record form names', () => { // Those four ARE addressable, and `validateTranslationReferences` accepts // bundles for them. This rule must stay silent there. - const paths = validateTranslatableSections(showcaseContactStack).map((f) => f.path); - expect(paths.filter((p) => p.startsWith('views[0].form.sections'))).toEqual([]); + expect(validateTranslatableSections(showcaseContactStack)).toEqual([]); expect( validateTranslationReferences({ objects: [Contact], @@ -533,8 +542,9 @@ describe('validateTranslatableSections — the showcase contact surface (#5415)' describe('[#22161] one-line verdict — translation-section-name-missing', () => { it('every verdict the cases above fired is one line of at most 200 characters', () => { const converted = fired.filter((f) => f.rule === TRANSLATION_SECTION_NAME_MISSING); - // The coverage control first: the id fired, on a view's form sections and - // on a page's `record:details` sections. + // The coverage control first: the id fired, on a form item's sections, on a + // view record's sections and on a page's `record:details` sections. + expect(converted.some((f) => f.path.startsWith('forms['))).toBe(true); expect(converted.some((f) => f.path.startsWith('views['))).toBe(true); expect(converted.some((f) => f.path.includes('.properties.sections['))).toBe(true); for (const f of converted) { @@ -546,7 +556,7 @@ describe('[#22161] one-line verdict — translation-section-name-missing', () => it('reads as one sentence', () => { const [first] = validateTranslatableSections({ objects: [crmCase], - views: [{ name: 'case_views', formViews: { edit: { type: 'simple', data, sections: hotcrmSections } } }], + forms: [{ name: 'crm_case.edit', object: 'crm_case', type: 'simple', sections: hotcrmSections }], translations: caseTranslated, }); expect(first!.message).toBe( @@ -580,8 +590,9 @@ describe('[#22161] one-line verdict — translation-section-name-missing', () => describe('[#22161] one-line fix — translation-section-name-missing', () => { it('every `fix:` line the cases above fired is one line of at most 200 characters', () => { const converted = fired.filter((f) => f.rule === TRANSLATION_SECTION_NAME_MISSING); - // Coverage control: the id fired, on a view's form sections and on a - // page's `record:details` sections. + // Coverage control: the id fired, on a form item's sections, on a view + // record's sections and on a page's `record:details` sections. + expect(converted.some((f) => f.path.startsWith('forms['))).toBe(true); expect(converted.some((f) => f.path.startsWith('views['))).toBe(true); expect(converted.some((f) => f.path.includes('.properties.sections['))).toBe(true); for (const f of converted) { @@ -593,7 +604,7 @@ describe('[#22161] one-line fix — translation-section-name-missing', () => { it('reads as one remedy', () => { const [first] = validateTranslatableSections({ objects: [crmCase], - views: [{ name: 'case_views', formViews: { edit: { type: 'simple', data, sections: hotcrmSections } } }], + forms: [{ name: 'crm_case.edit', object: 'crm_case', type: 'simple', sections: hotcrmSections }], translations: caseTranslated, }); expect(first!.hint).toBe( diff --git a/packages/lint/src/validate-translatable-sections.ts b/packages/lint/src/validate-translatable-sections.ts index 079ff17a87c..533210f5b8a 100644 --- a/packages/lint/src/validate-translatable-sections.ts +++ b/packages/lint/src/validate-translatable-sections.ts @@ -85,13 +85,14 @@ * this package's `_sections` fact set (`validate-translation-references.ts` * `addSections`, #5422): * - * - a view container's `sections`, its DEFAULT `form.sections` (#5415 — the - * anchor that is neither a `formViews.*` entry nor the record's own), and - * every `listViews.*` / `formViews.*` sub-container's `sections` — reached - * through the shared `view-walk.ts` ladder (#6381; never a private copy, - * for the reason that file's header states — three copies of this descent - * had each been fixed separately, twice for the same missing rung); - * - the same three on views embedded in an object (`objects[].views`, + * - a `forms[]` item's `sections` ([ADR-0159 D9]: a form is its own item + * from protocol 19, and it carries its own `object`); + * - a view container's `sections` and every `listViews.*` sub-container's + * `sections` — reached through the shared `view-walk.ts` ladder (#6381; + * never a private copy, for the reason that file's header states — three + * copies of this descent had each been fixed separately, twice for the + * same missing rung); + * - the same two on views embedded in an object (`objects[].views`, * `objects[].listViews`); * - `record:details` sections nested anywhere in a page's component tree, * via the shared `walkPageComponents` traversal (never a private copy — @@ -105,7 +106,7 @@ import { collectionEntries } from './collection-entries.js'; import { walkPageComponents } from './page-walk.js'; -import { viewContainerSites, viewObjectName } from './view-walk.js'; +import { formItemName, formItemSites, viewContainerSites, viewObjectName } from './view-walk.js'; export const TRANSLATION_SECTION_NAME_MISSING = 'translation-section-name-missing'; @@ -116,9 +117,9 @@ export interface TranslatableSectionFinding { severity: TranslatableSectionSeverity; /** Diagnostic rule id. */ rule: string; - /** Human-readable location, e.g. `object "crm_case" · view "case_views" · formViews.create`. */ + /** Human-readable location, e.g. `object "crm_case" · form "crm_case.intake" · section "Details"`. */ where: string; - /** Config path, e.g. `views[0].formViews.create.sections[1]`. */ + /** Config path, e.g. `forms[0].sections[1]`. */ path: string; /** What is wrong. */ message: string; @@ -141,7 +142,7 @@ interface SectionSite { /** Path of the `sections` array itself. */ path: string; /** - * Human-readable container the array hangs off (`formViews.create`), WITHOUT + * Human-readable container the array hangs off (`form "crm_case.intake"`), WITHOUT * the object — the object is prepended once at emission so every finding in * the family reads the same way. Empty when the container has no name of its * own to add beyond what `path` already says. @@ -165,10 +166,9 @@ function joinWhere(...parts: string[]): string { /** * Register every `sections` array ONE view container declares. * - * The DESCENT is the shared one (`view-walk.ts`, #6381) — the entry itself, the - * container's default `form` (#5415: the anchor that is neither a `formViews.*` - * entry nor the record's own), and every `listViews.*` / `formViews.*` - * sub-container. This rule takes the FULL ladder, `listViews.*` included: that + * The DESCENT is the shared one (`view-walk.ts`, #6381) — the entry itself and + * every `listViews.*` sub-container. A form is a `forms[]` item and is + * registered beside these, below. This rule takes the FULL ladder, `listViews.*` included: that * rung is how it reaches an object's own `listViews` container, which the module * docblock above declares as part of its section face. * @@ -271,6 +271,16 @@ export function validateTranslatableSections(stack: AnyRec): TranslatableSection collectViewSites(view, path, viewLabel(view), sites); } + // ── [ADR-0159 D9] `forms[]` items: a form's own sections, under its object ── + for (const site of formItemSites(stack)) { + sites.push({ + path: `${site.path}.sections`, + surface: `form "${formItemName(site)}"`, + objectName: viewObjectName(site.view), + sections: site.view.sections, + }); + } + // ── Pages: `record:details` sections, anywhere in the component tree ── for (const { rec: page, path: pagePath } of collectionEntries(stack.pages, 'pages')) { const pageName = strName(page.name); diff --git a/packages/lint/src/validate-translation-references.test.ts b/packages/lint/src/validate-translation-references.test.ts index 49059954a37..7a93a52b6af 100644 --- a/packages/lint/src/validate-translation-references.test.ts +++ b/packages/lint/src/validate-translation-references.test.ts @@ -161,11 +161,7 @@ describe('validateTranslationReferences — orphan keys', () => { }, }, ]), - views: [{ - name: 'lead_forms', - objectName: 'crm_lead', - formViews: { web: { type: 'simple', data: { provider: 'object', object: 'crm_lead' }, sections } }, - }], + forms: [{ name: 'crm_lead.web', object: 'crm_lead', type: 'simple', sections }], }); const findings = validateTranslationReferences(stack([ { name: 'contact', label: 'Contact', fields: [{ field: 'name', label: 'Your name', placeholder: 'Jane', helpText: 'Full' }, 'status'] }, @@ -3050,17 +3046,37 @@ describe('validateTranslationReferences — the canonical view-record shape', () my_leads: { name: 'my_leads', type: 'grid', data: { provider: 'object', object: 'crm_lead' } }, kanban_by_status: { name: 'kanban_by_status', type: 'kanban' }, }, - formViews: { - default: { - type: 'simple', - data: { provider: 'object', object: 'crm_lead' }, - sections: [{ name: 'contact_info', label: 'Contact Info' }], - }, - }, + }, + ], + // [ADR-0159 D9] The form is a `forms[]` item from protocol 19; the + // container above holds its lists alone. + forms: [ + { + name: 'crm_lead.default', + object: 'crm_lead', + type: 'simple', + sections: [{ name: 'contact_info', label: 'Contact Info' }], }, ], }; + it('a form item is no `_views` name: its label is keyed at `forms.`, and the key it had under a view is reported', () => { + const bundle = (views: Record) => ({ + ...leadViews, + translations: [ + { + en: { + objects: { crm_lead: { label: 'Lead', _views: views } }, + forms: { 'crm_lead.default': { label: 'Default Form' } }, + }, + }, + ], + }); + expect(validateTranslationReferences(bundle({ all_leads: { label: 'All Leads' } }))).toEqual([]); + const findings = validateTranslationReferences(bundle({ all_leads: { label: 'All Leads' }, default: { label: 'Default Form' } })); + expect(findings.map((f) => f.path)).toEqual(['translations[0].en.objects.crm_lead._views.default']); + }); + it('resolves the default list, every named tab, and a form section', () => { const findings = validateTranslationReferences({ ...leadViews, @@ -3074,7 +3090,6 @@ describe('validateTranslationReferences — the canonical view-record shape', () all_leads: { label: 'All Leads' }, my_leads: { label: 'My Leads' }, kanban_by_status: { label: 'By Status' }, - default: { label: 'Default Form' }, }, _sections: { contact_info: { label: 'Contact' } }, }, @@ -3217,20 +3232,22 @@ describe('validateTranslationReferences — the canonical view-record shape', () expect(findings[0].path).toBe('translations[0].en.objects.crm_lead._views.default_3'); }); - it('the default FORM contributes sections but no `_views` name — `_views.*` is a list convention', () => { - // The composer does name the default form `crm_lead.form`, but the i18n - // walker emits no `_views` entry for any form view, so a `_views.form` + it('a form item contributes sections but no `_views` name — `_views.*` is a list convention', () => { + // A form is its own item, served under its own `name`; a `_views.form` // key would be one nothing reads. Its `_sections` still resolve (#5415). const withForm = { objects: [{ name: 'crm_lead', fields: { name: { type: 'text' } } }], views: [ { list: { type: 'grid', label: 'All', data: { provider: 'object', object: 'crm_lead' } }, - form: { - type: 'simple', - data: { provider: 'object', object: 'crm_lead' }, - sections: [{ name: 'contact_info', label: 'Contact Info' }], - }, + }, + ], + forms: [ + { + name: 'crm_lead.form', + object: 'crm_lead', + type: 'simple', + sections: [{ name: 'contact_info', label: 'Contact Info' }], }, ], }; @@ -3298,63 +3315,72 @@ describe('validateTranslationReferences — the canonical view-record shape', () expect(findings[0].path).toBe('translations[0].en.objects.crm_lead._views.open_leads'); }); - it('the same narrowing holds on the formViews branch', () => { + it('a form item is a `_views` name under NEITHER spelling — the branch the narrowing held on is retired', () => { + // Under protocol 18 a `formViews.` entry was keyed by its map key, + // like a `listViews.` entry. A form is its own item from protocol + // 19, so neither its key nor any inner name is a view name; its copy is + // keyed at `forms.`. const stack = { objects: [{ name: 'crm_lead', fields: { name: { type: 'text' } } }], views: [ { - formViews: { - quick: { - name: 'quick_form', - type: 'simple', - data: { provider: 'object', object: 'crm_lead' }, - }, + listViews: { + open: { name: 'open_leads', type: 'grid', data: { provider: 'object', object: 'crm_lead' } }, }, }, ], + forms: [{ name: 'crm_lead.quick', object: 'crm_lead', type: 'simple' }], }; + // Lit control on the same fixture: the list entry's map key resolves. expect( - validateTranslationReferences({ ...stack, ...bundle({ quick: { label: 'Quick' } }) }), + validateTranslationReferences({ ...stack, ...bundle({ open: { label: 'Open' } }) }), ).toEqual([]); - const findings = validateTranslationReferences({ - ...stack, - ...bundle({ quick_form: { label: 'Quick Form' } }), - }); - expect(findings).toHaveLength(1); - expect(findings[0].path).toBe('translations[0].en.objects.crm_lead._views.quick_form'); - }); - - it('a collision-renamed formViews entry is legal under the renamed key — the author who wrote the registry key is not an orphan', () => { - // The #6422 sharp case. The nameless default `list` claims - // `crm_lead.default` first, so `formViews.default` is renamed - // `crm_lead.default_2` — and the rename IS the registry key. Before this - // rule asked the composer, it accepted `default` for the form (a key - // that resolves to the LIST) and reported `default_2` — the one spelling - // that actually resolves the form — as an orphan. - // - // The shape is dormant in shipped configs only because the view-ref lint - // (`lint-view-refs.ts`) makes every view-key collision a hard error. - // That dormancy depends on ANOTHER rule staying strict, which is exactly - // why it is pinned here instead of trusted silently. + for (const spelling of ['quick', 'quick_form']) { + const findings = validateTranslationReferences({ + ...stack, + ...bundle({ open: { label: 'Open' }, [spelling]: { label: 'Quick' } }), + }); + expect(findings.map((f) => f.path), spelling).toEqual([ + `translations[0].en.objects.crm_lead._views.${spelling}`, + ]); + } + expect( + validateTranslationReferences({ + ...stack, + translations: [{ en: { objects: { crm_lead: { label: 'Lead' } }, forms: { 'crm_lead.quick': { label: 'Quick' } } } }], + }), + ).toEqual([]); + }); + + it('a form named like the default list does not rename either — the collision the registry key answered is retired', () => { + // The #6422 sharp case, at protocol 19. Under protocol 18 the nameless + // default `list` claimed `crm_lead.default` first, so a + // `formViews.default` beside it was renamed `crm_lead.default_2`, and + // the rename WAS the registry key a bundle had to spell. A form is its + // own item now and never enters the view names this rule asks the + // composer for: `default` resolves the list, and nothing resolves + // `default_2`. const collided = { objects: [{ name: 'crm_lead', fields: { name: { type: 'text' } } }], views: [ { list: { type: 'grid', data: { provider: 'object', object: 'crm_lead' } }, - formViews: { - default: { type: 'simple', data: { provider: 'object', object: 'crm_lead' } }, - }, }, ], + forms: [{ name: 'crm_lead.default', object: 'crm_lead', type: 'simple' }], }; - // `default` resolves the list, `default_2` resolves the form: both are - // registry keys, so both are legal bundle spellings. expect( validateTranslationReferences({ ...collided, - ...bundle({ default: { label: 'All' }, default_2: { label: 'Form' } }), + ...bundle({ default: { label: 'All' } }), }), ).toEqual([]); + // The key the renamed form used to resolve under is an orphan now. + const renamed = validateTranslationReferences({ + ...collided, + ...bundle({ default: { label: 'All' }, default_2: { label: 'Form' } }), + }); + expect(renamed.map((f) => f.path)).toEqual(['translations[0].en.objects.crm_lead._views.default_2']); // Planted bad key on the SAME fixture: the green above is not an empty run. const findings = validateTranslationReferences({ ...collided, @@ -3406,48 +3432,64 @@ describe('validateTranslationReferences — the canonical view-record shape', () }); /** - * `_views..title` — a FORM view's heading. `translateView` overlays it - * onto the served form item's `config.title`, keyed by the item's runtime - * identity: a `formViews.` entry, the default `form` (`form`, or its - * `name`), or a `viewKind: 'form'` item. A list view has no title, so the key - * over one resolves nothing — refused, pointing at the tab's `label`. + * A form's heading. Under protocol 18 it was keyed `_views..title`, by + * the runtime identity of a form held in a view. [ADR-0159 D8] A view holds + * lists only from protocol 19 and a form is its own item, so the heading is + * keyed at the form's own node, `forms..title`, and the `_views` + * tail resolves nothing — refused, on a list view and on the key a form in a + * view used to be translated under alike. */ describe('validateTranslationReferences — a form view\'s title (`_views..title`)', () => { - const stack = (views: Record) => ({ + const stack = (views: Record, forms: Record = {}) => ({ objects: [{ name: 'crm_lead', fields: { name: { type: 'text' } } }], views: [ { list: { type: 'grid', name: 'all_leads', label: 'All Leads', data: { provider: 'object', object: 'crm_lead' } }, - form: { type: 'simple', title: 'New lead', data: { provider: 'object', object: 'crm_lead' } }, - formViews: { - web_to_lead: { type: 'simple', title: 'Contact us', data: { provider: 'object', object: 'crm_lead' } }, - }, - }, - { - name: 'quick_lead', - object: 'crm_lead', - viewKind: 'form', - config: { type: 'simple', title: 'Quick lead', data: { provider: 'object', object: 'crm_lead' } }, }, ], - translations: [{ 'zh-CN': { objects: { crm_lead: { label: '线索', _views: views } } } }], + forms: [ + { name: 'crm_lead.form', object: 'crm_lead', type: 'simple', title: 'New lead' }, + { name: 'crm_lead.web_to_lead', object: 'crm_lead', type: 'simple', title: 'Contact us', sections: [{ name: 'contact', fields: ['name'] }] }, + { name: 'crm_lead.quick_lead', object: 'crm_lead', type: 'simple', title: 'Quick lead' }, + ], + translations: [{ 'zh-CN': { objects: { crm_lead: { label: '线索', _views: views } }, forms } }], + }); + const HEADING = 'No view of object "crm_lead" carries a heading, so no title resolves this key: a view holds lists only, and a form is its own item.'; + + it('accepts a title at each form item\'s own `forms.` node', () => { + const findings = validateTranslationReferences(stack({}, { + 'crm_lead.web_to_lead': { title: '联系我们' }, + 'crm_lead.form': { title: '新建线索' }, + 'crm_lead.quick_lead': { title: '快速线索' }, + })); + expect(findings).toEqual([]); }); - it('accepts a title over a named form view, the default form and a form item', () => { + it('refuses the same titles under `_views`, the key a form held in a view was translated under', () => { const findings = validateTranslationReferences(stack({ web_to_lead: { title: '联系我们' }, form: { title: '新建线索' }, quick_lead: { title: '快速线索' }, })); - expect(findings).toEqual([]); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, 'error', 'translations[0]["zh-CN"].objects.crm_lead._views.web_to_lead.title'], + [TRANSLATION_TARGET_UNKNOWN, 'error', 'translations[0]["zh-CN"].objects.crm_lead._views.form.title'], + [TRANSLATION_TARGET_UNKNOWN, 'error', 'translations[0]["zh-CN"].objects.crm_lead._views.quick_lead.title'], + ]); + expect(findings.map((f) => f.message)).toEqual([HEADING, HEADING, HEADING]); + expect(findings[0].hint).toContain('`forms..title`'); + expect(findings[0].hint).toContain('"crm_lead.web_to_lead"'); }); it('the same fixture still reports a key nothing declares (the green above is not an empty run)', () => { - const findings = validateTranslationReferences(stack({ - web_to_lead: { title: '联系我们' }, - ghost_form: { title: 'x' }, - })); - expect(findings.map((f) => f.path)).toEqual(['translations[0]["zh-CN"].objects.crm_lead._views.ghost_form']); + const findings = validateTranslationReferences(stack( + { ghost_view: { label: 'x' } }, + { 'crm_lead.web_to_lead': { title: '联系我们', sections: { ghost_section: { label: 'x' } } } }, + )); + expect(findings.map((f) => f.path).sort()).toEqual([ + 'translations[0]["zh-CN"].forms["crm_lead.web_to_lead"].sections.ghost_section', + 'translations[0]["zh-CN"].objects.crm_lead._views.ghost_view', + ]); }); it('refuses a title over a LIST view by name, pointing at its `label`', () => { @@ -3455,7 +3497,7 @@ describe('validateTranslationReferences — a form view\'s title (`_views. expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ [TRANSLATION_TARGET_UNKNOWN, 'error', 'translations[0]["zh-CN"].objects.crm_lead._views.all_leads.title'], ]); - expect(findings[0].message).toBe('View "all_leads" of object "crm_lead" is not a form view, so no title resolves this key.'); + expect(findings[0].message).toBe(HEADING); expect(findings[0].hint).toContain('`_views.all_leads.label`'); }); @@ -3463,43 +3505,60 @@ describe('validateTranslationReferences — a form view\'s title (`_views. expect(validateTranslationReferences(stack({ all_leads: { label: '全部线索' } }))).toEqual([]); }); - it('the default form\'s key stays a non-key for every tail but `title`', () => { - const findings = validateTranslationReferences(stack({ form: { label: '表单' } })); - expect(findings.map((f) => f.path)).toEqual(['translations[0]["zh-CN"].objects.crm_lead._views.form']); + it('the key a form in a view was translated under is a non-key for every tail, `title` included', () => { + const label = validateTranslationReferences(stack({ form: { label: '表单' } })); + expect(label.map((f) => f.path)).toEqual(['translations[0]["zh-CN"].objects.crm_lead._views.form']); + const title = validateTranslationReferences(stack({ form: { title: '新建线索' } })); + expect(title.map((f) => f.path)).toEqual(['translations[0]["zh-CN"].objects.crm_lead._views.form.title']); }); }); /** - * A form view's thank-you panel (`_views..submitBehavior`) is legal on - * exactly the views a `title` is — a named form view, the default form, a - * `viewKind: 'form'` item — because `translateView` overlays both onto the - * served form's `config`. A list view submits nothing, so the key over one - * resolves nothing. + * A form's thank-you panel is keyed where its heading is: at the form's own + * node, `forms..submitBehavior` (ADR-0159 D8). The + * `_views..submitBehavior` tail it had under protocol 18 resolves + * nothing: a view holds lists only and a list submits nothing. */ describe('validateTranslationReferences — a form view\'s thank-you panel (`_views..submitBehavior`)', () => { const data = { provider: 'object', object: 'crm_lead' }; const panel = { kind: 'thank-you', title: 'Thanks!', message: 'We will reach out.' }; - const stack = (views: Record) => ({ + const stack = (views: Record, forms: Record = {}) => ({ objects: [{ name: 'crm_lead', fields: { name: { type: 'text' } } }], views: [ { list: { type: 'grid', name: 'all_leads', label: 'All Leads', data }, - form: { type: 'simple', data, submitBehavior: panel }, - formViews: { web_to_lead: { type: 'simple', data, submitBehavior: panel } }, }, - { name: 'quick_lead', object: 'crm_lead', viewKind: 'form', config: { type: 'simple', data, submitBehavior: panel } }, ], - translations: [{ 'zh-CN': { objects: { crm_lead: { label: '线索', _views: views } } } }], + forms: [ + { name: 'crm_lead.form', object: 'crm_lead', type: 'simple', submitBehavior: panel }, + { name: 'crm_lead.web_to_lead', object: 'crm_lead', type: 'simple', submitBehavior: panel }, + { name: 'crm_lead.quick_lead', object: 'crm_lead', type: 'simple', submitBehavior: panel }, + ], + translations: [{ 'zh-CN': { objects: { crm_lead: { label: '线索', _views: views } }, forms } }], }); const zh = { title: '感谢您!', message: '我们会联系您。' }; + const PANEL = 'No view of object "crm_lead" submits anything, so no thank-you panel resolves this key: a view holds lists only, and a form is its own item.'; - it('accepts a panel over a named form view, the default form and a form item', () => { + it('accepts a panel at each form item\'s own `forms.` node', () => { + const findings = validateTranslationReferences(stack({}, { + 'crm_lead.web_to_lead': { submitBehavior: zh }, + 'crm_lead.form': { title: '新建线索', submitBehavior: zh }, + 'crm_lead.quick_lead': { submitBehavior: zh }, + })); + expect(findings).toEqual([]); + }); + + it('refuses the same panels under `_views`, the key a form held in a view was translated under', () => { const findings = validateTranslationReferences(stack({ web_to_lead: { submitBehavior: zh }, - form: { title: '新建线索', submitBehavior: zh }, quick_lead: { submitBehavior: zh }, })); - expect(findings).toEqual([]); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, 'error', 'translations[0]["zh-CN"].objects.crm_lead._views.web_to_lead.submitBehavior'], + [TRANSLATION_TARGET_UNKNOWN, 'error', 'translations[0]["zh-CN"].objects.crm_lead._views.quick_lead.submitBehavior'], + ]); + expect(findings.map((f) => f.message)).toEqual([PANEL, PANEL]); + expect(findings[0].hint).toContain('`forms..submitBehavior`'); }); it('refuses a panel over a LIST view by name', () => { @@ -3507,7 +3566,7 @@ describe('validateTranslationReferences — a form view\'s thank-you panel (`_vi expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ [TRANSLATION_TARGET_UNKNOWN, 'error', 'translations[0]["zh-CN"].objects.crm_lead._views.all_leads.submitBehavior'], ]); - expect(findings[0].message).toBe('View "all_leads" of object "crm_lead" is not a form view, so no thank-you panel resolves this key.'); + expect(findings[0].message).toBe(PANEL); }); it('CONTROL: the default form\'s key stays a non-key for a tail beside the panel', () => { @@ -3517,15 +3576,14 @@ describe('validateTranslationReferences — a form view\'s thank-you panel (`_vi }); describe('validateTranslationReferences — section anchors', () => { - it('resolves a section named on a form view or a record:details page', () => { + it('resolves a section named on a form or a record:details page', () => { const stack = { objects: [{ name: 'crm_lead', fields: { name: { type: 'text' } } }], views: [ - { - name: 'lead_form', - objectName: 'crm_lead', - formViews: { default: { sections: [{ name: 'contact_info', label: 'Contact Info' }] } }, - }, + { name: 'lead_lists', objectName: 'crm_lead', list: { type: 'grid' } }, + ], + forms: [ + { name: 'crm_lead.intake', object: 'crm_lead', sections: [{ name: 'contact_info', label: 'Contact Info' }] }, ], pages: [ { @@ -3559,7 +3617,7 @@ describe('validateTranslationReferences — section anchors', () => { it('explains that an unnamed section cannot be translated at all', () => { const findings = validateTranslationReferences({ objects: [{ name: 'crm_lead', fields: { name: { type: 'text' } } }], - views: [{ name: 'lead_form', objectName: 'crm_lead', formViews: { default: { sections: [{ label: 'Deal' }] } } }], + forms: [{ name: 'crm_lead.intake', object: 'crm_lead', sections: [{ label: 'Deal' }] }], translations: [{ en: { objects: { crm_lead: { label: 'Lead', _sections: { deal_info: { label: 'Deal' } } } } } }], }); expect(findings).toHaveLength(1); @@ -3570,23 +3628,25 @@ describe('validateTranslationReferences — section anchors', () => { ); }); - // #5415. `collectViewRecord` walked `['listViews', 'formViews']` and the - // record's own `sections`; the CONTAINER's default form — `defineView({ form: - // … })`, the one `ObjectForm` renders when no named form view is asked for — - // was in neither, so its named sections contributed nothing and a correct - // translation of a heading that DOES render was reported as an unknown - // target. - it('resolves a section named on the container default `form`', () => { + // #5415. A form's named sections are `_sections` anchors of the object it + // binds to, wherever the list of that object sits: a correct translation of + // a heading that DOES render must not be reported as an unknown target. + // [ADR-0159 D9] The form is a `forms[]` item from protocol 19; under 18 it + // was the container's default `form`, which this rule had once missed. + it('resolves a section named on a form beside the container of its object', () => { const stack = { objects: [{ name: 'crm_lead', fields: { name: { type: 'text' } } }], views: [ { list: { type: 'grid', name: 'all_leads', data: { provider: 'object', object: 'crm_lead' } }, - form: { - type: 'simple', - data: { provider: 'object', object: 'crm_lead' }, - sections: [{ name: 'contact_info', label: 'Contact Info' }], - }, + }, + ], + forms: [ + { + name: 'crm_lead.intake', + object: 'crm_lead', + type: 'simple', + sections: [{ name: 'contact_info', label: 'Contact Info' }], }, ], translations: [ @@ -3594,18 +3654,27 @@ describe('validateTranslationReferences — section anchors', () => { ], }; expect(validateTranslationReferences(stack)).toEqual([]); + // The retired slot is no anchor: the same section held in the container's + // `form` resolves nothing, so the key over it is reported. + const held = { + ...stack, + forms: [], + views: [{ ...stack.views[0], form: { type: 'simple', sections: stack.forms[0].sections } }], + }; + expect(validateTranslationReferences(held).map((f) => f.path)).toEqual([ + 'translations[0].en.objects.crm_lead._sections.contact_info', + ]); }); - it('binds the default `form` by its OWN data, not by the list beside it', () => { - // Two objects in one record: the list shows leads, the form edits contacts. - // The section belongs to whatever `form.data.object` says — the same - // resolution the CLI i18n walker's `viewObjectName` performs. + it('binds a form by its OWN `object`, not by the list beside it', () => { + // Two objects in one stack: the list shows leads, the form edits contacts. + // The section belongs to whatever the form's `object` says. // // Both directions are asserted in ONE stack on purpose. "crm_lead is still - // reported" alone would pass just as well if the default form contributed - // NOTHING (the pre-#5415 behaviour) — it is the `crm_contact` half, which - // resolves only once the form is collected under its own binding, that - // makes the pair falsifiable. + // reported" alone would pass just as well if the form contributed NOTHING + // (the pre-#5415 behaviour) — it is the `crm_contact` half, which resolves + // only once the form is collected under its own binding, that makes the + // pair falsifiable. const stack = (objectName: string) => ({ objects: [ { name: 'crm_lead', fields: { name: { type: 'text' } } }, @@ -3614,11 +3683,14 @@ describe('validateTranslationReferences — section anchors', () => { views: [ { list: { type: 'grid', name: 'all_leads', data: { provider: 'object', object: 'crm_lead' } }, - form: { - type: 'simple', - data: { provider: 'object', object: 'crm_contact' }, - sections: [{ name: 'contact_info', label: 'Contact Info' }], - }, + }, + ], + forms: [ + { + name: 'crm_contact.intake', + object: 'crm_contact', + type: 'simple', + sections: [{ name: 'contact_info', label: 'Contact Info' }], }, ], translations: [ @@ -4969,7 +5041,8 @@ describe('[#22161] one-line verdicts — translation-target-unknown, translation 'not an `approval`; its label is keyed', 'so its drawn step keeps its authored label', '`screen` node; its heading is keyed `screens.collect.title`', - 'is not a form view, so no title resolves this key', + 'carries a heading, so no title resolves this key', + 'submits anything, so no thank-you panel resolves this key', 'Translations are keyed to parameter "', 'does not declare in `outcomeMessages`', 'declares no `outcomeMessages` at all', diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index de14c15fb78..e394900d708 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -552,10 +552,11 @@ const IMPLICIT_FIELDS: ReadonlySet = new Set([ ]); /** - * The `_views` tails only a FORM view resolves — `title` (the form's heading, - * `config.title`) and `submitBehavior` (its thank-you panel, - * `config.submitBehavior`), both overlaid by `translateView`. The default - * form's key is legal for these alone. + * [ADR-0159 D8] The two `_views` tails that were a FORM's — `title` (its + * heading) and `submitBehavior` (its thank-you panel). From protocol 19 a view + * holds lists only, the translator reads a form's copy at `forms.`, and + * the translation schema refuses both tails under `_views`. Neither resolves + * anything there, whatever the view. */ const FORM_ONLY_VIEW_TAILS: ReadonlySet = new Set(['title', 'submitBehavior']); @@ -563,17 +564,6 @@ const FORM_ONLY_VIEW_TAILS: ReadonlySet = new Set(['title', 'submitBehav interface ObjectFacts { fields: Map; views: Set; - /** - * The `_views` keys of the FORM views this object's containers serve — each - * `formViews.` entry, the default `form`, and a `viewKind: 'form'` - * item — the views a `_views..title` or `.submitBehavior` key - * addresses (`translateView` overlays them onto the form's `config.title` - * and `config.submitBehavior`). A list view carries neither, so either key - * over one resolves nothing. The default form's key is legal for those two - * alone ({@link FORM_ONLY_VIEW_TAILS}): its other `_views` tails stay - * non-keys (see {@link collectViewRecord}). - */ - forms: Set; actions: Map; sections: Set; /** @@ -784,7 +774,6 @@ function emptyFacts(): ObjectFacts { return { fields: new Map(), views: new Set(), - forms: new Set(), actions: new Map(), sections: new Set(), sectionEntries: new Map(), @@ -797,15 +786,17 @@ function emptyFacts(): ObjectFacts { /** * Register everything ONE view record contributes: the `_views` names it makes - * legal, and the `_sections` names its form views declare — each under the - * object that container actually binds. + * legal, and the `_sections` names it declares itself when it is a bare form + * view — each under the object that container actually binds. A form is a + * `forms:` item ([ADR-0159 D9]); its sections are registered where the stack's + * forms are read, not here. * * Two things about the real shape make this more than "read `view.name`", and * both were learned from the HotCRM corpus (~18k lines of shipped metadata), * where a first pass reported ~40 correct keys as orphans: * * 1. A view record is a CONTAINER, not a view. The default list sits at - * `list`; the named tabs at `listViews.` and `formViews.`. + * `list`; the named tabs at `listViews.`. * 2. The object binding lives INSIDE the container (`list.data.object`), not * at the record root. A record-level lookup alone resolves to nothing on * the canonical shape, which silently drops the whole record — a rule that @@ -821,22 +812,14 @@ function emptyFacts(): ObjectFacts { * Every `_views` key therefore comes from the composer: the default list's * via {@link defaultListViewKey}, the named entries' via {@link namedViewKeys} * — asked, never re-derived. See those functions for the composer facts that - * live there and nowhere else (collision renames included: `formViews.default` - * beside a default `list` is registered as `default_2`, because the rename IS - * the registry key — the map key it was written under resolves to the OTHER - * view). - * - * A third thing was learned later, from the showcase (#5415): the container's - * DEFAULT form (`form`) is a section anchor too. It is not one of the - * `formViews.*` entries and it is not the record's own `sections` either, so - * its named sections contributed NOTHING to the fact set — and a - * bundle that correctly translated one of them was reported as keyed to a - * section "nothing declares", with a hint advising the author to delete a - * translation that renders. `ObjectForm` reads that form and resolves its - * headings through the same `sectionLabel(object, section.name, …)` convention - * as any named form view, so every anchor below feeds ONE collector: the list - * of anchors is now a list of call sites, not four copies of a loop that can - * drift apart one at a time. + * live there and nowhere else (collision renames included: `listViews.default` + * beside a default `list` is registered under the renamed key, because the + * rename IS the registry key — the map key it was written under resolves to + * the OTHER view). + * + * Every section anchor feeds ONE collector ({@link addFormSections}): the list + * of anchors is a list of call sites, not copies of a loop that can drift + * apart one at a time. */ /** * Register the `_sections` names one form-ish container declares, under the @@ -845,9 +828,9 @@ function emptyFacts(): ObjectFacts { * Form sections carry an OPTIONAL `name` that exists purely for the * `_sections` lookup (`ui/view.zod.ts`: "Stable section identifier for i18n * lookup"). A section without one cannot be translated at all, so it - * contributes nothing here. A form view's container and a `form` item - * (ADR-0159) both feed it: `translateForm` reads a form item's section - * headings at `objects.._sections.`, as a form view's are read. + * contributes nothing here. A `form` item (ADR-0159) and a bare form view + * both feed it: `translateForm` reads a form item's section headings at + * `objects.._sections.`. */ function addFormSections(container: AnyRec, binding: string | undefined, factsFor: (objectName: string) => ObjectFacts): void { if (!binding) return; @@ -875,62 +858,35 @@ function collectViewRecord(view: AnyRec, factsFor: (objectName: string) => Objec const addView = (objectName: string | undefined, name: string | undefined) => { if (objectName && name) factsFor(objectName).views.add(name); }; - const addForm = (objectName: string | undefined, name: string | undefined) => { - if (objectName && name) factsFor(objectName).forms.add(name); - }; - const addSections = (container: AnyRec, binding: string | undefined) => addFormSections(container, binding, factsFor); const listBinding = isRec(view.list) ? bindingOf(view.list) : undefined; if (isRec(view.list)) addView(listBinding, defaultListViewKey(listBinding, view)); - addView(recordObject ?? listBinding, strName(view.name)); - if (view.viewKind === 'form') addForm(recordObject ?? listBinding, strName(view.name)); + // [ADR-0159 D7] A `viewKind: 'form'` item is a retired shape: it is no view + // a `_views` key can address. + if (view.viewKind !== 'form') addView(recordObject ?? listBinding, strName(view.name)); const named = namedViewKeys(view); - for (const family of ['listViews', 'formViews'] as const) { - const container = view[family]; - if (!isRec(container)) continue; - const registryKeys = family === 'listViews' ? named.list : named.form; + const container = view.listViews; + if (isRec(container)) { let at = 0; for (const sub of Object.values(container)) { // Advance in lockstep with the composer: it makes an item for every // object-typed value (arrays included), so the index moves for each. if (!sub || typeof sub !== 'object') continue; - const registryKey = registryKeys[at++]; + const registryKey = named[at++]; if (!isRec(sub)) continue; const binding = bindingOf(sub) ?? listBinding; addView(binding, registryKey); - if (family === 'formViews') addForm(binding, registryKey); addSections(sub, binding); } } - // The container's default form — the one `defineView({ form: … })` declares - // and `ObjectForm` renders when no named form view is asked for. Bound the - // way the CLI i18n walker's `viewObjectName` resolves `view.form.data.object` - // (#5415), so the two agree on which object the headings belong to. - // - // Deliberately sections only, and #5164 is now settled enough to say WHY - // rather than defer: the composer does give the default form a runtime - // identity (`.form`), but `_views.*` is a LIST-view convention — - // `viewLabel` / `viewDescription` resolve view tabs, and the i18n walker - // emits no `_views` entry for any form view (`i18n-walk.ts`: "form views - // have no counterpart in the `viewLabel` / `_views.*` resolver convention"). - // A `_views` name registered here for the default form would make a key - // legal that no consumer ever reads. Its SECTIONS are a different matter — - // `ObjectForm` resolves those, which is exactly what #5415 established. - // - // Two `_views` tails of the default form ARE read: its `title` and its - // `submitBehavior`, which `translateView` overlays onto the served - // `.form` item's `config.title` and `config.submitBehavior`. So its - // runtime key is registered as a FORM key only (`forms`), legal for those - // two and nothing else. - if (isRec(view.form)) { - const formBinding = bindingOf(view.form) ?? listBinding; - addSections(view.form, formBinding); - addForm(formBinding, defaultFormViewKey(formBinding, view)); - } + // [ADR-0159 D7] The container's `form` and `formViews` are retired slots the + // parse refuses: no `_views` key and no section is registered from either. + // The forms an app authors are `forms:` items, registered with the stack's + // forms. addSections(view, recordObject ?? listBinding); } @@ -1033,31 +989,15 @@ function defaultListViewKey(object: string | undefined, container: AnyRec): stri } /** - * The bare `_views` key the RUNTIME assigns to a container's default `form` — - * `form`, or the author's `form.name`, renamed on a collision. Asked of the - * composer, like {@link defaultListViewKey}: the default form is the one form - * item the composer marks `isDefault`. - */ -function defaultFormViewKey(object: string | undefined, container: AnyRec): string | undefined { - if (!object || !isRec(container.form)) return undefined; - const item = expandViewContainer(object, container).find( - (i) => i.viewKind === 'form' && i.isDefault, - ); - if (!item) return undefined; - const prefix = `${object}.`; - return item.name.startsWith(prefix) ? item.name.slice(prefix.length) : item.name; -} - -/** - * The bare `_views` keys the RUNTIME assigns to a container's NAMED entries — - * `listViews.` / `formViews.` — in authoring order per family. + * The bare `_views` keys the RUNTIME assigns to a container's NAMED list + * views — `listViews.` — in authoring order. * * {@link defaultListViewKey}'s sibling, and a thin reader of the same composer * (#6422, the named-branch limb of the #5164 ruling): the composer constructs * each named entry's identity from the MAP KEY alone — the inner `name` is * ignored — and renames on collision (`.default` already claimed by - * the default `list` ⇒ `formViews.default` is registered as - * `.default_2`). Both facts live in the composer and nowhere else, so + * the default `list` ⇒ `listViews.default` is registered under a renamed + * key). Both facts live in the composer and nowhere else, so * both are asked of it, never re-derived. The rename matters even though the * view-ref lint makes collisions a hard error: this rule must agree with the * registry, not with another rule staying strict — under a collision the map @@ -1076,25 +1016,21 @@ function defaultFormViewKey(object: string | undefined, container: AnyRec): stri * different objects still gets each key filed under its own entry's binding by * the caller. */ -function namedViewKeys(container: AnyRec): { - list: Array; - form: Array; -} { +function namedViewKeys(container: AnyRec): Array { const object = 'probe'; const prefix = `${object}.`; const bare = (name: string) => (name.startsWith(prefix) ? name.slice(prefix.length) : name); - const countEntries = (v: unknown) => - isRec(v) ? Object.values(v).filter((e) => !!e && typeof e === 'object').length : 0; - const listCount = countEntries(container.listViews); - const formCount = countEntries(container.formViews); - if (!listCount && !formCount) return { list: [], form: [] }; - const items = expandViewContainer(object, container); - const keysOf = (kind: 'list' | 'form', count: number) => - items - .filter((i) => i.viewKind === kind) - .slice(0, count) - .map((i) => bare(i.name)); - return { list: keysOf('list', listCount), form: keysOf('form', formCount) }; + const listCount = isRec(container.listViews) + ? Object.values(container.listViews).filter((e) => !!e && typeof e === 'object').length + : 0; + if (!listCount) return []; + // The whole container goes to the composer, as the registry expands it, so + // a rename it makes is the rename the registry makes; only the list keys + // are read back. + return expandViewContainer(object, container) + .filter((i) => i.viewKind === 'list') + .slice(0, listCount) + .map((i) => bare(i.name)); } /** @@ -1588,8 +1524,7 @@ function buildUniverse(stack: AnyRec): Universe { collectViewRecord(view, factsFor); } // [ADR-0159 card ②] A `form` item's named sections are `_sections` facts of - // the object it binds to (its one `object`), the same anchor a form view's - // sections are. Its own label, title and panel live in the `forms` family, + // the object it binds to (its one `object`). Its own label, title and panel live in the `forms` family, // keyed by its name, so it contributes no `_views` fact. // [ADR-0159 D8] …and the form's own `forms..sections` node, read // before that default: the same sections and entries, keyed by the form. @@ -2208,33 +2143,38 @@ export function validateTranslationReferences( // _views. for (const [viewName, rawView] of Object.entries(asRecord(rawNode._views))) { - const isForm = facts.forms.has(viewName); - // A `title` key translates a FORM view's heading only: over a list - // view it resolves nothing (a list view has no title), where the - // author most likely meant the tab's `label`. - if (isRec(rawView) && 'title' in rawView && !isForm && facts.views.has(viewName)) { + // [ADR-0159 D8] `title` and `submitBehavior` were a form's tails + // under `_views`. A view holds lists only, so neither resolves + // anything there: a form's heading and panel are keyed at the + // form's own node, `forms.`. Reported on a view the + // object declares, and on a key that carries nothing else (the + // key a form in a view used to be translated under). + const onlyFormTails = isRec(rawView) + && Object.keys(rawView).length > 0 + && Object.keys(rawView).every((k) => FORM_ONLY_VIEW_TAILS.has(k)); + if (isRec(rawView) && 'title' in rawView && (facts.views.has(viewName) || onlyFormTails)) { orphan( `${inLocale} · object "${objectName}" · view "${viewName}"`, `${objPath}._views.${viewName}.title`, - `View "${viewName}" of object "${objectName}" is not a form view, so no title resolves this key.`, - `A view's tab label is keyed \`_views.${viewName}.label\`; only a form view has a \`title\`.`, + `No view of object "${objectName}" carries a heading, so no title resolves this key: a view holds ` + + `lists only, and a form is its own item.`, + `Key a form's heading as \`forms..title\` (the form's \`name\`, such as ` + + `"${objectName}.${viewName}"); a view's tab label is keyed \`_views.${viewName}.label\`.`, ); continue; } - // A `submitBehavior` key translates a FORM view's thank-you panel - // only: a list view submits nothing, so the key resolves nothing. - if (isRec(rawView) && 'submitBehavior' in rawView && !isForm && facts.views.has(viewName)) { + if (isRec(rawView) && 'submitBehavior' in rawView && (facts.views.has(viewName) || onlyFormTails)) { orphan( `${inLocale} · object "${objectName}" · view "${viewName}"`, `${objPath}._views.${viewName}.submitBehavior`, - `View "${viewName}" of object "${objectName}" is not a form view, so no thank-you panel resolves this key.`, - `Only a form view has a \`submitBehavior\`; key its panel under that form's own \`_views\` entry, or drop it.`, + `No view of object "${objectName}" submits anything, so no thank-you panel resolves this key: a view ` + + `holds lists only, and a form is its own item.`, + `Key a form's panel as \`forms..submitBehavior\` (the form's \`name\`, such as ` + + `"${objectName}.${viewName}"), or drop it.`, ); continue; } if (facts.views.has(viewName)) continue; - // The default form's key is legal for its form-only tails alone. - if (isForm && isRec(rawView) && Object.keys(rawView).every((k) => FORM_ONLY_VIEW_TAILS.has(k))) continue; orphan( `${inLocale} · object "${objectName}" · view "${viewName}"`, `${objPath}._views.${viewName}`, @@ -2259,9 +2199,9 @@ export function validateTranslationReferences( `${inLocale} · object "${objectName}" · section "${sectionName}" · entry "${fieldName}"`, `${objPath}._sections.${sectionName}.fields.${fieldName}`, `Translations are keyed to entry "${fieldName}" of section "${sectionName}", which no ` + - `form view section of that name on object "${objectName}" declares, so nothing reads them.` + + `form section of that name on object "${objectName}" declares, so nothing reads them.` + suggest(fieldName, entries), - `Key the entry by its \`field\` under a form view section's \`name\`, or drop the ` + + `Key the entry by its \`field\` under a form section's \`name\`, or drop the ` + `translation. A bare field name authors no copy: translate the field itself at ` + `\`objects.${objectName}.fields.${fieldName}\`.`, ); diff --git a/packages/lint/src/validate-view-containers.test.ts b/packages/lint/src/validate-view-containers.test.ts index 31347ad4128..faaec7459ce 100644 --- a/packages/lint/src/validate-view-containers.test.ts +++ b/packages/lint/src/validate-view-containers.test.ts @@ -29,7 +29,10 @@ describe('validateViewContainers (defineView container shape guardrail)', () => expect(findings).toHaveLength(0); }); - it('passes a container with only named listViews / formViews', () => { + // The second container holds only a retired slot (protocol 19 refuses + // `formViews` at the parse, with its prescription). Authored here on purpose: + // this rule must not also call it an empty container. + it('passes a container with only named listViews, and does not call one that holds only a retired form slot empty', () => { const findings = validateViewContainers({ views: [ { listViews: { urgent: { type: 'grid', columns: ['title'] } } }, @@ -146,8 +149,7 @@ describe('[#22161] one-line verdicts — view-container-shape', () => { + 'schema, this rule and the registration loop all refuse it.', 'Flat list-view object is not a view container: its single-view keys sit where the container slots ' + 'belong, so the stack schema and the registration loop refuse it.', - 'View container defines no views — all of `list` / `form` / `listViews` / `formViews` are absent or ' - + 'empty, so nothing registers.', + 'View container defines no views — `list` and `listViews` are both absent or empty, so nothing registers.', ]); }); @@ -168,7 +170,8 @@ describe('[#22161] one-line verdicts — view-container-shape', () => { expect(entry, 'no `os explain view-container-shape` entry').toBeDefined(); const text = entry!.paragraphs.join('\n'); for (const fact of [ - '`{ list, form, listViews, formViews }`', + '`{ list, listViews }`', + 'refused by the parse at that key', 'no switcher entry', '`ViewSchema` is strict', '`isViewContainerShaped`, 422 `INVALID_METADATA`', diff --git a/packages/lint/src/validate-view-containers.ts b/packages/lint/src/validate-view-containers.ts index 2d26eabefba..ea882f16f4a 100644 --- a/packages/lint/src/validate-view-containers.ts +++ b/packages/lint/src/validate-view-containers.ts @@ -4,8 +4,8 @@ // // A pure `(stack) => Finding[]` rule (ADR-0019), run from `os validate`. It // catches the container that registers ZERO views: `ViewSchema` is a container -// (`{ list, form, listViews, formViews }`) whose slots are all optional, so a -// container with none of them set is schema-valid, the loader finds nothing to +// (`{ list, listViews }`) whose slots are both optional, so a +// container with neither set is schema-valid, the loader finds nothing to // expand, and the Console silently renders no view (no switcher entry). The // third-party 15.1 evaluation hit exactly this via the old docs. // @@ -66,6 +66,10 @@ export const VIEW_CONTAINER_SHAPE = 'view-container-shape'; type AnyRec = Record; +// [ADR-0159 D7] `form` and `formViews` are retired slots from protocol 19: the +// parse refuses each at its own key, with its prescription. They stay in this +// list and in the count below so a raw config that still holds one is not +// also called an empty container here. const CONTAINER_SLOT_KEYS = ['list', 'form', 'listViews', 'formViews'] as const; /** Coerce an array-or-name-keyed-map collection to indexed entries. */ @@ -162,10 +166,10 @@ export function validateViewContainers(stack: Record): ViewCont message: looksFlat ? 'Flat list-view object is not a view container: its single-view keys sit where the ' + 'container slots belong, so the stack schema and the registration loop refuse it.' - : 'View container defines no views — all of `list` / `form` / `listViews` / ' - + '`formViews` are absent or empty, so nothing registers.', + : 'View container defines no views — `list` and `listViews` are both absent or ' + + 'empty, so nothing registers.', hint: 'Wrap every view in a defineView container: defineView({ list: { type, data, ' - + 'columns, ... }, listViews: { ... }, formViews: { ... } }). See ' + + 'columns, ... }, listViews: { ... } }). See ' + 'examples/app-showcase/src/ui/views/task.view.ts.', }); } diff --git a/packages/lint/src/validate-visibility-predicates.test.ts b/packages/lint/src/validate-visibility-predicates.test.ts index 45c8650bb3e..9d097431338 100644 --- a/packages/lint/src/validate-visibility-predicates.test.ts +++ b/packages/lint/src/validate-visibility-predicates.test.ts @@ -278,27 +278,24 @@ describe('the layer a site declares for itself (#7815)', () => { }); it('derives per SITE, not per stack — one entry can carry both kinds', () => { - // `formViews.` sub-containers each declare their own `data`, so a - // stack-level layer would be wrong for one of these two no matter which - // value it took. + // A schema-bound form view declares its own `data`, and a `forms[]` item + // binds a business object by `object` (ADR-0159 D2), so a stack-level layer + // would be wrong for one of these two no matter which value it took. const stack = { views: [{ - name: 'mixed', + name: 'meta', + data: { provider: 'schema', schemaId: 'field' }, + sections: [{ fields: [{ field: 'a', visibleWhen: "data.type == 'grid'" }] }], + }], + forms: [{ + name: 'account.live', object: 'account', - formViews: { - meta: { - data: { provider: 'schema', schemaId: 'field' }, - sections: [{ fields: [{ field: 'a', visibleWhen: "data.type == 'grid'" }] }], - }, - live: { - sections: [{ fields: [{ field: 'b', visibleWhen: "data.type == 'grid'" }] }], - }, - }, + sections: [{ fields: [{ field: 'b', visibleWhen: "data.type == 'grid'" }] }], }], }; const findings = validateVisibilityPredicates(stack); expect(findings.map((f) => f.rule)).toEqual([VISIBILITY_ROOT_MISLAYERED]); - expect(findings[0].path).toBe('views[0].formViews.live.sections[0].fields[0]'); + expect(findings[0].path).toBe('forms[0].sections[0].fields[0]'); }); it('`opts.layer` still governs every site that declares no data source', () => { @@ -468,55 +465,64 @@ describe('visibility-bare-identifier (#6128 / #5149 requirement 3)', () => { // ── The traversal the rule was measured against ───────────────────── // - // `os build` on examples/app-showcase emits its single view-form predicate at - // `views[0].formViews.edit.sections[0].fields[6].visibleWhen`: on the runtime - // app shape a `views[]` entry is a view CONTAINER, and `sections` live under - // `form` / `formViews.`. Reading only `views[].sections` reported clean - // on that stack — an `error`-level gate that cannot fire on the shape #5149's - // own repro used (an object create dialog's `type: 'tabbed'` form view). + // Under protocol 18 `os build` on examples/app-showcase emitted its single + // view-form predicate at + // `views[0].formViews.edit.sections[0].fields[6].visibleWhen`: a `views[]` + // entry was a view CONTAINER, and `sections` lived under `form` / + // `formViews.`. Reading only `views[].sections` reported clean on that + // stack — an `error`-level gate that could not fire on the shape #5149's own + // repro used. + // + // [ADR-0159 D9] From protocol 19 a real stack carries its forms as `forms[]` + // items, so that is the site these cases reach. A view container holds lists + // only, and its retired `form` / `formViews` slots are no site. describe('reaches the form views a real stack actually carries', () => { - it('a container\'s named `formViews.` — the shape app-showcase emits', () => { + it('a `forms[]` item — the shape app-showcase emits', () => { const stack = { views: [ { name: 'showcase_task', list: { type: 'grid' }, - formViews: { - edit: { type: 'simple', sections: [{ fields: [{ field: 'notes', visibleWhen: "priority == 'urgent'" }] }] }, - }, + }, + ], + forms: [ + { + name: 'showcase_task.edit', + object: 'showcase_task', + type: 'simple', + sections: [{ fields: [{ field: 'notes', visibleWhen: "priority == 'urgent'" }] }], }, ], }; expect(bareFindings(stack).map((f) => f.path)).toEqual([ - 'views[0].formViews.edit.sections[0].fields[0]', + 'forms[0].sections[0].fields[0]', ]); }); - it('names the sub-container in `where`, so two form views are distinguishable', () => { + it('names the form in `where`, so two forms of one object are distinguishable', () => { const stack = { - views: [ - { - object: 'showcase_task', - formViews: { - edit: { sections: [{ visibleWhen: 'approved', fields: [] }] }, - tabbed: { sections: [{ visibleWhen: 'approved', fields: [] }] }, - }, - }, + views: [{ object: 'showcase_task', list: { type: 'grid' } }], + forms: [ + { name: 'showcase_task.edit', object: 'showcase_task', sections: [{ visibleWhen: 'approved', fields: [] }] }, + { name: 'showcase_task.tabbed', object: 'showcase_task', sections: [{ visibleWhen: 'approved', fields: [] }] }, ], }; - // No `name` on the container (the emitted-artifact shape) — it falls back - // to the `object` binding, and the surface tells the two forms apart. expect(bareFindings(stack).map((f) => f.where).sort()).toEqual([ - 'view "showcase_task" · formViews.edit', - 'view "showcase_task" · formViews.tabbed', + 'form "showcase_task.edit"', + 'form "showcase_task.tabbed"', ]); }); - it('a container\'s DEFAULT `form`', () => { + it('a container\'s retired `form` and `formViews` slots are no site (ADR-0159 D7)', () => { + // The parse refuses both keys by name. Paired with a form item carrying + // the same predicate, so the silence on the slots is a verdict about the + // slots and not about an unread stack. + const section = { visibleWhen: 'approved', fields: [] }; const stack = { - views: [{ name: 'v', form: { sections: [{ visibleWhen: 'approved', fields: [] }] } }], + views: [{ name: 'v', form: { sections: [section] }, formViews: { edit: { sections: [section] } } }], + forms: [{ name: 'task.intake', object: 'task', sections: [section] }], }; - expect(bareFindings(stack).map((f) => f.path)).toEqual(['views[0].form.sections[0]']); + expect(bareFindings(stack).map((f) => f.path)).toEqual(['forms[0].sections[0]']); }); it('a bare form view whose `sections` sit at the top (the `defineMetadataForm` shape)', () => { @@ -524,12 +530,13 @@ describe('visibility-bare-identifier (#6128 / #5149 requirement 3)', () => { expect(bareFindings(stack).map((f) => f.path)).toEqual(['views[0].sections[0]']); }); - it('a name-keyed `views` map reports the KEY, not a synthetic index', () => { - const stack = { - views: { task_form: { formViews: { edit: { sections: [{ visibleWhen: 'approved', fields: [] }] } } } }, - }; - expect(bareFindings(stack).map((f) => f.path)).toEqual([ - 'views.task_form.formViews.edit.sections[0]', + it('a name-keyed collection reports the KEY, not a synthetic index', () => { + const section = { visibleWhen: 'approved', fields: [] }; + expect(bareFindings({ views: { task_form: { sections: [section] } } }).map((f) => f.path)).toEqual([ + 'views.task_form.sections[0]', + ]); + expect(bareFindings({ forms: { task_intake: { object: 'task', sections: [section] } } }).map((f) => f.path)).toEqual([ + 'forms.task_intake.sections[0]', ]); }); @@ -1155,12 +1162,13 @@ describe('visibility-predicate-syntax (#6253)', () => { expect(syntaxFindings(formStack({ dialect: 'cel', source: 'country === "USA"' }))).toHaveLength(1); }); - it('reaches a container\'s `formViews.` — the shape a real stack emits', () => { + it('reaches a `forms[]` item — the shape a real stack emits', () => { const stack = { - views: [{ object: 'showcase_task', formViews: { edit: { sections: [{ fields: [{ field: 'n', visibleWhen: 'country === "USA"' }] }] } } }], + views: [{ object: 'showcase_task', list: { type: 'grid' } }], + forms: [{ name: 'showcase_task.edit', object: 'showcase_task', sections: [{ fields: [{ field: 'n', visibleWhen: 'country === "USA"' }] }] }], }; expect(syntaxFindings(stack).map((f) => f.path)).toEqual([ - 'views[0].formViews.edit.sections[0].fields[0]', + 'forms[0].sections[0].fields[0]', ]); }); @@ -1879,11 +1887,12 @@ describe('visibility-predicate-has-argument (#25281)', () => { expect(hasArgFindings(formStack({ dialect: 'cel', source: 'has(status)' }))).toHaveLength(1); }); - it('reaches a container\'s `formViews.`', () => { + it('reaches a `forms[]` item', () => { const stack = { - views: [{ object: 'showcase_task', formViews: { edit: { sections: [{ fields: [{ field: 'n', visibleWhen: 'has(status)' }] }] } } }], + views: [{ object: 'showcase_task', list: { type: 'grid' } }], + forms: [{ name: 'showcase_task.edit', object: 'showcase_task', sections: [{ fields: [{ field: 'n', visibleWhen: 'has(status)' }] }] }], }; - expect(hasArgFindings(stack).map((f) => f.path)).toEqual(['views[0].formViews.edit.sections[0].fields[0]']); + expect(hasArgFindings(stack).map((f) => f.path)).toEqual(['forms[0].sections[0].fields[0]']); }); }); }); diff --git a/packages/lint/src/validate-visibility-predicates.ts b/packages/lint/src/validate-visibility-predicates.ts index 7f15e891a4d..2e4bc1f86c1 100644 --- a/packages/lint/src/validate-visibility-predicates.ts +++ b/packages/lint/src/validate-visibility-predicates.ts @@ -97,12 +97,11 @@ * from the caller (`opts.layer`, default `'runtime'`) only where it does not — * see §Which layer a site is on (#7815). * - * Scope: `views` — every form view reachable from a `views[]` entry (the entry - * itself when it IS a form view, plus the container's `form` and each - * `formViews.`), through the shared `view-walk.ts` ladder (#6381; see - * {@link formViewSites} for why reading only the first shape left this rule - * reporting clean on real metadata, and why `listViews.` is filtered out - * rather than absent) — and `pages`, through the shared `walkPageComponents` + * Scope ([ADR-0159 D9]): every `forms[]` item, and a `views[]` entry that IS a + * bare form view (the metadata-editing form shape), through the shared + * `view-walk.ts` walk ({@link formItemSites}, {@link formViewSites}; a view + * container holds lists only, and `listViews.` is filtered out rather + * than absent) — and `pages`, through the shared `walkPageComponents` * traversal. Data-field `visibleWhen` is already covered by * `validate-expressions` and is not re-checked here. * @@ -513,8 +512,8 @@ * advisory that is wrong on correct metadata, at the publish door, for a whole * surface class — and nothing goes red, which is what made it survive. * - * Derived per SITE rather than per stack because one `views[]` entry can carry - * both kinds (`formViews.` sub-containers each declare their own `data`), + * Derived per SITE rather than per stack because one stack carries both kinds + * (each form declares its own `data`), * and it is derived from the same `schemaIdOf` call that decides `literalRhs`, * so the layer verdict and the right-hand-slot stand-down can never disagree * about which surface they are on — the reason `schemaIdOf` is shared in the @@ -563,7 +562,7 @@ import { collectionEntries } from './collection-entries.js'; import type { UserTextParams } from './finding-user-text.js'; import { walkPageComponents } from './page-walk.js'; import { COMPREHENSION_MACROS, bareRhsOnlyIdentifiers, schemaIdOf } from './predicate-rhs-position.js'; -import { formViewSites } from './view-walk.js'; +import { formItemName, formItemSites, formViewSites, type ViewSite } from './view-walk.js'; export const VISIBILITY_ROOT_MISLAYERED = 'visibility-root-mislayered'; export const VISIBILITY_BARE_IDENTIFIER = 'visibility-bare-identifier'; @@ -657,11 +656,11 @@ export interface VisibilityFinding { } /** - * The element's owning surface, as the user sentence names it: the view or - * page, by the name the finding's `where` already shows. + * The element's owning surface, as the user sentence names it: the form, view + * or page, by the name the finding's `where` already shows. */ interface VisibilitySubject { - surface: 'view' | 'page'; + surface: 'form' | 'view' | 'page'; name: string; } @@ -1684,17 +1683,31 @@ export function validateVisibilityPredicates( const declaredLayer: VisibilityLayer = opts.layer ?? 'runtime'; const findings: VisibilityFinding[] = []; - // ── Views: every reachable form view's sections / groups, and their fields ── + // ── Forms: every form's sections / groups, and their fields ── + // + // [ADR-0159 D9] A form is a `forms[]` item; a `views[]` entry that is a bare + // form view (the metadata-editing form shape) is judged beside them. + const formSites: Array<{ site: ViewSite; where: string; subject: VisibilitySubject }> = []; + for (const site of formItemSites(stack)) { + const name = formItemName(site); + formSites.push({ site, where: `form "${name}"`, subject: { surface: 'form', name } }); + } for (const { rec: view, path: viewPath } of collectionEntries(stack.views, 'views')) { // A container names itself with `name`, or binds with `object` — and an // artifact-emitted one may carry neither, so the path is the last resort. const viewName = typeof view.name === 'string' ? view.name : typeof view.object === 'string' ? view.object : viewPath; - const viewSubject: VisibilitySubject = { surface: 'view', name: viewName }; - for (const site of formViewSites(view, viewPath)) { - const where = site.surface ? `view "${viewName}" · ${site.surface}` : `view "${viewName}"`; + formSites.push({ + site, + where: site.surface ? `view "${viewName}" · ${site.surface}` : `view "${viewName}"`, + subject: { surface: 'view', name: viewName }, + }); + } + } + { + for (const { site, where, subject: viewSubject } of formSites) { // A `{ provider: 'schema', schemaId }` data source is a METADATA-EDITING // form — the surface the console renders through its own predicate // evaluator, whose right-hand slot is a literal slot (objectui#4049). diff --git a/packages/lint/src/validate-visibility-predicates.user-text.ts b/packages/lint/src/validate-visibility-predicates.user-text.ts index 8256f30eab3..5883ab838cc 100644 --- a/packages/lint/src/validate-visibility-predicates.user-text.ts +++ b/packages/lint/src/validate-visibility-predicates.user-text.ts @@ -8,7 +8,7 @@ * own half of it, kept beside the rule so its wording and its translations * change together. * - * Who reads it: the person who saved a view or a page in Studio, in their own + * Who reads it: the person who saved a form, a view or a page in Studio, in their own * language, once the save door composes `RuntimeAuthoringIssueSchema.userMessage` * from it. So it says what the element does (it always shows) and the one * change that fixes it, in the console's own words: the `visibleWhen` rule, as @@ -17,14 +17,14 @@ * * Every other id of the family gates (it is an error, refused at the door with * its own English `message`), so this is the only entry. It reaches the - * publish door on a `view` and on a `page` write. + * publish door on a `form`, a `view` and a `page` write. * * The entry reads the `userTextParams` set at the push site (`checkElement`): * * | param | value | * |---|---| - * | `surface` | `view` · `page` — the element's owner, which picks the noun | - * | `name` | the view's or page's name, as the finding's `where` shows it | + * | `surface` | `form` · `view` · `page` — the element's owner, which picks the noun | + * | `name` | the form's, view's or page's name, as the finding's `where` shows it | * | `root` | the root the predicate wrongly uses: `data` on a runtime view or page (write `record.`), `record` on a metadata-editing form (write `data.`) | * * `finding-user-text.pages-forms.test.ts` renders the entry from the rule's @@ -35,15 +35,16 @@ import type { UserTextCatalog, UserTextParams } from './finding-user-text.js'; import { VISIBILITY_ROOT_MISLAYERED } from './validate-visibility-predicates.js'; /** The noun for the element's owner, per locale. */ -type SurfaceNouns = { readonly view: string; readonly page: string }; -const noun = (nouns: SurfaceNouns, p: UserTextParams): string => (p.surface === 'page' ? nouns.page : nouns.view); +type SurfaceNouns = { readonly form: string; readonly view: string; readonly page: string }; +const noun = (nouns: SurfaceNouns, p: UserTextParams): string => + (p.surface === 'page' ? nouns.page : p.surface === 'form' ? nouns.form : nouns.view); /** A metadata-editing form binds `data`; its predicate used `record`. */ const onMetadataForm = (p: UserTextParams): boolean => p.root === 'record'; export const VISIBILITY_PREDICATES_USER_TEXT: UserTextCatalog = Object.freeze({ [VISIBILITY_ROOT_MISLAYERED]: { en: (p) => { - const where = `${noun({ view: 'view', page: 'page' }, p)} "${p.name}"`; + const where = `${noun({ form: 'form', view: 'view', page: 'page' }, p)} "${p.name}"`; return onMetadataForm(p) ? `A visibleWhen rule on ${where} starts with "record.", but this form edits metadata and provides ` + `"data." instead, so the rule never matches and the element is always shown. Start the rule with ` + @@ -53,7 +54,7 @@ export const VISIBILITY_PREDICATES_USER_TEXT: UserTextCatalog = Object.freeze({ `record.status == 'open').`; }, 'zh-Hans': (p) => { - const where = `${noun({ view: '视图', page: '页面' }, p)}“${p.name}”`; + const where = `${noun({ form: '表单', view: '视图', page: '页面' }, p)}“${p.name}”`; return onMetadataForm(p) ? `${where}上的 visibleWhen 规则以“record.”开头,但这个表单编辑的是元数据,提供的是“data.”,` + `因此该规则永远不会匹配,元素始终显示。请让规则以“data.”开头(例如 data.type == 'grid')。` @@ -61,7 +62,7 @@ export const VISIBILITY_PREDICATES_USER_TEXT: UserTextCatalog = Object.freeze({ `因此该规则永远不会匹配,元素始终显示。请让规则以“record.”开头(例如 record.status == 'open')。`; }, 'zh-Hant': (p) => { - const where = `${noun({ view: '檢視', page: '頁面' }, p)}「${p.name}」`; + const where = `${noun({ form: '表單', view: '檢視', page: '頁面' }, p)}「${p.name}」`; return onMetadataForm(p) ? `${where}上的 visibleWhen 規則以「record.」開頭,但這個表單編輯的是中繼資料,提供的是「data.」,` + `因此該規則永遠不會符合,元素始終顯示。請讓規則以「data.」開頭(例如 data.type == 'grid')。` @@ -69,17 +70,17 @@ export const VISIBILITY_PREDICATES_USER_TEXT: UserTextCatalog = Object.freeze({ `因此該規則永遠不會符合,元素始終顯示。請讓規則以「record.」開頭(例如 record.status == 'open')。`; }, es: (p) => { - const where = `${noun({ view: 'la vista', page: 'la página' }, p)} "${p.name}"`; + const where = `${noun({ form: 'del formulario', view: 'de la vista', page: 'de la página' }, p)} "${p.name}"`; return onMetadataForm(p) - ? `Una regla visibleWhen de ${where} empieza por "record.", pero este formulario edita metadatos y ` + + ? `Una regla visibleWhen ${where} empieza por "record.", pero este formulario edita metadatos y ` + `ofrece "data.", así que la regla nunca coincide y el elemento se muestra siempre. Empiece la regla por ` + `"data." (por ejemplo, data.type == 'grid').` - : `Una regla visibleWhen de ${where} empieza por "data.", que solo ofrece un formulario de edición de ` + + : `Una regla visibleWhen ${where} empieza por "data.", que solo ofrece un formulario de edición de ` + `metadatos, así que la regla nunca coincide y el elemento se muestra siempre. Empiece la regla por ` + `"record." (por ejemplo, record.status == 'open').`; }, ar: (p) => { - const where = `${noun({ view: 'العرض', page: 'الصفحة' }, p)} "${p.name}"`; + const where = `${noun({ form: 'النموذج', view: 'العرض', page: 'الصفحة' }, p)} "${p.name}"`; return onMetadataForm(p) ? `تبدأ قاعدة visibleWhen في ${where} بـ "record."، لكن هذا النموذج يحرّر البيانات الوصفية ويوفّر "data." ` + `بدلًا منها، لذلك لا تتطابق القاعدة أبدًا ويظهر العنصر دائمًا. ابدأ القاعدة بـ "data." ` + @@ -89,17 +90,17 @@ export const VISIBILITY_PREDICATES_USER_TEXT: UserTextCatalog = Object.freeze({ `(مثلًا record.status == 'open').`; }, fr: (p) => { - const where = `${noun({ view: 'la vue', page: 'la page' }, p)} « ${p.name} »`; + const where = `${noun({ form: 'du formulaire', view: 'de la vue', page: 'de la page' }, p)} « ${p.name} »`; return onMetadataForm(p) - ? `Une règle visibleWhen de ${where} commence par « record. », mais ce formulaire modifie des ` + + ? `Une règle visibleWhen ${where} commence par « record. », mais ce formulaire modifie des ` + `métadonnées et fournit « data. » : la règle ne correspond donc jamais et l'élément est toujours ` + `affiché. Commencez la règle par « data. » (par exemple data.type == 'grid').` - : `Une règle visibleWhen de ${where} commence par « data. », que seul un formulaire d'édition de ` + + : `Une règle visibleWhen ${where} commence par « data. », que seul un formulaire d'édition de ` + `métadonnées fournit : la règle ne correspond donc jamais et l'élément est toujours affiché. ` + `Commencez la règle par « record. » (par exemple record.status == 'open').`; }, 'pt-BR': (p) => { - const where = `${noun({ view: 'da visualização', page: 'da página' }, p)} "${p.name}"`; + const where = `${noun({ form: 'do formulário', view: 'da visualização', page: 'da página' }, p)} "${p.name}"`; return onMetadataForm(p) ? `Uma regra visibleWhen ${where} começa com "record.", mas este formulário edita metadados e ` + `oferece "data.", então a regra nunca corresponde e o elemento é sempre exibido. Comece a regra com ` + @@ -109,7 +110,7 @@ export const VISIBILITY_PREDICATES_USER_TEXT: UserTextCatalog = Object.freeze({ `"record." (por exemplo, record.status == 'open').`; }, ru: (p) => { - const where = `${noun({ view: 'в представлении', page: 'на странице' }, p)} «${p.name}»`; + const where = `${noun({ form: 'в форме', view: 'в представлении', page: 'на странице' }, p)} «${p.name}»`; return onMetadataForm(p) ? `Правило visibleWhen ${where} начинается с «record.», но эта форма редактирует метаданные и ` + `предоставляет «data.», поэтому правило никогда не срабатывает и элемент отображается всегда. ` + @@ -119,17 +120,17 @@ export const VISIBILITY_PREDICATES_USER_TEXT: UserTextCatalog = Object.freeze({ `Начните правило с «record.» (например, record.status == 'open').`; }, de: (p) => { - const where = `${noun({ view: 'der Ansicht', page: 'der Seite' }, p)} „${p.name}“`; + const where = `${noun({ form: 'im Formular', view: 'in der Ansicht', page: 'in der Seite' }, p)} „${p.name}“`; return onMetadataForm(p) - ? `Eine visibleWhen-Regel in ${where} beginnt mit „record.“, aber dieses Formular bearbeitet Metadaten ` + + ? `Eine visibleWhen-Regel ${where} beginnt mit „record.“, aber dieses Formular bearbeitet Metadaten ` + `und stellt „data.“ bereit. Die Regel trifft daher nie zu, und das Element wird immer angezeigt. ` + `Beginnen Sie die Regel mit „data.“ (zum Beispiel data.type == 'grid').` - : `Eine visibleWhen-Regel in ${where} beginnt mit „data.“, das nur ein Formular zum Bearbeiten von ` + + : `Eine visibleWhen-Regel ${where} beginnt mit „data.“, das nur ein Formular zum Bearbeiten von ` + `Metadaten bereitstellt. Die Regel trifft daher nie zu, und das Element wird immer angezeigt. ` + `Beginnen Sie die Regel mit „record.“ (zum Beispiel record.status == 'open').`; }, ja: (p) => { - const where = `${noun({ view: 'ビュー', page: 'ページ' }, p)}「${p.name}」`; + const where = `${noun({ form: 'フォーム', view: 'ビュー', page: 'ページ' }, p)}「${p.name}」`; return onMetadataForm(p) ? `${where}の visibleWhen ルールは「record.」で始まっていますが、このフォームはメタデータを編集する` + `フォームで「data.」を提供するため、ルールは一致せず、要素は常に表示されます。ルールを「data.」で` + @@ -139,7 +140,7 @@ export const VISIBILITY_PREDICATES_USER_TEXT: UserTextCatalog = Object.freeze({ `始めてください(例: record.status == 'open')。`; }, ko: (p) => { - const where = `${noun({ view: '보기', page: '페이지' }, p)} "${p.name}"`; + const where = `${noun({ form: '양식', view: '보기', page: '페이지' }, p)} "${p.name}"`; return onMetadataForm(p) ? `${where}의 visibleWhen 규칙이 "record."로 시작하지만, 이 양식은 메타데이터를 편집하는 양식이라 ` + `"data."를 제공하므로 규칙이 일치하지 않고 요소가 항상 표시됩니다. 규칙을 "data."로 시작하세요 ` + diff --git a/packages/lint/src/view-walk.test.ts b/packages/lint/src/view-walk.test.ts index 817a8b801fa..c08e7090d62 100644 --- a/packages/lint/src/view-walk.test.ts +++ b/packages/lint/src/view-walk.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'; -import { viewContainerSites, formViewSites, viewObjectName } from './view-walk.js'; +import { viewContainerSites, formViewSites, formItemSites, formItemName, viewObjectName } from './view-walk.js'; import { validateVisibilityPredicates } from './validate-visibility-predicates.js'; import { validateFormLayout } from './validate-form-layout.js'; import { validateTranslatableSections } from './validate-translatable-sections.js'; @@ -16,21 +16,32 @@ describe('viewContainerSites — the ladder (#6381)', () => { name: 'case_views', sections: [], list: { type: 'grid' }, - form: { sections: [] }, listViews: { all: { type: 'grid' }, mine: { type: 'grid' } }, - formViews: { edit: { sections: [] }, create: { sections: [] } }, }; // Order is contract, not accident: findings are emitted in walk order, so - // `self → form → listViews.* → formViews.*` is what both consumers' - // pinned output orders depend on. + // `self → listViews.*` is what the consumers' pinned output orders depend + // on. expect(viewContainerSites(view, 'views[0]')).toEqual([ { view, path: 'views[0]', surface: '', kind: 'self' }, - { view: view.form, path: 'views[0].form', surface: 'form', kind: 'form' }, { view: (view.listViews as AnyRec).all, path: 'views[0].listViews.all', surface: 'listViews.all', kind: 'listView' }, { view: (view.listViews as AnyRec).mine, path: 'views[0].listViews.mine', surface: 'listViews.mine', kind: 'listView' }, - { view: (view.formViews as AnyRec).edit, path: 'views[0].formViews.edit', surface: 'formViews.edit', kind: 'formView' }, - { view: (view.formViews as AnyRec).create, path: 'views[0].formViews.create', surface: 'formViews.create', kind: 'formView' }, + ]); + }); + + it('a container\'s retired `form` and `formViews` slots are no rung (ADR-0159 D7)', () => { + // Protocol 19 refuses both keys at the parse, with a prescription naming + // `forms:`. A raw source that still carries them is walked for its lists + // alone; the forms are read where they live now (`formItemSites`). + const view: AnyRec = { + name: 'case_views', + form: { sections: [{ label: 'Basics' }] }, + listViews: { all: { type: 'grid' } }, + formViews: { edit: { sections: [{ label: 'Basics' }] } }, + }; + expect(viewContainerSites(view, 'views[0]').map((s) => [s.kind, s.path])).toEqual([ + ['self', 'views[0]'], + ['listView', 'views[0].listViews.all'], ]); }); @@ -49,17 +60,16 @@ describe('viewContainerSites — the ladder (#6381)', () => { }); it('skips a rung that is not a record (string / array / number / null)', () => { - const sites = viewContainerSites( - { form: 'nope', formViews: ['nope'], listViews: 42, list: null }, - 'views[0]', - ); - expect(sites.map((s) => s.kind)).toEqual(['self']); + for (const listViews of ['nope', ['nope'], 42, null]) { + const sites = viewContainerSites({ listViews, list: null }, 'views[0]'); + expect(sites.map((s) => s.kind), JSON.stringify(listViews)).toEqual(['self']); + } }); it('skips a non-record sub-entry but keeps its record siblings', () => { const ok = { sections: [] }; - const sites = viewContainerSites({ formViews: { bad: null, ok } }, 'views[0]'); - expect(sites.map((s) => s.path)).toEqual(['views[0]', 'views[0].formViews.ok']); + const sites = viewContainerSites({ listViews: { bad: null, ok } }, 'views[0]'); + expect(sites.map((s) => s.path)).toEqual(['views[0]', 'views[0].listViews.ok']); expect(sites[1].view).toBe(ok); }); @@ -68,18 +78,44 @@ describe('viewContainerSites — the ladder (#6381)', () => { }); }); -describe('formViewSites — the form-carrying subset', () => { +describe('formItemSites — the `forms[]` items (ADR-0159 D9)', () => { + it('yields one site per item, in collection order, at the item itself', () => { + const intake = { name: 'crm_case.intake', object: 'crm_case', sections: [] }; + const survey = { name: 'crm_case.survey', object: 'crm_case', sections: [] }; + expect(formItemSites({ forms: [intake, survey] })).toEqual([ + { view: intake, path: 'forms[0]', surface: '', kind: 'form' }, + { view: survey, path: 'forms[1]', surface: '', kind: 'form' }, + ]); + }); + + it('reads a name-keyed map too, at a path an author can look up', () => { + const sites = formItemSites({ forms: { 'crm_case.intake': { object: 'crm_case', sections: [] } } }); + expect(sites.map((s) => [s.kind, s.path, formItemName(s)])).toEqual([ + ['form', 'forms.crm_case.intake', 'crm_case.intake'], + ]); + }); + + it('skips an entry that is not a record, and a stack with no `forms`', () => { + const ok = { name: 'crm_case.intake', object: 'crm_case' }; + expect(formItemSites({ forms: [null, 'nope', ok] }).map((s) => s.view)).toEqual([ok]); + expect(formItemSites({})).toEqual([]); + expect(formItemSites({ forms: 42 })).toEqual([]); + }); + + it('names an item by its `name`, else by its path', () => { + expect(formItemSites({ forms: [{ object: 'crm_case' }] }).map(formItemName)).toEqual(['forms[0]']); + }); +}); + +describe('formViewSites — the form-carrying subset of a `views[]` entry', () => { const view: AnyRec = { - form: { sections: [] }, + sections: [], listViews: { all: { sections: [] } }, - formViews: { edit: { sections: [] } }, }; - it('is the ladder minus `listViews.*`, order preserved', () => { + it('is the ladder minus `listViews.*`: the entry itself', () => { expect(formViewSites(view, 'views[0]').map((s) => [s.kind, s.path])).toEqual([ ['self', 'views[0]'], - ['form', 'views[0].form'], - ['formView', 'views[0].formViews.edit'], ]); }); @@ -94,7 +130,7 @@ describe('formViewSites — the form-carrying subset', () => { }); /** - * The property this convergence buys: ONE ladder, THREE consumers. + * The property this convergence buys: ONE walk, THREE consumers. * * Each rung below is fed to all three rules at once. Break a rung in * `view-walk.ts` and every column of the table that depends on it goes red @@ -128,14 +164,30 @@ describe('one ladder, three consumers (#6381)', () => { ], }); - const rungs: Array<{ rung: string; view: AnyRec; sitePath: string }> = [ - { rung: 'the entry itself (bare form view)', view: { object: 'crm_case', ...body() }, sitePath: 'views[0]' }, - { rung: 'the container default `form` (#5415)', view: { object: 'crm_case', form: body() }, sitePath: 'views[0].form' }, - { rung: '`formViews.`', view: { object: 'crm_case', formViews: { edit: body() } }, sitePath: 'views[0].formViews.edit' }, + const rungs: Array<{ rung: string; stack: AnyRec; sitePath: string }> = [ + { + rung: 'the entry itself (bare form view)', + stack: { objects, views: [{ name: 'case_views', object: 'crm_case', ...body() }], translations }, + sitePath: 'views[0]', + }, + { + rung: 'a `forms[]` item (ADR-0159 D9)', + stack: { objects, forms: [{ name: 'crm_case.edit', object: 'crm_case', ...body() }], translations }, + sitePath: 'forms[0]', + }, + { + rung: 'a `forms[]` item beside a list-only container, at its own index', + stack: { + objects, + views: [{ name: 'case_views', object: 'crm_case', list: { type: 'grid' } }], + forms: [{ name: 'crm_case.form', object: 'crm_case', sections: [] }, { name: 'crm_case.edit', object: 'crm_case', ...body() }], + translations, + }, + sitePath: 'forms[1]', + }, ]; - for (const { rung, view, sitePath } of rungs) { - const stack = { objects, views: [{ name: 'case_views', ...view }], translations }; + for (const { rung, stack, sitePath } of rungs) { it(`all three rules reach ${rung}`, () => { const visibility = validateVisibilityPredicates(stack); @@ -237,9 +289,8 @@ describe('viewObjectName — the base binding ladder (#6662)', () => { /** * The property this convergence buys: ONE base ladder, THREE binding consumers. * - * The stack below binds its view through the DEEPEST rung only - * (`data.object`) — the rung a hand-written ladder is likeliest to drop, and the - * one the canonical container shape actually uses. All three rules must resolve + * The stack below binds its form through the item's own `object`, the one + * binding a `form` item carries (ADR-0159 D2). All three rules must resolve * `crm_case` from it, and each is asserted through an observable that only * exists when the binding resolved: * @@ -258,17 +309,13 @@ describe('viewObjectName — the base binding ladder (#6662)', () => { describe('one base ladder, three binding consumers (#6662)', () => { const objects = [{ name: 'crm_case', fields: { subject: { type: 'text' } } }]; - /** A container whose ONLY binding is the deepest rung, on the container itself. */ - const container = (data: unknown) => ({ - name: 'case_views', - ...(data === undefined ? {} : { data }), - formViews: { - edit: { - sections: [ - { name: 'basics', label: 'Basics', fields: ['ghost_field'] }, - ], - }, - }, + /** A form item whose ONLY binding is its own `object`, the rung a `form` item binds by. */ + const container = (object: string | undefined) => ({ + name: 'crm_case.edit', + ...(object === undefined ? {} : { object }), + sections: [ + { name: 'basics', label: 'Basics', fields: ['ghost_field'] }, + ], }); const translations = [ @@ -281,13 +328,13 @@ describe('one base ladder, three binding consumers (#6662)', () => { }, ]; - const bound = { objects, views: [container({ provider: 'object', object: 'crm_case' })], translations }; - const unbound = { objects, views: [container(undefined)], translations }; + const bound = { objects, forms: [container('crm_case')], translations }; + const unbound = { objects, forms: [container(undefined)], translations }; it('validate-form-layout resolves it — and reference-checks against it', () => { const findings = validateFormLayout(bound); expect(findings.map((f) => f.path)).toEqual([ - 'views[0].formViews.edit.sections[0].fields[0]', + 'forms[0].sections[0].fields[0]', ]); expect(findings[0].message).toContain('crm_case'); @@ -302,31 +349,31 @@ describe('one base ladder, three binding consumers (#6662)', () => { // nameless section the rule does report. const nameless = { objects, - views: [ + forms: [ { - name: 'case_views', - data: { provider: 'object', object: 'crm_case' }, - formViews: { edit: { sections: [{ label: 'Basics' }] } }, + name: 'crm_case.edit', + object: 'crm_case', + sections: [{ label: 'Basics' }], }, ], translations, }; const findings = validateTranslatableSections(nameless); - expect(findings.map((f) => f.path)).toEqual(['views[0].formViews.edit.sections[0]']); + expect(findings.map((f) => f.path)).toEqual(['forms[0].sections[0]']); expect(findings[0].where).toContain('object "crm_case"'); // Negative half: strip the binding and the rule has no object to judge // against, so it reports nothing at all. const stripped = { ...nameless, - views: [{ name: 'case_views', formViews: { edit: { sections: [{ label: 'Basics' }] } } }], + forms: [{ name: 'crm_case.edit', sections: [{ label: 'Basics' }] }], }; expect(validateTranslatableSections(stripped)).toEqual([]); }); it('validate-translation-references resolves it — and files sections under it', () => { - // Accepted: `basics` is declared on a form bound to `crm_case` by the - // deepest rung, so the bundle translating it names something that renders. + // Accepted: `basics` is declared on a form bound to `crm_case` by its own + // `object`, so the bundle translating it names something that renders. expect(validateTranslationReferences(bound)).toEqual([]); // Negative half: with the binding gone the section is filed under no diff --git a/packages/lint/src/view-walk.ts b/packages/lint/src/view-walk.ts index 5f24e2efd30..e88ab9fd246 100644 --- a/packages/lint/src/view-walk.ts +++ b/packages/lint/src/view-walk.ts @@ -7,9 +7,8 @@ * This walk had grown THREE independent implementations in this package, and * the same rung was measured missing twice in two consecutive issues. Both * times the traversal read only the container's own keys and therefore reported - * clean on real app metadata: `os build` on `examples/app-showcase` emits its - * form sections at `views[0].formViews.edit.sections[…]`, and a walker that - * reads `views[0].sections` finds nothing there. + * clean on real app metadata, whose form sections sat one level down in the + * container, where a walker that reads `views[0].sections` finds nothing. * * - `validate-visibility-predicates.ts` — hole found by #6128, fixed by #6248. * - `validate-form-layout.ts` — same hole, same rule family, found by #6251, @@ -25,35 +24,35 @@ * * ## The ladder, rung by rung, and what the schema says about each * - * A `views[]` entry is authored in one of two shapes, and the rungs below cover - * both: - * - * - **View CONTAINER** (the runtime app shape). `ViewSchema` - * (`packages/spec/src/ui/view.zod.ts:1885`) is a `strictObject` whose own - * keys are `name` / `label` / `object` / `list` / `form` / `listViews` / - * `formViews` (`view.zod.ts:1926-1929`). Sections therefore live one level - * down. - * - **A bare FORM VIEW** (`FormViewSchema`, `view.zod.ts:1599`), whose - * `sections` (`:1649`) and `groups` (`:1650`, the legacy alias) sit at the - * top. This is the `defineMetadataForm` shape the `*.metadata-form.ts` metadata-editing forms - * use. - * - * | rung | `kind` | why it is walked | - * | --- | --- | --- | - * | the entry itself | `self` | the bare `FormViewSchema` shape | - * | `form` | `form` | the container's DEFAULT form (#5415) | - * | `listViews.` | `listView` | `objects[].listViews` / container list views — see below | - * | `formViews.` | `formView` | the named form views #6128 / #6251 both missed | - * - * ### `form` — the default anchor, established deliberately (#5415) - * - * The container's `form` is the one `defineView({ form: … })` declares and - * `ObjectForm` renders when no named form view is asked for. It is neither a - * `formViews.*` entry nor the record's own `sections`, so a walker that - * enumerates only those two misses it — which is exactly what #5415 measured - * against `examples/app-showcase`'s `contact.view.ts`: four correctly - * translated section headings reported as stale keys. All three ladders walk - * this rung today and it must stay walked. + * From protocol 19 a form is its own metadata item and a `view` holds lists + * only (ADR-0159 D7, D9: "the walker reads form items"). So the records that + * can carry `sections` sit in two collections, and this file walks both: + * + * - **A `forms[]` item** (`FormSchema`, `defineForm`): `name`, `object` and + * the form body at the top level, `sections` and `groups` (the legacy + * alias) included. {@link formItemSites} yields one site per item. + * - **A `views[]` entry**, in one of two shapes. A view CONTAINER + * (`ViewSchema`, a `strictObject` whose slots are `list` and `listViews`) + * carries no section of its own. A bare FORM VIEW (`FormViewSchema`), whose + * `sections` and `groups` sit at the top, is the `defineMetadataForm` shape + * the `*.metadata-form.ts` metadata-editing forms use. + * {@link viewContainerSites} yields the entry and its `listViews.`. + * + * | collection | rung | `kind` | why it is walked | + * | --- | --- | --- | --- | + * | `forms[]` | the item itself | `form` | a `form` item, the one place an app authors a form | + * | `views[]` | the entry itself | `self` | the bare `FormViewSchema` shape | + * | `views[]` | `listViews.` | `listView` | `objects[].listViews` / container list views — see below | + * + * ### The container's `form` and `formViews.` — retired rungs + * + * Through protocol 18 a container also held a default `form` and named + * `formViews.`, and this ladder walked both. Protocol 19 tombstones the + * two keys: the parse refuses each at its own key with a prescription naming + * `forms:`, and the major's conversion moves each form to a `forms[]` item. A + * rung keyed on either could only fire for a stack the schema already refuses + * by name, so both are gone and the forms they held are walked where they + * live now. * * ### `listViews.` — kept, and why it is not deleted as dead * @@ -104,36 +103,38 @@ * `validate-form-layout` falls back to the container, * `validate-translatable-sections` falls back to the container and then to the * default `list`'s binding, `validate-translation-references` falls back to the - * record, and `validate-visibility-predicates` needs no binding at all. Folding + * record, and `validate-visibility-predicates` needs no binding at all. A + * `forms[]` item needs no fallback: it carries its own `object`. Folding * those fallbacks into one walk would change verdicts, which a refactor may not * do; sharing the rung they all start from cannot. */ +import { collectionEntries } from './collection-entries.js'; + type AnyRec = Record; -/** Which rung of the container ladder a site sits on. */ -export type ViewSiteKind = 'self' | 'form' | 'listView' | 'formView'; +/** Which rung a site sits on: a `forms[]` item, a `views[]` entry, or one of its `listViews`. */ +export type ViewSiteKind = 'self' | 'form' | 'listView'; /** One record on the ladder, with everything a rule needs to locate it. */ export interface ViewSite { - /** The record itself — the `views[]` entry, or one of its sub-containers. */ + /** The record itself — a `forms[]` item, a `views[]` entry, or one of its `listViews`. */ view: AnyRec; /** - * Config path of that record — `views[0]`, `views[0].form`, - * `views[0].formViews.edit`. Consumers append the bucket they read + * Config path of that record — `forms[0]`, `views[0]`, + * `views[0].listViews.all`. Consumers append the bucket they read * (`.sections`, `.groups[2].fields[1]`, …); findings are consumed as edit * targets (`os lint --json`, Studio's finding renderer), so the path has to * be one an author can actually look up. */ path: string; /** - * The sub-container segment for a human-readable `where`, WITHOUT the view's - * own name — `''` for the entry itself, else `form` / `formViews.edit` / - * `listViews.all`. It earns its place on exactly the shape this traversal was - * extended for: a runtime container carries neither `name` nor `object` in - * the emitted artifact, so without it every finding under one view reads - * `view "views[0]"` and the author cannot tell the `edit` form from the - * `create` one. + * The sub-container segment for a human-readable `where`, WITHOUT the + * record's own name — `''` for a `forms[]` item and for a `views[]` entry + * itself, else `listViews.all`. A runtime container carries neither `name` + * nor `object` in the emitted artifact, so without it every finding under + * one view reads `view "views[0]"` and the author cannot tell one of its + * list views from another. */ surface: string; /** Which rung this is — see {@link ViewSiteKind}. */ @@ -186,8 +187,9 @@ export function viewObjectName(view: AnyRec): string | undefined { } /** - * EVERY site one `views[]` entry can carry sections on, in ladder order: - * the entry itself, its default `form`, its `listViews.*`, its `formViews.*`. + * EVERY site one `views[]` entry can carry sections on, in ladder order: the + * entry itself, then its `listViews.*`. A form is not among them: it is a + * `forms[]` item ({@link formItemSites}). * * `basePath` is the caller's path prefix for the entry (e.g. `views[3]`). * @@ -202,21 +204,15 @@ export function viewContainerSites(view: AnyRec, basePath: string): ViewSite[] { const sites: ViewSite[] = [{ view, path: basePath, surface: '', kind: 'self' }]; - if (isRec(view.form)) { - sites.push({ view: view.form, path: `${basePath}.form`, surface: 'form', kind: 'form' }); - } - - for (const key of ['listViews', 'formViews'] as const) { - const container = view[key]; - if (!isRec(container)) continue; - const kind: ViewSiteKind = key === 'listViews' ? 'listView' : 'formView'; + const container = view.listViews; + if (isRec(container)) { for (const [subKey, sub] of Object.entries(container)) { if (!isRec(sub)) continue; sites.push({ view: sub, - path: `${basePath}.${key}.${subKey}`, - surface: `${key}.${subKey}`, - kind, + path: `${basePath}.listViews.${subKey}`, + surface: `listViews.${subKey}`, + kind: 'listView', }); } } @@ -225,8 +221,32 @@ export function viewContainerSites(view: AnyRec, basePath: string): ViewSite[] { } /** - * The FORM-carrying subset of {@link viewContainerSites}: the entry itself, the - * default `form`, and each `formViews.`. + * [ADR-0159 D9] One site per `forms[]` item, in collection order: the form + * itself, whose `sections` / `groups` sit at its top level beside `name` and + * `object`. `forms` is read as an array or as a name-keyed map, the two + * shapes a stack collection is authored in (`collectionEntries`), so the path + * is one an author can look up (`forms[2]`, `forms.contact_signup`). + */ +export function formItemSites(stack: AnyRec): ViewSite[] { + if (!isRec(stack)) return []; + return collectionEntries(stack.forms, 'forms').map(({ rec, path }) => ({ + view: rec, + path, + surface: '', + kind: 'form' as const, + })); +} + +/** The name a `forms[]` item is served under, or its path when it carries none. */ +export function formItemName(site: ViewSite): string { + return strName(site.view.name) ?? site.path; +} + +/** + * The FORM-carrying subset of {@link viewContainerSites}: the entry itself, + * when it is a bare form view. The forms an app authors are `forms[]` items; + * a rule that judges form sections reads those through {@link formItemSites} + * and this subset beside them. * * `list` / `listViews.` are `ObjectListViewSchema` and declare no * `sections` (proof in the module docblock), so a rule that judges form diff --git a/packages/metadata-core/src/anonymous-form-intake.test.ts b/packages/metadata-core/src/anonymous-form-intake.test.ts index 99f7d986f04..dd5bdbe4ca4 100644 --- a/packages/metadata-core/src/anonymous-form-intake.test.ts +++ b/packages/metadata-core/src/anonymous-form-intake.test.ts @@ -170,14 +170,21 @@ describe('where the reason is located, and the reason itself', () => { .toEqual(['form.sharing', 'formViews.contact.sharing', 'config.sharing']); }); - it('anonymousFormObjectName: the form\'s own data.object first, then the view\'s', () => { + it('anonymousFormObjectName: the form\'s own data.object first, then the body\'s form and object', () => { const view = { object: 'v_obj', list: { data: { object: 'list_obj' } } }; expect(anonymousFormObjectName(view, { data: { object: 'form_obj' } })).toBe('form_obj'); - expect(anonymousFormObjectName(view, {})).toBe('list_obj'); + expect(anonymousFormObjectName({ ...view, form: { data: { object: 'slot_obj' } } }, {})).toBe('slot_obj'); expect(anonymousFormObjectName({ object: 'v_obj' }, {})).toBe('v_obj'); expect(anonymousFormObjectName(undefined, undefined)).toBeUndefined(); }); + // [ADR-0159 D7] Since @objectstack/spec 19 a form reads no binding off a list. + it('anonymousFormObjectName: a list beside the form lends it no object', () => { + const view = { object: 'v_obj', list: { data: { object: 'list_obj' } } }; + expect(anonymousFormObjectName(view, {})).toBe('v_obj'); + expect(anonymousFormObjectName({ list: { data: { object: 'list_obj' } } }, {})).toBeUndefined(); + }); + it('the message names the slug, the object, the column and the posture, and ends with the remedy', () => { const u = { object: 'inquiry', posture: 'isolated' as const, tenantField: 'organization_id' }; const message = anonymousFormIntakeUnavailableMessage('contact-us', u); diff --git a/packages/metadata-core/src/anonymous-form-intake.ts b/packages/metadata-core/src/anonymous-form-intake.ts index 42188ea5e8e..3bfaa31640e 100644 --- a/packages/metadata-core/src/anonymous-form-intake.ts +++ b/packages/metadata-core/src/anonymous-form-intake.ts @@ -26,6 +26,13 @@ * `false`), matched by slot or by slug, closes it, and layering may only narrow * intake, never re-open it ({@link anonymousFormIntakeWithdrawnIn}). * + * [ADR-0159 D7] Since @objectstack/spec 19 a form is its own metadata type and + * a `view` holds lists only: the doors offer `form` items alone, and no door + * admits a `view` body that carries a form. The `view`-body half of this rule + * is still read, for one purpose: a stored body of the old shapes that + * withdraws a form keeps closing it, so the withdrawal layer reads those + * bodies as stored (ADR-0159 D6 rule 10). + * * [#21476] The module also answers the second question an open form raises: * can it take an anonymous submission on THIS deployment's posture * ({@link anonymousFormIntakeUnavailability})? Three readers ask it — both @@ -64,9 +71,10 @@ export { export type { AnonymousFormIntakeCandidate } from '@objectstack/spec/ui'; /** - * Where a candidate's `sharing` sits in the `view` body — `form.sharing`, - * `formViews.KEY.sharing` or `config.sharing`. Item-relative: the admin read - * states it as is, and the authoring gate prefixes the write's own root. + * Where a candidate's `sharing` sits in a `view` body of the shapes that held a + * form before @objectstack/spec 19 — `form.sharing`, `formViews.KEY.sharing` or + * `config.sharing`. Item-relative: the authoring gate prefixes the write's own + * root. A `form` item's own `sharing` is located at `sharing`, with no call here. */ export function anonymousFormSharingPath(view: Record, candidate: AnonymousFormIntakeCandidate): string { if (candidate.form === view.form) return 'form.sharing'; diff --git a/packages/metadata-core/src/form-predicate-root-policy.test.ts b/packages/metadata-core/src/form-predicate-root-policy.test.ts index 3a772544dc8..6708b6edf78 100644 --- a/packages/metadata-core/src/form-predicate-root-policy.test.ts +++ b/packages/metadata-core/src/form-predicate-root-policy.test.ts @@ -447,6 +447,48 @@ describe('detectUnboundFormViewPredicateRoots — traversal', () => { expect(detectUnboundFormViewPredicateRoots(listItem)).toEqual([]); }); + // [ADR-0159 D7] Since @objectstack/spec 19 a form is a `forms[]` item, its + // body at the item's top level. + it('reads a `forms[]` item: field and section predicates, named by the form', () => { + const findings = detectUnboundFormViewPredicateRoots({ + forms: [ + { + name: 'crm_lead.edit', + object: 'crm_lead', + sections: [ + { + visibleWhen: CEL('stage == "closed"'), + fields: ['title', { field: 'a', visibleWhen: CEL('status == "x"') }], + }, + ], + }, + ], + }); + expect(findings).toEqual([ + { path: 'forms[0].sections[0].visibleWhen', view: 'crm_lead.edit', root: 'stage', source: 'stage == "closed"', surface: 'section' }, + { path: 'forms[0].sections[0].fields[1].visibleWhen', view: 'crm_lead.edit', root: 'status', source: 'status == "x"', surface: 'field' }, + ]); + }); + + it('a `forms[]` item whose predicates carry a bound root says nothing; a nameless one is named by its object', () => { + const item = (source: string) => ({ + forms: [{ object: 'crm_lead', sections: [{ fields: [{ field: 'a', visibleWhen: CEL(source) }] }] }], + }); + expect(detectUnboundFormViewPredicateRoots(item('record.status == "x"'))).toEqual([]); + expect(detectUnboundFormViewPredicateRoots(item('current_user.role == "admin"'))).toEqual([]); + expect(detectUnboundFormViewPredicateRoots(item('status == "x"')).map((f) => f.view)).toEqual(['crm_lead']); + }); + + it('reads `forms[]` beside `views[]`, the form items first, and is silent on a `forms` it cannot read', () => { + const findings = detectUnboundFormViewPredicateRoots({ + forms: [{ name: 'crm_lead.edit', object: 'crm_lead', sections: [{ fields: [{ field: 'a', visibleWhen: CEL('status == "x"') }] }] }], + views: [{ name: 'crm_lead.all', object: 'crm_lead', viewKind: 'list', config: { columns: ['a'] } }], + }); + expect(findings.map((f) => f.path)).toEqual(['forms[0].sections[0].fields[0].visibleWhen']); + expect(detectUnboundFormViewPredicateRoots({ forms: 'nope' })).toEqual([]); + expect(detectUnboundFormViewPredicateRoots({ forms: [null, 7, 'x', { name: 'f' }] })).toEqual([]); + }); + it('is silent — never throwing — on shapes it cannot read', () => { expect(detectUnboundFormViewPredicateRoots(undefined)).toEqual([]); expect(detectUnboundFormViewPredicateRoots(null)).toEqual([]); diff --git a/packages/metadata-core/src/form-predicate-root-policy.ts b/packages/metadata-core/src/form-predicate-root-policy.ts index f437755e366..ff3ed0e8364 100644 --- a/packages/metadata-core/src/form-predicate-root-policy.ts +++ b/packages/metadata-core/src/form-predicate-root-policy.ts @@ -40,7 +40,9 @@ * ## What this module is, and deliberately is not * * It is a **detector**: given an artifact's stack definition, report every - * form-view predicate naming an unbound root. Its caller turns that into one + * form predicate naming an unbound root, in its `forms[]` items (the form's + * home since @objectstack/spec 19, ADR-0159 D7) and in the shapes a `views[]` + * entry carried a form in before that. Its caller turns that into one * deduped operator-facing boot line at the artifact door. * * - **Not a rewriter.** Prefixing a bare root with `record.` is the ADR-0087 @@ -214,9 +216,12 @@ export type FormPredicateSurface = 'field' | 'section'; /** One form-view predicate naming a root that is not bound where it evaluates. */ export interface UnboundFormPredicateRoot { - /** Dotted path into the stack definition, e.g. `views[3].form.sections[0].fields[2].visibleWhen`. */ + /** Dotted path into the stack definition, e.g. `forms[3].sections[0].fields[2].visibleWhen`. */ path: string; - /** Operator-legible identity of the view carrying it (view name, else its object). */ + /** + * Operator-legible identity of the form carrying it: a `forms[]` item's name + * (else its object), or the name of the `views[]` entry an old shape sits in. + */ view: string; /** The root identifier that is not bound on this surface. */ root: string; @@ -417,6 +422,14 @@ function readArmObject(arm: unknown): string | undefined { return typeof object === 'string' && object !== '' ? object : undefined; } +/** Operator-legible identity for one `forms[]` item: its name, else the object it submits into. */ +function formLabel(entry: Record, index: number): string { + const name = entry.name; + if (typeof name === 'string' && name !== '') return name; + const object = entry.object; + return typeof object === 'string' && object !== '' ? object : `forms[${index}]`; +} + /** Operator-legible identity for one `views[]` entry. */ function viewLabel(entry: Record, index: number): string { const name = entry.name; @@ -439,15 +452,32 @@ function viewLabel(entry: Record, index: number): string { * means "nothing to say", which is also the answer for a definition this * cannot read — silence is the safe direction (see the module doc). * - * Both `views[]` shapes are visited: the aggregated container - * (`{ list, form, listViews, formViews }`, identified by the ABSENCE of - * `viewKind`) and the independent ViewItem (`{ name, object, viewKind, config }`). - * A ViewItem whose `viewKind` is not `'form'` carries no form-view predicate - * and is skipped. + * [ADR-0159 D7] A form is its own metadata type since @objectstack/spec 19, so + * the forms a definition serves are its `forms[]` items: the body sits at the + * item's top level (`{ name, object, sections, … }`), and each is scanned there. + * + * The three shapes a `views[]` entry carried a form in before 19 are scanned + * as well: the aggregated container (`{ list, form, listViews, formViews }`, + * identified by the ABSENCE of `viewKind`) and the independent ViewItem + * (`{ name, object, viewKind: 'form', config }`). This scan runs BEFORE the + * strict parse, which refuses a definition that still carries one, so on such + * an artifact the notice precedes that refusal and names predicates of forms + * the artifact will not serve until it is rebuilt from a migrated source. A + * ViewItem whose `viewKind` is not `'form'` carries no form predicate and is + * skipped. */ export function detectUnboundFormViewPredicateRoots(definition: unknown): UnboundFormPredicateRoot[] { const out: UnboundFormPredicateRoot[] = []; if (!isPlainObject(definition)) return out; + + const forms = definition.forms; + if (Array.isArray(forms)) { + forms.forEach((entry, index) => { + if (!isPlainObject(entry)) return; + scanFormView(entry, `forms[${index}]`, formLabel(entry, index), out); + }); + } + const views = definition.views; if (!Array.isArray(views)) return out; diff --git a/packages/metadata-protocol/src/destructive-still-shown-by.ts b/packages/metadata-protocol/src/destructive-still-shown-by.ts index 33af57a2158..4ac727b533c 100644 --- a/packages/metadata-protocol/src/destructive-still-shown-by.ts +++ b/packages/metadata-protocol/src/destructive-still-shown-by.ts @@ -41,16 +41,16 @@ * (`protocol-meta-list-reads.ts`, `isAggregatedViewContainer`). So the * type-change half reads `config` and the item's own root, and nothing else. * - * The `form` listing (ADR-0159) serves the authored `form` items and, marked - * by `PROJECTED_FORM_SOURCE_KEY`, the forms it projects out of old-shape - * `view` rows. A projected form is the `view` listing's item already, named - * there, so only the authored items are read. The form-layout judge walks - * `views[]` alone, so each authored form is put before the judges in the - * stored form view item shape that judge reads (`{ name, object, viewKind: - * 'form', config }`, the shape Studio saves through `PUT /meta/view`), and a - * finding on it is named as the `form` it is, at its own path. The form also - * stays in `forms[]`, so a judge that comes to read `forms[]` itself names the - * same positions, and the two are one entry. + * The `form` listing (ADR-0159) serves the `form` items. [ADR-0159 D7] Since + * protocol 19 neither listing serves a form out of a stored old-shape `view` + * row: the `view` listing holds lists only and the `form` listing projects + * none, so a form such a row still holds is shown by no served item and is + * named nowhere. The form-layout judge walks `views[]` alone, so each form is + * put before the judges in the form view item shape that judge reads + * (`{ name, object, viewKind: 'form', config }`), and a finding on it is named + * as the `form` it is, at its own path. The form also stays in `forms[]`, so a + * judge that comes to read `forms[]` itself names the same positions, and the + * two are one entry. * * ## How it reaches the judges * @@ -66,7 +66,7 @@ import type { FieldStillShownBy } from '@objectstack/spec/api'; import { filterOperatorFieldTypeFit } from '@objectstack/spec/data'; -import { PROJECTED_FORM_SOURCE_KEY, isViewFilterOrGroup } from '@objectstack/spec/ui'; +import { isViewFilterOrGroup } from '@objectstack/spec/ui'; /** One destructive-change finding as `detectDestructiveObjectChanges` produces it. */ export interface DestructiveFinding { @@ -128,8 +128,6 @@ export async function withStillShownBy( const lists = await Promise.all(wanted.map(([, type]) => listServed(type))); stack = { objects: [], views: [], datasets: [], dashboards: [], pages: [], flows: [], reports: [], forms: [] }; wanted.forEach(([collection], i) => { stack[collection] = lists[i] ?? []; }); - // A projected form is the `view` listing's item, named there. - stack.forms = stack.forms.filter((form) => isRecord(form) && !(PROJECTED_FORM_SOURCE_KEY in form)); } catch (error) { // Not computed, said once: the refusal itself stands unchanged. console.warn( @@ -234,7 +232,7 @@ function removalSurfaces( const withAll: AnyRec = { ...nextBody, name: str(nextBody.name) ?? objectName, fields: restored }; const others = stack.objects.filter((o) => !(isRecord(o) && o.name === objectName)); - // Each authored form, as the form view item the form-layout judge reads, + // Each form, as the form view item the form-layout judge reads, // after the served views; `formOf` maps its position back to the form. const formOf = new Map(); const formViews: AnyRec[] = []; diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index 3d9fee13a40..15f630d3a35 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -350,6 +350,8 @@ export type { ServedOverrideEntry } from './protocol-served-overrides.js'; export type { PackagelessOverlayCensus, PackagelessOverlayMigration } from './protocol-packageless-overlay-migration.js'; // [ADR-0159 D7, card ⑤a] The stored-form ceremony's census and precheck: `os migrate stored-forms` prints them. export { listStoredFormsOf } from './protocol-stored-form-migration.js'; +// [ADR-0159 D7] The census's own identification reading, for tests of the census alone (⛔ not a served read). +export { censusFormsServedBeforeTheSwitchOf } from './protocol-stored-form-migration.js'; export type { StoredFormAddress, StoredFormAddressPlan, diff --git a/packages/metadata-protocol/src/metadata-diagnostics.ts b/packages/metadata-protocol/src/metadata-diagnostics.ts index 3ec1ebd837c..abd22b58e9f 100644 --- a/packages/metadata-protocol/src/metadata-diagnostics.ts +++ b/packages/metadata-protocol/src/metadata-diagnostics.ts @@ -537,14 +537,14 @@ export function withPublishAdvisories( } // --------------------------------------------------------------------------- -// [#29196] The lint's `form-field-unknown` on a served view's `_diagnostics` +// [#29196] The lint's `form-field-unknown` on a served form's `_diagnostics` // [#29309] …and its sibling `form-section-group-unknown` // --------------------------------------------------------------------------- // // A form section naming a field its object does not have is Zod-valid, so the // schema verdict above reads `valid: true`, and the renderer skips the field. // `validateFormLayout` (`@objectstack/lint`) is the rule that says so, and it -// ran only in the CLI. The view read now runs that rule on the body it serves +// ran only in the CLI. The read now runs that rule on the body it serves // and puts each `form-field-unknown` finding in `_diagnostics.warnings`, with // the rule's own message: one spelling, no second rule. [#29309] The rule's // other finding, `form-section-group-unknown` (a section's `group` names a @@ -552,8 +552,15 @@ export function withPublishAdvisories( // nothing), is the same silent skip and travels the same way. The objects the // lookup answers carry their `fieldGroups`, which is all that finding reads. // +// [ADR-0159 D9] A form is a `form` item from protocol 19, so the `form` read is +// the one that carries both findings: the served item is handed to the rule as +// the stack's `forms[]` entry, the shape the save and publish gate judges. A +// `view` read still runs the rule on the body it serves, where the only form +// the rule reads is a bare form view (root `sections`); a view container holds +// lists only and the rule reads no form out of one. +// // Save and publish answer both findings as `advisories` on their own: the -// rule is crossed to the runtime gate (`runtimeTypes: ['view']` in +// rule is crossed to the runtime gate (`runtimeTypes: ['form']` in // `@objectstack/lint`'s `AUTHORING_RULES`). That is not a second report on // this read: the read carries no runtime advisory, only the publish verdict's // refusals (`withPublishVerdict`), and these findings are never refusals. @@ -564,7 +571,7 @@ export function withPublishAdvisories( // shape the read's other derived warnings already take (the admin read's // anonymous-intake reasons, a view container's rename note). // -// The field set is the one the door already resolves for the view: the +// The field set is the one the door already resolves for the item: the // caller's object lookup (`registry.getObject` at the read, the served object // with its extensions folded on), asked for the object names the body itself // spells. A name it cannot resolve is left out of the universe, and the rule @@ -572,7 +579,7 @@ export function withPublishAdvisories( // // Loaded lazily from the package root, as `build-probes.ts` loads its lint // rule: the kernel boot path reaches `@objectstack/lint` only through its -// `/runtime` entry, and a view read is where this one is first needed. +// `/runtime` entry, and a form or view read is where this one is first needed. /** The names this pass reads from `@objectstack/lint`. */ interface FormLayoutLint { @@ -616,7 +623,8 @@ function spelledObjectNames(value: unknown, into: Set, depth = 0): Set( served: T, getObject: ((name: string) => unknown) | undefined, ): Promise { - if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'view' || !isRec(served) || !getObject) return served; + const singular = PLURAL_TO_SINGULAR[type] ?? type; + if ((singular !== 'form' && singular !== 'view') || !isRec(served) || !getObject) return served; const lint = await loadFormLayoutLint(); if (!lint) return served; - // [#29309] The served body is the rule's input as it is: the rule reads a - // form `ViewItem`'s `config` rung itself, the same walk the save and - // publish gate runs, so the read needs no adapter of its own. + // [#29309] The served body is the rule's input as it is, under the stack + // key of its own type (`forms` for a form item, `views` for a view): the + // same walk the save and publish gate runs, so the read needs no adapter + // of its own. + const stackKey = singular === 'form' ? 'forms' : 'views'; const objects: Rec[] = []; for (const name of spelledObjectNames(served, new Set())) { const object = getObject(name); @@ -639,10 +650,10 @@ export async function withFormLayoutWarnings( } if (objects.length === 0) return served; const name = typeof served.name === 'string' ? served.name : ''; - const warnings = lint.validateFormLayout({ objects, views: [served] }) + const warnings = lint.validateFormLayout({ objects, [stackKey]: [served] }) .filter((finding) => lint.servedRules.has(finding.rule)) .map((finding) => ({ - path: itemRelativeIssuePath('view', name, finding.path), + path: itemRelativeIssuePath(singular, name, finding.path), message: finding.message, })); if (warnings.length === 0) return served; @@ -751,7 +762,8 @@ export async function withListViewFieldWarnings( // --------------------------------------------------------------------------- /** - * [#34901] The objects a `view` write is judged against: each object a + * [#34901] The objects a `view` write, and [ADR-0159 D7] a `form` write, is + * judged against: each object a * disabled package extends, folded with that package's `extend` contribution * IN (`includeDisabledExtensions`, the fold the storage layer keeps), and * every other object exactly as served. @@ -768,9 +780,10 @@ export async function withListViewFieldWarnings( * * The runtime authoring gate applies it to the merged universe (registered * and stored halves alike), so a stored overlay of an extended object is - * folded the same way. ⛔ View writes ONLY: a flow, a formula or a - * validation rule written while the package is off would read a field the - * served object does not carry. A served view's lint reads the same fold + * folded the same way. ⛔ View and form writes ONLY (a form left the `view` + * type on 19 and its sections still name its object's fields): a flow, a + * formula or a validation rule written while the package is off would read a + * field the served object does not carry. A served view's lint reads the same fold * ({@link viewLintObjectLookup}), so the read and the save door judge one * body alike. */ @@ -822,9 +835,10 @@ export function viewLintObjectLookup(registry: unknown): (name: string) => unkno } /** - * The two lint passes a served view's read runs, in order: the form layout - * ({@link withFormLayoutWarnings}) and the list-view field references - * ({@link withListViewFieldWarnings}). + * The two lint passes a served read runs, in order: the form layout + * ({@link withFormLayoutWarnings}: a `form` item, or a bare form view) and + * the list-view field references ({@link withListViewFieldWarnings}: a `view` + * only). */ export async function withViewLintWarnings( type: string, diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 737f6447bf3..8b477e37419 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -704,10 +704,12 @@ export async function judgeRuntimeAuthoringRules( name: evt.name, state: evt.state, body: evt.body, - // [#34901] A `view` write judges its field names against the STORAGE - // fold ({@link withDisabledExtensionsFolded}); every other type keeps - // the served objects. - objects: singular === 'view' ? withDisabledExtensionsFolded(this.engine?.registry, objects) : objects, + // [#34901] A `view` write, and [ADR-0159 D7] a `form` write (a form + // left the `view` type, its sections still name the object's fields), + // judges its field names against the STORAGE fold + // ({@link withDisabledExtensionsFolded}); every other type keeps the + // served objects. + objects: singular === 'view' || singular === 'form' ? withDisabledExtensionsFolded(this.engine?.registry, objects) : objects, permissions, books, datasets, diff --git a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts index 60828c2f52e..0b72b62782e 100644 --- a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts +++ b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts @@ -76,7 +76,6 @@ import type { ApiRoutes, CapabilityDescriptor, ServiceInfo, WellKnownCapabilitie // `DiscoverySchema` "System Identity" field — never a literal again. import { resolveDiscoveryVersion } from './discovery-version.js'; import { CORE_SERVICE_PROVIDER, serviceUnavailableMessage } from '@objectstack/spec/system'; -import { projectViewForms } from '@objectstack/spec/ui'; import { SERVICE_CONFIG } from './protocol-discovery-services.js'; import type { ProtocolHost } from './protocol-host.js'; import { servedOverrideBaseOf } from './served-override.js'; @@ -955,18 +954,13 @@ export class ProtocolDiscoveryAndBasesFacet { /** * The body of `ObjectStackProtocolImplementation#getPackagedFormBase`; the - * method's docblock there is its contract. [ADR-0159 D5, ADR-0029 D9.2a] - * The base's authored `form` item, else the form its old shape carries at - * the name, read through THE projection: until card ④ a `form` override's - * base still ships most first-party forms as an old shape, and the text the - * override changed outranks that base's catalog either way. + * method's docblock there is its contract. [ADR-0159 D7, ADR-0029 D9.2a] + * The base's authored `form` item, the one base a served `form` has since + * protocol 19: a `view` holds lists only and the projection serves no + * content, so no packaged `view` is read as a form's base. */ static getPackagedFormBase(host: Pick, name: string): unknown { - const authored = host.packagedArtifactBase('form', name); - if (authored !== undefined && authored !== null) return authored; - const view = host.packagedArtifactBase('view', name); - if (view === undefined || view === null) return undefined; - return projectViewForms(view).forms.find((form) => form.name === name); + return host.packagedArtifactBase('form', name); } /** The body of `ObjectStackProtocolImplementation#servedOverrideBaseOf`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol-form-reads.ts b/packages/metadata-protocol/src/protocol-form-reads.ts index 816cf86d0ec..dd591610190 100644 --- a/packages/metadata-protocol/src/protocol-form-reads.ts +++ b/packages/metadata-protocol/src/protocol-form-reads.ts @@ -44,7 +44,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { pairsOf, type InstalledManifestLookup } from '@objectstack/metadata-core'; -import { PROJECTED_FORM_SOURCE_KEY, isAggregatedViewContainer, projectViewForms, type UnreadableFormBody } from '@objectstack/spec/ui'; +import { PROJECTED_FORM_SOURCE_KEY, isAggregatedViewContainer, isServedViewItem, projectViewForms, type UnreadableFormBody } from '@objectstack/spec/ui'; import { installedManifestsOfEngine } from './installed-manifests.js'; import type { ProtocolHost } from './protocol-host.js'; import { holdsServedOverlayCandidate, servedOverlayRowCandidates } from './protocol-overlay-merge.js'; @@ -222,7 +222,9 @@ async function storedEntries(host: FormReadHost, type: 'form' | 'view'): Promise * container as the items the runtime door expands it to (the same expansion * the `view` list serves, {@link FormReadHost.expandStoredViewContainers}). * So a member of a named container on another package's object is named - * `OBJECT.CONTAINER.KEY`, as the `view` list and the doors serve it. + * `OBJECT.CONTAINER.KEY`, as the `view` list and the doors serve it; from + * protocol 19 a stored row is read under the name its package's form is + * served under (`expandUnderOwnName`). * * THE one naming of a stored row's forms: the `form` read * ({@link storedFormPlaces}) and the `form` write's old-shape row removal @@ -369,17 +371,57 @@ function projectedServed(item: Record, packageId: string | unde } /** - * [ADR-0159 D5] The effective `form` list ({@link FormReadHost}): the generic - * `form` list, the projection of the served `view` list, and the cross-type - * resolution at each address whose package authors the form as a `form` item. - * See the module header for the three readings and how they combine. + * [ADR-0159 D7] Which reading of the stored old shapes a `form` read takes. + * + * - `'major-19'`, every read that serves or executes a form: the projection + * serves no content. A stored old-shape row is never a served item, and + * where the served-row order picks one at a package's address nothing of + * that name is served from the package while it stands (rule 11's kept + * replacement check, "After the major"). + * - `'before-the-switch'`, the readings that identify what the stored old + * shapes hold and serve no document from it: what the read served before + * the switch, the projected items included. Two readers: the stored-form + * census (`listStoredForms`, ADR-0159 D7-c), so that the ceremony moves + * exactly the forms served before it; and the public-address clash + * judgement of a `form` write (`formAddressClashRefusal`), so that a form a + * stored old-shape row holds an address by still holds it. + */ +export type StoredShapeReading = 'major-19' | 'before-the-switch'; + +/** + * [ADR-0159 D7] The by-name `view` answer a `view` read serves: every item + * but a `viewKind: 'form'` one ({@link isServedViewItem}), for which it + * answers no `item`, which both transports answer `404`: the answer of a name + * the served `view` list does not hold (`servedViewList`, + * `protocol-meta-list-reads.ts`). So a list passes, and so does a stored + * old-shape container, which is served by name as stored, its form members + * included. A stored `viewKind: 'form'` row at the name is not rewritten and + * not refused: it is left out of this served answer alone, and every reader + * of stored forms reads it raw ({@link storedViewRowHoldings}, + * `getViewItemsWithStoredForms`, the layered read). A new envelope: the + * answer it came from may be a cached one and is never mutated. + */ +export function servedViewItemAnswer(answer: T): T { + const item = (answer as { item?: unknown } | null | undefined)?.item; + if (item === undefined || item === null || isServedViewItem(item)) return answer; + const { item: _item, ...rest } = answer as Record; + return rest as T; +} + +/** + * [ADR-0159 D5, D7] The effective `form` list ({@link FormReadHost}): the + * generic `form` list, the projection of the served `view` list, and the + * cross-type resolution at each address whose package authors the form as a + * `form` item. See the module header for the three readings and how they + * combine, and {@link StoredShapeReading} for what the projection serves. */ export async function readEffectiveForms( host: FormReadHost, request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', + reading: StoredShapeReading = 'major-19', ): Promise { - return (await readEffectiveFormList(host, request, audience)).items; + return (await readEffectiveFormList(host, request, audience, reading)).items; } /** @@ -411,9 +453,12 @@ export async function readEffectiveFormList( host: FormReadHost, request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', + reading: StoredShapeReading = 'major-19', ): Promise<{ type: string; items: unknown[] } & Record> { // Every reading below reads through one request scope: each stored row set once. host = formRequestScope(host); + // [ADR-0159 D7] Whether a projected item is served (the census's reading only). + const servesProjection = reading === 'before-the-switch'; const { packageId: scope, names, ...rest } = request; const unscoped = { ...rest, type: 'form', ...(names !== undefined ? { names } : {}) }; const genericList = await host.readFlattenedMetaItems(unscoped, audience) as { items: unknown[] } & Record; @@ -506,8 +551,10 @@ export async function readEffectiveFormList( put(key, item); continue; } - // A stored `view` row is the served row at this address. - if (served.holding.kind === 'form') put(key, projectedServed(served.holding.item, pkg)); + // A stored `view` row is the served row at this address. [ADR-0159 D7] + // Since protocol 19 it serves no content: nothing of the name is served + // from the package while it stands (rule 11's kept replacement check). + if (servesProjection && served.holding.kind === 'form') put(key, projectedServed(served.holding.item, pkg)); // …else the closed reading: nothing is served for the name from the package. } // A package that authors the form but has no item in the generic list (its @@ -541,7 +588,8 @@ export async function readEffectiveFormList( continue; } } - put(key, item); + // [ADR-0159 D7] Since protocol 19 a projected item is not served. + if (servesProjection) put(key, item); } // …and a package-less `form` row that stood in at no such address is // listed as its own item, as the generic list serves it. diff --git a/packages/metadata-protocol/src/protocol-form-writes.ts b/packages/metadata-protocol/src/protocol-form-writes.ts index 298825293d1..f460467b2aa 100644 --- a/packages/metadata-protocol/src/protocol-form-writes.ts +++ b/packages/metadata-protocol/src/protocol-form-writes.ts @@ -18,6 +18,11 @@ * Each judges bodies through THE projection ({@link projectViewForms}), never * by re-reading `formViews` by hand; the old-shape row removal names a stored * row's forms as the `form` read names them ({@link storedViewRowHoldings}). + * + * [ADR-0159 D7] Since protocol 19 no door admits an old-shape `view` body and + * no read serves one. These judgements still read the stored rows of those + * shapes, raw: a row stored before the upgrade stands until the stored-form + * ceremony or a `form` write at its address moves it. */ import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; @@ -114,11 +119,13 @@ export function formHeldSlug(form: unknown): string | undefined { * * A form holds an address while its `sharing.publicLink` names it, switched on * or off: a switched-off form that keeps its link still holds it. "Another - * form" is judged over the effective `form` read, so a projected old-shape - * form holding the slug counts. A write that leaves the form closed is never - * refused, so switching off either form of a clashing pair saves. ⛔ A - * refusal on the new type only: an old-shape `view` write keeps today's - * first-match behaviour. + * form" is judged over the effective `form` read WITH the forms of the stored + * old-shape rows (`'before-the-switch'`, `StoredShapeReading`): since + * protocol 19 such a form is served nowhere, and it still holds the address + * its link names, so a form a stored old-shape body switched off is not + * written over by another form opened on its address. A write that leaves the + * form closed is never refused, so switching off either form of a clashing + * pair saves. * * `409`, code {@link FORM_ADDRESS_TAKEN}, with the holding form as `holder` * (`{ name, packageId }`), answered as `details.holder`. @@ -135,7 +142,9 @@ export async function formAddressClashRefusal( const slug = anonymousFormIntakeSlug((item as { sharing?: unknown }).sharing); if (slug === null) return undefined; const pkg = isPackageless(packageId) ? undefined : packageId as string; - const forms = await readEffectiveForms(host, { type: 'form' }, 'execution'); + // [ADR-0159 D7] An identification read of the stored old shapes, never a + // served one: who holds the address, the stored old-shape rows included. + const forms = await readEffectiveForms(host, { type: 'form' }, 'execution', 'before-the-switch'); const holder = forms.find((form) => { const f = form as { name?: unknown; _packageId?: unknown; overrides?: { package?: unknown } }; if (formHeldSlug(form) !== slug) return false; diff --git a/packages/metadata-protocol/src/protocol-legacy-organization-rows.ts b/packages/metadata-protocol/src/protocol-legacy-organization-rows.ts index aba54e58163..2e8e40e86fb 100644 --- a/packages/metadata-protocol/src/protocol-legacy-organization-rows.ts +++ b/packages/metadata-protocol/src/protocol-legacy-organization-rows.ts @@ -8,12 +8,15 @@ * * - `legacyOrganizationRowsOf` — those rows of one table, read off the * physical column through the table's driver (a read inside a transaction - * joins it). + * joins it: the one its context threads, else the engine's ambient one, + * {@link legacyOrganizationRowsRead}). * - `withoutLegacyOrganizationRows` — a row list with those rows left out. * * A MOVE, not a redesign. Each function below is the body of the * `ObjectStackProtocolImplementation` method of the same name as it stood, - * re-indented one level and otherwise unedited. + * re-indented one level and otherwise unedited; since then + * `legacyOrganizationRowsOf` resolves its transaction through + * {@link legacyOrganizationRowsRead}, which the repository reads too. * * ## How the moved bodies reach the class * @@ -65,10 +68,57 @@ export function legacyOrganizationRowsOf( table: string, context?: unknown, ): Promise> { - const transaction = (context as { transaction?: unknown } | undefined)?.transaction; - return readLegacyOrganizationRows( - (this.engine as { getDriverForObject?: (objectName: string) => unknown }).getDriverForObject?.(table), - table, - transaction !== undefined ? { transaction } : {}, - ); + const { driver, options } = legacyOrganizationRowsRead(this.engine, table, context); + return readLegacyOrganizationRows(driver, table, options); +} + +/** The slice of the engine's ambient transaction store (ADR-0034) {@link legacyOrganizationRowsRead} reads. */ +interface AmbientTransactionEngine { + getDriverForObject?: (objectName: string) => unknown; + txStore?: { getStore(): { transaction?: unknown; scope?: { driver?: unknown } } | undefined }; + isClosedUnitHandle?: (handle: unknown) => boolean; +} + +/** + * Where the legacy organization-row read of `table` runs: the table's driver, + * and the transaction its statements join. The read goes to the driver + * directly, past the engine's own reads, so it resolves the transaction the + * way the engine resolves one for those reads (`buildDriverOptions`): the + * handle `context.transaction` threads wins, and with none (or one whose unit + * has closed) the engine's ambient transaction is joined. A write the engine + * runs in `transaction()` holds the one connection a single-connection pool + * (SQLite) has, and reads made inside it without a handle of their own wait + * for a second one that never comes. + * + * The ambient handle is joined only by the driver that owns it (the + * same-origin rule of `transactionCoversDriverFor`): a handle handed to + * another driver runs the statement on the wrong connection. An engine with + * no ambient store (a double) is read from `context` alone. Also read by the + * repository's own legacy-row read (`SysMetadataRepository`). + */ +export function legacyOrganizationRowsRead( + engine: unknown, + table: string, + context?: unknown, +): { driver: unknown; options: { transaction?: unknown } } { + // A structural cast: nothing compiles against the engine's own `txStore` + // and `isClosedUnitHandle`. A rename there falls back to the read with no + // handle; the two SQLite pins of + // `packages/runtime/src/form-save-legacy-organization-transaction.integration.test.ts` + // ("a published form save into a pair completes while a legacy + // organization row is stored", "a form draft saved into a pair and then + // published completes with the organization column on disk") are what + // would time out. + const e = engine as AmbientTransactionEngine | null | undefined; + const driver = e?.getDriverForObject?.(table); + const closed = (handle: unknown): boolean => + typeof e?.isClosedUnitHandle === 'function' && e.isClosedUnitHandle(handle) === true; + const explicit = (context as { transaction?: unknown } | undefined)?.transaction; + if (explicit !== undefined && !closed(explicit)) return { driver, options: { transaction: explicit } }; + const store = typeof e?.txStore?.getStore === 'function' ? e.txStore.getStore() : undefined; + const ambient = store?.transaction; + if (ambient == null || closed(ambient)) return { driver, options: {} }; + const owner = store?.scope?.driver; + if (owner !== undefined && owner !== driver) return { driver, options: {} }; + return { driver, options: { transaction: ambient } }; } diff --git a/packages/metadata-protocol/src/protocol-meta-list-reads.ts b/packages/metadata-protocol/src/protocol-meta-list-reads.ts index be949c2bad8..42131deeb3f 100644 --- a/packages/metadata-protocol/src/protocol-meta-list-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-list-reads.ts @@ -20,7 +20,7 @@ import { ITEM_KEY_DISCRIMINATORS, isTenantAuthored, packageDependencyClosure, pairsOf } from '@objectstack/metadata-core'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared'; -import { isAggregatedViewContainer } from '@objectstack/spec/ui'; +import { isAggregatedViewContainer, isServedViewItem } from '@objectstack/spec/ui'; import { type ItemAddress, type ItemLock, @@ -34,7 +34,8 @@ import { } from './protocol-authoring-refusals.js'; import { shippingPackageIds } from './protocol-environment-rows.js'; import type { ProtocolHost } from './protocol-host.js'; -import { formRequestScope, inFormRequestScope, readEffectiveFormList, withProjectedPerPackageForms, type FormReadHost } from './protocol-form-reads.js'; +import { formRequestScope, inFormRequestScope, readEffectiveFormList, servedViewItemAnswer, withProjectedPerPackageForms, type FormReadHost } from './protocol-form-reads.js'; +import { getMetaItem } from './protocol-meta-item-reads.js'; import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { mergePackageAwareOverlay, servedViewExpansion, withoutServedRowName } from './protocol-overlay-merge.js'; import { @@ -96,7 +97,49 @@ export async function getMetaItems(host: FormReadHost, request: { type: string; // generic read where the list names no package (`readEffectiveFormList`). if (canonical.type === 'form') return effectiveFormList(host, canonical, 'served'); // Inside a form request's reading (`readInFormRequest`), through its scope. - return inFormRequestScope(host).readFlattenedMetaItems(canonical, 'served'); + const answer = await inFormRequestScope(host).readFlattenedMetaItems(canonical, 'served'); + // [ADR-0159 D7] A `view` read serves lists only. + return canonical.type === 'view' ? servedViewList(answer) : answer; +} + +/** + * [ADR-0159 D7] The `view` list a `view` read serves: lists only. A stored + * old-shape row is not rewritten and not refused (constraint: the stored seam + * stays on STORED_ROWS_NOT_REWRITTEN): its form items are left out of the + * served answer, and every reader of stored forms reads them raw + * ({@link getViewItemsWithStoredForms}, the stored-row reads of + * `protocol-form-reads.ts`). A new envelope; the scoped read it came from is + * shared by the request's other readings and is never mutated. + */ +function servedViewList(answer: T): T { + const items = answer.items.filter(isServedViewItem); + return items.length === answer.items.length ? answer : { ...answer, items }; +} + +/** + * [ADR-0159 D7] The body of `ObjectStackProtocolImplementation#getMetaItem`: + * the by-name read of any type (`getMetaItem`, `protocol-meta-item-reads.ts`), + * and at a `view` name the lists-only answer (`servedViewItemAnswer`), in + * every state the read serves. The filter sits here, at the one door every + * transport reads through; the read under it stays raw for the readers of + * stored forms. + */ +export async function getServedMetaItem(host: Parameters[0], request: Parameters[1]) { + // #4432 — CANONICAL TYPE KEY, folded HERE as {@link getMetaItems} folds: the + // filter below asks the canonical type, never a spelling of it. + const canonical = canonicalizeMetaRequestType(request); + const answer = await getMetaItem(host, canonical); + return canonical.type === 'view' ? servedViewItemAnswer(answer) : answer; +} + +/** + * The body of `ObjectStackProtocolImplementation#getViewItemsWithStoredForms`; + * the method's docblock there is its contract. + */ +export async function getViewItemsWithStoredForms(host: FormReadHost, request: { type?: string; packageId?: string; previewDrafts?: boolean }) { + // Inside a form request's reading (`readInFormRequest`), through its scope: + // the same read the served `view` list filters. + return inFormRequestScope(host).readFlattenedMetaItems({ ...request, type: 'view' }, 'served'); } /** The body of `ObjectStackProtocolImplementation#getMetaItemsForExecution`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol-package-bindings.ts b/packages/metadata-protocol/src/protocol-package-bindings.ts index c457fb72507..c015cd61c46 100644 --- a/packages/metadata-protocol/src/protocol-package-bindings.ts +++ b/packages/metadata-protocol/src/protocol-package-bindings.ts @@ -404,6 +404,10 @@ export const BORROWED_ENVELOPE_DECLINED_TYPES: ReadonlySet = new Set([ * instead, while the lists answered the override, and the layered read's * effective layer and the pair's per-package layer never saw it. * + * [ADR-0159 D7] `form` joined when forms left the `view` type: a pair's + * declared override of a packaged `form` item was served by the `form` list + * and not by the by-name read, which answered the base's body. + * * [#30062] `mapping` joined once its reads were measured: before, a pair's * mapping override saved and published, and every read (the by-name read the * import door resolves a mapping through, `@objectstack/rest`'s @@ -417,7 +421,7 @@ export const BORROWED_ENVELOPE_DECLINED_TYPES: ReadonlySet = new Set([ * {@link BORROWED_ENVELOPE_DECLINED_TYPES}: the bare entry served no reader * the row does not serve now. */ -const SEALED_ROW_SERVED_OVERRIDE_TYPES: ReadonlySet = new Set(['page', 'app', 'dataset', 'doc', 'book', 'mapping']); +const SEALED_ROW_SERVED_OVERRIDE_TYPES: ReadonlySet = new Set(['page', 'app', 'dataset', 'doc', 'book', 'mapping', 'form']); /** [#29613] Whether `type` is one of {@link SEALED_ROW_SERVED_OVERRIDE_TYPES}, folded to the canonical singular. */ function servesSealedOverrideRow(type: string): boolean { diff --git a/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts b/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts index 71bbd31be11..8939a73cc2f 100644 --- a/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts +++ b/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts @@ -1435,8 +1435,11 @@ export function overrideWriteVerdict( // [ADR-0159 D4, D7-b] …and, for a `form`, a base that ships the form // as an OLD SHAPE: the `view` artifacts of the name read through the // projection (the expanded `viewKind: 'form'` items a container - // registers, a form `view` item). Until card ④ every first-party form - // is an old shape, and its `form` override switches it off. + // registers, a form `view` item). An identification read, kept on + // protocol 19: a host that registers a package past the strict + // parse still holds such an artifact, no read serves it, and the + // `form` override that switches it off is admitted over it as + // `os validate` admits it (`validate-form-override-base`). ...((PLURAL_TO_SINGULAR[request.type] ?? request.type) === 'form' ? this.shippedArtifactsOf('view', request.name) .filter((a) => projectViewForms(a).forms.some((form) => form.name === request.name)) diff --git a/packages/metadata-protocol/src/protocol-registry-view-predicates.ts b/packages/metadata-protocol/src/protocol-registry-view-predicates.ts index dfe70dda07f..6c6d1ad85da 100644 --- a/packages/metadata-protocol/src/protocol-registry-view-predicates.ts +++ b/packages/metadata-protocol/src/protocol-registry-view-predicates.ts @@ -37,6 +37,7 @@ * not move. */ +import { expandViewContainer } from '@objectstack/spec/ui'; import type { ObjectStackProtocolImplementation } from './protocol.js'; /** @@ -50,6 +51,7 @@ export interface RegistryViewPredicatesHost { readonly engine: ObjectStackProtocolImplementation['engine']; readonly environmentId: ObjectStackProtocolImplementation['environmentId']; readonly expandRuntimeViewContainer: ObjectStackProtocolImplementation['expandRuntimeViewContainer']; + readonly lookupArtifactItem: ObjectStackProtocolImplementation['lookupArtifactItem']; readonly runtimeViewContainerObject: ObjectStackProtocolImplementation['runtimeViewContainerObject']; readonly runtimeViewContainerPackage: ObjectStackProtocolImplementation['runtimeViewContainerPackage']; readonly shippedViewContainerOf: ObjectStackProtocolImplementation['shippedViewContainerOf']; @@ -81,14 +83,41 @@ export function runtimeViewContainerObject(container: Record): stri /** The body of `ObjectStackProtocolImplementation#copiesOwnShippedViewContainer`; the method's docblock there is its contract. */ export function copiesOwnShippedViewContainer( - this: Pick, + this: Pick, type: string, object: string, container: Record, ownPackageId: string | undefined, ): boolean { const shipped = this.shippedViewContainerOf(type, container.name, ownPackageId); - return shipped !== undefined && this.runtimeViewContainerObject(shipped) === object; + if (shipped !== undefined && this.runtimeViewContainerObject(shipped) === object) return true; + return shipsAFormOfTheCopy.call(this, object, container, ownPackageId); +} + +/** + * [ADR-0159 D7] From protocol 19 a package ships each form it used to ship in + * a view container as a `form` item, under the name the container served it + * under (`.`). A stored copy one of whose form members expands + * to a form `ownPackageId` ships, bound to the same object, is that package's + * copy too: it expands to the package's names, so a stored copy's withdrawal + * keeps closing the copying package's form after the 19 switch. Counts only + * which names the package ships; every other judgement is unchanged. + */ +function shipsAFormOfTheCopy( + this: Pick, + object: string, + container: Record, + ownPackageId: string | undefined, +): boolean { + if (ownPackageId === undefined) return false; + for (const member of expandViewContainer(object, container)) { + if (member.viewKind !== 'form') continue; + const form = this.lookupArtifactItem('form', String(member.name), ownPackageId) as + | { _packageId?: unknown; object?: unknown } + | undefined; + if (form?._packageId === ownPackageId && form.object === object) return true; + } + return false; } /** The body of `ObjectStackProtocolImplementation#isAnotherPackagesObject`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 5fa64130d91..8ade7ae2f33 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -246,7 +246,7 @@ export class ProtocolSaveFacet { const kindOn = (view: Record) => `${String(view.viewKind)} view on '${String(view.object)}'`; const viewItem = (name: string) => `a view item (name, object, viewKind and config) under '${name}'`; const asMemberOf = (container: string) => - `Add the view as a member of the container '${container}' (its list, listViews, form or formViews)`; + `Add the view as a member of the container '${container}' (its list or listViews)`; const ofItsOwn = 'the container under a name of its own that no package ships and no stored container expands'; // ⛔ Every message names the owner, then gives the prescription, and @@ -1527,8 +1527,9 @@ export class ProtocolSaveFacet { } // [ADR-0159 ruled question 3 = A] …and a `form` that would be left // open on a public address another form holds (the effective - // `form` read, projected old shapes included), `409` - // `FORM_ADDRESS_TAKEN`. See {@link formAddressClashRefusal}. + // `form` read, with the forms a stored old-shape row still holds + // an address by), `409` `FORM_ADDRESS_TAKEN`. See + // {@link formAddressClashRefusal}. { const clash = await formAddressClashRefusal( host, singularType, request.item, request.name, request.packageId, diff --git a/packages/metadata-protocol/src/protocol-stored-form-migration.ts b/packages/metadata-protocol/src/protocol-stored-form-migration.ts index c3a6509f9b9..89bc5fd8428 100644 --- a/packages/metadata-protocol/src/protocol-stored-form-migration.ts +++ b/packages/metadata-protocol/src/protocol-stored-form-migration.ts @@ -442,7 +442,7 @@ function declaredOverrideOf(body: unknown): string | undefined { * [ADR-0159 D7] The record-form slots a stored `view` row puts a form in, * named as the read serves them: the container's default `form`, its * `formViews.default` and `formViews.create`, an item with `isDefault: true`, - * and any form named `OBJECT.create` — the slots `form-view-internal-not-loaded` + * and any form named `OBJECT.create` — the record-form slots ADR-0159 D1 * names. The expansion is the spec's own, so the names are the served ones. */ function recordSlotNames(body: unknown): Set { @@ -1757,10 +1757,11 @@ function collectFormActionTargets(value: unknown, out: Set, depth = 0): export async function listStoredForms(host: StoredFormCensusHost): Promise { const places = await storedFormPlaces(host); const installed = installedManifestsOfEngine(host.engine); - // The forms the read serves today, by package and name: the list the doors read. + // The forms the read serves today, by package and name: the list the doors + // read before the switch, the projected items included (ADR-0159 D7). const servedNow = new Set(); const servedNames = new Set(); - for (const item of await readEffectiveForms(host, { type: 'form' }, 'served')) { + for (const item of await readEffectiveForms(host, { type: 'form' }, 'served', 'before-the-switch')) { const { name, _packageId: packageId } = (item ?? {}) as { name?: unknown; _packageId?: unknown }; if (typeof name !== 'string') continue; servedNames.add(name); @@ -1875,3 +1876,17 @@ export async function listStoredForms(host: StoredFormCensusHost): Promise { return listStoredForms(protocolHost(protocol)); } + +/** + * [ADR-0159 D7] The forms the census identifies as served before the switch, + * over a live protocol instance: the one reading {@link listStoredForms} + * plans from (`readEffectiveForms(…, 'before-the-switch')`), the projected + * items included. For tests of the census alone: a test states "what the read + * serves today" in the census's own reading, so its premise and the plan it + * checks cannot drift apart. ⛔ Not a served read: no route, no door and no + * renderer calls it, and the major's served `form` list is `getMetaItems`. + * Writes nothing. + */ +export function censusFormsServedBeforeTheSwitchOf(protocol: ObjectStackProtocolImplementation): Promise { + return readEffectiveForms(protocolHost(protocol), { type: 'form' }, 'served', 'before-the-switch'); +} diff --git a/packages/metadata-protocol/src/protocol-view-expansion-names.ts b/packages/metadata-protocol/src/protocol-view-expansion-names.ts index 108c63a6653..84a209857bf 100644 --- a/packages/metadata-protocol/src/protocol-view-expansion-names.ts +++ b/packages/metadata-protocol/src/protocol-view-expansion-names.ts @@ -13,7 +13,8 @@ * `ObjectStackProtocolImplementation` method of the same name as it stood, * re-indented one level and otherwise unedited: the same reads in the same * order, the same `#5532` discrimination, the same selection, and the same - * names given to the expanded items. + * names given to the expanded items. One reading was added since, in + * `expandUnderOwnName`: `formMembersAPackageShips` (ADR-0159 D7). * * ## How the moved bodies reach the class * @@ -49,6 +50,7 @@ export interface ViewExpansionNamesHost { readonly namesWithOwnStoredRow: ObjectStackProtocolImplementation['namesWithOwnStoredRow']; readonly readActiveOverlayRows: ObjectStackProtocolImplementation['readActiveOverlayRows']; readonly rethrowUnlessMetadataStoreUnprovisioned: ObjectStackProtocolImplementation['rethrowUnlessMetadataStoreUnprovisioned']; + readonly shippedArtifactsOf: ObjectStackProtocolImplementation['shippedArtifactsOf']; readonly storedOverlayEntries: ObjectStackProtocolImplementation['storedOverlayEntries']; } @@ -88,7 +90,7 @@ export async function resolveRowlessExpandedView( /** The body of `ObjectStackProtocolImplementation#expandUnderOwnName`; the method's docblock there is its contract. */ export function expandUnderOwnName( - this: Pick, + this: Pick, type: string, object: string, container: Record, @@ -103,7 +105,12 @@ export function expandUnderOwnName( const source = bare ? { ...container, list: { ...list, name: ownName } } : container; const bareSpelled = `${expandAt}.${ownName}`; const underIsShipped = this.isShippedByAnotherPackage(type, under, ownPackageId); + const shippedForms = ownPackageId === undefined ? formMembersAPackageShips.call(this, object, container) : []; + let formMember = 0; return expandViewContainer(expandAt, source).map((vi) => { + // [ADR-0159 D7] Read under its package's form name (`formMembersAPackageShips`). + const shipped = vi.viewKind === 'form' ? shippedForms[formMember++] : undefined; + if (shipped !== undefined) return { ...shipped }; const item: Record = { ...vi, object }; const name = String(item.name); const fromBare = bare @@ -123,3 +130,30 @@ export function expandUnderOwnName( return item; }); } + +/** + * [ADR-0159 D7] One slot per form member of `container`, in the spec's + * expansion order: the member as the loaders name it, where a package ships a + * `form` item of that name bound to `object`; `undefined` where none does. + * + * From protocol 19 a stored row is read under the name its package's form is + * served under. The item carries no package, as its row carries none, so a + * row whose package cannot be told apart is read at every package that ships + * the name, and reads closed at each. Every list, and every form member no + * package ships, keeps the name it had; so does every member of a container + * filed under another key than the loaders file one under (#21334). + */ +function formMembersAPackageShips( + this: Pick, + object: string, + container: Record, +): Array | undefined> { + if (container.name !== object) return []; + const members = expandViewContainer(object, container).filter((member) => member.viewKind === 'form'); + if (members.length === 0) return []; + return members.map((member) => { + const ships = this.shippedArtifactsOf('form', String(member.name)) + .some((form) => (form as { object?: unknown } | null)?.object === object); + return ships ? (member as unknown as Record) : undefined; + }); +} diff --git a/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts b/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts index f8d1eaca3ba..9c56a5c8adc 100644 --- a/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts +++ b/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts @@ -319,7 +319,7 @@ const contactQuickForm = row('form', 'crm_contact.quick_edit', { type: 'simple', sections: [{ label: 'Main', fields: [{ field: 'status' }] }], }); -/** An old-shape form item, which the served `form` listing also serves, projected and marked. */ +/** A stored old-shape form item: a `view` row holding a form, which protocol 19 serves under neither type. */ const leadEntryItem = row('view', 'crm_lead.entry', { name: 'crm_lead.entry', object: 'crm_lead', @@ -333,9 +333,12 @@ describe('a refused field removal names the authored forms that still edit the f expect(err.code).toBe('DESTRUCTIVE_CHANGE'); expect(err.status).toBe(409); const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); - expect(removed.stillShownBy).toEqual([ - { type: 'view', name: 'crm_lead_edit', where: ['sections[0].fields[1]'] }, + // Each surface once. The order is the judges' arrival order, which is + // not part of the answer: the form rules read `forms[]` themselves. + const byType = (x: { type: string }, y: { type: string }) => (x.type < y.type ? -1 : x.type > y.type ? 1 : 0); + expect([...removed.stillShownBy].sort(byType)).toEqual([ { type: 'form', name: 'crm_lead.quick_edit', where: ['sections[0].fields[1]'] }, + { type: 'view', name: 'crm_lead_edit', where: ['sections[0].fields[1]'] }, ]); expect(removed.message).toContain('form "crm_lead.quick_edit"'); }); @@ -346,16 +349,19 @@ describe('a refused field removal names the authored forms that still edit the f expect(removed.stillShownBy).toEqual([]); }); - it('CONTROL: a form the `form` listing projects from an old-shape view is named once, as the view', async () => { + it('CONTROL: a form a stored old-shape view row still holds is served under neither type, so it is named nowhere', async () => { const { protocol } = makeKernel([leadObject, leadEntryItem]); - // The premise: the served `form` listing does serve the projection. + // The premise (protocol 19): the served `form` listing serves no + // projection of the row, and the served `view` listing holds lists only. const forms = await protocol.getMetaItems({ type: 'form' }); - expect(forms.items.map((i: any) => i.name)).toContain('crm_lead.entry'); + expect(forms.items.map((i: any) => i.name)).not.toContain('crm_lead.entry'); + const views = await protocol.getMetaItems({ type: 'view' }); + expect(views.items.map((i: any) => i.name)).not.toContain('crm_lead.entry'); const err = await refusalOf(protocol, withoutStatus); + // The removal is still refused; the list is computed, and empty. + expect([err.code, err.status]).toEqual(['DESTRUCTIVE_CHANGE', 409]); const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); - expect(removed.stillShownBy).toEqual([ - { type: 'view', name: 'crm_lead.entry', where: ['config.sections[0].fields[1]'] }, - ]); + expect(removed.stillShownBy).toEqual([]); }); it('produces a `form` entry the declared wire shape parses (DestructiveChangeIssueSchema)', async () => { diff --git a/packages/metadata-protocol/src/protocol.form-layout-diagnostics.test.ts b/packages/metadata-protocol/src/protocol.form-layout-diagnostics.test.ts index 722555c17db..3096d07bfd0 100644 --- a/packages/metadata-protocol/src/protocol.form-layout-diagnostics.test.ts +++ b/packages/metadata-protocol/src/protocol.form-layout-diagnostics.test.ts @@ -1,18 +1,26 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * #29196 — a form view naming a field its object lacks reads with the lint's + * #29196 — a form naming a field its object lacks reads with the lint's * `form-field-unknown` warning in its `_diagnostics`. * * ## The defect, measured on `origin/main` before this file was written * - * The body below is QA's reproduction (a stored form `ViewItem`, one section - * naming `no_such_field`). It saved as a draft, published, and both its draft - * read and its active read answered `_diagnostics: { valid: true }`: the door - * judged the Zod shape only, and `validateFormLayout`, the rule that says such - * a field "is silently skipped and never renders on the form", ran only in the + * QA's reproduction was a stored form `ViewItem`, one section naming + * `no_such_field`. It saved as a draft, published, and both its draft read and + * its active read answered `_diagnostics: { valid: true }`: the door judged + * the Zod shape only, and `validateFormLayout`, the rule that says such a + * field "is silently skipped and never renders on the form", ran only in the * CLI. * + * ## Protocol 19 (ADR-0159) + * + * A form is a `form` item, its sections at the top level; a view holds lists + * only, and the `view` door refuses a form authored in one. Every form below + * is authored as a `form` item and read through the `form` door, which carries + * the same two warnings the `view` read carried for a form before 19. The + * list-view cases at the end stay on the `view` door. + * * ## What is pinned * * - The draft still saves and the publish is not refused: the finding is a @@ -20,7 +28,7 @@ * - The draft read and the active read both carry one `warnings[]` entry, * located at the field reference and worded exactly as `validateFormLayout` * words it (compared against the rule run in the same test). - * - The field set is the one the door resolves for the view's object + * - The field set is the one the door resolves for the form's object * (`registry.getObject`, the served object with its extensions): a field the * resolver knows is not reported. * - A form naming only real fields, and a form whose object does not resolve, @@ -184,36 +192,36 @@ function makeStubEngine() { } const PKG = 'app.tasks'; -/** QA's reproduction shape: a stored form `ViewItem`, sections under `config`. */ +/** QA's reproduction as protocol 19 authors it: a `form` item, sections at the top level. */ function formItem(name: string, object: string, fields: string[]) { return { name, object, - viewKind: 'form', - isDefault: true, - config: { - type: 'tabbed', - data: { provider: 'object', object }, - sections: [{ name: 'overview', label: 'Overview', columns: 2, fields }], - }, + type: 'tabbed', + sections: [{ name: 'overview', label: 'Overview', columns: 2, fields }] as Array>, }; } type Diagnostics = { valid: boolean; errors?: unknown[]; warnings?: Array<{ path: string; message: string }> }; -async function readDiagnostics(protocol: ObjectStackProtocolImplementation, name: string, state: 'draft' | 'active') { - const read: any = await protocol.getMetaItem({ type: 'view', name, state, packageId: PKG } as any); +async function readDiagnostics( + protocol: ObjectStackProtocolImplementation, + name: string, + state: 'draft' | 'active', + type: 'form' | 'view' = 'form', +) { + const read: any = await protocol.getMetaItem({ type, name, state, packageId: PKG } as any); return read.item._diagnostics as Diagnostics; } /** The lint's own words for the item, from the rule itself — the one spelling. */ function lintMessages(item: ReturnType, object: Record) { - return validateFormLayout({ objects: [object], views: [{ name: item.name, object: item.object, form: item.config }] }) + return validateFormLayout({ objects: [object], forms: [item] }) .filter((f) => f.rule === FORM_FIELD_UNKNOWN) .map((f) => f.message); } -describe('a form view naming a field its object lacks reads with the lint warning (#29196)', () => { +describe('a form naming a field its object lacks reads with the lint warning (#29196)', () => { let warn: ReturnType; beforeEach(() => { warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -230,32 +238,40 @@ describe('a form view naming a field its object lacks reads with the lint warnin expect(expected).toHaveLength(1); expect(expected[0]).toContain('"no_such_field"'); - const saved: any = await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); + const saved: any = await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG, mode: 'draft' }); expect(saved).toMatchObject({ success: true, state: 'draft' }); - const warning = { path: 'config.sections.0.fields.1', message: expected[0] }; + const warning = { path: 'sections.0.fields.1', message: expected[0] }; expect(await readDiagnostics(protocol, item.name, 'draft')).toEqual({ valid: true, warnings: [warning] }); - const published: any = await protocol.publishMetaItem({ type: 'view', name: item.name, packageId: PKG } as any); + const published: any = await protocol.publishMetaItem({ type: 'form', name: item.name, packageId: PKG } as any); expect(published).toMatchObject({ success: true }); expect(await readDiagnostics(protocol, item.name, 'active')).toEqual({ valid: true, warnings: [warning] }); }); - it('a view container\'s named form is judged on the same door, located under its own key', async () => { - const { engine } = makeStubEngine(); + it('a view container\'s named form is refused at the view door, and the same form as a form item is judged on the form door, located under its own key', async () => { + const { engine, rows } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - const container = { - name: 'task', - object: 'task', - formViews: { edit: { type: 'simple', sections: [{ name: 'main', fields: ['no_such_field', 'title'] }] } }, - }; - - await (protocol as any).saveMetaItem({ type: 'view', name: container.name, item: container, packageId: PKG, mode: 'draft' }); - const draft = await readDiagnostics(protocol, container.name, 'draft'); + const edit = { type: 'simple', sections: [{ name: 'main', fields: ['no_such_field', 'title'] }] }; + const container = { name: 'task', object: 'task', formViews: { edit } }; + + // Protocol 19: a view holds lists only. The container is refused with + // the prescription naming `forms:`, and no row is written. + const refused = await (protocol as any) + .saveMetaItem({ type: 'view', name: container.name, item: container, packageId: PKG, mode: 'draft' }) + .catch((e: any) => e); + expect(refused).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(JSON.stringify(refused.issues ?? refused.details ?? refused.message)).toContain('forms'); + expect(rows.size).toBe(0); + + // The form the container held, authored where 19 authors it. + const form = { name: 'task.edit', object: 'task', ...edit }; + await (protocol as any).saveMetaItem({ type: 'form', name: form.name, item: form, packageId: PKG, mode: 'draft' }); + const draft = await readDiagnostics(protocol, form.name, 'draft'); expect(draft.valid).toBe(true); - expect(draft.warnings).toEqual([{ path: 'formViews.edit.sections.0.fields.0', message: expect.stringContaining('"no_such_field"') }]); + expect(draft.warnings).toEqual([{ path: 'sections.0.fields.0', message: expect.stringContaining('"no_such_field"') }]); }); it('control: a form naming only fields the served object has (an extension field among them) reads { valid: true }', async () => { @@ -263,10 +279,10 @@ describe('a form view naming a field its object lacks reads with the lint warnin const protocol = new ObjectStackProtocolImplementation(engine); const item = formItem('task.form', 'task', ['title', 'status', 'region__c']); - await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); + await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG, mode: 'draft' }); expect(await readDiagnostics(protocol, item.name, 'draft')).toEqual({ valid: true }); - await protocol.publishMetaItem({ type: 'view', name: item.name, packageId: PKG } as any); + await protocol.publishMetaItem({ type: 'form', name: item.name, packageId: PKG } as any); expect(await readDiagnostics(protocol, item.name, 'active')).toEqual({ valid: true }); }); @@ -275,7 +291,7 @@ describe('a form view naming a field its object lacks reads with the lint warnin const protocol = new ObjectStackProtocolImplementation(engine); const item = formItem('ghost.form', 'ghost', ['no_such_field']); - await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); + await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG, mode: 'draft' }); expect(await readDiagnostics(protocol, item.name, 'draft')).toEqual({ valid: true }); }); }); @@ -291,18 +307,20 @@ describe('a form view naming a field its object lacks reads with the lint warnin // `advisories` key at all (`validateFormLayout` was CLI-only in // `AUTHORING_RULES`). The publish gate's universe holds the bound object with // its extension fields on both doors that run rules (see `servedTask`), so the -// rule is crossed to `runtimeTypes: ['view']`. A draft save runs no registry -// rule (#4463 D1), so it carries no advisory; its read does. +// rule is crossed to the runtime gate: `runtimeTypes: ['form']` from protocol +// 19, where a form is a `form` item (it was `['view']` while a view held +// forms). A draft save runs no registry rule (#4463 D1), so it carries no +// advisory; its read does. // --------------------------------------------------------------------------- -/** A view container whose named form `edit` carries the given sections. */ -function formContainer(sections: Array>) { - return { name: 'task', object: 'task', formViews: { edit: { type: 'simple', sections } } }; +/** The form `task.edit` carrying the given sections: the form a container's `formViews.edit` was before 19. */ +function editForm(sections: Array>) { + return { name: 'task.edit', object: 'task', type: 'simple', sections }; } -/** The lint's findings on a container, from the rule itself — the one spelling. */ -function lintFindings(container: Record) { - return validateFormLayout({ objects: [servedTask], views: [container] }); +/** The lint's findings on a form item, from the rule itself — the one spelling. */ +function lintFindings(form: Record) { + return validateFormLayout({ objects: [servedTask], forms: [form] }); } type Advisory = { rule: string; path: string; message: string; hint: string; severity: string }; @@ -328,18 +346,16 @@ describe('form-section-group-unknown on the read, and both findings on save and const item = formItem('task.form', 'task', ['title']); // A group-referencing section takes its presentation from the group, // so it carries no `name` / `label` of its own (the save refuses both). - (item.config as { sections: unknown[] }).sections = [{ group: 'no_such_group' }]; - const expected = validateFormLayout({ - objects: [servedTask], - views: [{ name: item.name, object: item.object, form: item.config }], - }).filter((f) => f.rule === FORM_SECTION_GROUP_UNKNOWN); + item.sections = [{ group: 'no_such_group' }]; + const expected = validateFormLayout({ objects: [servedTask], forms: [item] }) + .filter((f) => f.rule === FORM_SECTION_GROUP_UNKNOWN); expect(expected).toHaveLength(1); - await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); - const warning = { path: 'config.sections.0.group', message: expected[0].message }; + await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG, mode: 'draft' }); + const warning = { path: 'sections.0.group', message: expected[0].message }; expect(await readDiagnostics(protocol, item.name, 'draft')).toEqual({ valid: true, warnings: [warning] }); - const published: any = await protocol.publishMetaItem({ type: 'view', name: item.name, packageId: PKG } as any); + const published: any = await protocol.publishMetaItem({ type: 'form', name: item.name, packageId: PKG } as any); expect(published).toMatchObject({ success: true }); expect(await readDiagnostics(protocol, item.name, 'active')).toEqual({ valid: true, warnings: [warning] }); }); @@ -347,14 +363,14 @@ describe('form-section-group-unknown on the read, and both findings on save and it('an active save naming an unknown field and an unknown group answers both as warnings, and the write lands', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - const container = formContainer([ + const form = editForm([ { name: 'main', fields: ['no_such_field', 'title'] }, { group: 'no_such_group' }, ]); - const expected = lintFindings(container); + const expected = lintFindings(form); expect(expected.map((f) => f.rule).sort()).toEqual([FORM_FIELD_UNKNOWN, FORM_SECTION_GROUP_UNKNOWN]); - const saved: any = await (protocol as any).saveMetaItem({ type: 'view', name: container.name, item: container, packageId: PKG }); + const saved: any = await (protocol as any).saveMetaItem({ type: 'form', name: form.name, item: form, packageId: PKG }); expect(saved).toMatchObject({ success: true }); const advisories = formLayoutAdvisories(saved); expect(advisories.map((a) => a.severity)).toEqual(['warning', 'warning']); @@ -363,7 +379,7 @@ describe('form-section-group-unknown on the read, and both findings on save and // One finding, once: the active read carries each as a warning, and // the read runs no runtime advisory of its own. - const read = await readDiagnostics(protocol, container.name, 'active'); + const read = await readDiagnostics(protocol, form.name, 'active'); expect(read.valid).toBe(true); expect(read.warnings?.map((w) => w.message).sort()).toEqual(expected.map((f) => f.message).sort()); }); @@ -371,16 +387,16 @@ describe('form-section-group-unknown on the read, and both findings on save and it('a publish of a draft naming an unknown field answers it as a warning, and is not refused', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - const container = formContainer([{ name: 'main', fields: ['title', 'no_such_field'] }]); - const expected = lintFindings(container); + const form = editForm([{ name: 'main', fields: ['title', 'no_such_field'] }]); + const expected = lintFindings(form); expect(expected.map((f) => f.rule)).toEqual([FORM_FIELD_UNKNOWN]); - const saved: any = await (protocol as any).saveMetaItem({ type: 'view', name: container.name, item: container, packageId: PKG, mode: 'draft' }); + const saved: any = await (protocol as any).saveMetaItem({ type: 'form', name: form.name, item: form, packageId: PKG, mode: 'draft' }); expect(saved).toMatchObject({ success: true, state: 'draft' }); // D1: a draft save runs no registry rule, so it carries no advisory. expect(formLayoutAdvisories(saved)).toEqual([]); - const published: any = await protocol.publishMetaItem({ type: 'view', name: container.name, packageId: PKG } as any); + const published: any = await protocol.publishMetaItem({ type: 'form', name: form.name, packageId: PKG } as any); expect(published).toMatchObject({ success: true }); expect(formLayoutAdvisories(published).map(({ rule, message, hint, severity }) => ({ rule, message, hint, severity }))) .toEqual([{ rule: FORM_FIELD_UNKNOWN, message: expected[0].message, hint: expected[0].hint, severity: 'warning' }]); @@ -389,33 +405,35 @@ describe('form-section-group-unknown on the read, and both findings on save and it('control: a form naming only real fields (an extension field among them) and a declared group answers no advisory', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); - const container = formContainer([ + const form = editForm([ { name: 'main', fields: ['title', 'status', 'region__c'] }, { group: 'details' }, ]); - expect(lintFindings(container)).toEqual([]); + expect(lintFindings(form)).toEqual([]); - const saved: any = await (protocol as any).saveMetaItem({ type: 'view', name: container.name, item: container, packageId: PKG }); + const saved: any = await (protocol as any).saveMetaItem({ type: 'form', name: form.name, item: form, packageId: PKG }); expect(saved).toMatchObject({ success: true }); expect(formLayoutAdvisories(saved)).toEqual([]); - expect(await readDiagnostics(protocol, container.name, 'active')).toEqual({ valid: true }); + expect(await readDiagnostics(protocol, form.name, 'active')).toEqual({ valid: true }); - await (protocol as any).saveMetaItem({ type: 'view', name: 'task', item: container, packageId: PKG, mode: 'draft' }); - const published: any = await protocol.publishMetaItem({ type: 'view', name: 'task', packageId: PKG } as any); + await (protocol as any).saveMetaItem({ type: 'form', name: form.name, item: form, packageId: PKG, mode: 'draft' }); + const published: any = await protocol.publishMetaItem({ type: 'form', name: form.name, packageId: PKG } as any); expect(published).toMatchObject({ success: true }); expect(formLayoutAdvisories(published)).toEqual([]); }); }); // --------------------------------------------------------------------------- -// #29309 — the Studio-saved form ViewItem on the save and publish answers. +// #29309 — the Studio-saved form on the save and publish answers. // // Measured on a real showcase boot before the lint's view walk learned the -// `config` rung: `PUT /meta/view/showcase_account.probe_e` (a `viewKind: 'form'` -// item naming `no_such_field`) answered no advisory, while its read warned. +// item rung: `PUT /meta/view/showcase_account.probe_e` (then a +// `viewKind: 'form'` item naming `no_such_field`) answered no advisory, while +// its read warned. From protocol 19 the item is a `form` item on the `form` +// door, and both answers are pinned there. // --------------------------------------------------------------------------- -describe('a form ViewItem is judged on save and publish too (#29309)', () => { +describe('a form item is judged on save and publish too (#29309)', () => { let warn: ReturnType; beforeEach(() => { warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -428,27 +446,25 @@ describe('a form ViewItem is judged on save and publish too (#29309)', () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); const item = formItem('task.form', 'task', ['title', 'no_such_field']); - const expected = validateFormLayout({ - objects: [servedTask], - views: [{ name: item.name, object: item.object, form: item.config }], - }).filter((f) => f.rule === FORM_FIELD_UNKNOWN); + const expected = validateFormLayout({ objects: [servedTask], forms: [item] }) + .filter((f) => f.rule === FORM_FIELD_UNKNOWN); expect(expected).toHaveLength(1); const want = [{ rule: FORM_FIELD_UNKNOWN, message: expected[0].message, hint: expected[0].hint, severity: 'warning' }]; const pick = (r: any) => formLayoutAdvisories(r).map(({ rule, message, hint, severity }) => ({ rule, message, hint, severity })); - const saved: any = await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG }); + const saved: any = await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG }); expect(saved).toMatchObject({ success: true }); expect(pick(saved)).toEqual(want); - await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); - const published: any = await protocol.publishMetaItem({ type: 'view', name: item.name, packageId: PKG } as any); + await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG, mode: 'draft' }); + const published: any = await protocol.publishMetaItem({ type: 'form', name: item.name, packageId: PKG } as any); expect(published).toMatchObject({ success: true }); expect(pick(published)).toEqual(want); - // Once on the read, at the same `config` path #29196 pinned. + // Once on the read, at the same path #29196 pins. expect(await readDiagnostics(protocol, item.name, 'active')).toEqual({ valid: true, - warnings: [{ path: 'config.sections.0.fields.1', message: expected[0].message }], + warnings: [{ path: 'sections.0.fields.1', message: expected[0].message }], }); }); @@ -457,7 +473,7 @@ describe('a form ViewItem is judged on save and publish too (#29309)', () => { const protocol = new ObjectStackProtocolImplementation(engine); const item = formItem('task.form', 'task', ['title', 'region__c']); - const saved: any = await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG }); + const saved: any = await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG }); expect(saved).toMatchObject({ success: true }); expect(formLayoutAdvisories(saved)).toEqual([]); expect(await readDiagnostics(protocol, item.name, 'active')).toEqual({ valid: true }); @@ -465,7 +481,7 @@ describe('a form ViewItem is judged on save and publish too (#29309)', () => { }); // --------------------------------------------------------------------------- -// #29435 — the layered read (`?layers=true`) of the same form view. +// #29435 — the layered read (`?layers=true`) of the same form. // // Measured on `origin/main` `7dae3b3c` before the fix: `getMetaItemLayered` // computed its `_diagnostics` with `computeMetadataDiagnostics` alone, so a @@ -475,12 +491,12 @@ describe('a form ViewItem is judged on save and publish too (#29309)', () => { // when no draft is pending. // --------------------------------------------------------------------------- -async function readLayeredDiagnostics(protocol: ObjectStackProtocolImplementation, name: string) { - const read: any = await protocol.getMetaItemLayered({ type: 'view', name, packageId: PKG }); +async function readLayeredDiagnostics(protocol: ObjectStackProtocolImplementation, name: string, type: 'form' | 'view' = 'form') { + const read: any = await protocol.getMetaItemLayered({ type, name, packageId: PKG }); return read._diagnostics as Diagnostics; } -describe('the layered read of a form view carries the same form-layout warnings (#29435)', () => { +describe('the layered read of a form carries the same form-layout warnings (#29435)', () => { let warn: ReturnType; beforeEach(() => { warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -489,19 +505,19 @@ describe('the layered read of a form view carries the same form-layout warnings warn.mockRestore(); }); - it('a published form view naming an unknown field warns at the same path as getMetaItem', async () => { + it('a published form naming an unknown field warns at the same path as getMetaItem', async () => { const { engine } = makeStubEngine(); const protocol = new ObjectStackProtocolImplementation(engine); const item = formItem('task.form', 'task', ['title', 'no_such_field']); const expected = lintMessages(item, servedTask); expect(expected).toHaveLength(1); - await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); - await protocol.publishMetaItem({ type: 'view', name: item.name, packageId: PKG } as any); + await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG, mode: 'draft' }); + await protocol.publishMetaItem({ type: 'form', name: item.name, packageId: PKG } as any); const single = await readDiagnostics(protocol, item.name, 'active'); const layered = await readLayeredDiagnostics(protocol, item.name); - expect(layered).toEqual({ valid: true, warnings: [{ path: 'config.sections.0.fields.1', message: expected[0] }] }); + expect(layered).toEqual({ valid: true, warnings: [{ path: 'sections.0.fields.1', message: expected[0] }] }); expect(layered).toEqual(single); }); @@ -510,8 +526,8 @@ describe('the layered read of a form view carries the same form-layout warnings const protocol = new ObjectStackProtocolImplementation(engine); const item = formItem('task.form', 'task', ['title', 'status', 'region__c']); - await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); - await protocol.publishMetaItem({ type: 'view', name: item.name, packageId: PKG } as any); + await (protocol as any).saveMetaItem({ type: 'form', name: item.name, item, packageId: PKG, mode: 'draft' }); + await protocol.publishMetaItem({ type: 'form', name: item.name, packageId: PKG } as any); expect(await readLayeredDiagnostics(protocol, item.name)).toEqual({ valid: true }); }); @@ -575,10 +591,10 @@ function makeListViewEngine(codeViews: Record> = return { ...stub, objects }; } -async function readAllThree(protocol: ObjectStackProtocolImplementation, name: string) { - const active: any = await protocol.getMetaItem({ type: 'view', name } as any); - const scoped: any = await protocol.getMetaItem({ type: 'view', name, packageId: PKG } as any); - const layered: any = await protocol.getMetaItemLayered({ type: 'view', name } as any); +async function readAllThree(protocol: ObjectStackProtocolImplementation, name: string, type: 'form' | 'view' = 'view') { + const active: any = await protocol.getMetaItem({ type, name } as any); + const scoped: any = await protocol.getMetaItem({ type, name, packageId: PKG } as any); + const layered: any = await protocol.getMetaItemLayered({ type, name } as any); return [active.item._diagnostics, scoped.item._diagnostics, layered._diagnostics] as Diagnostics[]; } @@ -634,14 +650,14 @@ describe('a list view column naming a field its object lacks reads with the lint await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); expect(await protocol.publishMetaItem({ type: 'view', name: item.name, packageId: PKG } as any)).toMatchObject({ success: true }); - expect(await readDiagnostics(protocol, item.name, 'active')).toEqual({ valid: true }); + expect(await readDiagnostics(protocol, item.name, 'active', 'view')).toEqual({ valid: true }); // The object drops `total_cost` (renamed by a later release of its package). const renamed = { ...aiTraces, fields: { model: aiTraces.fields.model, cost: aiTraces.fields.total_cost } }; objects.ai_traces = renamed; const want = { valid: true, warnings: [{ path: 'config.columns.1.field', message: listViewFindings(item, renamed)[0].message }] }; - expect(await readDiagnostics(protocol, item.name, 'active')).toEqual(want); - expect(await readLayeredDiagnostics(protocol, item.name)).toEqual(want); + expect(await readDiagnostics(protocol, item.name, 'active', 'view')).toEqual(want); + expect(await readLayeredDiagnostics(protocol, item.name, 'view')).toEqual(want); }); it('a user filter field the ADR-0047 reference check already reports as an error is not repeated as a warning', async () => { @@ -677,7 +693,7 @@ describe('a list view column naming a field its object lacks reads with the lint const draft: any = await (protocol as any).saveMetaItem({ type: 'view', name: item.name, item, packageId: PKG, mode: 'draft' }); expect(draft).toMatchObject({ success: true, state: 'draft' }); - expect(await readDiagnostics(protocol, item.name, 'draft')).toEqual({ + expect(await readDiagnostics(protocol, item.name, 'draft', 'view')).toEqual({ valid: false, errors: [{ path: 'config.columns.1.field', message: finding.message, code: LIST_VIEW_FIELD_UNKNOWN }], }); @@ -705,20 +721,26 @@ describe('a list view column naming a field its object lacks reads with the lint for (const diagnostics of await readAllThree(protocol, ghost.name)) expect(diagnostics).toEqual({ valid: true }); }); - it('control: a container\'s form warnings are unchanged beside a valid list', async () => { + it('control: a form\'s warnings are unchanged beside a valid list of the same object', async () => { + // Protocol 19: the package ships the list in a `view` container and + // the form as a `form` item beside it. const container = { name: 'task', object: 'task', list: { type: 'grid', columns: [{ field: 'title' }, { field: 'region__c' }] }, - formViews: { edit: { type: 'simple', sections: [{ name: 'main', fields: ['no_such_field', 'title'] }] } }, }; + const form = editForm([{ name: 'main', fields: ['no_such_field', 'title'] }]); const { engine } = makeListViewEngine({ task: container }); + const { getItem, listItems } = engine.registry; + engine.registry.getItem = (type: string, name: string) => (type === 'form' && name === form.name ? form : getItem(type, name)); + engine.registry.listItems = (type: string) => (type === 'form' ? [form] : listItems(type)); const protocol = new ObjectStackProtocolImplementation(engine); - const formOnly = lintFindings({ name: container.name, object: container.object, formViews: container.formViews }) - .filter((f) => f.rule === FORM_FIELD_UNKNOWN); + const formOnly = lintFindings(form).filter((f) => f.rule === FORM_FIELD_UNKNOWN); expect(formOnly).toHaveLength(1); - const want = { valid: true, warnings: [{ path: 'formViews.edit.sections.0.fields.0', message: formOnly[0].message }] }; - for (const diagnostics of await readAllThree(protocol, container.name)) expect(diagnostics).toEqual(want); + const want = { valid: true, warnings: [{ path: 'sections.0.fields.0', message: formOnly[0].message }] }; + for (const diagnostics of await readAllThree(protocol, form.name, 'form')) expect(diagnostics).toEqual(want); + // The list beside it reads clean: the form's finding is the form's. + for (const diagnostics of await readAllThree(protocol, container.name)) expect(diagnostics).toEqual({ valid: true }); }); }); diff --git a/packages/metadata-protocol/src/protocol.graft-folded-form-sections.test.ts b/packages/metadata-protocol/src/protocol.graft-folded-form-sections.test.ts index 729b5006414..6b09c585036 100644 --- a/packages/metadata-protocol/src/protocol.graft-folded-form-sections.test.ts +++ b/packages/metadata-protocol/src/protocol.graft-folded-form-sections.test.ts @@ -38,12 +38,23 @@ * pins that asserted the verbatim save were re-judged where they stand. The * stage's own pins are the last three blocks, riding this file's pinned engine * double for the reason the #20051 door-half block below gives. + * + * ## Protocol 19 (ADR-0159): the fold lives on `form` items + * + * A form is a `form` item and a `view` holds lists only, so the form fixtures + * below are `form` items saved through the `form` door. That door is one of + * "the other types": it stores the body as authored with this graft applied, + * so the fold reaches the row and nothing else moves (no default, no + * normalised predicate). The three shapes a `view` held a form in (the + * flattened `viewKind: 'form'` overlay, the ViewItem record, the container's + * `form` / `formViews`) are refused by the `view` door with the `forms:` + * prescription and no row; each case that authored one pins that refusal. */ import { describe, expect, it, vi } from 'vitest'; // `./protocol.js` reaches `import('@objectstack/lint')` (the diagnostics and // build probes); pay its first load at collection, never inside a clocked case. import '@objectstack/lint'; -import { ViewMetadataSchema, VIEW_CONSOLE_ROUND_TRIP_KEYS } from '@objectstack/spec/ui'; +import { FormSchema, ViewMetadataSchema, VIEW_CONSOLE_ROUND_TRIP_KEYS } from '@objectstack/spec/ui'; import { getMetadataTypeSchema, registerMetadataTypeSchema } from '@objectstack/spec/kernel'; import { z } from 'zod'; import { @@ -151,11 +162,25 @@ async function storedViewBody(name: string, item: unknown): Promise { return JSON.parse(row!.metadata); } +/** Save a `form` item through the real write path and return the body the ROW holds. */ +async function storedFormBody(name: string, item: unknown): Promise { + const { protocol, rows } = makeProtocol(); + const result: any = await (protocol as any).saveMetaItem({ type: 'form', name, item }); + expect(result.success, JSON.stringify(result)).toBe(true); + const row = Array.from(rows.values()).find((r) => r.type === 'form'); + expect(row, 'the save persisted no form row at all').toBeDefined(); + return JSON.parse(row!.metadata); +} + /** - * [#26711] Save a view the door refuses: the 422 envelope, NO row written, and - * the `unrecognized_keys` issue the claimed member raised for the undeclared keys. + * [ADR-0159 D7] Save a body that holds a form in a `view` through the `view` + * door: the 422 envelope, NO row written, and the issues, each of which is + * the tombstone's refusal carrying the `forms:` prescription at `path`. */ -async function refusedUndeclared(item: Record): Promise<{ message: string }> { +async function refusedFormInView( + item: Record, + paths: readonly string[], +): Promise> { const { protocol, rows } = makeProtocol(); let err: any; try { @@ -163,7 +188,30 @@ async function refusedUndeclared(item: Record): Promise<{ messa } catch (e) { err = e; } expect(err?.code).toBe('INVALID_METADATA'); expect(err?.status).toBe(422); - expect(Array.from(rows.values()).filter((r) => r.type === 'view')).toHaveLength(0); + expect(rows.size, 'a refused save writes no row of any type').toBe(0); + const issues = err.issues as Array<{ path: string; code?: string; message: string }>; + for (const path of paths) { + const hit = issues.find((i) => i.path === path); + expect(hit, `no issue at \`${path}\` in ${JSON.stringify(issues)}`).toBeDefined(); + expect(hit!.message).toContain('was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)'); + expect(hit!.message).toContain('`forms:`'); + } + return issues; +} + +/** + * [#26711] Save an item the door refuses: the 422 envelope, NO row written, and + * the `unrecognized_keys` issue the claimed member raised for the undeclared keys. + */ +async function refusedUndeclared(item: Record, type: 'view' | 'form' = 'view'): Promise<{ message: string }> { + const { protocol, rows } = makeProtocol(); + let err: any; + try { + await (protocol as any).saveMetaItem({ type, name: item.name as string, item }); + } catch (e) { err = e; } + expect(err?.code).toBe('INVALID_METADATA'); + expect(err?.status).toBe(422); + expect(Array.from(rows.values()).filter((r) => r.type === type)).toHaveLength(0); const issue = (err.issues as Array<{ code?: string; message: string }>) .find((i) => i.code === 'unrecognized_keys'); expect(issue, JSON.stringify(err.issues)).toBeDefined(); @@ -175,7 +223,17 @@ const SECTION = { label: 'About you', fields: ['name', 'email'] }; const SHARING = { allowAnonymous: true, publicLink: '/forms/contact-us' }; const DATA = { provider: 'object', object: 'lead' }; -/** A flattened runtime FORM overlay — the shape a Studio form save sends. */ +/** A `form` item — the shape a Studio form save sends from protocol 19 (ADR-0159). */ +const formItem = (extra: Record = {}) => ({ + name: 'lead.contact_us', + object: 'lead', + label: 'Contact us', + type: 'simple', + sharing: SHARING, + ...extra, +}); + +/** The flattened `viewKind: 'form'` overlay a Studio form save sent before 19; the `view` door refuses it. */ const flatForm = (extra: Record = {}) => ({ name: 'contact_us', object: 'lead', @@ -186,73 +244,90 @@ const flatForm = (extra: Record = {}) => ({ ...extra, }); +/** The ViewItem record that held a form before 19. */ +const formRecord = (extra: Record = {}) => ({ + name: 'lead.contact_us', + object: 'lead', + viewKind: 'form', + label: 'Contact us', + config: { type: 'simple', data: DATA, sharing: SHARING, groups: [SECTION] }, + ...extra, +}); + describe('#7134 the save path persists the folded `sections`, at every depth a form lives', () => { - it('flattened form overlay: an authored `groups` reaches the row as `sections`', async () => { - const body = await storedViewBody('contact_us', flatForm({ groups: [SECTION] })); + it('form item: an authored `groups` reaches the row as `sections`', async () => { + const body = await storedFormBody('lead.contact_us', formItem({ groups: [SECTION] })); expect(body.sections).toEqual([SECTION]); expect(body, 'the authored alias must not survive into the row').not.toHaveProperty('groups'); }); - it('ViewItem `config.groups` reaches the row as `config.sections`', async () => { - const body = await storedViewBody('lead.contact_us', { - name: 'lead.contact_us', - object: 'lead', - viewKind: 'form', - label: 'Contact us', - config: { type: 'simple', data: DATA, sharing: SHARING, groups: [SECTION] }, - }); - expect(body.config.sections).toEqual([SECTION]); - expect(body.config).not.toHaveProperty('groups'); + it('the flattened `viewKind: \'form\'` overlay is refused at the view door with the `forms:` prescription; nothing is stored', async () => { + await refusedFormInView(flatForm({ groups: [SECTION] }), ['viewKind']); }); - it('container `form.groups` and `formViews.*.groups` both reach the row as `sections`', async () => { - // One save covering both container slots: a form slot the walk finds by - // structure, not by a maintained list of places a form can live. - const body = await storedViewBody('lead_views', { + it('ViewItem `config.groups`: the form record is refused at the view door; the same body as a form item reaches the row as `sections`', async () => { + const record = formRecord(); + await refusedFormInView(record, ['viewKind']); + // The prescription followed: the `config` body at the top level, bound with `object`. + const { data: _data, ...config } = record.config; + const body = await storedFormBody(record.name, { name: record.name, object: record.object, label: record.label, ...config }); + expect(body.sections).toEqual([SECTION]); + expect(body).not.toHaveProperty('groups'); + }); + + it('container `form.groups` and `formViews.*.groups` are refused at the view door, each slot by name; each as a form item reaches the row as `sections`', async () => { + // One save covering both container slots: each is refused at its own key. + const slot = { type: 'simple', sharing: SHARING, groups: [SECTION] }; + await refusedFormInView({ name: 'lead_views', - form: { type: 'simple', data: DATA, sharing: SHARING, groups: [SECTION] }, - formViews: { - intake: { type: 'simple', data: DATA, sharing: SHARING, groups: [SECTION] }, - }, - }); - expect(body.form.sections).toEqual([SECTION]); - expect(body.form).not.toHaveProperty('groups'); - expect(body.formViews.intake.sections).toEqual([SECTION]); - expect(body.formViews.intake).not.toHaveProperty('groups'); + form: { ...slot, data: DATA }, + formViews: { intake: { ...slot, data: DATA } }, + }, ['form', 'formViews']); + // The names the prescriptions give: `OBJECT.form` and `OBJECT.KEY`. + for (const name of ['lead.form', 'lead.intake']) { + const body = await storedFormBody(name, { name, object: 'lead', ...slot }); + expect(body.sections).toEqual([SECTION]); + expect(body).not.toHaveProperty('groups'); + } }); it('the row carries the AUTHORED array, not `parsed.data`\'s defaulted one', async () => { - // `parsed.data` would have stamped `collapsible`, `collapsed` and - // `columns` onto the section. Persisting those is the wholesale swap - // this whole design avoids — the graft moves the key, nothing else. - const body = await storedViewBody('contact_us', flatForm({ groups: [SECTION] })); + // `parsed.data` stamps `collapsible` and `collapsed` onto the section. + // Persisting those is the wholesale swap this whole design avoids — + // the graft moves the key, nothing else. + const authored = formItem({ groups: [SECTION] }); + expect(Object.keys((FormSchema as any).parse(authored).sections[0]).sort()) + .toEqual(['collapsed', 'collapsible', 'fields', 'label']); + const body = await storedFormBody(authored.name, authored); expect(Object.keys(body.sections[0]).sort()).toEqual(['fields', 'label']); }); it('`sections` wins when the author wrote both — `groups` is dropped, empty array included', async () => { // The producer's own precedence rule (`spec.sections ?? spec.groups`). - const body = await storedViewBody('contact_us', flatForm({ sections: [], groups: [SECTION] })); + const body = await storedFormBody('lead.contact_us', formItem({ sections: [], groups: [SECTION] })); expect(body.sections).toEqual([]); expect(body).not.toHaveProperty('groups'); }); - it('[#26711] the fold and the form overlay\'s declared keys coexist on one save; its undeclared ones are refused by name', async () => { - // Re-judged twice. At stage (iv) of #20051, which stores a view's parsed - // body, the undeclared keys were dropped from the row on a `200`. Since - // #26711 the form member is closed, so they are refused. The fold is - // stored, and so is `isDefault`, which the flattened FORM overlay - // declares. `isPinned` and `sortOrder` are the list switcher's row - // state: the form member declares neither and the console writes - // neither on a form row (`VIEW_CONSOLE_ROUND_TRIP_KEYS` maps no key to - // `formOverlay`). - const body = await storedViewBody('contact_us', flatForm({ groups: [SECTION], isDefault: false })); + it('[#26711] the fold and the form\'s declared keys coexist on one save; its undeclared ones are refused by name', async () => { + // Re-judged three times. At stage (iv) of #20051, which stores a view's + // parsed body, the undeclared keys were dropped from the row on a `200`. + // Since #26711 the form member is closed, so they are refused. From + // protocol 19 the form is a `form` item: the fold is stored beside the + // keys the item declares (`title` here). `isPinned` and `sortOrder` are + // the list switcher's row state, and `isDefault` is not carried over + // from the view item (ADR-0159 D1: a record form is the object's + // `fieldGroups`): the item declares none of the three. + const body = await storedFormBody('lead.contact_us', formItem({ groups: [SECTION], title: 'Contact us' })); expect(body.sections).toEqual([SECTION]); expect(body).not.toHaveProperty('groups'); - expect(body.isDefault).toBe(false); + expect(body.title).toBe('Contact us'); const refusal = await refusedUndeclared( - flatForm({ groups: [SECTION], isPinned: true, isDefault: false, sortOrder: 3 }), + formItem({ groups: [SECTION], isPinned: true, sortOrder: 3 }), 'form', ); - expect(refusal.message).toMatch(/^Unrecognized key\(s\) on this inline form view: `isPinned`, `sortOrder`\./); + expect(refusal.message).toMatch(/^Unrecognized key\(s\) on this form: `isPinned`, `sortOrder`\./); + const notCarried = await refusedUndeclared(formItem({ groups: [SECTION], isDefault: false }), 'form'); + expect(notCarried.message).toMatch(/^Unrecognized key\(s\) on this form: `isDefault`\./); }); }); @@ -291,13 +366,14 @@ describe('#7134 what the save path must NOT change', () => { // default: undeclared, the parse adds no key (the renderer picks the // density by available width). [#26711] The undeclared `isPinned` is // now refused by name (the test above), so the fixture no longer - // carries it and the row is the body as authored. - const authored = flatForm({ sections: [SECTION] }); - const parsed = (ViewMetadataSchema as any).parse(authored); + // carries it and the row is the body as authored. From protocol 19 the + // form is a `form` item, stored as authored by the `form` door. + const authored = formItem({ sections: [SECTION] }); + const parsed = (FormSchema as any).parse(authored); expect(parsed.sections[0]).toMatchObject({ collapsible: false, collapsed: false }); expect('columns' in parsed.sections[0]).toBe(false); expect(parsed.sharing.enabled).toBe(false); - expect(await storedViewBody('contact_us', authored)).toEqual(authored); + expect(await storedFormBody(authored.name, authored)).toEqual(authored); }); it('GUARD: a LIST overlay is untouched — this walk is form-shaped only', async () => { @@ -375,14 +451,15 @@ describe('graftFoldedFormSections — structural safety, no save involved', () = }); it('the fold it replays is the schema\'s own, not a second opinion', () => { - // Ties the helper to the producer: whatever `ViewMetadataSchema` decides - // about `groups`, the grafted body agrees with — key for key. - const authored = flatForm({ groups: [SECTION] }); - const parsed = (ViewMetadataSchema as any).safeParse(authored); + // Ties the helper to the producer: whatever `FormSchema` decides about + // `groups`, the grafted body agrees with — key for key. + const authored = formItem({ groups: [SECTION] }); + const parsed = (FormSchema as any).safeParse(authored); expect(parsed.success).toBe(true); const grafted = graftFoldedFormSections(authored, parsed.data) as Record; expect('groups' in grafted).toBe('groups' in parsed.data); expect('sections' in grafted).toBe('sections' in parsed.data); + expect('sections' in grafted).toBe(true); }); }); @@ -518,10 +595,21 @@ describe('#20186 the save door judges a flattened overlay by the member its view expect(issue.message).toMatch(/^This list view overlay sets `type` but lists no `columns`\./); }); - it('the mirror — list `columns` on a `viewKind: form` body: 422 at `columns`, with the count prescription', async () => { - const issue = at(await refused({ ...FORM, columns: ['name'] }), 'columns'); - expect(issue.code).toBe('invalid_type'); - expect(issue.message).toMatch(/^On a form view `columns` is the NUMBER of body columns/); + it('the mirror — a `viewKind: form` body is refused at `viewKind` with the `forms:` prescription, and list `columns` on a form item: 422 at `columns`', async () => { + // Protocol 19: no member of the `view` union is a form, so the body is + // refused at the discriminator before any form key is judged. + const moved = at(await refused({ ...FORM, columns: ['name'] }), 'viewKind'); + expect(moved.message).toContain('was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)'); + expect(moved.message).toContain('`forms:`'); + // The mirror itself, on the door a form is judged at: `columns` is the + // form's column count, so a list's column array is refused there. + const { protocol, rows } = makeProtocol(); + const err: any = await (protocol as any) + .saveMetaItem({ type: 'form', name: ID.name, item: { ...ID, type: 'simple', columns: ['name'] } }) + .catch((e: unknown) => e); + expect([err?.code, err?.status]).toEqual(['INVALID_METADATA', 422]); + expect(rows.size).toBe(0); + expect(at(err.issues, 'columns').code).toBe('invalid_type'); }); // W2 — declared widening (`Clause-②: yes (narrowing)`): a list-legal value @@ -536,9 +624,9 @@ describe('#20186 the save door judges a flattened overlay by the member its view expect(await storedViewBody(body.name, body)).toEqual(body); }); - it('controls: a real form overlay and a list overlay with `columns` save verbatim', async () => { - const form = { ...FORM, type: 'simple', sections: [{ label: 'Main', fields: ['name'] }] }; - expect(await storedViewBody(form.name, form)).toEqual(form); + it('controls: a real form item and a list overlay with `columns` save verbatim', async () => { + const form = { ...ID, type: 'simple', sections: [{ label: 'Main', fields: ['name'] }] }; + expect(await storedFormBody(form.name, form)).toEqual(form); const list = { ...LIST, columns: ['name'], sort: [{ field: 'name', order: 'asc' }] }; expect(await storedViewBody(list.name, list)).toEqual(list); }); @@ -626,47 +714,58 @@ describe('[#20051] stage (iv): a saved view stores the parsed value of every key expect(stored.filter).toEqual([{ field: 'status', operator: 'not_equals', value: 'done' }]); }); - it('a key normalised inside a moved key is stored with its parsed value, with no default beside it', async () => { - // `groups` → `sections` moves the bucket, and inside it each section and - // field predicate normalises to its envelope. (Until 18 the inner level - // was a key move too — `visibleOn` → `visibleWhen` — which retired with - // the key, #23543 F4.) The stored row keeps the parsed predicates and - // drops the section / field defaults. - const stored = await storedViewBody('contact_us', flatForm({ - groups: [{ - label: 'About you', - visibleWhen: 'record.stage == "open"', - fields: ['name', { field: 'email', visibleWhen: 'record.opted_in == true' }], - }], - })); - expect(stored).not.toHaveProperty('groups'); - expect(stored.sections).toEqual([{ + it('a moved key on a form item is stored as authored inside: the bucket moves, no predicate is normalised, no default is added', async () => { + // Re-judged at protocol 19. While a `view` held the form, stage (iv) + // stored the parsed value of each key, so the predicates inside the + // moved bucket were stored as their envelopes. The form is a `form` + // item now, and stage (iv) is gated on the `view` type (the block + // below): the `form` door stores the request body with the graft, so + // `groups` → `sections` moves the bucket and everything inside it is + // the authored value. The parse still normalises both predicates, + // which is what the row does NOT take. + const section = { label: 'About you', - visibleWhen: { dialect: 'cel', source: 'record.stage == "open"' }, - fields: ['name', { field: 'email', visibleWhen: { dialect: 'cel', source: 'record.opted_in == true' } }], - }]); + visibleWhen: 'record.stage == "open"', + fields: ['name', { field: 'email', visibleWhen: 'record.opted_in == true' }], + }; + const authored = formItem({ groups: [section] }); + const parsed = (FormSchema as any).parse(authored); + expect(parsed.sections[0].visibleWhen).toEqual({ dialect: 'cel', source: 'record.stage == "open"' }); + expect(parsed.sections[0].fields[1].visibleWhen).toEqual({ dialect: 'cel', source: 'record.opted_in == true' }); + const stored = await storedFormBody(authored.name, authored); + expect(stored).not.toHaveProperty('groups'); + expect(stored.sections).toEqual([section]); expect(stored.sharing).toEqual(SHARING); }); it('the persisted body parses to exactly what the save parsed', async () => { const bodies: Array> = [ ...TOOLBAR_SAVES.map(([, patch]) => ({ ...patch, ...OVERLAY_ID })), - flatForm({ groups: [SECTION], isDefault: true }), - { - name: 'lead.contact_us', object: 'lead', viewKind: 'form', label: 'Contact us', - config: { type: 'simple', data: DATA, sharing: SHARING, groups: [SECTION] }, - }, - { - name: 'lead_views', - list: { type: 'grid', data: DATA, columns: ['name'] }, - formViews: { intake: { type: 'simple', data: DATA, groups: [SECTION] } }, - }, + { name: 'lead_views', list: { type: 'grid', data: DATA, columns: ['name'] } }, ]; for (const body of bodies) { const stored = await storedViewBody(body.name as string, body); expect((ViewMetadataSchema as any).parse(stored), JSON.stringify(body)) .toEqual((ViewMetadataSchema as any).parse(body)); } + // Protocol 19: the forms a view held are `form` items, and the same + // holds on their door against their own schema. + const forms: Array> = [ + formItem({ groups: [SECTION] }), + { name: 'lead.intake', object: 'lead', type: 'simple', groups: [SECTION] }, + ]; + for (const form of forms) { + const stored = await storedFormBody(form.name as string, form); + expect((FormSchema as any).parse(stored), JSON.stringify(form)).toEqual((FormSchema as any).parse(form)); + } + // And the three shapes that held them are refused, with nothing stored. + await refusedFormInView(flatForm({ groups: [SECTION], isDefault: true }), ['viewKind']); + await refusedFormInView(formRecord(), ['viewKind']); + await refusedFormInView({ + name: 'lead_views', + list: { type: 'grid', data: DATA, columns: ['name'] }, + formViews: { intake: { type: 'simple', data: DATA, groups: [SECTION] } }, + }, ['formViews']); }); }); @@ -711,13 +810,19 @@ describe('[#20051] stage (iv): a ViewItem record\'s top-level `options` bag is r expect(issue.message).toContain('Move each `options.KIND` block to `config.KIND`'); }); - it('on the form arm too', async () => { - const issue = await refusedRecord({ + it('the record\'s form arm is gone: a form record is refused at `viewKind`, and a form item refuses the bag by name', async () => { + // Protocol 19: a view item record is a list, so the form record is + // refused at the discriminator with the `forms:` prescription. + await refusedFormInView({ name: 'lead.contact_us', object: 'lead', viewKind: 'form', label: 'Contact us', config: { type: 'simple', data: DATA, sections: [SECTION] }, options: { timeline: { titleField: 'name' } }, - }); - expect(issue.message).toMatch(/^A view item record carries no top-level `options` bag/); + }, ['viewKind']); + // On the door the form moved to, the bag is still refused by name. + const refusal = await refusedUndeclared( + formItem({ sections: [SECTION], options: { timeline: { titleField: 'name' } } }), 'form', + ); + expect(refusal.message).toMatch(/^Unrecognized key\(s\) on this form: `options`\./); }); it('control: the same record without the bag saves, and the row is the record', async () => { diff --git a/packages/metadata-protocol/src/protocol.lookup-artifact-item-call-sites.test.ts b/packages/metadata-protocol/src/protocol.lookup-artifact-item-call-sites.test.ts index c662e144a1a..222403fdb6e 100644 --- a/packages/metadata-protocol/src/protocol.lookup-artifact-item-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.lookup-artifact-item-call-sites.test.ts @@ -174,6 +174,10 @@ const SITES: ReadonlyArray { + // [ADR-0159 D7] Three arms since @objectstack/spec 19: the form arm left + // the union with the `form` metadata type. + it('control: `view` still answers a three-arm union', async () => { const served = (await servedSchemas()).get('view'); expect(Array.isArray(served!.anyOf)).toBe(true); - expect((served!.anyOf as unknown[]).length).toBe(4); + expect((served!.anyOf as unknown[]).length).toBe(3); }); }); diff --git a/packages/metadata-protocol/src/protocol.meta-types-unauthorable-columns.test.ts b/packages/metadata-protocol/src/protocol.meta-types-unauthorable-columns.test.ts index 6b5a30bf502..0ddd4d4cc02 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-unauthorable-columns.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-unauthorable-columns.test.ts @@ -526,7 +526,8 @@ describe('[#35879] the served types offer no key the platform stamps', () => { expect(Object.keys(object.properties.fields.additionalProperties.properties)).toContain(key); } const view = served.get('view') as any; - expect((view.anyOf as unknown[]).length).toBe(4); + // [ADR-0159 D7] Three arms since @objectstack/spec 19 (the form arm left the union). + expect((view.anyOf as unknown[]).length).toBe(3); }); it('over-drop guard: every stamped node the strip took is the envelope\'s own node, at a place the whole envelope is spread', () => { diff --git a/packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts b/packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts index 13725f26d72..f0fa489a9a4 100644 --- a/packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts +++ b/packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts @@ -47,11 +47,8 @@ import { afterEach, describe, expect, it } from 'vitest'; // `@objectstack/objectql`: objectql DEPENDS ON this package, so that import // would close a dependency cycle turbo rejects outright. import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, isCodeArtifactBody } from '@objectstack/metadata-core'; -// The anonymous form doors' own verdict (`registerFormEndpoints` in -// `@objectstack/rest`), applied here to the protocol's real list reads. -import { anonymousFormIntakeCandidates, anonymousFormIntakeWithdrawnIn } from '@objectstack/metadata-core'; import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; -import { expandViewContainer } from '@objectstack/spec/ui'; +import { expandViewContainer, formIntakeLayer, openFormAt } from '@objectstack/spec/ui'; import { ObjectStackProtocolImplementation } from './protocol.js'; /** @@ -408,25 +405,64 @@ describe('[ADR-0131 D6] no organization-scoped metadata write is accepted', () = }); }); -describe('two packages shipping a view name', () => { +/** + * The anonymous doors' own judgement at `slug` (`registerFormEndpoints` in + * `@objectstack/rest`), applied to the protocol's real reads, as protocol 19 + * composes it: the candidates are the effective `form` list; the withdrawal + * layer is the effective and per-package lists of both `form` and `view`, the + * `view` list read with its stored old-shape forms (`getViewItemsWithStoredForms`). + * Answers every candidate the doors would serve: one the layer does not close. + */ +async function doorsServeAt(protocol: any, slug: string): Promise>> { + const listOf = (r: any): any[] => (Array.isArray(r?.items) ? r.items : []); + const forms = listOf(await protocol.getMetaItems({ type: 'form' })); + const layer = formIntakeLayer({ + forms: [...forms, ...listOf(await protocol.getMetaItemsPerPackage({ type: 'form' }))], + views: [ + ...listOf(await protocol.getViewItemsWithStoredForms({})), + ...listOf(await protocol.getMetaItemsPerPackage({ type: 'view' })), + ], + unreadable: await protocol.getUnreadableFormBodies(), + }); + return forms.filter((form) => openFormAt([form], layer, slug) !== null); +} + +/** + * [ADR-0159] Two packages ship one form name. From protocol 19 a form is a + * `form` item, so each package ships `task.intake_form` as one. The `form` + * type takes no environment overlay, so a package's env-wide save of the + * name is refused (the managed seal); the withdrawal a release before 19 + * stored as that package's `view` row of the name is still read, and still + * closes the form in every package. + */ +describe('two packages shipping a form name', () => { const NAME = 'task.intake_form'; const LINK = '/forms/shared-intake'; - const formView = (allowAnonymous: boolean, label = 'Intake') => ({ + const sharing = (allowAnonymous: boolean) => ({ enabled: true, allowAnonymous, publicLink: LINK }); + const formItem = (allowAnonymous: boolean, label = 'Intake') => ({ name: NAME, label, object: 'task', - viewKind: 'form', - config: { sharing: { enabled: true, allowAnonymous, publicLink: LINK } }, + type: 'simple', + sections: [{ label: 'Main', fields: ['title'] }], + sharing: sharing(allowAnonymous), }); - const shippedA = { ...formView(true), _packageId: 'pkg_a' }; - const shippedB = { ...formView(true), _packageId: 'pkg_b' }; + /** The `view` row a release before 19 stored for a package's env-wide copy of the form. */ + const storedFormView = (allowAnonymous: boolean, label = 'Intake') => ({ + name: NAME, label, object: 'task', viewKind: 'form', config: { sharing: sharing(allowAnonymous) }, + }); + const shippedA = { ...formItem(true), _packageId: 'pkg_a', _provenance: 'package' }; + const shippedB = { ...formItem(true), _packageId: 'pkg_b', _provenance: 'package' }; /** Package A first in registry order: a lookup naming no package answers A's artifact. */ function makeTwoPackageProtocol() { const { engine, rows } = makeStubEngine(); - engine.registry.listItems = (type: string) => (type === 'view' ? [shippedA, shippedB] : []); + const listItems = engine.registry.listItems; + engine.registry.listItems = (type: string, packageId?: string) => (type === 'form' + ? [shippedA, shippedB].filter((f) => !packageId || f._packageId === packageId) + : listItems(type)); engine.registry.getArtifactItem = (type: string, name: string, pkg?: string) => { - if (type !== 'view' || name !== NAME) return undefined; + if (type !== 'form' || name !== NAME) return undefined; return pkg === 'pkg_b' ? shippedB : shippedA; }; const services = new Map([['tenancy', { defaultOrgId: async () => 'org_a' }]]); @@ -434,68 +470,66 @@ describe('two packages shipping a view name', () => { return { protocol, rows }; } - /** - * [ADR-0131 C7] The env-wide read's copies of the view, where the doors - * find the form: the legacy organization read is deleted. - */ - async function servedCopies(protocol: any): Promise>> { - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - return (envWide.items as any[]).filter((v) => v?.name === NAME); - } - - /** - * The copies the anonymous doors would serve for the slug, by their own - * composition: open, and not withdrawn by any body of the view name in - * that same env-wide list. - */ - async function doorsServe(protocol: any): Promise>> { - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - const layer: unknown[] = envWide.items; - return (await servedCopies(protocol)).filter((view) => anonymousFormIntakeCandidates(view) - .some((c) => c.slug === 'shared-intake' && !anonymousFormIntakeWithdrawnIn(layer, view, c))); + /** Each package's body of the form: the per-package `form` layer the doors judge withdrawals in. */ + async function perPackageCopies(protocol: any): Promise>> { + const layer: any = await protocol.getMetaItemsPerPackage({ type: 'form' }); + return (layer.items as any[]).filter((f) => f?.name === NAME); } - it('the doors serve each package\'s shipped copy', async () => { + it('the doors serve the shipped form, and the per-package layer holds each package\'s copy', async () => { const { protocol } = makeTwoPackageProtocol(); - const copies = await servedCopies(protocol); - expect(copies.map((v) => v.label)).toEqual(['Intake', 'Intake']); - expect(copies.map((v) => v._packageId).sort()).toEqual(['pkg_a', 'pkg_b']); - // Control: before any withdrawal the doors serve both copies. - expect(await doorsServe(protocol)).toHaveLength(2); + const copies = await perPackageCopies(protocol); + expect(copies.map((f) => f.label)).toEqual(['Intake', 'Intake']); + expect(copies.map((f) => f._packageId).sort()).toEqual(['pkg_a', 'pkg_b']); + // Control: before any withdrawal the doors serve the form. + expect((await doorsServeAt(protocol, 'shared-intake')).map((f) => f.name)).toContain(NAME); }); for (const [order, withdrawing] of [['first', 'pkg_a'], ['second', 'pkg_b']] as const) { describe(`the package ${order} in registry order withdraws the name env-wide`, () => { - async function withdrawAfterSave() { + /** + * The 19 door refuses the package's env-wide `form` save of the + * name, and stores nothing; the withdrawal stands as the `view` + * row a release before 19 stored for that package. + */ + async function withdrawnBeforeTheUpgrade() { const { protocol, rows } = makeTwoPackageProtocol(); - expect((await protocol.saveMetaItem({ - type: 'view', name: NAME, item: formView(false), packageId: withdrawing, - })).success).toBe(true); + const refusal = await protocol.saveMetaItem({ + type: 'form', name: NAME, item: formItem(false), packageId: withdrawing, + }).then(() => null, (e: any) => e); + expect({ code: refusal?.code, status: refusal?.status }).toEqual({ code: 'NOT_OVERRIDABLE', status: 403 }); + expect(Array.from(rows.values()), 'the refused save stores nothing').toEqual([]); + rows.set(`view|${NAME}|active|${withdrawing}`, { + id: `r_stored_${withdrawing}`, type: 'view', name: NAME, package_id: withdrawing, + state: 'active', metadata: JSON.stringify(storedFormView(false)), + }); return { protocol, rows }; } - it('the env-wide list the doors read holds the withdrawal beside the other package\'s body', async () => { - const { protocol } = await withdrawAfterSave(); - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - const named = (envWide.items as any[]).filter((v) => v?.name === NAME) - .map((v) => [v._packageId, v.config.sharing.allowAnonymous]) - .sort(); - expect(named).toEqual([['pkg_a', withdrawing !== 'pkg_a'], ['pkg_b', withdrawing !== 'pkg_b']]); + it('the stored withdrawal is in the view layer the doors read, beside each package\'s open form', async () => { + const { protocol } = await withdrawnBeforeTheUpgrade(); + const views: any = await protocol.getViewItemsWithStoredForms({}); + const named = (views.items as any[]).filter((v) => v?.name === NAME) + .map((v) => [v._packageId, v.config?.sharing?.allowAnonymous]); + expect(named).toEqual([[withdrawing, false]]); + expect((await perPackageCopies(protocol)).map((f) => [f._packageId, f.sharing.allowAnonymous]).sort()) + .toEqual([['pkg_a', true], ['pkg_b', true]]); }); it('the doors serve no copy once one package withdraws the name', async () => { - const { protocol } = await withdrawAfterSave(); - expect((await servedCopies(protocol)).map((v) => v._packageId).sort()).toEqual(['pkg_a', 'pkg_b']); - expect(await doorsServe(protocol)).toEqual([]); + const { protocol } = await withdrawnBeforeTheUpgrade(); + expect((await perPackageCopies(protocol)).map((f) => f._packageId).sort()).toEqual(['pkg_a', 'pkg_b']); + expect(await doorsServeAt(protocol, 'shared-intake')).toEqual([]); }); it('an organization-scoped save of the name is refused (no write is organization-scoped), and nothing changes', async () => { - const { protocol, rows } = await withdrawAfterSave(); + const { protocol, rows } = await withdrawnBeforeTheUpgrade(); const before = Array.from(rows.values()); await expect(protocol.saveMetaItem({ - type: 'view', name: NAME, item: formView(true, 'Intake (org, again)'), organizationId: 'org_a', + type: 'form', name: NAME, item: formItem(true, 'Intake (org, again)'), organizationId: 'org_a', })).rejects.toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403, organizationId: 'org_a' }); expect(Array.from(rows.values())).toEqual(before); + expect(await doorsServeAt(protocol, 'shared-intake')).toEqual([]); }); }); } @@ -624,15 +658,21 @@ describe('a publish that states no package, over a store that cannot be read', ( }); }); -// Each package's copy of a view container expands into that package's own -// slot. Two packages ship the container `task`, and the source registrars -// register its form `task.intake_form` once per package. An env-wide copy of -// the container stored for one package writes that package's item of each -// name it expands, and a package-less copy stands in for every package with -// no copy of its own (ADR-0048). So the env-wide view list the anonymous doors -// judge against holds every package's body of the form, and any package's -// withdrawal of it, shipped or saved, closes it. The by-name read naming a -// package serves the item that package's slot in the list serves. +// Each package's copy of a view container, from protocol 19 (ADR-0159 D7). +// Before 19 two packages shipped the container `task`, the source registrars +// registered its form `task.intake_form` once per package, and an env-wide +// copy of the container stored for one package (or package-less) wrote that +// package's slot of each name it expanded. From 19 a package ships the form as +// a `form` item named `OBJECT.KEY` and a `view` holds lists only, so: +// - a copy of the container that holds a form is refused at the view door +// (422, the `forms:` prescription, no row), and a package-bound `form` save +// of a name the package ships is refused by the managed seal (403, no row); +// - such a copy exists on 19 only as the row a release before 19 stored, so +// every pin below stands on that seeded row; +// - the anonymous doors judge the 19 composition (`doorsServeAt`): the +// candidates are the `form` items, and a stored copy's withdrawal, read raw +// with the stored forms (`getViewItemsWithStoredForms`), closes the form of +// its expanded name in every package. A stored copy opens nothing. describe('each package\'s copy of a view container expands into its own package\'s slot', () => { const NAME = 'task.intake_form'; const SLUG = 'shared-intake'; @@ -641,61 +681,78 @@ describe('each package\'s copy of a view container expands into its own package\ const container = (allowAnonymous: boolean, title = 'Intake') => ({ name: 'task', object: 'task', formViews: { intake_form: { title, sharing: sharing(allowAnonymous) } }, }); + /** A flat `viewKind: 'form'` row of the form's own name, as a release before 19 stored it. */ const formView = (allowAnonymous: boolean, title: string) => ({ name: NAME, label: title, object: 'task', viewKind: 'form', config: { title, sharing: sharing(allowAnonymous) }, }); + const titleOf = (v: any): unknown => v?.config?.title ?? v?.config?.label ?? v?.title; + + /** + * What a package ships for a container body on protocol 19: the container + * with its lists (`views:`), and each form member as the `form` item of + * the name the loaders served it under (`forms:`). + */ + const shippedItems = (body: Record) => { + const { form: _form, formViews: _formViews, ...lists } = body; + const forms = expandViewContainer('task', body) + .filter((vi) => vi.viewKind === 'form') + .map((vi: any) => ({ name: String(vi.name), object: 'task', ...(vi.config ?? {}) })); + const views = expandViewContainer('task', lists).map((vi) => ({ ...(vi as any) })); + return { container: { ...lists, name: 'task' }, views, forms }; + }; /** * The registry where these pins turn on it, held as the real - * `SchemaRegistry` holds it: each package's entries under - * `:` (the container and the views the source registrars - * expand from it), a row an unscoped kernel hydrates under the bare name, - * `getItem` bare slot first, and `getArtifactItem`'s package-scoped + * `SchemaRegistry` holds it, per type: each package's entries under + * `:`, a row an unscoped kernel hydrates under the bare + * name, `getItem` bare slot first, and `getArtifactItem`'s package-scoped * code-artifact lookup. `owner` is the code package that owns the object. */ function packagesRegistry(shipped: Array<[string, Record]>, owner?: string) { - const entries = new Map>(); - const register = (item: Record, packageId?: string) => { + const byType = new Map>>(); + const of = (type: string) => byType.get(type) ?? byType.set(type, new Map()).get(type)!; + const register = (type: string, item: Record, packageId?: string) => { if (packageId) { if (item._packageId === undefined) item._packageId = packageId; if (item._provenance === undefined) item._provenance = 'package'; } - entries.set(packageId ? `${packageId}:${String(item.name)}` : String(item.name), item); + of(type).set(packageId ? `${packageId}:${String(item.name)}` : String(item.name), item); }; for (const [packageId, body] of shipped) { - register({ ...body, name: 'task' }, packageId); - for (const vi of expandViewContainer('task', body)) register({ ...(vi as any) }, packageId); + const items = shippedItems(body); + register('view', { ...items.container }, packageId); + for (const vi of items.views) register('view', vi, packageId); + for (const form of items.forms) register('form', form, packageId); } - const composite = (name: string) => [...entries].filter(([key]) => key.endsWith(`:${name}`)).map(([, it]) => it); + const composite = (type: string, name: string) => [...of(type)].filter(([key]) => key.endsWith(`:${name}`)).map(([, it]) => it); + const typed = (type: string) => type === 'view' || type === 'form'; return { registerItem: (type: string, item: Record, _keyField?: string, packageId?: string) => { - if (type === 'view') register(item, packageId); + if (typed(type)) register(type, item, packageId); }, - listItems: (type: string, packageId?: string) => (type === 'view' - ? [...entries.values()].filter((it) => !packageId || it._packageId === packageId) + listItems: (type: string, packageId?: string) => (typed(type) + ? [...of(type).values()].filter((it) => !packageId || it._packageId === packageId) // [#26708] The `task` object, owned by `owner` when a code package owns it. : type === 'object' ? [taskObject(owner)] : []), - getItem: (type: string, name: string, packageId?: string) => (type !== 'view' + getItem: (type: string, name: string, packageId?: string) => (!typed(type) ? undefined - : entries.get(name) ?? (packageId ? entries.get(`${packageId}:${name}`) : undefined) ?? composite(name)[0]), + : of(type).get(name) ?? (packageId ? of(type).get(`${packageId}:${name}`) : undefined) ?? composite(type, name)[0]), getArtifactItem: (type: string, name: string, packageId?: string) => { - if (type !== 'view') return undefined; - const shippedAs = composite(name).filter((it) => isCodeArtifactBody(it)); + if (!typed(type)) return undefined; + const shippedAs = composite(type, name).filter((it) => isCodeArtifactBody(it)); return (packageId ? shippedAs.find((it) => it._packageId === packageId) : undefined) ?? shippedAs[0]; }, getPackagedObjectOwner: (name: string) => (owner && name === 'task' ? { packageId: owner, ownership: 'own' } : undefined), - // [#22057] The delete's heal, as `SchemaRegistry` holds it: the - // bare entry goes when a package's own entry is under it, and an - // entry that is no packaged artifact goes when nothing is. + // [#22057] The delete's heal, as `SchemaRegistry` holds it. removeRuntimeShadow: (type: string, name: string) => { - if (type !== 'view' || !entries.has(name)) return false; - if (!composite(name).some((it) => it._packageId && it._packageId !== 'sys_metadata')) return false; - entries.delete(name); + if (!typed(type) || !of(type).has(name)) return false; + if (!composite(type, name).some((it) => it._packageId && it._packageId !== 'sys_metadata')) return false; + of(type).delete(name); return true; }, removeOverlayEntry: (type: string, name: string) => { - if (type !== 'view' || !entries.has(name) || isCodeArtifactBody(entries.get(name))) return false; - entries.delete(name); + if (!typed(type) || !of(type).has(name) || isCodeArtifactBody(of(type).get(name))) return false; + of(type).delete(name); return true; }, getObject: () => undefined, @@ -725,86 +782,110 @@ describe('each package\'s copy of a view container expands into its own package\ const protocol = new ObjectStackProtocolImplementation(engine, () => services, environmentId) as any; return { protocol, rows, registry: engine.registry }; } + type Harness = ReturnType; - /** An env-wide copy of the container, stored for `packageId` (package-less when undefined). */ - async function saveCopy(protocol: any, packageId: string | undefined, allowAnonymous: boolean, title: string) { - expect((await protocol.saveMetaItem({ - type: 'view', name: 'task', item: container(allowAnonymous, title), ...(packageId ? { packageId } : {}), - })).success).toBe(true); + /** A row as a release before 19 stored it, written straight to the store. */ + function seedStored(h: Harness, type: string, name: string, packageId: string | undefined, body: Record) { + h.rows.set(`${type}|${name}|active|${packageId ?? '__nopkg__'}`, { + id: `r_stored_${h.rows.size + 1}`, type, name, package_id: packageId ?? null, + state: 'active', metadata: JSON.stringify(body), + }); + } + + /** [ADR-0159 D7] The view door refuses a body that holds a form: 422, the `forms:` prescription, no row. */ + async function expectViewSaveRefused(h: Harness, name: string, body: Record, packageId: string | undefined) { + const before = JSON.stringify([...h.rows.keys()]); + const error = await h.protocol.saveMetaItem({ + type: 'view', name, item: body, ...(packageId ? { packageId } : {}), + }).then(() => null, (e: any) => e); + expect({ code: error?.code, status: error?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect(String(error?.message)).toContain('was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)'); + expect(JSON.stringify([...h.rows.keys()]), 'a refused save stores nothing').toBe(before); + } + + /** The managed seal: a package-bound `form` save of a name the package ships is refused 403, no row. */ + async function expectFormCopySealed(h: Harness, name: string, packageId: string, body: Record) { + const before = JSON.stringify([...h.rows.keys()]); + const error = await h.protocol.saveMetaItem({ + type: 'form', name, packageId, item: { name, object: 'task', ...body }, + }).then(() => null, (e: any) => e); + expect({ code: error?.code, status: error?.status }).toEqual({ code: 'NOT_OVERRIDABLE', status: 403 }); + expect(JSON.stringify([...h.rows.keys()]), 'a sealed save stores nothing').toBe(before); } /** - * [#23165] A package-less copy stored BESIDE a package's copy. An author - * save naming no package now writes the row of the one package the item is - * bound to, so after pkg_b's copy it would update that copy instead. The - * row this pin reads is the package-less row such a save left before, and - * the door still writes it for a server-stated rewrite of that row - * (`packageId: null` with `source`, the stored-metadata migration's - * spelling), write-through included. + * An env-wide copy of the container for `packageId` (package-less when + * undefined): the view door refuses it, the package's `form` copy of the + * name is sealed where the package ships it, and the copy stands as the + * row a release before 19 stored. */ - async function saveUnboundCopyBeside(protocol: any, allowAnonymous: boolean, title: string) { - expect((await protocol.saveMetaItem({ - type: 'view', name: 'task', item: container(allowAnonymous, title), packageId: null, - source: 'migrate-stored', force: true, - })).success).toBe(true); + async function storedCopy(h: Harness, packageId: string | undefined, allowAnonymous: boolean, title: string, ships = true) { + const body = container(allowAnonymous, title); + await expectViewSaveRefused(h, 'task', body, packageId); + if (packageId && ships) await expectFormCopySealed(h, NAME, packageId, { title, sharing: sharing(allowAnonymous) }); + seedStored(h, 'view', 'task', packageId, body); } - /** Each body of the form in the env-wide view list: [package, allowAnonymous, title]. */ - async function envWideBodies(protocol: any): Promise> { - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - return (envWide.items as any[]).filter((v) => v?.name === NAME) + /** Each body of the form in the layer the doors read for withdrawals, raw: [package, allowAnonymous, title]. */ + async function storedBodies(protocol: any): Promise> { + const raw: any = await protocol.getViewItemsWithStoredForms({}); + return (raw.items as any[]).filter((v) => v?.name === NAME) .map((v): [unknown, unknown, unknown] => [v._packageId ?? null, v.config?.sharing?.allowAnonymous, v.config?.title]) .sort((x, y) => String(x[0]).localeCompare(String(y[0]))); } - - /** - * What the anonymous doors serve for the slug, by their own composition - * (`registerFormEndpoints`): the env-wide read, each open candidate - * judged over that same list (the legacy organization read is deleted, - * ADR-0131 C7). - */ - async function doorsServe(protocol: any): Promise { - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - return (envWide.items as any[]).filter((view) => anonymousFormIntakeCandidates(view) - .some((c) => c.slug === SLUG && !anonymousFormIntakeWithdrawnIn(envWide.items, view, c))); + /** Each package's `form` item of the name, per-package: [package, allowAnonymous, title]. */ + async function formBodies(protocol: any, name = NAME): Promise> { + const layer: any = await protocol.getMetaItemsPerPackage({ type: 'form' }); + return (layer.items as any[]).filter((f) => f?.name === name) + .map((f): [unknown, unknown, unknown] => [f._packageId ?? null, f.sharing?.allowAnonymous, titleOf(f)]) + .sort((x, y) => String(x[0]).localeCompare(String(y[0]))); } + /** The view doors serve no form: the served list and the by-name read answer nothing of `name`. */ + async function expectNoViewOf(protocol: any, name: string, packageId?: string) { + const served: any = await protocol.getMetaItems({ type: 'view' }); + expect((served.items as any[]).filter((v) => v?.name === name), `${name}: no view in the served list`).toEqual([]); + const read = await protocol.getMetaItem({ type: 'view', name, ...(packageId ? { packageId } : {}) }); + expect(read?.item, `${name}: no view by name`).toBeUndefined(); + } + const doorsServe = (protocol: any) => doorsServeAt(protocol, SLUG); describe('(a) one package\'s env-wide copy is saved with the form open, and another package ships it withdrawn', () => { for (const [kernel, environmentId] of KERNELS) { for (const owner of [undefined, 'pkg_a'] as const) { const where = `${kernel}, ${owner ? 'the copy\'s package owns the object' : 'no code package owns the object'}`; - it(`${where}: the env-wide list holds the shipped withdrawal beside the copy, and the doors serve no copy`, async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(false)]], environmentId, owner); - await saveCopy(protocol, 'pkg_a', true, 'Intake (pkg_a copy)'); + it(`${where}: the layer holds the shipped withdrawal beside the stored copy, and the doors serve no copy`, async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(false)]], environmentId, owner); + await storedCopy(h, 'pkg_a', true, 'Intake (pkg_a copy)'); - expect(await envWideBodies(protocol)).toEqual([ - ['pkg_a', true, 'Intake (pkg_a copy)'], - ['pkg_b', false, 'Intake'], - ]); - expect(await doorsServe(protocol)).toEqual([]); + expect(await formBodies(h.protocol)).toEqual([['pkg_a', true, 'Intake'], ['pkg_b', false, 'Intake']]); + expect(await storedBodies(h.protocol)).toContainEqual(['pkg_a', true, 'Intake (pkg_a copy)']); + expect(await doorsServe(h.protocol)).toEqual([]); }); } } - it('control: with no package withdrawing the form, the doors serve the copy', async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], 'env_prod'); - await saveCopy(protocol, 'pkg_a', true, 'Intake (pkg_a copy)'); - expect((await doorsServe(protocol)).length).toBeGreaterThan(0); + it('control: with no package withdrawing the form, the doors serve the shipped form, and the stored copy closes nothing', async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], 'env_prod'); + await storedCopy(h, 'pkg_a', true, 'Intake (pkg_a copy)'); + const served = await doorsServe(h.protocol); + expect(served.length).toBeGreaterThan(0); + expect(served.map(titleOf), 'the doors serve a shipped form, never the stored copy').not.toContain('Intake (pkg_a copy)'); }); }); describe('(b) the same, with the withdrawal saved in the other package\'s own env-wide copy', () => { for (const [kernel, environmentId] of KERNELS) { for (const order of [['pkg_a', 'pkg_b'], ['pkg_b', 'pkg_a']] as const) { - it(`${kernel}, ${order[0]}'s copy saved first: each copy serves its own package's slot, and the doors serve no copy`, async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); - for (const pkg of order) await saveCopy(protocol, pkg, pkg === 'pkg_a', `Intake (${pkg} copy)`); + it(`${kernel}, ${order[0]}'s copy stored first: each stored copy is read in its own package's slot, and the doors serve no copy`, async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); + for (const pkg of order) await storedCopy(h, pkg, pkg === 'pkg_a', `Intake (${pkg} copy)`); - expect(await envWideBodies(protocol)).toEqual([ + expect(await storedBodies(h.protocol)).toEqual([ ['pkg_a', true, 'Intake (pkg_a copy)'], ['pkg_b', false, 'Intake (pkg_b copy)'], ]); - expect(await doorsServe(protocol)).toEqual([]); + expect(await formBodies(h.protocol), 'the shipped forms are untouched').toEqual([['pkg_a', true, 'Intake'], ['pkg_b', true, 'Intake']]); + expect(await doorsServe(h.protocol)).toEqual([]); }); } } @@ -812,135 +893,132 @@ describe('each package\'s copy of a view container expands into its own package\ describe('(c) a package-less env-wide copy stands in for every package with no copy of its own', () => { for (const [kernel, environmentId] of KERNELS) { - it(`${kernel}: the package-less copy serves each package's slot, so the administrator's switch opens the form for every package`, async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(false)]], environmentId); - await saveCopy(protocol, undefined, true, 'Intake (env-wide copy)'); - - expect(await envWideBodies(protocol)).toEqual([ - ['pkg_a', true, 'Intake (env-wide copy)'], - ['pkg_b', true, 'Intake (env-wide copy)'], - ]); - expect((await doorsServe(protocol)).length).toBeGreaterThan(0); + // [ADR-0159 D7] Before 19 the administrator's open package-less copy + // replaced pkg_b's shipped withdrawal and opened the form. The + // withdrawal is now pkg_b's shipped `form` item, which no stored + // copy replaces: a stored copy opens nothing. + it(`${kernel}: the package-less copy is read in each package's slot, and a stored copy opens nothing: pkg_b's shipped withdrawal keeps the doors closed`, async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(false)]], environmentId); + await storedCopy(h, undefined, true, 'Intake (env-wide copy)'); + + expect((await storedBodies(h.protocol)).map(([, open, title]) => [open, title])) + .toContainEqual([true, 'Intake (env-wide copy)']); + expect(await formBodies(h.protocol)).toEqual([['pkg_a', true, 'Intake'], ['pkg_b', false, 'Intake']]); + expect(await doorsServe(h.protocol)).toEqual([]); }); for (const order of [[undefined, 'pkg_b'], ['pkg_b', undefined]] as const) { - it(`${kernel}, ${order[0] ?? 'the package-less'} copy saved first: a package's own copy serves that package's slot ahead of the package-less copy`, async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); + it(`${kernel}, ${order[0] ?? 'the package-less'} copy stored first: a package's own stored copy is read in that package's slot, and its withdrawal closes the doors`, async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); for (const pkg of order) { - if (pkg === undefined && order[0] === 'pkg_b') { - await saveUnboundCopyBeside(protocol, true, 'Intake (env-wide copy)'); - continue; - } - await saveCopy(protocol, pkg, pkg === undefined, pkg ? `Intake (${pkg} copy)` : 'Intake (env-wide copy)'); + await storedCopy(h, pkg, pkg === undefined, pkg ? `Intake (${pkg} copy)` : 'Intake (env-wide copy)'); } - expect(await envWideBodies(protocol)).toEqual([ - ['pkg_a', true, 'Intake (env-wide copy)'], - ['pkg_b', false, 'Intake (pkg_b copy)'], - ]); - expect(await doorsServe(protocol)).toEqual([]); + expect(await storedBodies(h.protocol)).toContainEqual(['pkg_b', false, 'Intake (pkg_b copy)']); + expect(await doorsServe(h.protocol)).toEqual([]); }); } } }); describe('(d) the list\'s slot for a package and the by-name read naming that package serve the same item', () => { - const projection = (v: any) => (v ? { name: v.name, viewKind: v.viewKind, config: v.config, _packageId: v._packageId } : v); - - /** For each package: one item in the env-wide list, and the by-name read and the list scoped to the package serve it. */ - async function expectAgreement(protocol: any, titles: Record) { - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - for (const [pkg, title] of Object.entries(titles)) { - const slot = (envWide.items as any[]).filter((v) => v?.name === NAME && v._packageId === pkg); - expect(slot.map((v) => v.config?.title), `${pkg}: its one item in the env-wide list`).toEqual([title]); - const byName = (await protocol.getMetaItem({ type: 'view', name: NAME, packageId: pkg })).item; - expect(projection(byName), `${pkg}: the by-name read naming the package`).toEqual(projection(slot[0])); - const scoped: any = await protocol.getMetaItems({ type: 'view', packageId: pkg }); - expect((scoped.items as any[]).filter((v) => v?.name === NAME).map(projection), `${pkg}: the list scoped to the package`) - .toEqual([projection(slot[0])]); + const projection = (f: any) => (f ? { name: f.name, title: titleOf(f), sharing: f.sharing, _packageId: f._packageId } : f); + + /** + * [ADR-0159 D6 rule 11, D7] For each package whose address of the name + * a stored copy holds: the stored row replaces the package's shipped + * form and the projection serves no content, so the by-name read + * naming the package and the list scoped to it agree on serving + * nothing. The per-package layer the doors judge withdrawals over + * still holds the shipped body. The `view` doors serve no form. + */ + async function expectAgreement(protocol: any) { + const layer: any = await protocol.getMetaItemsPerPackage({ type: 'form' }); + for (const pkg of ['pkg_a', 'pkg_b']) { + const slot = (layer.items as any[]).filter((f) => f?.name === NAME && f._packageId === pkg); + expect(slot.map(titleOf), `${pkg}: its one item in the per-package layer`).toEqual(['Intake']); + const byName = (await protocol.getMetaItem({ type: 'form', name: NAME, packageId: pkg })).item; + expect(projection(byName), `${pkg}: the by-name read naming the package serves nothing`).toBeUndefined(); + const scoped: any = await protocol.getMetaItems({ type: 'form', packageId: pkg }); + expect((scoped.items as any[]).filter((f) => f?.name === NAME).map(projection), `${pkg}: the list scoped to the package agrees`) + .toEqual([]); + await expectNoViewOf(protocol, NAME, pkg); } } for (const [kernel, environmentId] of KERNELS) { - it(`${kernel}: a name two packages' own copies expand`, async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); - await saveCopy(protocol, 'pkg_a', true, 'Intake (pkg_a copy)'); - await saveCopy(protocol, 'pkg_b', false, 'Intake (pkg_b copy)'); - await expectAgreement(protocol, { pkg_a: 'Intake (pkg_a copy)', pkg_b: 'Intake (pkg_b copy)' }); + it(`${kernel}: a name two packages' own stored copies expand`, async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); + await storedCopy(h, 'pkg_a', true, 'Intake (pkg_a copy)'); + await storedCopy(h, 'pkg_b', false, 'Intake (pkg_b copy)'); + await expectAgreement(h.protocol); }); - it(`${kernel}: a name a package-less copy expands, standing in for each package`, async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); - await saveCopy(protocol, undefined, true, 'Intake (env-wide copy)'); - await expectAgreement(protocol, { pkg_a: 'Intake (env-wide copy)', pkg_b: 'Intake (env-wide copy)' }); + it(`${kernel}: a name a stored package-less copy expands, standing in for each package`, async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); + await storedCopy(h, undefined, true, 'Intake (env-wide copy)'); + await expectAgreement(h.protocol); }); } }); // A stored row under exactly the form's name is that name's own row - // (ADR-0005), and it is the row of its own package's slot (ADR-0048): it - // keeps another package's copy out of that package's slot only when it is - // package-less, as the by-name read naming that package decides. + // (ADR-0005), and the row of its own package's slot (ADR-0048). From 19 + // the view door refuses the flat form row; it stands as the row a release + // before 19 stored, and its withdrawal and the copy's are both read. describe('(e) a stored row of the form\'s own name serves its own package\'s slot, and hides no other package\'s copy', () => { for (const [kernel, environmentId] of KERNELS) { - it(`${kernel}: one package's row of the name and another package's withdrawing copy are both in the env-wide list, and the doors serve no copy`, async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); - expect((await protocol.saveMetaItem({ - type: 'view', name: NAME, item: formView(true, 'Intake (pkg_a row)'), packageId: 'pkg_a', - })).success).toBe(true); - await saveCopy(protocol, 'pkg_b', false, 'Intake (pkg_b copy)'); - - expect(await envWideBodies(protocol)).toEqual([ - ['pkg_a', true, 'Intake (pkg_a row)'], - ['pkg_b', false, 'Intake (pkg_b copy)'], - ]); - expect(await doorsServe(protocol)).toEqual([]); - const byName = (await protocol.getMetaItem({ type: 'view', name: NAME, packageId: 'pkg_b' })).item; - expect([byName?.config?.title, byName?.config?.sharing?.allowAnonymous]).toEqual(['Intake (pkg_b copy)', false]); + it(`${kernel}: one package's stored row of the name and another package's stored withdrawing copy are both in the layer, and the doors serve no copy`, async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); + await expectViewSaveRefused(h, NAME, formView(true, 'Intake (pkg_a row)'), 'pkg_a'); + seedStored(h, 'view', NAME, 'pkg_a', formView(true, 'Intake (pkg_a row)')); + await storedCopy(h, 'pkg_b', false, 'Intake (pkg_b copy)'); + + const stored = await storedBodies(h.protocol); + expect(stored).toContainEqual(['pkg_a', true, 'Intake (pkg_a row)']); + expect(stored).toContainEqual(['pkg_b', false, 'Intake (pkg_b copy)']); + expect(await doorsServe(h.protocol)).toEqual([]); + await expectNoViewOf(h.protocol, NAME, 'pkg_b'); }); - it(`${kernel}, control: a package-less row of the name serves every package's slot, ahead of any copy`, async () => { - const { protocol } = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); - expect((await protocol.saveMetaItem({ - type: 'view', name: NAME, item: formView(true, 'Intake (env-wide row)'), - })).success).toBe(true); - await saveCopy(protocol, 'pkg_b', false, 'Intake (pkg_b copy)'); - - expect(await envWideBodies(protocol)).toEqual([ - ['pkg_a', true, 'Intake (env-wide row)'], - ['pkg_b', true, 'Intake (env-wide row)'], - ]); - const byName = (await protocol.getMetaItem({ type: 'view', name: NAME, packageId: 'pkg_b' })).item; - expect(byName?.config?.title).toBe('Intake (env-wide row)'); + it(`${kernel}, control: a stored package-less row of the name is read in the layer, and opens nothing over the stored withdrawing copy`, async () => { + const h = harness([['pkg_a', container(true)], ['pkg_b', container(true)]], environmentId); + await expectViewSaveRefused(h, NAME, formView(true, 'Intake (env-wide row)'), undefined); + seedStored(h, 'view', NAME, undefined, formView(true, 'Intake (env-wide row)')); + await storedCopy(h, 'pkg_b', false, 'Intake (pkg_b copy)'); + + expect((await storedBodies(h.protocol)).map(([, open, title]) => [open, title])).toContainEqual([true, 'Intake (env-wide row)']); + expect(await doorsServe(h.protocol)).toEqual([]); + // [ADR-0159 D6 rule 11] pkg_b's stored copy holds pkg_b's address: its form read serves nothing. + const byName = (await h.protocol.getMetaItem({ type: 'form', name: NAME, packageId: 'pkg_b' })).item; + expect(byName, 'pkg_b\'s address, held by its stored copy').toBeUndefined(); }); } }); - // The family's closing enumeration. The loaders register a container a - // package ships as `.` for that package, whichever package - // owns the object, so a stored copy of that container overlays those - // names, in that package's own slot. Any other container on another - // package's object keeps the own-name arm. Every placement a package's - // stored copy can take is derived below as a cross product: who owns the - // object (the copying package, another package, none), whether the + // The family's closing enumeration, on protocol 19. Every placement a + // package's stored copy can take is derived as a cross product: who owns + // the object (the copying package, another package, none), whether the // copying package ships the container, and which member the copy changes // (the bare list, a keyed member, the default form). For each one, on // both kernels: - // - the copy's member is served under the name its placement gives it, - // in the copying package's slot of the env-wide list and on the - // by-name read naming that package; - // - no name it writes is another package's, and every name the other - // package ships keeps that package's body on both read doors; - // - for a form, the withdrawal saved in the copy closes the anonymous - // doors (their own composition, as above), and the same copy saved - // open leaves them serving. A list carries no anonymous intake - // (`anonymousFormIntakeCandidates` reads forms only), so the bare - // list's reach is pinned on the two read doors alone. + // - the bare list saves through the view door and is served under the + // name its placement gives it, in the copying package's slot of the + // env-wide list and on the by-name read naming that package; + // - a form member is refused by the view door and stands as the stored + // row: the view doors serve none of it, the raw read the doors judge + // withdrawals over reads it under the name its placement gives it, and + // every form the other package ships keeps that package's body on the + // `form` doors; + // - for a form, where the copying package ships the form of that name + // open, the withdrawal stored in the copy closes the anonymous doors, + // and the same copy stored open leaves them serving the shipped form. + // Where it ships none, a stored copy opens nothing, open or withdrawn. describe('(f) every placement a package\'s stored copy of a view container can take', () => { const COPYING = 'pkg_b'; const OTHER = 'pkg_a'; // The other package's own form is its own to serve: it gets a slug of - // its own, so the doors' answer at SLUG is the copy's alone. + // its own, so the doors' answer at SLUG is the copying package's alone. const OTHER_SLUG = 'owner-intake'; const COPY_TITLE = `Intake (${COPYING} copy)`; const SHIPPED_TITLE = (pkg: string) => `Intake (shipped by ${pkg})`; @@ -992,41 +1070,55 @@ describe('each package\'s copy of a view container expands into its own package\ ...(p.ships ? [[COPYING, shippedBy(p, COPYING)] as [string, Record]] : []), ]; /** - * The name the copy's member is served under: the name the loaders - * gave the copying package where it ships the container, the own-name - * arm on another package's object otherwise, and `.` - * on an object of its own or of none. + * The name the copy's member is served (a list) or read raw (a form) + * under: the name the loaders gave the copying package where it ships + * the container, the own-name arm on another package's object + * otherwise, and `.` on an object of its own or of none. */ const servedName = (p: Placement) => (p.owner === OTHER && !p.ships ? p.m.ownNameAs : loaderNames(p.m.body(COPY_TITLE, true, SLUG))[0]); const label = (p: Placement) => `${p.ownership}, ${p.shipping}, ${p.m.member}`; - async function saveCopyOf(protocol: any, p: Placement, allowAnonymous: boolean) { - expect((await protocol.saveMetaItem({ - type: 'view', name: 'task', packageId: COPYING, - item: { name: 'task', object: 'task', ...p.m.body(COPY_TITLE, allowAnonymous, SLUG) }, - })).success).toBe(true); + /** + * The copying package's env-wide copy of the container. A list saves + * through the view door. A form member is refused there, the + * package's `form` copy of the name it ships is sealed, and the copy + * stands as the row a release before 19 stored. + */ + async function saveCopyOf(h: Harness, p: Placement, allowAnonymous: boolean) { + const body = { name: 'task', object: 'task', ...p.m.body(COPY_TITLE, allowAnonymous, SLUG) }; + if (!p.m.isForm) { + expect((await h.protocol.saveMetaItem({ type: 'view', name: 'task', packageId: COPYING, item: body })).success).toBe(true); + return; + } + await expectViewSaveRefused(h, 'task', body, COPYING); + if (p.ships) { + const [name] = loaderNames(body); + await expectFormCopySealed(h, name, COPYING, form(allowAnonymous, COPY_TITLE, SLUG)); + } + seedStored(h, 'view', 'task', COPYING, body); } - const titleOf = (v: any): unknown => v?.config?.title ?? v?.config?.label; - /** The titles a package's slot of `name` serves in the env-wide list. */ - async function slotTitles(protocol: any, name: string, pkg: string): Promise { - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - return (envWide.items as any[]).filter((v) => v?.name === name && v._packageId === pkg).map(titleOf); + /** The titles a package's slot of `name` serves: the env-wide `view` list, or (a form) the per-package `form` layer. */ + async function slotTitles(protocol: any, name: string, pkg: string, type: 'view' | 'form' = 'view'): Promise { + const list: any = type === 'view' + ? await protocol.getMetaItems({ type: 'view' }) + : await protocol.getMetaItemsPerPackage({ type: 'form' }); + return (list.items as any[]).filter((v) => v?.name === name && v._packageId === pkg).map(titleOf); } - /** Every item through which the env-wide list serves the copy's body for the copying package. */ - async function itemsOfTheCopy(protocol: any): Promise { - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - return (envWide.items as any[]).filter((v) => v?._packageId === COPYING && titleOf(v) === COPY_TITLE); + /** Every item through which a read serves the copy's body for the copying package. */ + async function itemsOfTheCopy(protocol: any, raw = false): Promise { + const list: any = raw ? await protocol.getViewItemsWithStoredForms({}) : await protocol.getMetaItems({ type: 'view' }); + return (list.items as any[]).filter((v) => v?._packageId === COPYING && titleOf(v) === COPY_TITLE); } - async function byNameTitle(protocol: any, name: string, pkg: string): Promise { - return titleOf((await protocol.getMetaItem({ type: 'view', name, packageId: pkg })).item); + async function byNameTitle(protocol: any, name: string, pkg: string | undefined, type: 'view' | 'form' = 'view'): Promise { + return titleOf((await protocol.getMetaItem({ type, name, ...(pkg ? { packageId: pkg } : {}) })).item); } it('the population is the cross product of the three dimensions, each placement once', () => { expect(PLACEMENTS).toHaveLength(OWNERS.length * SHIPPING.length * MEMBERS.length); expect(new Set(PLACEMENTS.map(label)).size).toBe(PLACEMENTS.length); - // The three members, as the loaders place them: the bare list, a keyed member, the default form. + // The three members, as the loaders placed them before 19: the bare list, a keyed member, the default form. expect(MEMBERS.map((m) => expandViewContainer('task', m.body('x', true, SLUG)) .map((vi) => [vi.name, vi.viewKind, vi.isDefault === true]))) .toEqual([[['task.default', 'list', true]], [['task.intake_form', 'form', false]], [['task.form', 'form', true]]]); @@ -1034,52 +1126,85 @@ describe('each package\'s copy of a view container expands into its own package\ for (const [kernel, environmentId] of KERNELS) { for (const p of PLACEMENTS) { - it(`${kernel}; ${label(p)}: served as ${servedName(p)} in the copying package's slot on both read doors, writing no other package's name`, async () => { - const { protocol } = harness(shippedIn(p), environmentId, p.owner); - await saveCopyOf(protocol, p, false); + const read = p.m.isForm + ? `refused at the view door; stored, it is read raw as ${servedName(p)} in the copying package's slot, the view doors serve none of it` + : `served as ${servedName(p)} in the copying package's slot on both read doors`; + it(`${kernel}; ${label(p)}: ${read}, writing no other package's name`, async () => { + const h = harness(shippedIn(p), environmentId, p.owner); + const { protocol } = h; + await saveCopyOf(h, p, false); const name = servedName(p); - const copyItems = await itemsOfTheCopy(protocol); - expect(copyItems.map((v) => v.name), 'the names the copy is served under').toEqual([name]); + const copyItems = await itemsOfTheCopy(protocol, p.m.isForm); + expect(copyItems.map((v) => v.name), 'the names the copy is read under').toEqual([name]); // The seat's answer on the own-name arm stands for every container on // another package's object, a copy included: it declares no default. const declaresDefault = expandViewContainer('task', p.m.body(COPY_TITLE, false, SLUG))[0]?.isDefault === true; expect(copyItems.map((v) => v.isDefault === true), 'the default it declares') .toEqual([p.owner !== OTHER && declaresDefault]); - expect(await slotTitles(protocol, name, COPYING), 'the copying package\'s slot').toEqual([COPY_TITLE]); - expect(await byNameTitle(protocol, name, COPYING), 'the by-name read naming the copying package').toBe(COPY_TITLE); + if (p.m.isForm) { + // [ADR-0159 D7] A view holds lists only: no view door serves the stored form member. + expect(await itemsOfTheCopy(protocol), 'the served view list holds none of the copy').toEqual([]); + await expectNoViewOf(protocol, name, COPYING); + } else { + expect(await slotTitles(protocol, name, COPYING), 'the copying package\'s slot').toEqual([COPY_TITLE]); + expect(await byNameTitle(protocol, name, COPYING), 'the by-name read naming the copying package').toBe(COPY_TITLE); + } const otherNames = p.owner === OTHER ? loaderNames(shippedBy(p, OTHER)) : []; const ownNames = p.ships ? loaderNames(shippedBy(p, COPYING)) : []; expect(otherNames.includes(name) && !ownNames.includes(name), 'a name only another package ships').toBe(false); + const type = p.m.isForm ? 'form' : 'view'; for (const shipped of otherNames) { - expect(await slotTitles(protocol, shipped, OTHER), `${OTHER}'s slot of ${shipped}`).toEqual([SHIPPED_TITLE(OTHER)]); - expect(await byNameTitle(protocol, shipped, OTHER), `the by-name read of ${shipped} naming ${OTHER}`) + expect(await slotTitles(protocol, shipped, OTHER, type), `${OTHER}'s slot of ${shipped}`).toEqual([SHIPPED_TITLE(OTHER)]); + expect(await byNameTitle(protocol, shipped, OTHER, type), `the by-name read of ${shipped} naming ${OTHER}`) .toBe(SHIPPED_TITLE(OTHER)); } }); if (p.m.isForm) { - it(`${kernel}; ${label(p)}: the withdrawal saved in the copy closes the anonymous doors, and saved open the doors serve`, async () => { + // [ADR-0159 D6 rule 11] Where the copying package ships the form, the + // copy expands to that form's name (on another package's object too) + // and the stored row holds that address: withdrawn it closes the doors, + // and open it opens nothing. + const holdsShipped = p.ships; + const verdict = holdsShipped + ? (p.owner === OTHER + ? 'the withdrawal stored in the copy closes the anonymous doors, and stored open the copy opens nothing (it holds the shipped form\'s address)' + : 'the withdrawal stored in the copy keeps the doors closed, and stored open the copy opens nothing (it holds the shipped form\'s address)') + : 'the copying package ships no form there, and a stored copy opens nothing, open or withdrawn'; + it(`${kernel}; ${label(p)}: ${verdict}`, async () => { for (const allowAnonymous of [false, true]) { - const { protocol } = harness(shippedIn(p), environmentId, p.owner); - await saveCopyOf(protocol, p, allowAnonymous); - const served = await doorsServe(protocol); - if (allowAnonymous) expect(served.length, 'saved open: the doors serve the copy').toBeGreaterThan(0); - else expect(served, 'withdrawn in the copy: the doors serve no copy').toEqual([]); + const h = harness(shippedIn(p), environmentId, p.owner); + await saveCopyOf(h, p, allowAnonymous); + const served = await doorsServe(h.protocol); + if (!allowAnonymous) expect(served, 'withdrawn in the stored copy: the doors serve no copy').toEqual([]); + else expect(served, 'a stored copy opens nothing').toEqual([]); + // The stored copy is read where the doors judge withdrawals. + const raw = (await itemsOfTheCopy(h.protocol, true)).filter((v) => v.name === servedName(p)); + expect(raw.map((v) => v.config?.sharing?.allowAnonymous), 'the stored copy, read raw').toEqual([allowAnonymous]); } }); } } } + /** A copy for `copying` of a container both packages ship (shipped open at SLUG): saved (a list), or refused, sealed and stored (a form). */ + async function copyOfShared(h: Harness, m: Member, copying: string, title: string, allowAnonymous: boolean) { + const body = { name: 'task', object: 'task', ...m.body(title, allowAnonymous, SLUG) }; + if (!m.isForm) { + expect((await h.protocol.saveMetaItem({ type: 'view', name: 'task', packageId: copying, item: body })).success).toBe(true); + return; + } + await expectViewSaveRefused(h, 'task', body, copying); + await expectFormCopySealed(h, loaderNames(body)[0], copying, form(allowAnonymous, title, SLUG)); + seedStored(h, 'view', 'task', copying, body); + } + // Two packages ship the container on an object no code package owns, - // and only one of them stores a copy. On an unscoped kernel the copy's - // expansion used to be registered under the bare name, which the - // registry answers ahead of either package's own entry, so the by-name - // read naming the OTHER package served the copy while the list served - // that package's own item. Each package's by-name read answers its own - // item, on both kernels, whichever package stores the copy. + // and only one of them stores a copy. Each package's by-name read + // answers its own item, on both kernels, whichever package stores the + // copy: the view doors for the list, the `form` doors for a form. describe('(g) two packages ship the container and one stores a copy: the by-name read naming each package answers its own item', () => { const PACKAGES = [OTHER, COPYING] as const; for (const [kernel, environmentId] of KERNELS) { @@ -1089,16 +1214,20 @@ describe('each package\'s copy of a view container expands into its own package\ const copyTitle = `Intake (${copying} copy)`; const shipped = PACKAGES.map((pkg): [string, Record] => [pkg, { object: 'task', ...m.body(SHIPPED_TITLE(pkg), true, SLUG) }]); - const { protocol } = harness(shipped, environmentId); - expect((await protocol.saveMetaItem({ - type: 'view', name: 'task', packageId: copying, - item: { name: 'task', object: 'task', ...m.body(copyTitle, false, SLUG) }, - })).success).toBe(true); + const h = harness(shipped, environmentId); + await copyOfShared(h, m, copying, copyTitle, false); const [name] = loaderNames(m.body('x', true, SLUG)); + const type = m.isForm ? 'form' : 'view'; for (const pkg of PACKAGES) { - const own = pkg === copying ? copyTitle : SHIPPED_TITLE(pkg); - expect(await byNameTitle(protocol, name, pkg), `the by-name read of ${name} naming ${pkg}`).toBe(own); - expect(await slotTitles(protocol, name, pkg), `${pkg}'s slot of ${name}`).toEqual([own]); + // [ADR-0159 D6 rule 11, D7] A stored form copy is served by no door and + // holds its package's address: that package's form read serves nothing, + // the other keeps its shipped form, and the per-package layer the doors + // judge withdrawals over holds each shipped body. + const own = pkg === copying && !m.isForm ? copyTitle : SHIPPED_TITLE(pkg); + const read = pkg === copying && m.isForm ? undefined : own; + expect(await byNameTitle(h.protocol, name, pkg, type), `the by-name read of ${name} naming ${pkg}`).toBe(read); + expect(await slotTitles(h.protocol, name, pkg, type), `${pkg}'s slot of ${name}`).toEqual([own]); + if (m.isForm) await expectNoViewOf(h.protocol, name, pkg); } }); } @@ -1106,14 +1235,10 @@ describe('each package\'s copy of a view container expands into its own package\ } }); - // The condition on the hydration line above: the by-name read that - // names NO package is the generic reader of a hydrated bare entry. For - // a name two packages ship, after one of them stores a copy, it answers - // on both kernels, never an absence; both kernels answer the same body; - // and that body is one the env-wide list serves under the name. Which - // package's body it is stays ADR-0048's ambiguous case (two packages - // ship one name): it is the copy's, the last expansion of the name, as - // the read naming no package selects (servedViewExpansion). + // The by-name read that names NO package, for a name two packages + // ship, after one of them stores a copy: it answers on both kernels, + // never an absence; both kernels answer the same body; and that body + // is one its type's list serves under the name. describe('(h) a name two packages ship: the by-name read naming no package answers on both kernels, with the same body', () => { const ORDERS = [[OTHER, COPYING], [COPYING, OTHER]] as const; for (const m of MEMBERS) { @@ -1122,19 +1247,23 @@ describe('each package\'s copy of a view container expands into its own package\ const ownership = owner ? 'another package owns the object' : 'no code package owns the object'; it(`${m.member}; ${ownership}; ${order[0]} registered first`, async () => { const [name] = loaderNames(m.body('x', true, SLUG)); + const type = m.isForm ? 'form' : 'view'; const answers: unknown[] = []; for (const [kernel, environmentId] of KERNELS) { const shipped = order.map((pkg): [string, Record] => [pkg, { object: 'task', ...m.body(SHIPPED_TITLE(pkg), true, pkg === COPYING ? SLUG : OTHER_SLUG) }]); - const { protocol } = harness(shipped, environmentId, owner); + const h = harness(shipped, environmentId, owner); const placement = PLACEMENTS.find((q) => q.m === m && q.owner === owner && q.ships); if (!placement) throw new Error(`no placement for ${ownership}, ${m.member}`); - await saveCopyOf(protocol, placement, false); - const item = (await protocol.getMetaItem({ type: 'view', name })).item; + await saveCopyOf(h, placement, false); + const item = (await h.protocol.getMetaItem({ type, name })).item; expect(item, `${kernel}: the read naming no package answers ${name}`).toBeTruthy(); - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - const listed = (envWide.items as any[]).filter((v) => v?.name === name).map(titleOf); - expect(listed, `${kernel}: a body the env-wide list serves under ${name}`).toContain(titleOf(item)); + const list: any = type === 'view' + ? await h.protocol.getMetaItems({ type: 'view' }) + : await h.protocol.getMetaItemsPerPackage({ type: 'form' }); + const listed = (list.items as any[]).filter((v) => v?.name === name).map(titleOf); + expect(listed, `${kernel}: a body the list serves under ${name}`).toContain(titleOf(item)); + if (m.isForm) expect(titleOf(item), `${kernel}: never the stored copy`).not.toBe(COPY_TITLE); answers.push(titleOf(item)); } expect(answers[1], 'the unscoped kernel answers what the environment-scoped kernel answers').toBe(answers[0]); @@ -1144,32 +1273,34 @@ describe('each package\'s copy of a view container expands into its own package\ } }); - // The body (h) pins is the copy's, and the read wears the envelope of - // the package whose copy it serves: the copy's own `_packageId`, as the - // env-wide list's slot of that body wears it, never the first-registered - // package's. The read naming each package keeps its own body and its - // own envelope. A stored row of the name bound to one package is served - // the same way. A package-less copy names no package: its read wears - // the envelope of a package whose list slot serves that same body. + // The read naming no package wears the envelope of the package whose + // body it serves, as its type's list wears it for that body; the read + // naming each package keeps its own body and its own envelope. For a + // list that body is the copy's. [ADR-0159 D7] For a form a stored copy + // or a stored flat row serves no body: it is a shipped form's. describe('(i) the by-name read naming no package wears the envelope of the package whose body it serves', () => { const ORDERS = [[OTHER, COPYING], [COPYING, OTHER]] as const; const envelopeOf = (v: any) => [titleOf(v), v?._packageId, v?._provenance]; const shippedFor = (m: Member, order: readonly string[]) => order.map((pkg): [string, Record] => [pkg, { object: 'task', ...m.body(SHIPPED_TITLE(pkg), true, pkg === COPYING ? SLUG : OTHER_SLUG) }]); - /** The env-wide list's [title, package, provenance] for every item it serves under `name`. */ - async function listedEnvelopes(protocol: any, name: string): Promise { - const envWide: any = await protocol.getMetaItems({ type: 'view' }); - return (envWide.items as any[]).filter((v) => v?.name === name).map(envelopeOf); + /** Its type's list's [title, package, provenance] for every item it serves under `name`. */ + async function listedEnvelopes(protocol: any, name: string, type: 'view' | 'form'): Promise { + const list: any = type === 'view' + ? await protocol.getMetaItems({ type: 'view' }) + : await protocol.getMetaItemsPerPackage({ type: 'form' }); + return (list.items as any[]).filter((v) => v?.name === name).map(envelopeOf); } + /** The envelope the read naming no package must wear: the copy's for a list, a shipped form's (its own package's) for a form. */ + const expectedEnvelope = (type: 'view' | 'form', read: any) => (type === 'view' + ? [COPY_TITLE, COPYING, 'package'] + : [SHIPPED_TITLE(String(read?._packageId)), read?._packageId, 'package']); - /** - * One store the read naming no package serves COPYING's body from, written on a fresh harness of one - * kernel. `named`: the reads naming each package are pinned on it too (the copies of a container, - * the measured case). - */ interface Cell { readonly label: string; readonly named: boolean; + readonly type: 'view' | 'form'; + /** A form cell: its stored copy holds COPYING's address (it expands to COPYING's shipped form). */ + readonly holds: boolean; readonly setUp: (environmentId: string | undefined) => Promise<{ protocol: any; name: string }>; } const KEYED = MEMBERS.find((m) => m.member === 'a keyed member'); @@ -1182,35 +1313,39 @@ describe('each package\'s copy of a view container expands into its own package\ return { label: `${m.member}; ${ownership}; ${order[0]} registered first; ${COPYING} stores a copy of the container`, named: true, + type: m.isForm ? 'form' : 'view', + holds: m.isForm, setUp: async (environmentId) => { - const { protocol } = harness(shippedFor(m, order), environmentId, owner); - await saveCopyOf(protocol, placement, false); - return { protocol, name: loaderNames(m.body('x', true, SLUG))[0] }; + const h = harness(shippedFor(m, order), environmentId, owner); + await saveCopyOf(h, placement, false); + return { protocol: h.protocol, name: loaderNames(m.body('x', true, SLUG))[0] }; }, }; }))), ...ORDERS.map((order): Cell => ({ label: `${KEYED.member}; ${order[0]} registered first; a stored row of the name, bound to ${COPYING}`, named: false, + type: 'form', + holds: true, setUp: async (environmentId) => { const [name] = loaderNames(KEYED.body('x', true, SLUG)); - const { protocol } = harness(shippedFor(KEYED, order), environmentId); - expect((await protocol.saveMetaItem({ - type: 'view', name, packageId: COPYING, - item: { name, label: COPY_TITLE, object: 'task', viewKind: 'form', config: { title: COPY_TITLE } }, - })).success).toBe(true); - return { protocol, name }; + const h = harness(shippedFor(KEYED, order), environmentId); + const row = { name, label: COPY_TITLE, object: 'task', viewKind: 'form', config: { title: COPY_TITLE } }; + await expectViewSaveRefused(h, name, row, COPYING); + seedStored(h, 'view', name, COPYING, row); + return { protocol: h.protocol, name }; }, })), ]; for (const cell of CELLS) { - it(`(a) ${cell.label}: the read naming no package serves that body under ${COPYING}'s envelope, on both kernels`, async () => { + it(`(a) ${cell.label}: the read naming no package serves a body under that body's package's envelope, on both kernels`, async () => { for (const [kernel, environmentId] of KERNELS) { const { protocol, name } = await cell.setUp(environmentId); - const read = await protocol.getMetaItem({ type: 'view', name }); - expect(envelopeOf(read.item), `${kernel}: the item`).toEqual([COPY_TITLE, COPYING, 'package']); - expect(read.packageId, `${kernel}: the envelope the read reports`).toBe(COPYING); + const read = await protocol.getMetaItem({ type: cell.type, name }); + expect(envelopeOf(read.item), `${kernel}: the item`).toEqual(expectedEnvelope(cell.type, read.item)); + expect(read.packageId, `${kernel}: the envelope the read reports`).toBe(read.item?._packageId); + if (cell.type === 'form') await expectNoViewOf(protocol, name); } }); @@ -1218,54 +1353,61 @@ describe('each package\'s copy of a view container expands into its own package\ for (const [kernel, environmentId] of KERNELS) { const { protocol, name } = await cell.setUp(environmentId); for (const pkg of [OTHER, COPYING]) { - const named = await protocol.getMetaItem({ type: 'view', name, packageId: pkg }); - const own = pkg === COPYING ? COPY_TITLE : SHIPPED_TITLE(pkg); + const named = await protocol.getMetaItem({ type: cell.type, name, packageId: pkg }); + if (pkg === COPYING && cell.holds) { + // [ADR-0159 D6 rule 11] The stored copy holds COPYING's address: nothing is served there. + expect(named.item, `${kernel}: the read naming ${pkg}`).toBeUndefined(); + continue; + } + const own = pkg === COPYING && cell.type === 'view' ? COPY_TITLE : SHIPPED_TITLE(pkg); expect(envelopeOf(named.item), `${kernel}: the read naming ${pkg}`).toEqual([own, pkg, 'package']); expect(named.packageId, `${kernel}: the envelope the read naming ${pkg} reports`).toBe(pkg); } } }); - it(`(c) ${cell.label}: the env-wide list wears the same envelope for the body the read naming no package serves, on both kernels`, async () => { + it(`(c) ${cell.label}: its type's list wears the same envelope for the body the read naming no package serves, on both kernels`, async () => { for (const [kernel, environmentId] of KERNELS) { const { protocol, name } = await cell.setUp(environmentId); - const read = await protocol.getMetaItem({ type: 'view', name }); - expect(await listedEnvelopes(protocol, name), `${kernel}: the list's envelope of that body`) + const read = await protocol.getMetaItem({ type: cell.type, name }); + expect(await listedEnvelopes(protocol, name, cell.type), `${kernel}: the list's envelope of that body`) .toContainEqual(envelopeOf(read.item)); } }); } for (const order of ORDERS) { - it(`control: a package-less copy stands in for both packages; ${order[0]} registered first: the read wears a package whose list slot serves it`, async () => { + it(`control: a stored package-less copy holds both packages' addresses; ${order[0]} registered first: no form read serves a body there`, async () => { const [name] = loaderNames(KEYED.body('x', true, SLUG)); for (const [kernel, environmentId] of KERNELS) { - const { protocol } = harness(shippedFor(KEYED, order), environmentId); - expect((await protocol.saveMetaItem({ - type: 'view', name: 'task', item: { name: 'task', object: 'task', ...KEYED.body('Intake (env-wide copy)', true, SLUG) }, - })).success).toBe(true); - - const read = await protocol.getMetaItem({ type: 'view', name }); - expect(titleOf(read.item), `${kernel}: the read naming no package`).toBe('Intake (env-wide copy)'); - const listed = await listedEnvelopes(protocol, name); - expect(listed.map(([, pkg]) => pkg).sort(), `${kernel}: the list serves the copy in both packages' slots`).toEqual([OTHER, COPYING]); - expect(listed, `${kernel}: the env-wide list wears the same envelope for the same body`).toContainEqual(envelopeOf(read.item)); + const h = harness(shippedFor(KEYED, order), environmentId); + const body = { name: 'task', object: 'task', ...KEYED.body('Intake (env-wide copy)', true, SLUG) }; + await expectViewSaveRefused(h, 'task', body, undefined); + seedStored(h, 'view', 'task', undefined, body); + + // [ADR-0159 D6 rule 11] A package-less stored copy holds every package's + // address: no form read serves its body, or a shipped one in its place. + const read = await h.protocol.getMetaItem({ type: 'form', name }); + expect(read.item, `${kernel}: the read naming no package`).toBeUndefined(); + for (const pkg of [OTHER, COPYING]) { + expect((await h.protocol.getMetaItem({ type: 'form', name, packageId: pkg })).item, `${kernel}: the read naming ${pkg}`).toBeUndefined(); + } + const listed = await listedEnvelopes(h.protocol, name, 'form'); + expect(listed.map(([, pkg]) => pkg).sort(), `${kernel}: the per-package layer holds both packages' shipped forms`).toEqual([OTHER, COPYING]); + await expectNoViewOf(h.protocol, name); } }); } }); - // [#22057] A stored row of a view item name two packages ship, bound to - // one of them. The hydration used to register it under the bare name, - // which the registry answers ahead of either package's own entry, so - // the by-name read naming the OTHER package found no row of its own, - // expanded nothing, and served this row's body under that package's - // envelope, while the list's slot for that package served its own item. - // A cold boot hydrates the stored rows through the same door on either - // kernel. Such a row is not registered: the reads answer it from its - // row, for its own package and for a read naming none, on every kernel. - // ⛔ View only: a row of any other type keeps the bare entry (#4624), - // pinned as the control (e) below. + // [#22057] A stored flat form row of a name two packages ship, bound to + // one of them. Before 19 the view door saved it and the reads answered + // it from its row. [ADR-0159 D7] The view door refuses a `viewKind: + // 'form'` row now; it stands as the row a release before 19 stored. The + // `form` read naming each package answers that package's shipped form, + // the view doors serve no form, and the raw read the doors judge + // withdrawals over still reads the row. A cold boot hydrates it on + // either kernel. describe('(j) a stored row bound to one package, of a name another package ships: the read naming each package answers its own item', () => { const ORDERS = [[OTHER, COPYING], [COPYING, OTHER]] as const; const KEYED_MEMBER = MEMBERS.find((m) => m.member === 'a keyed member'); @@ -1276,23 +1418,28 @@ describe('each package\'s copy of a view container expands into its own package\ const shippedBy = (packages: readonly string[]) => packages.map((pkg): [string, Record] => [pkg, { object: 'task', ...KEYED_MEMBER.body(SHIPPED_TITLE(pkg), true, pkg === COPYING ? SLUG : OTHER_SLUG) }]); const rowOf = (name: string, title: string) => ({ name, label: title, object: 'task', viewKind: 'form', config: { title } }); - async function saveRow(protocol: any, name: string, packageId: string | undefined, title: string) { - expect((await protocol.saveMetaItem({ - type: 'view', name, item: rowOf(name, title), ...(packageId ? { packageId } : {}), - })).success).toBe(true); + /** The view door refuses the flat form row; it stands as the row a release before 19 stored. */ + async function saveRow(h: Harness, name: string, packageId: string | undefined, title: string) { + await expectViewSaveRefused(h, name, rowOf(name, title), packageId); + seedStored(h, 'view', name, packageId, rowOf(name, title)); } /** A cold boot over the stored rows: a fresh registry of the shipped items, then the boot's hydration. */ async function bootOver( rows: Map, shipped: Array<[string, Record]>, environmentId: string | undefined, - ): Promise> { + ): Promise { const booted = harness(shipped, environmentId); for (const [key, row] of rows) booted.rows.set(key, row); expect((await booted.protocol.loadMetaFromDb()).errors, 'the boot hydrates every stored row').toBe(0); return booted; } - const STARTS = [['saved on the running kernel', false], ['after a cold boot over the stored row', true]] as const; + /** The raw read the doors judge withdrawals over: the row's [package, title] under `name`. */ + async function rawRows(protocol: any, name: string): Promise { + const raw: any = await protocol.getViewItemsWithStoredForms({}); + return (raw.items as any[]).filter((v) => v?.name === name && titleOf(v) === ROW_TITLE).map((v) => [v._packageId ?? null, titleOf(v)]); + } + const STARTS = [['stored on the running kernel', false], ['after a cold boot over the stored row', true]] as const; for (const [kernel, environmentId] of KERNELS) { for (const order of ORDERS) { @@ -1300,42 +1447,44 @@ describe('each package\'s copy of a view container expands into its own package\ const where = `${kernel}; ${order[0]} registered first; ${start}`; const setUp = async () => { const saved = harness(shippedBy(order), environmentId); - await saveRow(saved.protocol, SHARED, COPYING, ROW_TITLE); + await saveRow(saved, SHARED, COPYING, ROW_TITLE); return boot ? bootOver(saved.rows, shippedBy(order), environmentId) : saved; }; - it(`(a) ${where}: the read naming ${OTHER} serves ${OTHER}'s own item under ${OTHER}'s envelope`, async () => { + it(`(a) ${where}: the form read naming ${OTHER} serves ${OTHER}'s own form under ${OTHER}'s envelope`, async () => { const { protocol, registry } = await setUp(); - const read = await protocol.getMetaItem({ type: 'view', name: SHARED, packageId: OTHER }); + const read = await protocol.getMetaItem({ type: 'form', name: SHARED, packageId: OTHER }); expect(envelopeOf(read.item), `the read naming ${OTHER}`).toEqual([SHIPPED_TITLE(OTHER), OTHER, 'package']); expect(read.packageId, 'the envelope the read reports').toBe(OTHER); - expect(await slotTitles(protocol, SHARED, OTHER), `${OTHER}'s slot in the env-wide list`).toEqual([SHIPPED_TITLE(OTHER)]); + expect(await slotTitles(protocol, SHARED, OTHER, 'form'), `${OTHER}'s slot in the per-package layer`).toEqual([SHIPPED_TITLE(OTHER)]); // ADR-0048 §3.3: a registry read that carries its package id never mis-resolves. - expect(titleOf(registry.getItem('view', SHARED, OTHER)), `the registry read naming ${OTHER}`).toBe(SHIPPED_TITLE(OTHER)); + expect(titleOf(registry.getItem('form', SHARED, OTHER)), `the registry read naming ${OTHER}`).toBe(SHIPPED_TITLE(OTHER)); + await expectNoViewOf(protocol, SHARED, OTHER); }); - it(`(b) ${where}: the read naming ${COPYING}, the read naming no package and the list scoped to ${COPYING} serve the row`, async () => { + it(`(b) ${where}: the form read naming ${COPYING} serves nothing, the view doors serve no form, and the raw read holds the row`, async () => { const { protocol } = await setUp(); - for (const packageId of [COPYING, undefined]) { - const named = packageId ?? 'no package'; - const read = await protocol.getMetaItem({ type: 'view', name: SHARED, ...(packageId ? { packageId } : {}) }); - expect(envelopeOf(read.item), `the read naming ${named}`).toEqual([ROW_TITLE, COPYING, 'package']); - expect(read.packageId, `the envelope the read naming ${named} reports`).toBe(COPYING); - } + // [ADR-0159 D6 rule 11] The stored row holds COPYING's address: nothing is served there. + const named = await protocol.getMetaItem({ type: 'form', name: SHARED, packageId: COPYING }); + expect(named.item, `the read naming ${COPYING}`).toBeUndefined(); + const read = await protocol.getMetaItem({ type: 'form', name: SHARED }); + // MEASURED: the read naming no package answers one of the two shipped forms + // (ADR-0048's ambiguous case, by registry order), under its own envelope. + const pkg = String(read.item?._packageId); + expect([OTHER, COPYING], 'the read naming no package').toContain(pkg); + expect(envelopeOf(read.item), 'its envelope').toEqual([SHIPPED_TITLE(pkg), pkg, 'package']); + for (const packageId of [COPYING, undefined]) await expectNoViewOf(protocol, SHARED, packageId); const scoped: any = await protocol.getMetaItems({ type: 'view', packageId: COPYING }); - expect((scoped.items as any[]).filter((v) => v?.name === SHARED).map(envelopeOf), `the list scoped to ${COPYING}`) - .toEqual([[ROW_TITLE, COPYING, 'package']]); - expect(await slotTitles(protocol, SHARED, COPYING), `${COPYING}'s slot in the env-wide list`).toEqual([ROW_TITLE]); + expect((scoped.items as any[]).filter((v) => v?.name === SHARED), `the view list scoped to ${COPYING}`).toEqual([]); + expect(await rawRows(protocol, SHARED), 'the raw read holds the stored row').toEqual([[COPYING, ROW_TITLE]]); }); } } } - // What stays registered under the bare name: a package-less row (the - // overlay of every package's item of the name, ADR-0005, standing in - // for each package, ADR-0048), and a row bound to a package of a name - // only that package ships, or no package ships. The unscoped kernel - // registers on save; a cold boot registers on either kernel. + // Before 19 these rows were served from the row and registered under + // the bare name. MEASURED on 19 (seeded, the view door refuses them): + // the reads serve no view of the name; the raw read holds the row. const STAYS = [ { row: 'a package-less row of a name one package ships', shipped: [OTHER], bound: undefined, name: SHARED, reads: [OTHER, undefined] }, { row: 'a package-less row of a name two packages ship', shipped: [OTHER, COPYING], bound: undefined, name: SHARED, reads: [OTHER, COPYING, undefined] }, @@ -1345,14 +1494,15 @@ describe('each package\'s copy of a view container expands into its own package\ for (const [kernel, environmentId] of KERNELS) { for (const [start, boot] of STARTS) { for (const stays of STAYS) { - it(`(c) ${kernel}; ${start}; ${stays.row}: served from the row, and registered under the bare name as before`, async () => { + it(`(c) ${kernel}; ${start}; ${stays.row}: no view door serves it, the raw read holds it, and it is registered under the bare name as before`, async () => { const saved = harness(shippedBy(stays.shipped), environmentId); - await saveRow(saved.protocol, stays.name, stays.bound, ROW_TITLE); + await saveRow(saved, stays.name, stays.bound, ROW_TITLE); const { protocol, registry } = boot ? await bootOver(saved.rows, shippedBy(stays.shipped), environmentId) : saved; - for (const packageId of stays.reads) { - const read = await protocol.getMetaItem({ type: 'view', name: stays.name, ...(packageId ? { packageId } : {}) }); - expect(titleOf(read.item), `the read naming ${packageId ?? 'no package'}`).toBe(ROW_TITLE); - } + for (const packageId of stays.reads) await expectNoViewOf(protocol, stays.name, packageId); + expect(await rawRows(protocol, stays.name), 'the raw read holds the stored row').toEqual([[stays.bound ?? null, ROW_TITLE]]); + // MEASURED: the boot hydrates the stored flat form row under the bare view + // name on either kernel, and an unscoped kernel's read registers it too; the + // view doors still serve no form. const registers = environmentId === undefined || boot; expect(titleOf(registry.getItem('view', stays.name)) === ROW_TITLE, 'the bare entry holds the row').toBe(registers); }); @@ -1360,26 +1510,27 @@ describe('each package\'s copy of a view container expands into its own package\ } } - // The delete's heal ({@link restoreArtifactRegistryView}): with no - // bare entry to drop, it re-registers the metadata service's answer - // for the name, read naming no package. Where that is one package's - // body under a name another package ships, it is not registered - // either. The service here answers that read alone, so the registry - // is the only thing the read naming the other package can reach. + // The delete's heal ({@link restoreArtifactRegistryView}) after the + // stored row is deleted: the registry read naming the other package, + // and the `form` read naming it, still answer that package's form. for (const order of ORDERS) { - it(`(d) an unscoped kernel; ${order[0]} registered first: after the row is deleted, the heal registers no package's body under the name`, async () => { + it(`(d) an unscoped kernel; ${order[0]} registered first: after the stored row is deleted, the form read naming the other package keeps its own form`, async () => { const service = { get: async (type: string, name: string, packageId?: string) => (type === 'view' && name === SHARED && packageId === undefined ? { ...rowOf(SHARED, SHIPPED_TITLE(COPYING)), _packageId: COPYING, _provenance: 'package' } : undefined), }; - const { protocol, registry } = harness(shippedBy(order), undefined, undefined, service); - await saveRow(protocol, SHARED, COPYING, ROW_TITLE); - expect((await protocol.deleteMetaItem({ type: 'view', name: SHARED })).success).toBe(true); + const h = harness(shippedBy(order), undefined, undefined, service); + await saveRow(h, SHARED, COPYING, ROW_TITLE); + const deleted = await h.protocol.deleteMetaItem({ type: 'view', name: SHARED }).then((r: any) => r, (e: any) => e); + expect(deleted?.success, 'the stored row is deleted').toBe(true); - expect(titleOf(registry.getItem('view', SHARED, OTHER)), `the registry read naming ${OTHER}`).toBe(SHIPPED_TITLE(OTHER)); - const read = await protocol.getMetaItem({ type: 'view', name: SHARED, packageId: OTHER }); + expect(titleOf(h.registry.getItem('form', SHARED, OTHER)), `the registry read naming ${OTHER}`).toBe(SHIPPED_TITLE(OTHER)); + const read = await h.protocol.getMetaItem({ type: 'form', name: SHARED, packageId: OTHER }); expect(envelopeOf(read.item), `the read naming ${OTHER}`).toEqual([SHIPPED_TITLE(OTHER), OTHER, 'package']); + // MEASURED: the heal re-registers the service's answer under the bare view name + // (no package ships a view of the name now); no view door serves that form. + await expectNoViewOf(h.protocol, SHARED, OTHER); }); } diff --git a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts index 18b484fa356..c2c8cecb2e0 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -1514,17 +1514,19 @@ describe('stored html page `requires` at load and at draft promotion (#20312)', describe('public-form intake advisory on save and publish (#21476)', () => { const SLUG = 'contact-us'; const NAME = 'showcase_inquiry'; - /** The showcase's contact form: a container whose public form is `formViews.contact`. */ + /** The body the showcase's public contact form carries, wherever it is held. */ + const contactBody = () => ({ + type: 'simple', + sections: [{ name: 'about', fields: [{ field: 'name' }, { field: 'email' }] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, + }); + /** [ADR-0159 D7] The showcase's contact form as protocol 19 holds it: a `form` item named `OBJECT.KEY`. */ + const FORM = `${NAME}.contact`; + const contactForm = () => ({ name: FORM, object: NAME, ...contactBody() }); + /** The shape before 19: a `view` container whose public form is `formViews.contact`. */ const contactContainer = () => ({ list: { type: 'grid', data: { provider: 'object', object: NAME }, columns: [{ field: 'name' }] }, - formViews: { - contact: { - type: 'simple', - data: { provider: 'object', object: NAME }, - sections: [{ name: 'about', fields: [{ field: 'name' }, { field: 'email' }] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, - }, - }, + formViews: { contact: { ...contactBody(), data: { provider: 'object', object: NAME } } }, }); /** The bound object as the live registry holds it — `organization_id` injected at registration. */ const inquiry = (tenancyDisabled: boolean) => ({ @@ -1557,10 +1559,10 @@ describe('public-form intake advisory on save and publish (#21476)', () => { } const put = (protocol: any, extra: Record = {}) => - protocol.saveMetaItem({ type: 'view', name: NAME, item: contactContainer(), ...extra }); + protocol.saveMetaItem({ type: 'form', name: FORM, item: contactForm(), ...extra }); const publish = async (protocol: any) => { await expect(put(protocol, { mode: 'draft' })).resolves.toMatchObject({ success: true }); - return protocol.publishMetaItem({ type: 'view', name: NAME }); + return protocol.publishMetaItem({ type: 'form', name: FORM }); }; const intake = (response: { advisories?: Array<{ rule: string }> }) => (response.advisories ?? []).filter((a) => a.rule === PUBLIC_FORM_INTAKE_UNAVAILABLE); @@ -1586,19 +1588,27 @@ describe('public-form intake advisory on save and publish (#21476)', () => { expect(response.advisories).toEqual([{ severity: 'warning', rule: PUBLIC_FORM_INTAKE_UNAVAILABLE, - where: `view "${NAME}" · public form "/forms/${SLUG}"`, - path: 'views[0].formViews.contact.sharing', + where: `form "${FORM}" · public form "/forms/${SLUG}"`, + path: 'forms[0].sharing', message: anonymousFormIntakeUnavailableMessage(SLUG, { object: NAME, posture, tenantField: 'organization_id', }), hint: expect.stringContaining('tenancy: { enabled: false }'), }]); // Never a refusal: the row landed active. - expect([...rows.values()].filter((r) => r.type === 'view' && r.state === 'active')).toHaveLength(1); + expect([...rows.values()].filter((r) => r.type === 'form' && r.state === 'active')).toHaveLength(1); }); } } + it('[ADR-0159 D7] the same form held by a `view` container is refused at `formViews` on a walled posture, with no advisory and no row', async () => { + const { protocol, rows } = hostOn('isolated'); + const err = await protocol.saveMetaItem({ type: 'view', name: NAME, item: contactContainer() }).catch((e: any) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect(err.issues.map((i: any) => i.path)).toContain('formViews'); + expect(rows.size).toBe(0); + }); + it.each<[string, Tenancy, boolean]>([ ['walled posture, object declared tenancy: { enabled: false }', 'isolated', true], ["the 'single' posture", 'single', false], @@ -4854,23 +4864,25 @@ describe('runtime authoring gate on PERMISSION writes — membership-key ownersh // ⚠️ This package reaches `@objectstack/lint` through its built `dist/`, so a // registry edit is invisible here until `pnpm --filter @objectstack/lint build` // has run. -describe('runtime authoring gate on VIEW writes — a public form declaring a file field (#25650)', () => { +describe('runtime authoring gate on FORM writes — a public form declaring a file field (#25650)', () => { const NAME = 'supplier_application'; + const FORM = `${NAME}.apply`; const RULE = 'public-form-file-field'; - /** A container whose `formViews.apply` is open to anonymous intake. */ + /** The form's body, open to anonymous intake, wherever it is held. */ + const body = (fields: unknown[]) => ({ + type: 'simple', + sections: [{ name: 'about', fields }], + sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/apply' }, + }); + /** [ADR-0159 D7] The form as protocol 19 holds it: a `form` item named `OBJECT.KEY`. */ + const form = (fields: unknown[]) => ({ name: FORM, object: NAME, ...body(fields) }); + /** The shape before 19: a `view` container whose `formViews.apply` is the public form. */ const container = (fields: unknown[]) => ({ list: { type: 'grid', data: { provider: 'object', object: NAME }, columns: [{ field: 'company' }] }, - formViews: { - apply: { - type: 'simple', - data: { provider: 'object', object: NAME }, - sections: [{ name: 'about', fields }], - sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/apply' }, - }, - }, + formViews: { apply: { ...body(fields), data: { provider: 'object', object: NAME } } }, }); - const withCertificate = () => container([{ field: 'company' }, { field: 'email' }, { field: 'certificate' }]); - const withoutCertificate = () => container([{ field: 'company' }, { field: 'email' }]); + const withCertificate = () => form([{ field: 'company' }, { field: 'email' }, { field: 'certificate' }]); + const withoutCertificate = () => form([{ field: 'company' }, { field: 'email' }]); const supplier = { name: NAME, label: 'Supplier application', @@ -4889,9 +4901,9 @@ describe('runtime authoring gate on VIEW writes — a public form declaring a fi return { protocol, rows }; } const saveView = (protocol: any, item: unknown, extra: Record = {}) => - protocol.saveMetaItem({ type: 'view', name: NAME, item, ...extra }); + protocol.saveMetaItem({ type: 'form', name: FORM, item, ...extra }); const activeViewRows = (rows: Map) => - Array.from(rows.values()).filter((r) => r.type === 'view' && r.state === 'active'); + Array.from(rows.values()).filter((r) => r.type === 'form' && r.state === 'active'); let warn: ReturnType; beforeEach(() => { @@ -4913,7 +4925,7 @@ describe('runtime authoring gate on VIEW writes — a public form declaring a fi const issues = (err.issues ?? []).filter((i: any) => i.rule === RULE); expect(issues, `issues: ${JSON.stringify(err.issues)}`).toHaveLength(1); expect(issues[0].severity).toBe('error'); - expect(issues[0].path).toContain('formViews.apply.sections[0].fields[2]'); + expect(issues[0].path).toContain('forms[0].sections[0].fields[2]'); expect(issues[0].message).toContain('"certificate"'); expect(activeViewRows(rows)).toEqual([]); }); @@ -4922,7 +4934,7 @@ describe('runtime authoring gate on VIEW writes — a public form declaring a fi const { protocol } = viewProtocol(); await expect(saveView(protocol, withCertificate(), { mode: 'draft' })).resolves.toMatchObject({ success: true }); - const err = await protocol.publishMetaItem({ type: 'view', name: NAME }).catch((e: any) => e); + const err = await protocol.publishMetaItem({ type: 'form', name: FORM }).catch((e: any) => e); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); expect(err.issues.map((i: any) => i.rule)).toContain(RULE); @@ -4933,7 +4945,7 @@ describe('runtime authoring gate on VIEW writes — a public form declaring a fi const err = await saveView(protocol, withCertificate()).catch((e: any) => e); const atDoor = (err.issues ?? []).filter((i: any) => i.rule === RULE); - const stack = { objects: [supplier], views: [{ name: NAME, ...withCertificate() }] }; + const stack = { objects: [supplier], forms: [withCertificate()] }; const atBuild = runAuthoringRules('build', { normalized: stack, parsed: stack }).filter((f) => f.rule === RULE); expect(atBuild).toHaveLength(1); @@ -4947,6 +4959,16 @@ describe('runtime authoring gate on VIEW writes — a public form declaring a fi await expect(saveView(protocol, withoutCertificate())).resolves.toMatchObject({ success: true }); expect(activeViewRows(rows)).toHaveLength(1); }); + + it('[ADR-0159 D7] the same form held by a `view` container is refused at `formViews`, file field or none, and nothing is stored', async () => { + for (const fields of [[{ field: 'company' }, { field: 'certificate' }], [{ field: 'company' }]]) { + const { protocol, rows } = viewProtocol(); + const err = await protocol.saveMetaItem({ type: 'view', name: NAME, item: container(fields) }).catch((e: any) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect(err.issues.map((i: any) => i.path)).toContain('formViews'); + expect(rows.size).toBe(0); + } + }); }); // ───────────────────────────────────────────────────────────────────────────── diff --git a/packages/metadata-protocol/src/protocol.save-union-issues.test.ts b/packages/metadata-protocol/src/protocol.save-union-issues.test.ts index f9285493315..f227c0749be 100644 --- a/packages/metadata-protocol/src/protocol.save-union-issues.test.ts +++ b/packages/metadata-protocol/src/protocol.save-union-issues.test.ts @@ -247,6 +247,13 @@ describe('#7510 the 422 for a broken ViewItem names its own key, not the contain * a nested block. It was measured on `publicPicker.sort`; [#21180] retired * that key (ruling E on #21079), so the repro rides on `keyField`, the other * strict block a form field carries — same shape, same door. + * + * [ADR-0159 D7] Protocol 19 took the form out of `view`: the same body is + * refused at `viewKind` whatever its subkeys hold, and the form is saved as + * a `form` item. So the repro is held on both sides of the move: a LIST + * ViewItem with an unknown subkey in a nested strict block (the view + * union's focusing, which is what #7510 fixed), and the form's body at the + * `form` door, where `sort` still reaches the author. */ const pickerReproView = () => ({ name: 'lead.contact', @@ -262,11 +269,30 @@ describe('#7510 the 422 for a broken ViewItem names its own key, not the contain }], }, }); + /** The same form as protocol 19 holds it: the `config` body at the top level, bound by `object`. */ + const pickerReproForm = () => { + const { viewKind: _viewKind, config, ...identity } = pickerReproView(); + const { data: _data, ...body } = config; + return { ...identity, ...body }; + }; + /** A list ViewItem carrying an unknown subkey in a nested strict block. */ + const listReproView = () => ({ + name: 'lead.all', + object: 'lead', + viewKind: 'list', + label: 'All leads', + config: { + type: 'grid', + data: { provider: 'object', object: 'lead' }, + columns: ['name'], + pagination: { pageSize: 10, sort: [{ field: 'email', order: 'desc' }] }, + }, + }); it('the issue\'s body: `sort` reaches the author, the container prescription does not', async () => { const { protocol, rows } = makeProtocol(); - const err = await rejection(save(protocol, pickerReproView(), 'lead.contact')); + const err = await rejection(save(protocol, listReproView(), 'lead.all')); expect(err.code).toBe('INVALID_METADATA'); expect(err.status).toBe(422); @@ -282,7 +308,7 @@ describe('#7510 the 422 for a broken ViewItem names its own key, not the contain const unknownKey = err.issues[0]; expect(unknownKey.code).toBe('unrecognized_keys'); expect(unknownKey.message).toContain('`sort`'); - expect(unknownKey.path).toBe('config.sections.0.fields.0.keyField'); + expect(unknownKey.path).toBe('config.pagination'); // ⛔ The measured misdirect, gone from the whole envelope: on // `origin/main` @ `9051802` this message was the container branch's. @@ -290,15 +316,46 @@ describe('#7510 the 422 for a broken ViewItem names its own key, not the contain expect(JSON.stringify(err.issues)).not.toContain('this view container'); }); - it('the same item minus the bad subkey still saves', async () => { + it('[ADR-0159 D7] the form body at the `view` door is refused at `viewKind`, with the `form` prescription and not the container\'s', async () => { const { protocol, rows } = makeProtocol(); - const item: any = pickerReproView(); - delete item.config.sections[0].fields[0].keyField.sort; - const result = await save(protocol, item, 'lead.contact'); + const err = await rejection(save(protocol, pickerReproView(), 'lead.contact')); - expect(result.success).toBe(true); - expect(rows.size).toBe(1); + expect([err.code, err.status]).toEqual(['INVALID_METADATA', 422]); + expect(rows.size).toBe(0); + const atKind = err.issues.find((i: any) => i.path === 'viewKind'); + expect(atKind, 'an issue located at `viewKind`').toBeDefined(); + expect(atKind.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D7\)/); + expect(err.message).not.toContain('belongs to a single VIEW, not to the container'); + expect(JSON.stringify(err.issues)).not.toContain('this view container'); + }); + + it('[ADR-0159 D7] the same form at the `form` door: `sort` reaches the author at its own path', async () => { + const { protocol, rows } = makeProtocol(); + + const err = await rejection(save(protocol, pickerReproForm(), 'lead.contact', 'form')); + + expect([err.code, err.status]).toEqual(['INVALID_METADATA', 422]); + expect(rows.size).toBe(0); + const unknownKey = err.issues[0]; + expect(unknownKey.code).toBe('unrecognized_keys'); + expect(unknownKey.message).toContain('`sort`'); + expect(unknownKey.path).toBe('sections.0.fields.0.keyField'); + }); + + it('the same item minus the bad subkey still saves', async () => { + // Each repro at its own door: the list as a `view`, the form as a `form`. + const list: any = listReproView(); + delete list.config.pagination.sort; + const form: any = pickerReproForm(); + delete form.sections[0].fields[0].keyField.sort; + + for (const [item, name, type] of [[list, 'lead.all', 'view'], [form, 'lead.contact', 'form']] as const) { + const { protocol, rows } = makeProtocol(); + const result = await save(protocol, item, name, type); + expect(result.success, `${type}/${name}`).toBe(true); + expect(rows.size).toBe(1); + } }); it('a genuine container failure keeps the container prescription', async () => { @@ -601,7 +658,8 @@ describe('#20230 a flattened overlay carrying a retired owner/hidden is refused it('READ PATH: `getMetaItem` serves a stored overlay without `owner` / `hidden` — valid with content, invalid when hide-only', async () => { const { protocol } = makeProtocol([ { type: 'view', name: 'task_list', metadata: { name: 'task_list', ...BOUND_LIST, isDefault: true, order: 2, owner: 'usr_7', hidden: true } }, - { type: 'view', name: 'task_hidden', metadata: { name: 'task_hidden', ...BOUND_FORM, hidden: true } }, + { type: 'view', name: 'task_hidden', metadata: { name: 'task_hidden', ...BOUND_LIST, hidden: true } }, + { type: 'view', name: 'task_entry_hidden', metadata: { name: 'task_entry_hidden', ...BOUND_FORM, hidden: true } }, ]); const content = (await protocol.getMetaItem({ type: 'view', name: 'task_list' })).item; @@ -615,15 +673,28 @@ describe('#20230 a flattened overlay carrying a retired owner/hidden is refused expect(hideOnly).not.toHaveProperty('hidden'); expect(hideOnly._diagnostics?.valid).toBe(false); expect(JSON.stringify(hideOnly._diagnostics)).toContain('only identity fields'); + + // [ADR-0159 D7] A `view` read serves lists only: the stored hide-only + // FORM overlay is left out of the by-name answer, and the row stays. + const formOverlay = await protocol.getMetaItem({ type: 'view', name: 'task_entry_hidden' }); + expect(formOverlay.item).toBeUndefined(); }); - it('CONTROL: the same bound overlays without the keys still save, one row each', async () => { - for (const bound of [BOUND_LIST, BOUND_FORM]) { - const { protocol, rows } = makeProtocol(); - const result = await save(protocol, { name: 'task_list', ...bound, isDefault: true, order: 2 }); - expect(result.success).toBe(true); - expect(rows.size).toBe(1); - } + it('CONTROL: the same bound list overlay without the keys still saves, one row', async () => { + const { protocol, rows } = makeProtocol(); + const result = await save(protocol, { name: 'task_list', ...BOUND_LIST, isDefault: true, order: 2 }); + expect(result.success).toBe(true); + expect(rows.size).toBe(1); + }); + + it('[ADR-0159 D7] the same bound FORM overlay without the keys is refused at `viewKind`, and persists nothing', async () => { + const { protocol, rows } = makeProtocol(); + const err = await rejection(save(protocol, { name: 'task_list', ...BOUND_FORM, isDefault: true, order: 2 })); + expect([err.code, err.status]).toEqual(['INVALID_METADATA', 422]); + expect(rows.size).toBe(0); + const atKind = err.issues.find((i: any) => i.path === 'viewKind'); + expect(atKind, 'an issue located at `viewKind`').toBeDefined(); + expect(atKind.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D7\)/); }); }); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index b0eff0aac4b..d1940dd2e22 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -588,6 +588,8 @@ import { getMetaItems, getMetaItemsForExecution, getMetaItemsPerPackage, + getServedMetaItem, + getViewItemsWithStoredForms, readFlattenedMetaItems, } from './protocol-meta-list-reads.js'; // [#25467 E2 cut 1b] The metadata item reads and the layered reads. @@ -3050,7 +3052,7 @@ export class ObjectStackProtocolImplementation implements return ProtocolDiscoveryAndBasesFacet.getPackagedMappingBase(protocolHost(this), name); } - /** Contract: the shared docblock on {@link getPackagedPageBase}; [ADR-0159 D5] an old-shape base's form is its projection. */ + /** Contract: the shared docblock on {@link getPackagedPageBase}; [ADR-0159 D7] the base is the package's authored `form` item. */ getPackagedFormBase(name: string): unknown { return ProtocolDiscoveryAndBasesFacet.getPackagedFormBase(protocolHost(this), name); } @@ -3532,6 +3534,23 @@ export class ObjectStackProtocolImplementation implements return getMetaItemsPerPackage(protocolHost(this), request); } + /** + * [ADR-0159 D7] The `view` list {@link getMetaItems} serves, WITH the form + * items of the stored old-shape rows it leaves out: a `view` read serves + * lists only since protocol 19, and a stored old-shape row is neither + * rewritten nor dropped by a read. A server-only extension, kept for one + * reader: **the anonymous form doors' withdrawal judgement** + * (`form-routes.ts` in `@objectstack/rest`), which reads every body the + * doors honoured (ADR-0159 D6 rule 10, the kept reader) and is never judged + * against a narrower layer than this one. + * + * ⛔ Never call this from a door that serves a caller a document: every + * such door serves {@link getMetaItems}. + */ + async getViewItemsWithStoredForms(request: { packageId?: string; previewDrafts?: boolean } = {}) { + return getViewItemsWithStoredForms(protocolHost(this), request); + } + /** Contract: {@link readUnreadableFormBodies} [ADR-0159 D6 rule 7]; a server-only extension the anonymous form doors feature-detect. */ async getUnreadableFormBodies(): Promise { return readUnreadableFormBodies(protocolHost(this)); @@ -4145,7 +4164,8 @@ export class ObjectStackProtocolImplementation implements userTextLocales?: readonly string[], }) { // [#25467 E1] The body moved to `protocol-meta-item-reads.ts`; it reaches this class through `protocol-host.ts`. - return getMetaItem(protocolHost(this), request); + // [ADR-0159 D7] A `view` read serves lists only, in every state it serves (`getServedMetaItem`). + return getServedMetaItem(protocolHost(this), request); } /** @@ -8291,7 +8311,9 @@ export class ObjectStackProtocolImplementation implements * under the copy's name ({@link shippedViewContainerOf}), bound to the * same object. The loaders registered that container's views under * `.` for that package, so the copy's names are that - * package's, and the copy expands to them. + * package's, and the copy expands to them. [ADR-0159 D7] So is a copy one + * of whose form members is a `form` item the package ships under that + * name, bound to the same object. */ private copiesOwnShippedViewContainer( type: string, @@ -8301,6 +8323,7 @@ export class ObjectStackProtocolImplementation implements ): boolean { // [#25467 cut 33] The body moved to `protocol-registry-view-predicates.ts` (see `RegistryViewPredicatesHost`). const host: ThisParameterType = { + lookupArtifactItem: (...a) => this.lookupArtifactItem(...a), runtimeViewContainerObject: (...a) => this.runtimeViewContainerObject(...a), shippedViewContainerOf: (...a) => this.shippedViewContainerOf(...a), }; @@ -8354,6 +8377,10 @@ export class ObjectStackProtocolImplementation implements * * A container with no name of its own has nothing to expand under, and * expands nothing. + * + * [ADR-0159 D7] One exception: from protocol 19 a stored row is read + * under the name its package's form is served under + * (`formMembersAPackageShips` in `protocol-view-expansion-names.ts`). */ private expandUnderOwnName( type: string, @@ -8364,6 +8391,7 @@ export class ObjectStackProtocolImplementation implements // [#25467 cut 22] The body moved to `protocol-view-expansion-names.ts` (see `ViewExpansionNamesHost`). const host: ThisParameterType = { isShippedByAnotherPackage: (...a) => this.isShippedByAnotherPackage(...a), + shippedArtifactsOf: (...a) => this.shippedArtifactsOf(...a), }; return expandUnderOwnName.call(host, type, object, container, ownPackageId); } diff --git a/packages/metadata-protocol/src/protocol.ui-view-response-conformance.test.ts b/packages/metadata-protocol/src/protocol.ui-view-response-conformance.test.ts index 5faf80579d6..cc808b69747 100644 --- a/packages/metadata-protocol/src/protocol.ui-view-response-conformance.test.ts +++ b/packages/metadata-protocol/src/protocol.ui-view-response-conformance.test.ts @@ -26,8 +26,21 @@ // version of this test that can fail when the producer drifts. import { describe, it, expect } from 'vitest'; -import { GetUiViewResponseSchema } from '@objectstack/spec/api'; +import { z } from 'zod'; +import { GetUiViewResponseSchema, type GetUiViewFormScaffold } from '@objectstack/spec/api'; +import { FormViewSchema } from '@objectstack/spec/ui'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// The protocol reaches `@objectstack/lint` only through a dynamic import; paid +// here at module scope so the first load lands during collection, not inside a +// clocked window (`pnpm check:test-source-alias`). +import '@objectstack/lint'; + +/** + * [ADR-0159 D7] The `type: 'form'` answer, `GetUiViewFormScaffold`: a view + * holds lists only since @objectstack/spec 19, so the form scaffold is not a + * `ViewSchema` and is parsed here against the form body schema it carries. + */ +const FormScaffoldSchema = z.strictObject({ object: z.string(), form: FormViewSchema }); const SCHEMA = { name: 'account', @@ -65,13 +78,41 @@ describe('[#5948] getUiView emits a body that satisfies its own declared schema' expect(parsed.success).toBe(true); }); - it('form branch parses GREEN against GetUiViewResponseSchema', async () => { + it('form branch parses GREEN as the form scaffold: `{ object, form }`, its `form` a form body', async () => { const p = protocolFor(); const body = await p.getUiView({ object: 'account', type: 'form' }); - const parsed = GetUiViewResponseSchema.safeParse(body); + const parsed = FormScaffoldSchema.safeParse(body); expect(explain(parsed)).toBe('GREEN'); expect(parsed.success).toBe(true); + // …and it is not a view: `ViewSchema.form` is retired in protocol 19. + expect(GetUiViewResponseSchema.safeParse(body).success).toBe(false); + }); + + it('the form answer is byte-equal to the protocol-18 answer', async () => { + const p = protocolFor(); + const body = await p.getUiView({ object: 'account', type: 'form' }); + const field = (name: string, label: unknown, type: string, required?: boolean, colSpan = 1) => ({ + field: name, label, required, readonly: undefined, type, colSpan, span: 'auto', + }); + const expected: GetUiViewFormScaffold = { + object: 'account', + form: { + type: 'simple', + sections: [{ + label: 'General Information', + columns: 2, + collapsible: false, + collapsed: false, + fields: [ + field('name', 'Name', 'text', true), + field('status', 'Status', 'text'), + field('notes', 'Notes', 'textarea', undefined, 2), + ] as any, + }], + }, + }; + expect(JSON.stringify(body)).toBe(JSON.stringify(expected)); }); // The three keys this issue removed, pinned by name. The GREEN assertions diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.public-form-intake.test.ts b/packages/metadata-protocol/src/runtime-authoring-gate.public-form-intake.test.ts index aa14f0c0ba7..7ebab0cffe8 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.public-form-intake.test.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.public-form-intake.test.ts @@ -5,11 +5,15 @@ * posture cannot take anonymous intake for. * * Both anonymous form doors withhold such a form, and the administrator's read - * of the view states why (`@objectstack/rest`). This is the publish half: the + * of the form states why (`@objectstack/rest`). This is the publish half: the * author who saves or publishes the form is told on the 2xx, as ONE `warning` * advisory located at the form's `sharing` and carrying the admin read's * reason — the same `@objectstack/metadata-core` export, so the same bytes. * + * [ADR-0159 D7] From protocol 19 a form is a `form` item and a `view` holds + * lists only, so the advisory judges `form` writes alone: a `view` body that + * holds a form is refused at the spec parse the save door runs first. + * * Harness: none. `evaluateRuntimeAuthoringGate` is pure — the posture in force * and the object universe arrive as arguments. The end-to-end rows through * `saveMetaItem` / `publishMetaItem` and a real `tenancy` service are in @@ -41,25 +45,23 @@ const inquiry = (extra: Record = {}) => ({ ...extra, }); -/** The showcase's contact form: a container whose public form is `formViews.contact`. */ -const contactContainer = (sharing: Record = SHARING) => ({ - list: { type: 'grid', data: { provider: 'object', object: 'showcase_inquiry' }, columns: [{ field: 'name' }] }, - formViews: { - contact: { - type: 'simple', - data: { provider: 'object', object: 'showcase_inquiry' }, - sections: [{ name: 'about', fields: [{ field: 'name' }, { field: 'email' }] }], - sharing, - }, - }, +const FORM = 'showcase_inquiry.contact'; + +/** The showcase's contact form, as protocol 19 ships it: a `form` item named `OBJECT.KEY`. */ +const contactForm = (sharing: Record = SHARING) => ({ + name: FORM, + object: 'showcase_inquiry', + type: 'simple', + sections: [{ name: 'about', fields: [{ field: 'name' }, { field: 'email' }] }], + sharing, }); const judge = (over: Partial[0]> = {}) => evaluateRuntimeAuthoringGate({ - type: 'view', - name: 'showcase_inquiry', + type: 'form', + name: FORM, state: 'active', - body: contactContainer(), + body: contactForm(), objects: [inquiry()], tenancyPostureInForce: 'isolated', ...over, @@ -78,20 +80,25 @@ describe('#21476 — public-form intake advisory (pure gate)', () => { expect(verdict.advisories[0]).toEqual({ severity: 'warning', rule: PUBLIC_FORM_INTAKE_UNAVAILABLE, - where: `view "showcase_inquiry" · public form "/forms/${SLUG}"`, - path: 'views[0].formViews.contact.sharing', + where: `form "${FORM}" · public form "/forms/${SLUG}"`, + path: 'forms[0].sharing', message: anonymousFormIntakeUnavailableMessage(SLUG, facts), hint: anonymousFormIntakeUnavailableRemedy(facts), }); }); } - it('locates each form shape at its own sharing: nested form, flattened form item', () => { - const nested = { form: { data: { object: 'showcase_inquiry' }, sharing: SHARING } }; - expect(intakeAdvisories(judge({ body: nested })).map((a) => a.path)).toEqual(['views[0].form.sharing']); - const flat = { name: 'showcase_inquiry.contact', viewKind: 'form', object: 'showcase_inquiry', config: { sharing: SHARING } }; - expect(intakeAdvisories(judge({ name: 'showcase_inquiry.contact', body: flat })).map((a) => a.path)) - .toEqual(['views[0].config.sharing']); + it('[ADR-0159 D7] judges form writes only: the old view shapes of the same open form raise nothing', () => { + // The shapes a `view` held a form in before protocol 19: the save door + // refuses each at its spec parse, so none reaches this gate on a save. + const shapes = [ + { formViews: { contact: { data: { object: 'showcase_inquiry' }, sharing: SHARING } } }, + { form: { data: { object: 'showcase_inquiry' }, sharing: SHARING } }, + { name: FORM, viewKind: 'form', object: 'showcase_inquiry', config: { sharing: SHARING } }, + ]; + for (const body of shapes) expect(intakeAdvisories(judge({ type: 'view', body })), JSON.stringify(body)).toEqual([]); + // Control: the same form as a `form` item is judged. + expect(intakeAdvisories(judge()).map((a) => a.path)).toEqual(['forms[0].sharing']); }); it('a pending object in the same batch is judged by its EFFECTIVE schema (no declared organization_id)', () => { @@ -104,9 +111,9 @@ describe('#21476 — public-form intake advisory (pure gate)', () => { ['an object declared tenancy: { enabled: false }', { objects: [inquiry({ tenancy: { enabled: false } })] }], ["the 'single' posture (a degraded walled request reads single in force)", { tenancyPostureInForce: 'single' }], ['no tenancy service (no posture in force)', { tenancyPostureInForce: undefined }], - ['a form withdrawn from anonymous intake', { body: contactContainer({ ...SHARING, allowAnonymous: false }) }], + ['a form withdrawn from anonymous intake', { body: contactForm({ ...SHARING, allowAnonymous: false }) }], ['a draft save (drafts are never gated, #4463 D1)', { state: 'draft' }], - ['a non-view write', { type: 'page', body: { name: 'landing', kind: 'html', source: '
' } }], + ['a non-form write', { type: 'page', body: { name: 'landing', kind: 'html', source: '
' } }], ])('CONTROL — %s: no advisory', (_label, over) => { const verdict = judge(over); expect(verdict.error).toBeNull(); @@ -117,10 +124,11 @@ describe('#21476 — public-form intake advisory (pure gate)', () => { expect(intakeAdvisories(judge({ orgWallEnforced: true, tenancyPostureInForce: 'single' }))).toEqual([]); }); - it('a refused view write discloses the rule among the rules that ran', () => { + it('[ADR-0159 D7] a refused view write does not list the rule among the rules that ran: it judges form writes only', () => { // A flattened list overlay sorting by a field the object does not have: // refused by the shared sort rule, so the verdict carries `rulesRun`. const verdict = judge({ + type: 'view', name: 'showcase_inquiry.custom', body: { name: 'showcase_inquiry.custom', object: 'showcase_inquiry', viewKind: 'list', type: 'grid', @@ -129,6 +137,7 @@ describe('#21476 — public-form intake advisory (pure gate)', () => { }); const err = verdict.error as { code?: string; status?: number; rulesRun?: string[] } | null; expect([err?.code, err?.status]).toEqual(['INVALID_METADATA', 422]); - expect(err?.rulesRun).toContain(PUBLIC_FORM_INTAKE_UNAVAILABLE); + expect(err?.rulesRun?.length).toBeGreaterThan(0); + expect(err?.rulesRun).not.toContain(PUBLIC_FORM_INTAKE_UNAVAILABLE); }); }); diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.ts b/packages/metadata-protocol/src/runtime-authoring-gate.ts index 8427b404abe..34926a44852 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.ts @@ -81,17 +81,14 @@ import type { IObjectQLEngine } from '@objectstack/spec/contracts'; import { findHierarchyScopeGrants, type TenancyPosture } from '@objectstack/spec/security'; // [#21476] The ONE answer to "can this open public form take anonymous intake // on this posture, and why not" — the same export both anonymous form doors and -// the administrator's read of the view call (`@objectstack/rest`), so the +// the administrator's read of the form call (`@objectstack/rest`), so the // advisory below is raised exactly when the doors withhold the form, at the // location and in the words the admin read uses. import { - anonymousFormIntakeCandidates, anonymousFormIntakeSlug, anonymousFormIntakeUnavailability, anonymousFormIntakeUnavailableMessage, anonymousFormIntakeUnavailableRemedy, - anonymousFormObjectName, - anonymousFormSharingPath, // [#29025] The one judge of an undeclared flow cycle (ADR-0044), the // function the engine's registration calls. findUndeclaredFlowCycle, @@ -423,17 +420,23 @@ export function findPlatformScheduleOrgGaps(args: { export const PUBLIC_FORM_INTAKE_UNAVAILABLE = 'public-form-intake-unavailable'; /** - * Judge one about-to-be-published `view` body: one `warning` per open public - * form whose object cannot take anonymous intake on `tenancyPostureInForce`. + * Judge one about-to-be-published `form` body: one `warning` when it is an + * open public form whose object cannot take anonymous intake on + * `tenancyPostureInForce`. * * PURE — the posture arrives as an argument and the object schemas come from * the resolution universe the gate already holds (`objects`, the live universe * plus this batch's pending drafts). It reads no service, no store and no * environment. * - * The location is the form's `sharing` as `anonymousFormSharingPath` places it, - * under the write's own root: a `view` write is the sole member of its - * snapshot collection, so `views[0]` IS this write (`RuntimeAuthoringIssue.path`). + * The location is the form's `sharing` under the write's own root: a `form` + * write is the sole member of its snapshot collection, so `forms[0]` IS this + * write (`RuntimeAuthoringIssue.path`). + * + * [ADR-0159 D7] Only a `form` write is judged. From protocol 19 a `view` holds + * lists only, and a `view` body that holds a form is refused at the spec parse + * the save door runs before this gate, so no `view` write reaches here with a + * form to judge. */ export function findPublicFormIntakeGaps(args: { /** Singular metadata type of the item being written. */ @@ -448,55 +451,27 @@ export function findPublicFormIntakeGaps(args: { tenancyPostureInForce?: TenancyPosture; }): RuntimeAuthoringIssue[] { if (!isRec(args.body)) return []; - // [ADR-0159 D6 rule 9] A `form` write is judged as the same form in a - // `view` write is: the form itself is its one candidate, at `forms[0]`. - if (args.type === 'form') { - const form = args.body; - const slug = anonymousFormIntakeSlug(form.sharing); - const object = typeof form.object === 'string' && form.object ? form.object : undefined; - if (slug === null || object === undefined) return []; - const unavailable = anonymousFormIntakeUnavailability( - object, - args.tenancyPostureInForce, - (): unknown => args.objects.find((o) => isRec(o) && o.name === object), - ); - if (!unavailable) return []; - const formName = typeof form.name === 'string' && form.name ? form.name : args.name; - return [{ - severity: 'warning', - rule: PUBLIC_FORM_INTAKE_UNAVAILABLE, - where: `form "${formName}" · public form "/forms/${slug}"`, - path: 'forms[0].sharing', - message: anonymousFormIntakeUnavailableMessage(slug, unavailable), - hint: anonymousFormIntakeUnavailableRemedy(unavailable), - }]; - } - if (args.type !== 'view') return []; - const view = args.body; - const candidates = anonymousFormIntakeCandidates(view); - if (candidates.length === 0) return []; - - const viewName = typeof view.name === 'string' && view.name ? view.name : args.name; - const issues: RuntimeAuthoringIssue[] = []; - for (const candidate of candidates) { - const object = anonymousFormObjectName(view, candidate.form); - if (!object) continue; - const unavailable = anonymousFormIntakeUnavailability( - object, - args.tenancyPostureInForce, - (): unknown => args.objects.find((o) => isRec(o) && o.name === object), - ); - if (!unavailable) continue; - issues.push({ - severity: 'warning', - rule: PUBLIC_FORM_INTAKE_UNAVAILABLE, - where: `view "${viewName}" · public form "/forms/${candidate.slug}"`, - path: `views[0].${anonymousFormSharingPath(view, candidate)}`, - message: anonymousFormIntakeUnavailableMessage(candidate.slug, unavailable), - hint: anonymousFormIntakeUnavailableRemedy(unavailable), - }); - } - return issues; + // [ADR-0159 D6 rule 9] The form itself is its one candidate, at `forms[0]`. + if (args.type !== 'form') return []; + const form = args.body; + const slug = anonymousFormIntakeSlug(form.sharing); + const object = typeof form.object === 'string' && form.object ? form.object : undefined; + if (slug === null || object === undefined) return []; + const unavailable = anonymousFormIntakeUnavailability( + object, + args.tenancyPostureInForce, + (): unknown => args.objects.find((o) => isRec(o) && o.name === object), + ); + if (!unavailable) return []; + const formName = typeof form.name === 'string' && form.name ? form.name : args.name; + return [{ + severity: 'warning', + rule: PUBLIC_FORM_INTAKE_UNAVAILABLE, + where: `form "${formName}" · public form "/forms/${slug}"`, + path: 'forms[0].sharing', + message: anonymousFormIntakeUnavailableMessage(slug, unavailable), + hint: anonymousFormIntakeUnavailableRemedy(unavailable), + }]; } // ───────────────────────────────────────────────────────────────────────────── @@ -1745,7 +1720,7 @@ export function evaluateRuntimeAuthoringGate(args: { const rulesRun = [ ...result.rulesRun, ...(args.type === 'flow' ? [FLOW_UNDECLARED_CYCLE, PLATFORM_SCHEDULE_CREATE_RECORD_ORG_MISSING] : []), - ...(args.type === 'view' || args.type === 'form' ? [PUBLIC_FORM_INTAKE_UNAVAILABLE] : []), + ...(args.type === 'form' ? [PUBLIC_FORM_INTAKE_UNAVAILABLE] : []), ...(args.type === 'permission' && args.hierarchyResolverMounted !== undefined ? [HIERARCHY_SCOPE_CAPABILITY_REQUIRED] : []), diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index a42882bb862..f6c9f42fb96 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -103,6 +103,7 @@ import type { MetadataAuthoringClient, MetadataAuthoringSurface } from '@objects // the stored form, one module the strict draft read reads it back through. import { draftChangedPaths, mergeDraftChanges, storedDraftChanges, type DraftChangeStamp } from './draft-changes.js'; import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; +import { legacyOrganizationRowsRead } from './protocol-legacy-organization-rows.js'; /** * Canonicalise a driver-materialised timestamp into the ISO-8601 string the @@ -2606,11 +2607,10 @@ export class SysMetadataRepository implements MetadataRepository { return legacy.size === 0 ? rows : rows.filter((row) => !legacy.has(String((row as { id?: unknown }).id))); } - /** Inside a write, the statements join its transaction (`context.transaction`). */ + /** Inside a write, the statements join its transaction: `context.transaction`, else the engine's ambient one ({@link legacyOrganizationRowsRead}). */ private async legacyOrganizationRowIds(context?: Record): Promise> { - const driver = (this.engine as { getDriverForObject?: (objectName: string) => unknown }).getDriverForObject?.('sys_metadata'); - const transaction = (context as { transaction?: unknown } | undefined)?.transaction; - return new Set((await readLegacyOrganizationRows(driver, 'sys_metadata', transaction !== undefined ? { transaction } : {})).keys()); + const { driver, options } = legacyOrganizationRowsRead(this.engine, 'sys_metadata', context); + return new Set((await readLegacyOrganizationRows(driver, 'sys_metadata', options)).keys()); } private assertOpen(): void { diff --git a/packages/metadata-protocol/src/view-container-runtime-expansion.test.ts b/packages/metadata-protocol/src/view-container-runtime-expansion.test.ts index 2af582d2205..f90c0b256a6 100644 --- a/packages/metadata-protocol/src/view-container-runtime-expansion.test.ts +++ b/packages/metadata-protocol/src/view-container-runtime-expansion.test.ts @@ -448,11 +448,17 @@ describe('#21334 a container on another package\'s object never takes that packa listViews: { in_progress: { label: 'In Progress', type: 'grid', data, columns: PACKAGED_COLUMNS.slice(0, 4) }, }, - form: { type: 'simple', sections: [{ label: 'Main', fields: ['title'] }] }, - formViews: { - edit: { type: 'tabbed', sections: [{ label: 'Edit', fields: ['title', 'status'] }] }, - }, }; + /** + * [ADR-0159] …and its forms, as protocol 19 ships them: `form` items named + * `OBJECT.KEY`, the names a container's `form` / `formViews.edit` were + * served under before 19. A stored old-shape container's form member + * still aims at these names, so the form probes below aim at them. + */ + const PACKAGED_FORMS = [ + { name: `${TASK}.form`, object: TASK, type: 'simple', sections: [{ label: 'Main', fields: ['title'] }] }, + { name: `${TASK}.edit`, object: TASK, type: 'tabbed', sections: [{ label: 'Edit', fields: ['title', 'status'] }] }, + ]; const PACKAGED = expandViewContainer(TASK, packagedTaskViews).map((vi) => ({ ...(vi as any) })); /** The card's own probe body, verbatim. */ const probe = (name: string) => ({ name, object: TASK, list: { type: 'grid', columns: ['title', 'status'] } }); @@ -540,6 +546,7 @@ describe('#21334 a container on another package\'s object never takes that packa for (const vi of expandViewContainer(TASK, packagedTaskViews)) { registry.registerItem('view', { ...(vi as any) }, 'name', SHOWCASE); } + for (const form of PACKAGED_FORMS) registry.registerItem('form', { ...form }, 'name', SHOWCASE); stub.engine.registry = registry; const protocol = new ObjectStackProtocolImplementation(stub.engine, undefined, environmentId); return { ...stub, registry, protocol }; @@ -559,7 +566,20 @@ describe('#21334 a container on another package\'s object never takes that packa expect(v?._packageId).toBe(SHOWCASE); expect(v?.isDefault).toBe(true); }; - /** (a) Every name the showcase ships answers the packaged view, once, on BOTH doors — the same row. */ + /** [ADR-0159] The `form` doors: the list read of the object's forms, and the by-name read. */ + const formDoor = async (protocol: Protocol) => + (((await protocol.getMetaItems({ type: 'form' } as any)) as any).items as any[]).filter((f) => f?.object === TASK); + const formByNameDoor = async (protocol: Protocol, name: string) => + ((await protocol.getMetaItem({ type: 'form', name } as any)) as any)?.item; + /** One packaged form, as the showcase ships it, on a `form` door's answer. */ + const expectPackagedForm = (answer: any, shipped: (typeof PACKAGED_FORMS)[number]) => + expect({ name: answer?.name, object: answer?.object, type: answer?.type, sections: answer?.sections, _packageId: answer?._packageId }) + .toEqual({ ...shipped, _packageId: SHOWCASE }); + /** + * (a) Every name the showcase ships answers the packaged item, once, on BOTH + * doors of its type — the same row: its views on the `view` doors, and + * [ADR-0159] its forms on the `form` doors. + */ const expectEveryPackagedNameIntact = async (protocol: Protocol, organizationId?: string) => { const served = await objectDoor(protocol, organizationId); for (const shipped of PACKAGED) { @@ -571,15 +591,25 @@ describe('#21334 a container on another package\'s object never takes that packa expect({ label: read?.label, config: read?.config, _packageId: read?._packageId }) .toEqual({ label: shipped.label, config: shipped.config, _packageId: SHOWCASE }); } + const forms = await formDoor(protocol); + for (const shipped of PACKAGED_FORMS) { + const listed = named(forms, shipped.name); + expect(listed, `exactly one item answers ${shipped.name} on the form door`).toHaveLength(1); + expectPackagedForm(listed[0], shipped); + expectPackagedForm(await formByNameDoor(protocol, shipped.name), shipped); + } }; - /** (c) The object's only defaults are the ones its owning package declares. */ + /** + * (c) The object's only defaults are the ones its owning package declares. + * [ADR-0159] A view is a list: the `view` door serves no form, so no form + * default either (a `form` item carries no `isDefault`). + */ const expectOnlyPackagedDefaults = (served: any[]) => { - for (const viewKind of ['list', 'form']) { - expect( - served.filter((v) => v.viewKind === viewKind && v.isDefault).map((v) => v.name), - `the ${viewKind} default stays the owning package's`, - ).toEqual(PACKAGED.filter((v) => v.viewKind === viewKind && v.isDefault).map((v) => v.name)); - } + expect(served.filter((v) => v.viewKind !== 'list').map((v) => v.name), 'the view door serves lists only').toEqual([]); + expect( + served.filter((v) => v.isDefault).map((v) => v.name), + 'the list default stays the owning package\'s', + ).toEqual(PACKAGED.filter((v) => v.isDefault).map((v) => v.name)); }; /** @@ -647,7 +677,7 @@ describe('#21334 a container on another package\'s object never takes that packa for (const [kind, c] of Object.entries(MEMBER_CASES)) { const names = expandViewContainer(TASK, c.member).map((vi) => vi.name); expect(names, kind).toEqual([c.shadows]); - expect(PACKAGED.map((v) => v.name), kind).toContain(c.shadows); + expect([...PACKAGED, ...PACKAGED_FORMS].map((v) => v.name), kind).toContain(c.shadows); } }); @@ -661,22 +691,113 @@ describe('#21334 a container on another package\'s object never takes that packa // [ADR-0131 D6/D7] No organization-scoped arm: no stored row carries // an organization. ] as { arm: string; packageId: string | undefined; organizationId: string | undefined; ownPackage: string | undefined }[]; - const save = (protocol: Protocol, name: string, item: unknown, c: (typeof CONTAINERS)[number]) => + const saveThroughTheDoor = (protocol: Protocol, name: string, item: unknown, c: (typeof CONTAINERS)[number]) => protocol.saveMetaItem({ type: 'view', name, item, ...(c.packageId ? { packageId: c.packageId } : {}), } as any); + /** Does the body hold a form in one of the slots a `view` held one in before protocol 19? */ + const holdsForm = (item: unknown): boolean => + !!item && typeof item === 'object' && ('form' in item || 'formViews' in item); + /** + * [ADR-0159 D7] The `view` door refuses a container that holds a form: 422 + * `INVALID_METADATA`, the tombstone's prescription naming `forms:` at the + * member's own key, and no row. + */ + const expectFormMemberRefused = async ( + harness: { protocol: Protocol; rows: Map }, name: string, item: Record, + c: { packageId: string | undefined }, mode?: 'draft', + ) => { + const before = harness.rows.size; + const error: any = await harness.protocol.saveMetaItem({ + type: 'view', name, item, ...(c.packageId ? { packageId: c.packageId } : {}), ...(mode ? { mode } : {}), + } as any).then(() => null, (e: unknown) => e); + expect({ code: error?.code, status: error?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + for (const key of ['form', 'formViews'].filter((k) => k in item)) { + const issue = (error.issues as Array<{ path: string; message: string }>).find((i) => i.path === key); + expect(issue, `an issue at \`${key}\` in ${JSON.stringify(error.issues)}`).toBeDefined(); + expect(issue!.message).toContain('was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)'); + expect(issue!.message).toContain('`forms:`'); + } + expect(harness.rows.size, 'a refused save stores nothing').toBe(before); + }; + /** + * A container row as a release before protocol 19 stored it, written + * straight to the store (the way the CONTROL rows below are): the only way + * a container that holds a form reaches a 19 deployment. + */ + const seedStoredContainer = ( + rows: Map, name: string, item: Record, c: { packageId: string | undefined }, + ) => { + rows.set(`${name}|stored|${c.packageId ?? '__nopkg__'}`, { + id: `r_stored_${rows.size + 1}`, type: 'view', name, + package_id: c.packageId ?? null, state: 'active', metadata: JSON.stringify(item), + }); + }; + /** + * Put a container in place for a case. A lists-only container is saved + * through the door. One that holds a form is first refused by the door + * ({@link expectFormMemberRefused}) and then seeded as the stored old-shape + * row it can only be on protocol 19 ({@link seedStoredContainer}). + */ + const save = async ( + harness: { protocol: Protocol; rows: Map }, name: string, item: Record, + c: (typeof CONTAINERS)[number], + ) => { + if (!holdsForm(item)) return saveThroughTheDoor(harness.protocol, name, item, c); + await expectFormMemberRefused(harness, name, item, c); + seedStoredContainer(harness.rows, name, item, c); + return { success: true }; + }; + + /** + * [ADR-0159 D7] What protocol 19 answers for the form member of a STORED + * old-shape container on another package's object: the member is served + * under no name on any door (not the name it would take from its own + * container, on the `view` doors or the `form` doors), and the name it + * aims at still answers the form the owning package ships. The container's + * own row is read whole by name, the member as stored. + */ + const expectStoredFormMemberServesNothing = async ( + protocol: Protocol, m: (typeof MEMBER_CASES)[string], ownPackage: string | undefined, + ) => { + const views = await objectDoor(protocol); + expect(views.filter((v) => String(v.name).startsWith(`${TASK}.${OWN}`)), 'no view of the container\'s own name').toEqual([]); + expect(await byNameDoor(protocol, m.servedAs), `${m.servedAs} answers no view`).toBeUndefined(); + const forms = await formDoor(protocol); + expect(forms.map((f) => f.name).sort(), 'the form door lists the packaged forms and nothing else') + .toEqual(PACKAGED_FORMS.map((f) => f.name).sort()); + expect(forms.filter((f) => f._packageId !== SHOWCASE), 'no form of another package').toEqual([]); + expect(await formByNameDoor(protocol, m.servedAs), `${m.servedAs} answers no form`).toBeUndefined(); + expectPackagedForm(await formByNameDoor(protocol, m.shadows), PACKAGED_FORMS.find((f) => f.name === m.shadows)!); + const row = await byNameDoor(protocol, OWN); + expect(row?.name).toBe(OWN); + expect(row?.object).toBe(TASK); + expect(row?._packageId).toBe(ownPackage); + for (const key of Object.keys(m.member)) expect(row?.[key], `the stored container carries ${key}`).toEqual(m.member[key]); + }; for (const [kernel, environmentId] of KERNELS) { describe(`on ${kernel}`, () => { for (const c of CONTAINERS) { for (const [kind, m] of Object.entries(MEMBER_CASES)) { - it(`${c.arm}, member ${kind}: no packaged name is replaced on either door, its own name is served with its own package, and it claims no default`, async () => { - const { protocol } = showcaseHarness(environmentId); - await save(protocol, OWN, { name: OWN, object: TASK, ...m.member }, c); + const what = holdsForm(m.member) + ? 'the door refuses it; as a stored row no packaged name is replaced on any door, and the member is served under no name' + : 'no packaged name is replaced on either door, its own name is served with its own package, and it claims no default'; + it(`${c.arm}, member ${kind}: ${what}`, async () => { + const harness = showcaseHarness(environmentId); + const { protocol } = harness; + await save(harness, OWN, { name: OWN, object: TASK, ...m.member }, c); // (a) await expectEveryPackagedNameIntact(protocol, c.organizationId); + if (holdsForm(m.member)) { + // (b), protocol 19: a stored form member takes no name at all. + await expectStoredFormMemberServesNothing(protocol, m, c.ownPackage); + // (c) + expectOnlyPackagedDefaults(await objectDoor(protocol, c.organizationId)); + return; + } // (b) const served = await objectDoor(protocol, c.organizationId); const own = served.filter((v) => String(v.name).startsWith(`${TASK}.${OWN}`)); @@ -696,8 +817,9 @@ describe('#21334 a container on another package\'s object never takes that packa } it(`${c.arm}: the card's probe — the packaged default unchanged on BOTH doors, and the object keeps ONE list default`, async () => { - const { protocol } = showcaseHarness(environmentId); - await save(protocol, 'os_qa_shadow_probe', probe('os_qa_shadow_probe'), c); + const harness = showcaseHarness(environmentId); + const { protocol } = harness; + await save(harness, 'os_qa_shadow_probe', probe('os_qa_shadow_probe'), c); const listed = named(await objectDoor(protocol, c.organizationId), DEFAULT); expect(listed, 'exactly one item answers .default on the object door').toHaveLength(1); @@ -834,11 +956,16 @@ describe('#21334 a container on another package\'s object never takes that packa for (const c of CONTAINERS) { for (const [kind, m] of Object.entries(MEMBER_CASES)) { it(`${c.arm}, member ${kind}: every name the object door lists answers that same item by name`, async () => { - const { protocol } = showcaseHarness(environmentId); - await save(protocol, OWN, { name: OWN, object: TASK, ...m.member }, c); + const harness = showcaseHarness(environmentId); + const { protocol } = harness; + await save(harness, OWN, { name: OWN, object: TASK, ...m.member }, c); const served = await objectDoor(protocol, c.organizationId); - expect(ownNames(served).map((v) => v.name), 'the expanded name is listed').toEqual([m.servedAs]); + // [ADR-0159] A stored form member is listed under no name, + // and by name it answers nothing: the doors still agree. + expect(ownNames(served).map((v) => v.name), 'the expanded name is listed') + .toEqual(holdsForm(m.member) ? [] : [m.servedAs]); + if (holdsForm(m.member)) await expectStoredFormMemberServesNothing(protocol, m, c.ownPackage); for (const listed of served) { const read = await byNameDoor(protocol, listed.name, c.organizationId); expect(withoutDiagnostics(read), `${listed.name} by name`).toEqual(withoutDiagnostics(listed)); @@ -852,9 +979,10 @@ describe('#21334 a container on another package\'s object never takes that packa } it(`${c.arm}: the layers name the container and its scope; history and diff resolve to the container's own row`, async () => { - const { protocol } = showcaseHarness(environmentId); + const harness = showcaseHarness(environmentId); + const { protocol } = harness; const member = MEMBER_CASES['listViews.*']; - await save(protocol, OWN, { name: OWN, object: TASK, ...member.member }, c); + await save(harness, OWN, { name: OWN, object: TASK, ...member.member }, c); const expanded = member.servedAs; const layered = await layers(protocol, expanded, c.organizationId); @@ -886,8 +1014,9 @@ describe('#21334 a container on another package\'s object never takes that packa }); it(`${c.arm}: the reads persist and register nothing, and a name nothing expands still answers nothing`, async () => { - const { protocol, rows, registry } = showcaseHarness(environmentId); - await save(protocol, OWN, { name: OWN, object: TASK, ...MEMBER_CASES['listViews.*'].member }, c); + const harness = showcaseHarness(environmentId); + const { protocol, rows, registry } = harness; + await save(harness, OWN, { name: OWN, object: TASK, ...MEMBER_CASES['listViews.*'].member }, c); const rowsBefore = JSON.stringify([...rows.keys()].sort()); const registryBefore = registrySnapshot(registry); @@ -941,9 +1070,15 @@ describe('#21334 a container on another package\'s object never takes that packa for (const [kind, m] of Object.entries(MEMBER_CASES)) { const answers = []; for (const [, environmentId] of KERNELS) { - const { protocol } = showcaseHarness(environmentId); - await save(protocol, OWN, { name: OWN, object: TASK, ...m.member }, c); - answers.push(withoutDiagnostics(await byNameDoor(protocol, m.servedAs, c.organizationId))); + const harness = showcaseHarness(environmentId); + const { protocol } = harness; + await save(harness, OWN, { name: OWN, object: TASK, ...m.member }, c); + // [ADR-0159] A stored form member answers no name: the + // kernels are compared on the container's own row. + answers.push(withoutDiagnostics( + await byNameDoor(protocol, holdsForm(m.member) ? OWN : m.servedAs, c.organizationId), + )); + if (holdsForm(m.member)) expect(await byNameDoor(protocol, m.servedAs, c.organizationId)).toBeUndefined(); } expect(answers[0], `${c.arm}, member ${kind}`).toBeTruthy(); expect(answers[1], `${c.arm}, member ${kind}`).toEqual(answers[0]); @@ -1092,8 +1227,9 @@ describe('#21334 a container on another package\'s object never takes that packa it(`${c.arm}, member ${kind}: the expanded view is not resettable and has no code layer, on both kernels alike`, async () => { const answers = []; for (const [, environmentId] of KERNELS) { - const { protocol } = showcaseHarness(environmentId); - await save(protocol, OWN, { name: OWN, object: TASK, ...m.member }, c); + const harness = showcaseHarness(environmentId); + const { protocol } = harness; + await save(harness, OWN, { name: OWN, object: TASK, ...m.member }, c); const a = await answer(protocol, m.servedAs); expect(a.resettable, `${kernelName(environmentId)}: no package ships it`).toBe(false); expect(a.code, `${kernelName(environmentId)}: no artifact, so no code layer`).toBeNull(); @@ -1104,9 +1240,10 @@ describe('#21334 a container on another package\'s object never takes that packa } it(`${c.arm}: on an unscoped kernel each registered expansion carries its container's tenant marker`, async () => { - const { protocol, registry } = showcaseHarness(undefined); + const harness = showcaseHarness(undefined); + const { registry } = harness; const m = MEMBER_CASES['listViews.*']; - await save(protocol, OWN, { name: OWN, object: TASK, ...m.member }, c); + await save(harness, OWN, { name: OWN, object: TASK, ...m.member }, c); const container = registry.getItem('view', OWN); expect(container?._provenance, 'the container is registered as tenant-authored').toBe('org'); @@ -1127,9 +1264,10 @@ describe('#21334 a container on another package\'s object never takes that packa }; const outcomes = []; for (const [, environmentId] of KERNELS) { - const { protocol, rows } = showcaseHarness(environmentId); - await save(protocol, OWN, { name: OWN, object: TASK, ...m.member }, c); - const saved = (await save(protocol, m.servedAs, byName, c)) as any; + const harness = showcaseHarness(environmentId); + const { protocol, rows } = harness; + await save(harness, OWN, { name: OWN, object: TASK, ...m.member }, c); + const saved = (await save(harness, m.servedAs, byName, c)) as any; const stored = [...rows.values()] .filter((r) => r.name === m.servedAs) .map((r) => ({ package_id: r.package_id, state: r.state, organization: 'organization_id' in r })); @@ -1242,13 +1380,20 @@ describe('#21334 a container on another package\'s object never takes that packa for (const organizationId of [undefined]) { const scope = organizationId ? 'organization-scoped' : 'environment-wide'; for (const [kind, m] of Object.entries(MEMBER_CASES)) { - it(`${scope}, member ${kind}: a container saved under ${m.shadows}, a name its own expansion produces, is refused VALIDATION_ERROR / 400; nothing is stored or registered`, async () => { - const { protocol, rows, registry } = showcaseHarness(environmentId); + const verdict = holdsForm(m.member) + ? 'is refused INVALID_METADATA / 422 with the `forms:` prescription (a view holds lists only)' + : 'is refused VALIDATION_ERROR / 400'; + it(`${scope}, member ${kind}: a container saved under ${m.shadows}, a name its own expansion produces, ${verdict}; nothing is stored or registered`, async () => { + const harness = showcaseHarness(environmentId); + const { protocol, rows, registry } = harness; const body = { name: m.shadows, object: TASK, ...m.member }; expect(expandViewContainer(TASK, body).map((vi) => vi.name), 'the save name is its own expansion\'s') .toEqual([m.shadows]); - expectRefused(await refusalOf(saveIn(protocol, m.shadows, body, organizationId)), m.shadows); + // [ADR-0159 D7] A container that holds a form is refused at + // the parse, before the name check: still refused, still unstored. + if (holdsForm(m.member)) await expectFormMemberRefused(harness, m.shadows, body, { packageId: undefined }); + else expectRefused(await refusalOf(saveIn(protocol, m.shadows, body, organizationId)), m.shadows); expect([...rows.values()].filter((r) => r.type === 'view'), 'no row is stored').toEqual([]); expect( registry.listItems('view').filter((it) => isAggregatedViewContainer(it) && it.name === m.shadows), @@ -1398,17 +1543,42 @@ describe('#21334 a container on another package\'s object never takes that packa const scope = organizationId ? 'organization-scoped' : 'environment-wide'; for (const [kind, member] of Object.entries(FIRST_CASES)) { - it(`${scope}, the first container's member ${kind}: a second container saved under the name it expands is refused VALIDATION_ERROR / 400; nothing is stored or registered, and the first container's view still answers on both doors`, async () => { - const { protocol, rows, registry } = showcaseHarness(environmentId); + const after = holdsForm(member) + ? 'and the stored first container stays whole by name while its form member answers no view and no form' + : 'and the first container\'s view still answers on both doors'; + it(`${scope}, the first container's member ${kind}: a second container saved under the name it expands is refused VALIDATION_ERROR / 400; nothing is stored or registered, ${after}`, async () => { + const harness = showcaseHarness(environmentId); + const { protocol, rows, registry } = harness; const firstBody = { name: FIRST, object: LEAD, ...member }; const [firstView] = expandViewContainer(LEAD, firstBody) as any[]; expect(expandViewContainer(LEAD, firstBody), 'the first container expands one name').toHaveLength(1); const name = String(firstView.name); - await saved(saveIn(protocol, FIRST, firstBody, organizationId)); + if (holdsForm(member)) { + // [ADR-0159 D7] The door refuses a first container that + // holds a form; it stands here as the row a release + // before protocol 19 stored. + await expectFormMemberRefused(harness, FIRST, firstBody, { packageId: undefined }); + seedStoredContainer(rows, FIRST, firstBody, { packageId: undefined }); + } else { + await saved(saveIn(protocol, FIRST, firstBody, organizationId)); + } expectRefused(await refusalOf(saveIn(protocol, name, secondKeyed(name), organizationId)), name, FIRST); expectNothingWritten(rows, registry, [FIRST], name); - await expectServed(protocol, name, organizationId, firstView.label); + if (!holdsForm(member)) { + await expectServed(protocol, name, organizationId, firstView.label); + return; + } + // [ADR-0159] A view holds lists only: the stored first + // container's form member is served under no name, on the + // `view` doors or the `form` doors, and the container's own + // row is read whole by name, the member as stored. + expect(named(await leadDoor(protocol, organizationId), name), `${name} on the object door`).toEqual([]); + expect(await byNameDoor(protocol, name, organizationId), `${name} answers no view`).toBeUndefined(); + expect(await formByNameDoor(protocol, name), `${name} answers no form`).toBeUndefined(); + const row = await byNameDoor(protocol, FIRST, organizationId); + expect({ name: row?.name, object: row?.object }).toEqual({ name: FIRST, object: LEAD }); + for (const key of Object.keys(member)) expect(row?.[key], `the stored container carries ${key}`).toEqual(member[key]); }); } @@ -1429,7 +1599,7 @@ describe('#21334 a container on another package\'s object never takes that packa it(`${scope}: a \`form\`-only second container is refused by this check, before the identity stamp could turn it into a malformed view item`, async () => { const { protocol, rows, registry } = showcaseHarness(environmentId); - await saved(saveIn(protocol, LEAD, { name: LEAD, object: LEAD, formViews: { edit: leadForm } }, organizationId)); + seedStoredContainer(rows, LEAD, { name: LEAD, object: LEAD, formViews: { edit: leadForm } }, { packageId: undefined }); const EDIT = `${LEAD}.edit`; expectRefused( await refusalOf(saveIn(protocol, EDIT, { name: EDIT, object: LEAD, form: leadForm }, organizationId)), EDIT, LEAD, @@ -1923,19 +2093,35 @@ describe('#21334 a container on another package\'s object never takes that packa for (const organizationId of [undefined] as Array) { const scope = organizationId ? 'organization-scoped' : 'environment-wide'; for (const c of AT_REST) { - it(`${scope}, ${c.member} stored at ${c.rowName}: ${c.spared} still answers the packaged view on both doors, and the container's view is served under its own name, with no package and no default`, async () => { + it(`${scope}, ${c.member} stored at ${c.rowName}: ${c.spared} still answers the packaged ${PACKAGED_FORMS.some((f) => f.name === c.spared) ? 'form on the form doors and no view' : 'view on both doors'}, and the container's view is served under its own name, with no package and no default`, async () => { const { protocol, rows } = showcaseHarness(environmentId); storeAtRest(rows, c.rowName, c.body, organizationId); - const shipped = PACKAGED.find((v) => v.name === c.spared)!; const served = await objectDoor(protocol, organizationId); - const listed = named(served, c.spared); - expect(listed, `exactly one item answers ${c.spared} on the object door`).toHaveLength(1); - expect({ label: listed[0].label, config: listed[0].config, _packageId: listed[0]._packageId }) - .toEqual({ label: shipped.label, config: shipped.config, _packageId: SHOWCASE }); - const read = await byNameDoor(protocol, c.spared, organizationId); - expect({ label: read?.label, config: read?.config, _packageId: read?._packageId }) - .toEqual({ label: shipped.label, config: shipped.config, _packageId: SHOWCASE }); + const shippedForm = PACKAGED_FORMS.find((f) => f.name === c.spared); + if (shippedForm) { + // [ADR-0159] The name the member would have replaced is a + // form the package ships as a `form` item: the container's + // list never takes it on the `view` doors, and the `form` + // doors still answer the packaged form. + expect(named(served, c.spared), `${c.spared} answers no view on the object door`).toEqual([]); + expect(await byNameDoor(protocol, c.spared, organizationId), `${c.spared} answers no view by name`).toBeUndefined(); + const forms = named(await formDoor(protocol), c.spared); + expect(forms, `exactly one item answers ${c.spared} on the form door`).toHaveLength(1); + expectPackagedForm(forms[0], shippedForm); + expectPackagedForm(await formByNameDoor(protocol, c.spared), shippedForm); + } + const shipped = PACKAGED.find((v) => v.name === c.spared); + if (shipped) { + const listed = named(served, c.spared); + expect(listed, `exactly one item answers ${c.spared} on the object door`).toHaveLength(1); + expect({ label: listed[0].label, config: listed[0].config, _packageId: listed[0]._packageId }) + .toEqual({ label: shipped.label, config: shipped.config, _packageId: SHOWCASE }); + const read = await byNameDoor(protocol, c.spared, organizationId); + expect({ label: read?.label, config: read?.config, _packageId: read?._packageId }) + .toEqual({ label: shipped.label, config: shipped.config, _packageId: SHOWCASE }); + } + expect(!!shipped !== !!shippedForm, `${c.spared} is one packaged item`).toBe(true); const own = named(served, c.servedAs); expect(own, `the container's view answers ${c.servedAs}`).toHaveLength(1); diff --git a/packages/metadata/src/owner-stamp-residual-build-boot.test.ts b/packages/metadata/src/owner-stamp-residual-build-boot.test.ts index b5df6258953..b6fd90055ae 100644 --- a/packages/metadata/src/owner-stamp-residual-build-boot.test.ts +++ b/packages/metadata/src/owner-stamp-residual-build-boot.test.ts @@ -17,7 +17,9 @@ * raises the judge's issue exactly when `unclaimedTopLevel` lists the item, * and the metadata door refuses exactly those; * - view containers, body shape by top-level shape: a container is claimed by - * the object it binds to however the binding is spelled. + * the object it binds to however the binding is spelled; + * - [ADR-0159 D7] the container that bound through a `form` alone: protocol + * 19 refuses the shape, and no stamp on it is registered at the boot. */ import { describe, it, expect } from 'vitest'; @@ -192,7 +194,6 @@ describe('[ADR-0010 · ADR-0130 D4] a view container is claimed by the object it const shapes: Record> = { 'own object': { object: 'probe_thing', list: listOf('probe_thing') }, 'list binding only': { list: listOf('probe_thing') }, - 'form binding only': { form: { type: 'simple', data: { provider: 'object', object: 'probe_thing' }, sections: [{ fields: ['title'] }] } }, 'another object, list binding only': { list: listOf('probe_other') }, 'another object, own object': { object: 'probe_other', list: listOf('probe_other') }, }; @@ -207,4 +208,41 @@ describe('[ADR-0010 · ADR-0130 D4] a view container is claimed by the object it // Claimed exactly when both bind the same object. expect(listed).toBe(body.startsWith('another') !== top.startsWith('another')); }); + + /** + * [ADR-0159 D7] Protocol 19: a `view` holds lists only, so the container + * that bound its object through a `form` alone is no longer a shape either + * door takes. The build door refuses it at the `form` key before any stamp + * is judged, wherever it sits. + */ + const FORM_ONLY = { form: { type: 'simple', data: { provider: 'object', object: 'probe_thing' }, sections: [{ fields: ['title'] }] } }; + const buildRefusalsAt = (stack: unknown): string[] => { + const result = ObjectStackDefinitionSchema.safeParse(stack); + return result.success ? [] : result.error.issues.map((i) => i.path.join('.')); + }; + + it.each([...Object.keys(shapes), 'form binding only'])('body container (form binding only) × top-level container (%s): the artifact is refused at both doors', async (top) => { + const artifact = artifactOf({ views: [FORM_ONLY] }); + const { stack } = withTopLevel(artifact, 'views', [{ ...(shapes[top] ?? FORM_ONLY), _packageId: FOREIGN }]); + expect(buildRefusalsAt(stack)).toContain('packages.0.manifest.views.0.form'); + // The boot does not read a claim out of a package entry it cannot take. + expect(() => unclaimedTopLevel(stack)).toThrowError(expect.objectContaining({ code: 'INVALID_ARTIFACT_PACKAGE_ENTRY' })); + await expect(MetadataPlugin.registerUnclaimedTopLevel( + { register: () => undefined, warn: () => undefined }, + stack, + { door: 'config', label: 'probe' }, + )).rejects.toMatchObject({ code: 'INVALID_ARTIFACT_PACKAGE_ENTRY' }); + }); + + it.each(Object.keys(shapes))('body container (%s) × top-level container (form binding only), stamped foreign: the build door refuses the shape, and the boot waves no stamp through', async (body) => { + const artifact = artifactOf({ views: [shapes[body]] }); + const { stack, at } = withTopLevel(artifact, 'views', [{ ...FORM_ONLY, _packageId: FOREIGN }]); + // The build door: the removed key, not a stamp verdict. + expect(buildRefusalsAt(stack)).toEqual([`views.${at}.form`]); + // The boot still reads which object the refused shape names, so a + // foreign stamp on it is judged as before and never registered. + const listed = bootListsResidual(stack, 'views', at); + expect(await bootRefusesStamp(stack)).toBe(listed); + expect(listed).toBe(body.startsWith('another')); + }); }); diff --git a/packages/metadata/src/plugin-artifact-forward-conversion-retired-after.test.ts b/packages/metadata/src/plugin-artifact-forward-conversion-retired-after.test.ts index 7dec75cc875..40a202bbe21 100644 --- a/packages/metadata/src/plugin-artifact-forward-conversion-retired-after.test.ts +++ b/packages/metadata/src/plugin-artifact-forward-conversion-retired-after.test.ts @@ -26,6 +26,8 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid during collection, not inside a clocked case: `plugin.ts` `import()`s it in a function body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/metadata-fs'; import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -154,6 +156,40 @@ describe('[#20390] artifact door — a 17.4.0-built artifact boots on unreleased * the notice must not wait for the package label to move. */ it('announces a bare-root form predicate once — the #12915 notice follows the per-entry window', async () => { + // [ADR-0159 D7] The form sits where @objectstack/spec 19 holds it, a + // `forms[]` item: the window is read off the artifact's floor, never + // off the shape, so the notice follows it for a form item too. + const forms = [{ + name: 'fwd_deal.form', + object: 'fwd_deal', + type: 'simple', + sections: [{ + name: 'deal', + fields: [ + { field: 'stage' }, + // Bare root: `stage`, not `record.stage` — unbound where it evaluates. + { field: 'amount', required: true, visibleWhen: { dialect: 'cel', source: 'stage == "won"' } }, + ], + }], + }]; + const artifact = () => ({ ...loadFixture(), forms: JSON.parse(JSON.stringify(forms)) }); + expect(artifact().manifest.engines.protocol).toBe('^17.4.0'); + + const plugin = newPlugin(); + const ctx = fakeCtx(); + await plugin._parseAndRegisterArtifact(ctx, artifact(), 'forward-probe-17.4-bare-root'); + // The HMR watcher replays the same artifact: still once. + await plugin._parseAndRegisterArtifact(ctx, artifact(), 'forward-probe-17.4-bare-root'); + + const unbound = (ctx.logger.warn.mock.calls as [string][]) + .map(([line]) => String(line)) + .filter((line) => line.includes('root identifier is NOT bound')); + expect(unbound).toHaveLength(1); + expect(unbound[0]).toContain("'stage'"); + expect(unbound[0]).toContain('1 view(s): fwd_deal.form'); + }); + + it('[ADR-0159 D7] the same predicate in a form the artifact still holds in `views[]`: announced once, and the artifact is refused at the form', async () => { const views = [{ form: { type: 'simple', @@ -162,25 +198,23 @@ describe('[#20390] artifact door — a 17.4.0-built artifact boots on unreleased name: 'deal', fields: [ { field: 'stage' }, - // Bare root: `stage`, not `record.stage` — unbound where it evaluates. { field: 'amount', required: true, visibleWhen: { dialect: 'cel', source: 'stage == "won"' } }, ], }], }, }]; - expect(loadFixtureWith(views).manifest.engines.protocol).toBe('^17.4.0'); - const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, loadFixtureWith(views), 'forward-probe-17.4-bare-root'); - // The HMR watcher replays the same artifact: still once. - await plugin._parseAndRegisterArtifact(ctx, loadFixtureWith(views), 'forward-probe-17.4-bare-root'); - + for (let replay = 0; replay < 2; replay++) { + const err: any = await plugin._parseAndRegisterArtifact(ctx, loadFixtureWith(views), 'forward-probe-17.4-view-form') + .then(() => undefined, (e: unknown) => e); + expect(err?.name).toBe('ZodError'); + expect((err.issues as any[]).map((issue) => issue.path.join('.'))).toEqual(['views.0.form']); + } const unbound = (ctx.logger.warn.mock.calls as [string][]) .map(([line]) => String(line)) .filter((line) => line.includes('root identifier is NOT bound')); expect(unbound).toHaveLength(1); - expect(unbound[0]).toContain("'stage'"); expect(unbound[0]).toContain('1 view(s): fwd_deal'); }); }); diff --git a/packages/metadata/src/plugin-artifact-view-container-object.test.ts b/packages/metadata/src/plugin-artifact-view-container-object.test.ts index c7be5b51564..e5bf61e1cd1 100644 --- a/packages/metadata/src/plugin-artifact-view-container-object.test.ts +++ b/packages/metadata/src/plugin-artifact-view-container-object.test.ts @@ -48,6 +48,8 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid during collection, not inside a clocked case: `plugin.ts` `import()`s it in a function body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/metadata-fs'; import { MetadataPlugin } from './plugin.js'; const logger = vi.hoisted(() => ({ @@ -74,11 +76,10 @@ const objectOnlyContainer = { object: 'crm_lead', list: { label: 'All Leads', type: 'grid', columns: [{ field: 'name' }, { field: 'company' }] }, listViews: { hot: { label: 'Hot Leads', type: 'grid', columns: [{ field: 'name' }] } }, - formViews: { edit: { type: 'simple', sections: [{ label: 'Info', fields: [{ field: 'name' }] }] } }, }; /** What `objectOnlyContainer` expands to, sorted — the whole expected answer. */ -const EXPANDED = ['crm_lead.default', 'crm_lead.edit', 'crm_lead.hot']; +const EXPANDED = ['crm_lead.default', 'crm_lead.hot']; /** The pre-existing shape: the binding lives only in `list.data.object`. */ const listDataObjectContainer = { @@ -88,7 +89,6 @@ const listDataObjectContainer = { columns: [{ field: 'name' }], data: { provider: 'object', object: 'crm_account' }, }, - formViews: { edit: { type: 'simple', sections: [{ label: 'Info', fields: [{ field: 'name' }] }] } }, }; function fakeCtx() { @@ -141,9 +141,9 @@ describe('#13912 artifact door — a container binds by its own top-level `objec const item = (await plugin.manager.get('view', name)) as any; expect(item, `expanded view '${name}' should register`).toBeDefined(); expect(item.object).toBe('crm_lead'); - expect(item.viewKind === 'list' || item.viewKind === 'form').toBe(true); + expect(item.viewKind).toBe('list'); } - // One container + three expanded items. + // One container + its two expanded lists. expect(total).toBe(1 + EXPANDED.length); }); @@ -205,9 +205,27 @@ describe('#13912 artifact door — a container binds by its own top-level `objec expect(await plugin.manager.get('view', 'crm_account')).toBeDefined(); expect(names(await plugin.manager.getViewsByObject('crm_account'))).toEqual([ 'crm_account.default', - 'crm_account.edit', ]); - expect(total).toBe(3); + expect(total).toBe(2); + }); + + // [ADR-0159 D7] Since @objectstack/spec 19 a container holds lists only. + // The door does not replay the form move (the switch owns it), so a + // container that still holds a form is refused by the strict parse, located + // at the member, and nothing of the artifact registers. + it.each([ + ['formViews', { ...objectOnlyContainer, formViews: { edit: { type: 'simple', sections: [{ label: 'Info', fields: [{ field: 'name' }] }] } } }], + ['form', { ...objectOnlyContainer, form: { type: 'simple', sections: [{ label: 'Info', fields: [{ field: 'name' }] }] } }], + ] as const)('a container that still holds `%s` is refused at the door, located at the member', async (member, container) => { + const plugin = newPlugin(); + const definition = JSON.parse(JSON.stringify({ manifest: MANIFEST, views: [container] })); + const err: any = await plugin._parseAndRegisterArtifact(fakeCtx(), definition, 'fixture-13912-form') + .then(() => undefined, (e: unknown) => e); + expect(err?.name).toBe('ZodError'); + const refused = (err.issues as any[]).map((issue) => [issue.path.join('.'), String(issue.message).split(' was removed')[0]]); + expect(refused).toEqual([[`views.0.${member}`, `\`view.${member}\``]]); + expect(await plugin.manager.get('view', 'crm_lead')).toBeUndefined(); + expect(await plugin.manager.get('view', 'crm_lead.default')).toBeUndefined(); }); it('CONTROL: a container with no derivable binding at all is still skipped', async () => { diff --git a/packages/metadata/src/plugin-unbound-form-predicate-roots.test.ts b/packages/metadata/src/plugin-unbound-form-predicate-roots.test.ts index 14e0a7e68ac..f16c7be4073 100644 --- a/packages/metadata/src/plugin-unbound-form-predicate-roots.test.ts +++ b/packages/metadata/src/plugin-unbound-form-predicate-roots.test.ts @@ -21,6 +21,8 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid during collection, not inside a clocked case: `plugin.ts` `import()`s it in a function body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/metadata-fs'; import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -64,6 +66,42 @@ function currentSurfaceFloor(): string { return `${major}.${minor}.${patch + 1}`; } +/** + * [ADR-0159 D7] The door's answer to an artifact that still holds a form in + * `views[]`, since @objectstack/spec 19: the predicate scan runs first, on the + * definition as forwarded, and the strict parse then refuses the artifact, + * located at each form it holds. The notice assertions below read what the + * scan logged before that refusal. + */ +async function ingestRefusedForItsViewForms(plugin: any, ctx: any, artifact: any, label: string): Promise { + const err: any = await plugin._parseAndRegisterArtifact(ctx, artifact, label).then(() => undefined, (e: unknown) => e); + expect(err?.name, `'${label}' is refused`).toBe('ZodError'); + const refused = (err.issues as any[]).map((issue) => [issue.path.join('.'), String(issue.message).split(' was removed')[0]]); + expect(refused.length).toBeGreaterThan(0); + for (const [path, key] of refused) { + expect(path).toMatch(/^views\.\d+\.form$/); + expect(key).toBe('`view.form`'); + } +} + +/** + * [ADR-0159 D7] The same artifact with each form where @objectstack/spec 19 + * holds it: a `forms[]` item named `OBJECT.form`, bound with `object`, its body + * at the top level; a list stays in its `views[]` container. + */ +function loadFormItemFixture(): any { + const fixture = loadFixture(); + fixture.forms = fixture.views.map((view: any) => { + const { data, ...body } = view.form; + return { name: `${data.object}.form`, object: data.object, ...body }; + }); + fixture.views = fixture.views.flatMap((view: any) => { + const { form: _moved, ...rest } = view; + return Object.keys(rest).length > 0 ? [rest] : []; + }); + return fixture; +} + /** Just the notices this feature emits — never the #12772 conversion summaries. */ function unboundRootWarnings(ctx: any): string[] { return (ctx.logger.warn.mock.calls as any[]) @@ -104,7 +142,7 @@ describe('artifact door — unbound form-predicate roots are announced to the op const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, loadFixture(), 'fixture-bare-roots'); + await ingestRefusedForItsViewForms(plugin, ctx, loadFixture(), 'fixture-bare-roots'); const warnings = unboundRootWarnings(ctx); expect(warnings).toHaveLength(1); @@ -140,9 +178,9 @@ describe('artifact door — unbound form-predicate roots are announced to the op const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, loadFixture(), 'fixture-bare-roots'); - await plugin._parseAndRegisterArtifact(ctx, loadFixture(), 'fixture-bare-roots'); - await plugin._parseAndRegisterArtifact(ctx, loadFixture(), 'fixture-bare-roots'); + await ingestRefusedForItsViewForms(plugin, ctx, loadFixture(), 'fixture-bare-roots'); + await ingestRefusedForItsViewForms(plugin, ctx, loadFixture(), 'fixture-bare-roots'); + await ingestRefusedForItsViewForms(plugin, ctx, loadFixture(), 'fixture-bare-roots'); expect(unboundRootWarnings(ctx)).toHaveLength(1); }); @@ -166,7 +204,7 @@ describe('artifact door — unbound form-predicate roots are announced to the op const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, fixture, 'fixture-current-floor'); + await ingestRefusedForItsViewForms(plugin, ctx, fixture, 'fixture-current-floor'); expect(unboundRootWarnings(ctx)).toEqual([]); }); @@ -181,7 +219,7 @@ describe('artifact door — unbound form-predicate roots are announced to the op const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, fixture, 'fixture-record-rooted'); + await ingestRefusedForItsViewForms(plugin, ctx, fixture, 'fixture-record-rooted'); expect(unboundRootWarnings(ctx)).toEqual([]); }); @@ -213,7 +251,7 @@ describe('artifact door — unbound form-predicate roots are announced to the op const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, fixture, `fixture-cu-${source}`); + await ingestRefusedForItsViewForms(plugin, ctx, fixture, `fixture-cu-${source}`); expect(unboundRootWarnings(ctx), source).toEqual([]); } @@ -246,7 +284,7 @@ describe('artifact door — unbound form-predicate roots are announced to the op const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, fixture, 'fixture-section-cu'); + await ingestRefusedForItsViewForms(plugin, ctx, fixture, 'fixture-section-cu'); expect(unboundRootWarnings(ctx)).toEqual([]); }); @@ -272,7 +310,7 @@ describe('artifact door — unbound form-predicate roots are announced to the op const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, fixture, 'fixture-section-bare'); + await ingestRefusedForItsViewForms(plugin, ctx, fixture, 'fixture-section-bare'); const warnings = unboundRootWarnings(ctx); expect(warnings).toHaveLength(1); @@ -307,28 +345,67 @@ describe('artifact door — unbound form-predicate roots are announced to the op const plugin = newPlugin(); const ctx = fakeCtx(); - await plugin._parseAndRegisterArtifact(ctx, fixture, 'fixture-literal-control'); + await ingestRefusedForItsViewForms(plugin, ctx, fixture, 'fixture-literal-control'); expect(unboundRootWarnings(ctx)).toEqual([]); }); it('changes NO behaviour: the artifact still registers and its predicates are untouched', async () => { + // [ADR-0159 D7] Read on the artifact with its forms in `forms[]`: one + // that still holds them in `views[]` is refused by the strict parse, + // whatever this notice says (the cases above). const plugin = newPlugin(); const ctx = fakeCtx(); - const pristine = loadFixture(); + const pristine = loadFormItemFixture(); - const total = await plugin._parseAndRegisterArtifact(ctx, loadFixture(), 'fixture-bare-roots'); + const total = await plugin._parseAndRegisterArtifact(ctx, loadFormItemFixture(), 'fixture-bare-roots'); expect(total).toBeGreaterThan(0); // No refusal (the call above would have thrown) and no rewrite: the - // registered view carries the authored source verbatim, bare root and + // registered form carries the authored source verbatim, bare root and // all. Rewriting is #12915 scope A, deferred by the same ruling. - const registered: any = await plugin.manager.get('view', 'crm_lead'); + const registered: any = await plugin.manager.get('form', 'crm_lead.form'); expect(registered).toBeDefined(); - const authored = pristine.views[0].form.sections[0].fields; - const stored = registered.form.sections[0].fields; + const authored = pristine.forms[0].sections[0].fields; + const stored = registered.sections[0].fields; for (const [index, field] of authored.entries()) { expect(stored[index].visibleWhen?.source).toBe(field.visibleWhen?.source); } }); }); + +describe('[ADR-0159 D7] artifact door — the notice reads a form where protocol 19 holds it, in `forms[]`', () => { + it('emits ONE notice naming the form, located in `forms[]`, and the artifact registers', async () => { + const plugin = newPlugin(); + const ctx = fakeCtx(); + + const total = await plugin._parseAndRegisterArtifact(ctx, loadFormItemFixture(), 'fixture-form-items'); + expect(total).toBeGreaterThan(0); + + const warnings = unboundRootWarnings(ctx); + expect(warnings).toHaveLength(1); + const notice = warnings[0]!; + expect(notice).toContain('fixture-form-items'); + expect(notice).toContain('3 form-view predicate(s)'); + expect(notice).toContain("'status'"); + expect(notice).toContain("'duplicate_of_type'"); + expect(notice).toContain('crm_lead.form'); + expect(notice).toContain('forms[0].sections[0].fields[4].visibleWhen'); + expect(notice).not.toContain('form SECTION'); + // The healthy sibling form is NOT named. + expect(notice).not.toContain('crm_case'); + }); + + it('says NOTHING once every predicate of the form items carries a bound root', async () => { + const fixture = loadFormItemFixture(); + for (const field of fixture.forms[0].sections[0].fields) { + if (field.visibleWhen && !field.visibleWhen.source.startsWith('record.') && !field.visibleWhen.source.startsWith('current_user.')) { + field.visibleWhen.source = `record.${field.visibleWhen.source}`; + } + } + const plugin = newPlugin(); + const ctx = fakeCtx(); + await plugin._parseAndRegisterArtifact(ctx, fixture, 'fixture-form-items-rooted'); + expect(unboundRootWarnings(ctx)).toEqual([]); + }); +}); diff --git a/packages/objectql/src/protocol-duplicate-package-names-in-step.test.ts b/packages/objectql/src/protocol-duplicate-package-names-in-step.test.ts index ffeff54bb2a..5d8ee7c134a 100644 --- a/packages/objectql/src/protocol-duplicate-package-names-in-step.test.ts +++ b/packages/objectql/src/protocol-duplicate-package-names-in-step.test.ts @@ -144,9 +144,7 @@ const NOTE_PROSE = 'Attached to dupsrc_note; see x_dupsrc_note.'; const RULE = { readable: true, editable: false }; const grid = (object: string, columns: string[]) => ({ type: 'grid', data: { provider: 'object', object }, columns }); -const form = (object: string, fields: string[]) => ({ - type: 'simple', data: { provider: 'object', object }, sections: [{ label: 'Main', fields }], -}); +const form = (fields: string[]) => ({ type: 'simple', sections: [{ label: 'Main', fields }] }); /** * A prefixed object with a field named after it, and one whose name merely @@ -186,9 +184,13 @@ const extBody = { fields: { name: { name: 'name', type: 'text', label: 'Name' } }, }; -const viewItem = (object: string, key: string, viewKind: 'list' | 'form', config: unknown) => ({ +const viewItem = (object: string, key: string, viewKind: 'list', config: unknown) => ({ name: `${object}.${key}`, object, viewKind, label: key, config, }); +/** A form as major 19 stores it (ADR-0159 D7): a `form` item, its body at the top level, named `OBJECT.KEY`. */ +const formItem = (object: string, key: string, body: Record) => ({ + name: `${object}.${key}`, object, label: key, ...body, +}); const formAction = (name: string, objectName: string, target: string) => ({ name, label: name, type: 'form', objectName, target, }); @@ -272,8 +274,8 @@ describe('ADR-0070 D4 — duplicatePackage keeps a copied name in step with what await save(P, 'view', viewItem('dupsrc_customer', 'board', 'list', grid('dupsrc_customer', ['full_name', 'dupsrc_customer', 'x_dupsrc_customer']))); await save(P, 'view', viewItem('dupext_account', 'board', 'list', grid('dupext_account', ['name']))); await save(P, 'view', viewItem('dupsrc_ext', 'board', 'list', grid('dupsrc_ext', ['name']))); - await save(P, 'view', viewItem('ticket', 'entry', 'form', form('ticket', ['title']))); - await save(P, 'view', viewItem('dupsrc_customer', 'entry', 'form', form('dupsrc_customer', ['full_name', 'dupsrc_customer']))); + await save(P, 'form', formItem('ticket', 'entry', form(['title']))); + await save(P, 'form', formItem('dupsrc_customer', 'entry', form(['full_name', 'dupsrc_customer']))); await save(P, 'action', formAction('dupsrc_new_ticket', 'ticket', 'ticket.entry')); await save(P, 'action', formAction('dupsrc_new_customer', 'dupsrc_customer', 'dupsrc_customer.entry')); await save(P, 'action', formAction('dupsrc_new_account', 'dupext_account', 'dupext_account.entry')); @@ -327,17 +329,17 @@ describe('ADR-0070 D4 — duplicatePackage keeps a copied name in step with what expect(res.failed).toEqual([]); expect(res.copied).toEqual(expect.arrayContaining([ { type: 'view', name: 'dupdst_customer.board' }, - { type: 'view', name: 'dupdst_customer.entry' }, + { type: 'form', name: 'dupdst_customer.entry' }, ])); // A value naming the FIELD keeps naming it: list-view columns and form fields. const board = storedBody('view', 'dupdst_customer.board', Q); expect(board.config.columns).toEqual(['full_name', 'dupsrc_customer', 'x_dupsrc_customer']); - const entry = storedBody('view', 'dupdst_customer.entry', Q); - expect(entry.config.sections[0].fields).toEqual(['full_name', 'dupsrc_customer']); + const entry = storedBody('form', 'dupdst_customer.entry', Q); + expect(entry.sections[0].fields).toEqual(['full_name', 'dupsrc_customer']); expect(Object.keys(storedBody('object', 'dupdst_customer', Q).fields)).toContain('dupsrc_customer'); // A value naming the OBJECT at a reference property follows the copy. expect(board).toMatchObject({ object: 'dupdst_customer', config: { data: { object: 'dupdst_customer' } } }); - expect(entry).toMatchObject({ object: 'dupdst_customer', config: { data: { object: 'dupdst_customer' } } }); + expect(entry).toMatchObject({ name: 'dupdst_customer.entry', object: 'dupdst_customer' }); expect(storedBody('object', 'dupdst_ticket', Q).fields.customer.reference).toBe('dupdst_customer'); expect(storedBody('object', 'dupdst_note', Q).fields.customer.reference).toBe('dupdst_customer'); expect(storedBody('action', 'dupdst_new_customer', Q).objectName).toBe('dupdst_customer'); @@ -378,21 +380,21 @@ describe('ADR-0070 D4 — duplicatePackage keeps a copied name in step with what expect(storedBody('view', 'dupsrc_ext.board', Q)).toMatchObject({ object: 'dupsrc_ext' }); expect(storedNames('view', Q)).toEqual([ 'dupdst_customer.board', - 'dupdst_customer.entry', 'dupdst_ticket.board', - 'dupdst_ticket.entry', 'dupext_account.board', 'dupsrc_ext.board', ]); + // A form is its own type on major 19 (ADR-0159 D7): its `OBJECT.KEY` name follows the object the same way. + expect(storedNames('form', Q)).toEqual(['dupdst_customer.entry', 'dupdst_ticket.entry']); + expect(storedBody('form', 'dupdst_ticket.entry', Q)).toMatchObject({ name: 'dupdst_ticket.entry', object: 'dupdst_ticket' }); // The source keeps every item under its own name. expect(storedNames('view', P)).toEqual([ 'dupext_account.board', 'dupsrc_customer.board', - 'dupsrc_customer.entry', 'dupsrc_ext.board', 'ticket.board', - 'ticket.entry', ]); + expect(storedNames('form', P)).toEqual(['dupsrc_customer.entry', 'ticket.entry']); }); it('a form action\'s view-item target follows the copied view item', async () => { diff --git a/packages/objectql/src/protocol-meta.test.ts b/packages/objectql/src/protocol-meta.test.ts index e2d761d1c1c..68f829e9e87 100644 --- a/packages/objectql/src/protocol-meta.test.ts +++ b/packages/objectql/src/protocol-meta.test.ts @@ -453,17 +453,26 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { ).resolves.toMatchObject({ success: true }); }); - it('accepts a container-shape view payload (form only)', async () => { + it('[ADR-0159 D7] refuses a container-shape view payload holding a form only, at `form`; the same form saves as a `form` item', async () => { + const body = { + type: 'tabbed', + sections: [{ name: 'main', label: 'Main', fields: [{ field: 'first_name' }] }], + }; const formContainer = { name: 'lead_form_only', - form: { - type: 'tabbed', - data: { provider: 'object', object: 'lead' }, - sections: [{ name: 'main', label: 'Main', fields: [{ field: 'first_name' }] }], - }, + form: { ...body, data: { provider: 'object', object: 'lead' } }, }; + const err: any = await protocol + .saveMetaItem({ type: 'view', name: 'lead_form_only', item: formContainer }) + .catch((e: unknown) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const atForm = err.issues.find((i: any) => i.path === 'form'); + expect(atForm, JSON.stringify(err.issues)).toBeDefined(); + expect(atForm.message).toMatch(/^`view\.form` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D7\)/); + + // Protocol 19: the form is its own item, named `OBJECT.KEY`. await expect( - protocol.saveMetaItem({ type: 'view', name: 'lead_form_only', item: formContainer }) + protocol.saveMetaItem({ type: 'form', name: 'lead.form', item: { name: 'lead.form', object: 'lead', ...body } }) ).resolves.toMatchObject({ success: true }); }); diff --git a/packages/objectql/src/protocol-stored-form-migration.test.ts b/packages/objectql/src/protocol-stored-form-migration.test.ts index a19ea52383f..d3af0585444 100644 --- a/packages/objectql/src/protocol-stored-form-migration.test.ts +++ b/packages/objectql/src/protocol-stored-form-migration.test.ts @@ -31,7 +31,7 @@ import './__fixtures__/lint-root-preload.testkit.js'; import { describe, expect, it } from 'vitest'; import type { ServiceObject } from '@objectstack/spec/data'; -import { ObjectStackProtocolImplementation, applyStoredFormsOf, listStoredFormsOf } from '@objectstack/metadata-protocol'; +import { ObjectStackProtocolImplementation, applyStoredFormsOf, censusFormsServedBeforeTheSwitchOf, listStoredFormsOf } from '@objectstack/metadata-protocol'; import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject } from '@objectstack/metadata-core'; import { ObjectQL } from './engine.js'; @@ -237,6 +237,15 @@ const viewItem = (name: string, object: string, extra: Record = const census = (protocol: ObjectStackProtocolImplementation): Promise => listStoredFormsOf(protocol); +/** + * "What the read serves today", in the census's own reading: the forms served + * before the switch, the projected items included (the list `listStoredForms` + * plans from). ⛔ Never a served read of the major: that one serves no + * projected item, so a premise read through it and the plan would disagree. + */ +const servedToday = async (protocol: ObjectStackProtocolImplementation): Promise => + (await censusFormsServedBeforeTheSwitchOf(protocol)) as any[]; + describe('[ADR-0159 D7] listStoredForms over the real protocol', () => { it('lists a package-less old-shape row over the base\'s linked form as moving into the pair, and writes nothing', async () => { const { engine, protocol, snapshot } = await boot(); @@ -298,7 +307,7 @@ describe('[ADR-0159 D7] listStoredForms over the real protocol', () => { const before = snapshot(); // The read today: the bound row seats the base's address, and the override is // the body served there and at the pair's; the bound row's body is served nowhere. - const served = ((await protocol.getMetaItems({ type: 'form' })) as any).items.filter((item: any) => item?.name === name); + const served = (await servedToday(protocol)).filter((item: any) => item?.name === name); expect(served.map((item: any) => [item._packageId, item.label]).sort()).toEqual([ [BASE, 'Override in the pair'], [PAIR, 'Override in the pair'], @@ -321,7 +330,7 @@ describe('[ADR-0159 D7] listStoredForms over the real protocol', () => { describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another address than the package it is bound to, over the real protocol', () => { /** The effective `form` items of the name: the package each is served under, and its label. */ const servedForms = async (protocol: ObjectStackProtocolImplementation): Promise> => - ((await protocol.getMetaItems({ type: 'form' })) as any).items + (await servedToday(protocol)) .filter((item: any) => item?.name === SUITE_NAME) .map((item: any) => [item._packageId, item.label] as [string, string]); const switchedOff = { ...viewItem(SUITE_NAME, SUITE_OBJECT, sharing(false)), label: 'Switched off' }; @@ -418,7 +427,7 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr const { engine, protocol } = await bootSuite({ appOwnsObject: true, moduleForm: {} }); await storeRow(engine, SUITE_OBJECT, { name: SUITE_OBJECT, object: SUITE_OBJECT, formViews: { contact: formBody(SUITE_OBJECT, { layout: 'horizontal' }) } }, SUITE); // The read today: one form of the name, the module's own, under the module. - const served = ((await protocol.getMetaItems({ type: 'form' })) as any).items.filter((item: any) => item?.name === SUITE_NAME); + const served = (await servedToday(protocol)).filter((item: any) => item?.name === SUITE_NAME); expect(served.map((item: any) => [item._packageId, item.layout])).toEqual([[MODULE, undefined]]); expect((await plansOf(protocol)).map((f) => [f.address.packageId, f.served.packageId, f.served.grain, f.outcome, f.destination])).toEqual([ [SUITE, SUITE, 'expansion', 'left_in_place', undefined], @@ -499,7 +508,7 @@ describe('[ADR-0159 D7, ruling 7254350842] a row the read serves at another addr await storeRow(engine, NAME, { ...viewItem(NAME, OBJECT, sharing(true)), label: 'Linked' }, 'com.example.other'); const before = snapshot(); // The read today: the package-less row's body at both Apps' addresses. - const served = ((await protocol.getMetaItems({ type: 'form' })) as any).items + const served = (await servedToday(protocol)) .filter((item: any) => item?.name === NAME) .map((item: any) => [item._packageId, item.label]); expect(served.sort()).toEqual([[BASE, 'Internal'], ['com.example.other.desk', 'Internal']]); @@ -594,7 +603,7 @@ describe('[ADR-0159 D7] applyStoredForms over the real protocol', () => { ((await engine.find('sys_metadata', { where: { type, name, state: 'active' } }, { context: { isSystem: true } })) as any[]) .map((r) => ({ packageId: r.package_id ?? null, body: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata })); const formsAt = async (protocol: ObjectStackProtocolImplementation, name: string): Promise> => - ((await protocol.getMetaItems({ type: 'form' })) as any).items + (await servedToday(protocol)) .filter((item: any) => item?.name === name) .map((item: any) => [item._packageId, item.sharing?.enabled]); const apply = (protocol: ObjectStackProtocolImplementation): Promise => applyStoredFormsOf(protocol, { actor: null }); @@ -695,7 +704,7 @@ describe('[ADR-0159 D7] applyStoredForms over the real protocol', () => { describe('[ADR-0159 D7] a held row: applyStoredForms writes nothing at any address', () => { /** Every effective `form` item of `name`: the package it is served under, and its body. */ const servedAt = async (protocol: ObjectStackProtocolImplementation, name: string): Promise => - JSON.stringify(((await protocol.getMetaItems({ type: 'form' })) as any).items + JSON.stringify((await servedToday(protocol)) .filter((item: any) => item?.name === name) .map((item: any) => [item._packageId, item]) .sort((a: any, b: any) => String(a[0]).localeCompare(String(b[0])))); diff --git a/packages/objectql/src/protocol-unmanaged-import-rename-battery.test.ts b/packages/objectql/src/protocol-unmanaged-import-rename-battery.test.ts index fe3e050800e..1fa5caa3908 100644 --- a/packages/objectql/src/protocol-unmanaged-import-rename-battery.test.ts +++ b/packages/objectql/src/protocol-unmanaged-import-rename-battery.test.ts @@ -125,7 +125,7 @@ interface Fixture { /** The manifest collection each fixture type is declared under. */ const COLLECTION: Record = { - object: 'objects', view: 'views', action: 'actions', permission: 'permissions', flow: 'flows', hook: 'hooks', + object: 'objects', view: 'views', form: 'forms', action: 'actions', permission: 'permissions', flow: 'flows', hook: 'hooks', capability: 'capabilities', }; @@ -244,12 +244,14 @@ const PROSE = 'Linked from dupsrc_customer; see x_dupsrc_customer.'; const NOTE_PROSE = 'Attached to dupsrc_note; see x_dupsrc_note.'; const RULE = { readable: true, editable: false }; const grid = (object: string, columns: string[]) => ({ type: 'grid', data: { provider: 'object', object }, columns }); -const form = (object: string, fields: string[]) => ({ - type: 'simple', data: { provider: 'object', object }, sections: [{ label: 'Main', fields }], -}); -const viewItem = (object: string, key: string, viewKind: 'list' | 'form', config: unknown) => ({ +const form = (fields: string[]) => ({ type: 'simple', sections: [{ label: 'Main', fields }] }); +const viewItem = (object: string, key: string, viewKind: 'list', config: unknown) => ({ name: `${object}.${key}`, object, viewKind, label: key, config, }); +/** A form as major 19 stores it (ADR-0159 D7): a `form` item, its body at the top level, named `OBJECT.KEY`. */ +const formItem = (object: string, key: string, body: Record) => ({ + name: `${object}.${key}`, object, label: key, ...body, +}); const formAction = (name: string, objectName: string, target: string) => ({ name, label: name, type: 'form', objectName, target, }); @@ -291,8 +293,8 @@ const namesInStep: Fixture[] = [ { type: 'view', item: viewItem('dupsrc_customer', 'board', 'list', grid('dupsrc_customer', ['full_name', 'dupsrc_customer', 'x_dupsrc_customer'])) }, { type: 'view', item: viewItem('dupext_account', 'board', 'list', grid('dupext_account', ['name'])) }, { type: 'view', item: viewItem('dupsrc_ext', 'board', 'list', grid('dupsrc_ext', ['name'])) }, - { type: 'view', item: viewItem('ticket', 'entry', 'form', form('ticket', ['title'])) }, - { type: 'view', item: viewItem('dupsrc_customer', 'entry', 'form', form('dupsrc_customer', ['full_name', 'dupsrc_customer'])) }, + { type: 'form', item: formItem('ticket', 'entry', form(['title'])) }, + { type: 'form', item: formItem('dupsrc_customer', 'entry', form(['full_name', 'dupsrc_customer'])) }, { type: 'action', item: formAction('dupsrc_new_ticket', 'ticket', 'ticket.entry') }, { type: 'action', item: formAction('dupsrc_new_customer', 'dupsrc_customer', 'dupsrc_customer.entry') }, { type: 'action', item: formAction('dupsrc_new_account', 'dupext_account', 'dupext_account.entry') }, @@ -447,12 +449,15 @@ describe('[#30794] the duplicate battery, replayed through the unmanaged import .toEqual(['full_name', 'dupsrc_customer', 'x_dupsrc_customer']); expect(Object.keys(itemsOf(imp.h, Q)).filter((k) => k.startsWith('view/'))).toEqual([ 'view/dupdst_customer.board', - 'view/dupdst_customer.entry', 'view/dupdst_ticket.board', - 'view/dupdst_ticket.entry', 'view/dupext_account.board', 'view/dupsrc_ext.board', ]); + // A form is its own type on major 19 (ADR-0159 D7): its `OBJECT.KEY` name follows the object the same way. + expect(Object.keys(itemsOf(imp.h, Q)).filter((k) => k.startsWith('form/'))).toEqual([ + 'form/dupdst_customer.entry', + 'form/dupdst_ticket.entry', + ]); expect(storedBody(imp.h, 'action', 'dupdst_new_ticket', Q)).toMatchObject({ objectName: 'dupdst_ticket', target: 'dupdst_ticket.entry', }); diff --git a/packages/objectql/src/protocol-withheld-extension-fields.test.ts b/packages/objectql/src/protocol-withheld-extension-fields.test.ts index ec0d28117ee..30197419a7e 100644 --- a/packages/objectql/src/protocol-withheld-extension-fields.test.ts +++ b/packages/objectql/src/protocol-withheld-extension-fields.test.ts @@ -103,10 +103,9 @@ async function boot() { // A code-registered view that never passed a write door, with a typo'd column: the read still warns on it. typo: { label: 'Typo', type: 'grid', data: { provider: 'object', object: O }, columns: [{ field: 'name' }, { field: 'crm_projcet' }] }, }, - formViews: { - main: { type: 'simple', data: { provider: 'object', object: O }, sections: [{ label: 'Main', columns: 2, fields: ['name', 'crm_project'] }] }, - }, }], + // A form is its own type on major 19 (ADR-0159 D7): the App ships it under `forms:`. + forms: [{ name: 'crm_expense.main', object: O, label: 'Main', type: 'simple', sections: [{ label: 'Main', columns: 2, fields: ['name', 'crm_project'] }] }], } as any); engine.registerApp({ id: P, name: 'projects', version: '1.0.0', namespace: 'crm', type: 'app', dependencies: { [Q]: '^1.0.0' }, @@ -237,15 +236,14 @@ describe('[#34901] a view over a field a disabled package contributes', () => { const { registry, protocol } = await boot(); registry.disablePackage(P); const form = async (field: string) => { - const { _packageId, _provenance, _diagnostics, ...body } = (await protocol.getMetaItem({ type: 'view', name: FORM })).item; - const config = { ...body.config, sections: [{ label: 'Main', columns: 2, fields: ['name', field] }] }; - return { ...body, config, overrides: { package: Q, basedOn: '1.0.0' } }; + const { _packageId, _provenance, _diagnostics, ...body } = (await protocol.getMetaItem({ type: 'form', name: FORM })).item; + return { ...body, sections: [{ label: 'Main', columns: 2, fields: ['name', field] }], overrides: { package: Q, basedOn: '1.0.0' } }; }; const advised = (result: any) => ((result?.advisories ?? []) as any[]).map((a) => `${a.rule}@${a.path}`); - const saved = await protocol.saveMetaItem({ type: 'view', name: FORM, item: await form('crm_project'), packageId: PAIR }); + const saved = await protocol.saveMetaItem({ type: 'form', name: FORM, item: await form('crm_project'), packageId: PAIR }); expect(saved.success).toBe(true); expect(advised(saved).filter((a) => a.startsWith('form-field-unknown'))).toEqual([]); - const typo = await protocol.saveMetaItem({ type: 'view', name: FORM, item: await form('crm_projcet'), packageId: PAIR }); + const typo = await protocol.saveMetaItem({ type: 'form', name: FORM, item: await form('crm_projcet'), packageId: PAIR }); expect(advised(typo).filter((a) => a.startsWith('form-field-unknown')), 'control: the position is judged').toHaveLength(1); }); }); @@ -283,12 +281,12 @@ describe('[#34901 L2 S1] a served view judges the withheld field as the save doo it('a form section naming the withheld field reads back with no form-field-unknown; with P on there was none either', async () => { const { registry, protocol } = await boot(); - const on = (await protocol.getMetaItem({ type: 'view', name: FORM })).item; - expect(on.config.sections[0].fields, 'precondition: the form names it').toContain('crm_project'); + const on = (await protocol.getMetaItem({ type: 'form', name: FORM })).item; + expect(on.sections[0].fields, 'precondition: the form names it').toContain('crm_project'); expect(warningsOf(on).filter((w) => w.includes('crm_project'))).toEqual([]); registry.disablePackage(P); - const off = (await protocol.getMetaItem({ type: 'view', name: FORM })).item; + const off = (await protocol.getMetaItem({ type: 'form', name: FORM })).item; expect(warningsOf(off).filter((w) => w.includes('crm_project'))).toEqual([]); }); }); diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 4ee052f5e49..a5d53fe321c 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -698,8 +698,18 @@ export class AuthPlugin implements Plugin { * Organization, and on a kernel that composes the guard (`os serve`) a * database the guard refuses must be left as the guard found it, so the * organization is created only once the guard has judged. + * + * `com.objectstack.form-type-switch-boot-guard` — the protocol-19 boot guard + * (`@objectstack/runtime`'s `FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME`, spelled + * here for the same reason; ADR-0159 D7), order-if-present and for the same + * property: a database that guard refuses is left as it found it, so nothing + * `start()` writes is written before its verdict. */ - optionalDependencies = ['com.objectstack.service.settings', 'com.objectstack.organization-ownership-boot-guard']; + optionalDependencies = [ + 'com.objectstack.service.settings', + 'com.objectstack.organization-ownership-boot-guard', + 'com.objectstack.form-type-switch-boot-guard', + ]; private options: AuthPluginOptions; diff --git a/packages/plugins/plugin-auth/src/form-type-switch-guard-ordering.pin.test.ts b/packages/plugins/plugin-auth/src/form-type-switch-guard-ordering.pin.test.ts new file mode 100644 index 00000000000..dc57a657ab5 --- /dev/null +++ b/packages/plugins/plugin-auth/src/form-type-switch-guard-ordering.pin.test.ts @@ -0,0 +1,88 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Nothing the auth family writes at start is written before the protocol-19 + * boot guard has judged the database (ADR-0159 D7) — declared, not incidental. + * + * `AuthPlugin.start()` and `IdentityObjectsPlugin.start()` write identity rows + * (the Default Organization under `single`, ADR-0131 D3). The guard + * (`@objectstack/runtime`'s `FormTypeSwitchBootGuardPlugin`) judges in its own + * `start()`, and a database it refuses must be left as it found it, so both + * plugins name it in `optionalDependencies`, beside the v18 guard + * (`default-organization-guard-ordering.pin.test.ts`). This file proves the + * declaration is what moves the order: a hostile registry (the writer used + * BEFORE the guard) still starts the guard first, and the same registry with + * the declaration removed does not. The real guard on a real kernel is + * `runtime/src/form-type-switch-boot-guard.kernel.test.ts`. + * + * The guard is a NAME-ONLY stub carrying the real guard's own order-if-present + * edges: this package does not depend on the runtime, and + * `resolvePluginOrder` reads only the `OrderablePlugin` surface. + */ + +import { describe, expect, it } from 'vitest'; +import { resolvePluginOrder } from '@objectstack/core'; +import type { OrderablePlugin } from '@objectstack/core'; +import { AuthPlugin } from './auth-plugin.js'; +import { IdentityObjectsPlugin } from './identity-objects-plugin.js'; + +// Pay the first transform of the dist-resolved dependency `auth-plugin`'s +// reach loads through a dynamic `import()` at MODULE LOAD, never inside a +// case's clocked window (`scripts/check-test-source-alias.mjs`). +import '@objectstack/core/egress'; + +const GUARD_PLUGIN = 'com.objectstack.form-type-switch-boot-guard'; +const OWNERSHIP_GUARD_PLUGIN = 'com.objectstack.organization-ownership-boot-guard'; +const ENGINE_PLUGIN = 'com.objectstack.engine.objectql'; + +const writers: Array<[string, () => OrderablePlugin]> = [ + ['AuthPlugin', () => new AuthPlugin({ secret: 'test-secret-at-least-32-chars-long!!' }) as unknown as OrderablePlugin], + ['IdentityObjectsPlugin', () => new IdentityObjectsPlugin() as unknown as OrderablePlugin], +]; + +/** The guard as the resolver sees it: its name and its own order-if-present edges. */ +const guardStub = (): OrderablePlugin => ({ + name: GUARD_PLUGIN, + optionalDependencies: [ENGINE_PLUGIN, 'com.objectstack.platform-objects', OWNERSHIP_GUARD_PLUGIN], +}); + +const orderOf = (...plugins: OrderablePlugin[]): string[] => + resolvePluginOrder(new Map(plugins.map((p) => [p.name, p]))).map((p) => p.name); + +describe.each(writers)('%s writes its identity rows only after the protocol-19 boot guard has judged', (_label, make) => { + it('declares the guard as an OPTIONAL dependency', () => { + const writer = make(); + expect(writer.optionalDependencies ?? []).toContain(GUARD_PLUGIN); + expect(writer.dependencies ?? []).not.toContain(GUARD_PLUGIN); + }); + + it('⭐ the declaration moves the order: used BEFORE the guard, it still starts after it', () => { + const writer = make(); + const ordered = orderOf({ name: ENGINE_PLUGIN }, writer, guardStub()); + expect(ordered.indexOf(GUARD_PLUGIN)).toBeLessThan(ordered.indexOf(writer.name)); + }); + + it('…and the declaration is what does it: forget it and the writer starts first', () => { + const writer = make(); + writer.optionalDependencies = (writer.optionalDependencies ?? []).filter((d) => d !== GUARD_PLUGIN); + const ordered = orderOf({ name: ENGINE_PLUGIN }, writer, guardStub()); + expect(ordered.indexOf(writer.name)).toBeLessThan(ordered.indexOf(GUARD_PLUGIN)); + }); + + it('beside the v18 guard: used before both, it starts after both, the older guard judging first', () => { + const writer = make(); + const ordered = orderOf( + { name: ENGINE_PLUGIN }, + writer, + guardStub(), + { name: OWNERSHIP_GUARD_PLUGIN, optionalDependencies: [ENGINE_PLUGIN] }, + ); + expect(ordered.indexOf(OWNERSHIP_GUARD_PLUGIN)).toBeLessThan(ordered.indexOf(GUARD_PLUGIN)); + expect(ordered.indexOf(GUARD_PLUGIN)).toBeLessThan(ordered.indexOf(writer.name)); + }); + + it('order-if-present: a kernel that composes no guard resolves as before', () => { + const writer = make(); + expect(orderOf({ name: ENGINE_PLUGIN }, writer)).toContain(writer.name); + }); +}); diff --git a/packages/plugins/plugin-auth/src/identity-objects-plugin.ts b/packages/plugins/plugin-auth/src/identity-objects-plugin.ts index 164e60460fb..0c7d4dcb144 100644 --- a/packages/plugins/plugin-auth/src/identity-objects-plugin.ts +++ b/packages/plugins/plugin-auth/src/identity-objects-plugin.ts @@ -94,9 +94,15 @@ export class IdentityObjectsPlugin implements Plugin { * `auth` service is registered by the time `init()` asks, and the pair is * refused there. And the v18 boot guard's (ADR-0131 D10 item 5; see * `AuthPlugin.optionalDependencies`): `start()` creates the Default - * Organization only once the guard has judged the database. + * Organization only once the guard has judged the database. And the + * protocol-19 boot guard's (ADR-0159 D7), for the same property: nothing + * `start()` writes is written before that guard's verdict. */ - optionalDependencies: string[] = ['com.objectstack.auth', 'com.objectstack.organization-ownership-boot-guard']; + optionalDependencies: string[] = [ + 'com.objectstack.auth', + 'com.objectstack.organization-ownership-boot-guard', + 'com.objectstack.form-type-switch-boot-guard', + ]; requiresServices: string[] = ['manifest']; private readonly options: IdentityObjectsPluginOptions; diff --git a/packages/qa/dogfood/test/form-type-switch-boot-refusal.dogfood.test.ts b/packages/qa/dogfood/test/form-type-switch-boot-refusal.dogfood.test.ts new file mode 100644 index 00000000000..17a8d423b83 --- /dev/null +++ b/packages/qa/dogfood/test/form-type-switch-boot-refusal.dogfood.test.ts @@ -0,0 +1,143 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0159 D7] A runtime on protocol major 19 serves a database only once the +// protocol-19 switch is recorded on it, and the refusal is the way through, +// never a dead end. +// +// Measured here end to end, on the showcase composition over SQLite files: +// +// 1. a database an earlier boot left behind, with no switch record, is +// refused, naming the command. It stores no form in an old shape at all: +// the command still has to run once, because only its census can say so; +// 2. `os migrate protocol --to 19` previews and writes nothing; with +// `--apply --yes` it records the switch — through the real CLI binary, +// with the arguments, working directory and environment an operator's run +// has, and with no boot in between; +// 3. the next boot is served; +// 4. a database this boot creates from empty needs no command: the boot +// records the switch itself as a birth marker, and the boot after it reads +// that record like any other. +// +// The guard is composed here as `os serve` composes it: its own plugin, judged +// in its own `start()`. A boot without it (`bootShowcase` composes none of its +// own) is how step 1's database comes to exist with no record. + +import { spawnSync } from 'node:child_process'; +import { copyFileSync, mkdtempSync, rmSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { DatabaseSync } from 'node:sqlite'; +import { afterAll, describe, expect, it } from 'vitest'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { FormTypeSwitchBootGuardPlugin, isFormTypeSwitchBootRefusal } from '@objectstack/runtime'; +import { FORM_TYPE_SWITCH_MIGRATION_ID } from '@objectstack/spec/system'; +import { bootShowcase } from './showcase-boot.js'; + +const SHOWCASE_DIR = fileURLToPath(new URL('../../../../examples/app-showcase/', import.meta.url)); +const CLI_ROOT = dirname(createRequire(import.meta.url).resolve('@objectstack/cli/package.json')); +const CLI_BIN = join(CLI_ROOT, 'bin', 'run.js'); + +interface MarkerRow { verified_at: unknown; applied_at: unknown; blocking: unknown; details: unknown } + +/** The switch record of `file`, read on a connection of our own; undefined when there is none. */ +function switchMarker(file: string): MarkerRow | undefined { + const db = new DatabaseSync(file); + try { + return db.prepare('SELECT verified_at, applied_at, blocking, details FROM sys_migration WHERE id = ?') + .get(FORM_TYPE_SWITCH_MIGRATION_ID) as MarkerRow | undefined; + } finally { + db.close(); + } +} + +/** The guard's refusal down a failed boot's `cause` chain (the kernel reports a failed `start()` as its own error). */ +function refusalIn(error: unknown): unknown { + for (let e = error, depth = 0; !!e && typeof e === 'object' && depth < 8; e = (e as { cause?: unknown }).cause, depth++) { + if (isFormTypeSwitchBootRefusal(e)) return e; + } + return undefined; +} + +/** A boot of the showcase over `file`; with `guard`, the switch guard composed as `os serve` composes it. The failure, or null. */ +async function boot(file: string, guard: boolean): Promise { + try { + const stack = await bootShowcase({ + databaseFile: file, + security: new SecurityPlugin({ defaultPermissionSets: [...securityDefaultPermissionSets] }), + extraPlugins: guard ? [new FormTypeSwitchBootGuardPlugin()] : [], + }); + await stack.stop(); + return null; + } catch (error) { + return error; + } +} + +/** `os migrate protocol --to 19` over `file`, through the real binary, run from the showcase's directory. */ +const protocolCommand = (file: string, args: string[]) => spawnSync(process.execPath, [ + CLI_BIN, 'migrate', 'protocol', '--to', '19', '--database-url', `file:${file}`, ...args, +], { cwd: SHOWCASE_DIR, encoding: 'utf8', timeout: 300_000, env: { ...process.env, NO_COLOR: '1' } }); + +describe('[ADR-0159 D7] a database with no protocol-19 switch record is refused, and the named command is the way through', () => { + const dir = mkdtempSync(join(tmpdir(), 'dogfood-form-type-switch-')); + const file = join(dir, 'showcase.db'); + /** + * The command's output, copied the moment the switch is recorded. An + * operator's refused `os serve` process has exited before the command runs; + * the refused boot here lives on in this process with its SQLite driver + * never torn down (bootstrap failed before any handle came back), so the + * next boot reads the copied bytes, which is the operator's sequence. + */ + const switched = join(dir, 'showcase.switched.db'); + let refusal: unknown; + + afterAll(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + it('1. a database an earlier boot left with no switch record is refused, naming the command', async () => { + expect(await boot(file, false), 'the boot that leaves the database behind').toBeNull(); + expect(switchMarker(file), 'a boot without the guard records no switch').toBeUndefined(); + + refusal = refusalIn(await boot(file, true)); + expect(refusal, 'the boot was refused for the missing switch record').toBeDefined(); + expect((refusal as { reason?: string }).reason).toBe('absent'); + expect(String((refusal as Error).message)).toContain("'os migrate protocol --to 19 --apply --yes'"); + expect(switchMarker(file), 'a refused boot records nothing').toBeUndefined(); + }, 480_000); + + it('2. the command previews without writing, then records the switch with no boot in between', () => { + expect(refusal).toBeDefined(); + const preview = protocolCommand(file, []); + expect(preview.status, `${preview.stdout}\n${preview.stderr}`).toBe(0); + expect(switchMarker(file), 'the preview records nothing').toBeUndefined(); + + const run = protocolCommand(file, ['--apply', '--yes']); + expect(run.status, `${run.stdout}\n${run.stderr}`).toBe(0); + const marker = switchMarker(file); + expect(marker?.verified_at, 'the command verified its record').toBeTruthy(); + expect(Number(marker?.blocking)).toBe(0); + copyFileSync(file, switched); + }, 640_000); + + it('3. the next boot is served', async () => { + expect(await boot(switched, true)).toBeNull(); + }, 240_000); + + it('4. a database the boot creates from empty records the switch itself, and the boot after it is served', async () => { + const born = join(dir, 'born.db'); + expect(await boot(born, true)).toBeNull(); + const marker = switchMarker(born); + expect(marker?.verified_at, 'the birth marker is a verified record').toBeTruthy(); + expect(Number(marker?.blocking)).toBe(0); + // No ceremony ran: the record says how the database came to be, not that forms were moved. + expect(marker?.applied_at ?? null).toBeNull(); + const details = typeof marker?.details === 'string' ? JSON.parse(marker.details) : marker?.details; + expect(details?.birth?.protocol).toBe(19); + + expect(await boot(born, true)).toBeNull(); + expect(switchMarker(born)?.details, 'the second boot reads the record and leaves it as it is').toEqual(marker?.details); + }, 480_000); +}); diff --git a/packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts b/packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts index f99f65fe497..dbf834ea387 100644 --- a/packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts +++ b/packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts @@ -38,7 +38,7 @@ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { MetadataPlugin } from '@objectstack/metadata'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { definePermissionSet } from '@objectstack/spec/security'; import type { ApiEndpoint } from '@objectstack/spec/api'; @@ -157,14 +157,14 @@ const endpoints: ApiEndpoint[] = [ const intakeData = { provider: 'object' as const, object: OBJ.intake }; const IntakeViews = defineView({ list: { label: 'Intake', type: 'grid', data: intakeData, columns: [{ field: 'name' }] }, - formViews: { - intake: { - type: 'simple', - data: intakeData, - sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${FORM_SLUG}` }, - }, - }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`. */ +const IntakeForm = defineForm({ + name: `${OBJ.intake}.intake`, + object: OBJ.intake, + type: 'simple', + sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${FORM_SLUG}` }, }); const fixtureStack = defineStack({ @@ -178,6 +178,7 @@ const fixtureStack = defineStack({ }, objects, views: [IntakeViews], + forms: [IntakeForm], permissions: [GuestReader, FoldSet, EveryoneReader], apis: endpoints, } as any); diff --git a/packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts b/packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts index 9e2f1caaefb..3822d2d7002 100644 --- a/packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts +++ b/packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts @@ -36,7 +36,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { MetadataPlugin } from '@objectstack/metadata'; import { RecordChangeTriggerPlugin } from '@objectstack/trigger-record-change'; -import { defineStack, defineView, defineFlow } from '@objectstack/spec'; +import { defineForm, defineStack, defineView, defineFlow } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { definePermissionSet, describeAnchorForbiddenBits } from '@objectstack/spec/security'; import { SystemUserId } from '@objectstack/spec/system'; @@ -134,14 +134,14 @@ const create = (key: 'lead' | 'hooked' | 'flowed'): ApiEndpoint => ({ const intakeData = { provider: 'object' as const, object: OBJ.intake }; const IntakeViews = defineView({ list: { label: 'Intake', type: 'grid', data: intakeData, columns: [{ field: 'name' }] }, - formViews: { - intake: { - type: 'simple', - data: intakeData, - sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${FORM_SLUG}` }, - }, - }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`. */ +const IntakeForm = defineForm({ + name: `${OBJ.intake}.intake`, + object: OBJ.intake, + type: 'simple', + sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${FORM_SLUG}` }, }); const fixtureStack = defineStack({ @@ -157,6 +157,7 @@ const fixtureStack = defineStack({ requires: ['automation', 'triggers'], objects: [object(OBJ.lead), object(OBJ.hooked), object(OBJ.flowed), object(OBJ.intake)], views: [IntakeViews], + forms: [IntakeForm], flows: [AssignFlow], permissions: [GuestWriter, GuestWriterTransfer], apis: [create('lead'), create('hooked'), create('flowed')], diff --git a/packages/qa/dogfood/test/public-form-read-back-masking.dogfood.test.ts b/packages/qa/dogfood/test/public-form-read-back-masking.dogfood.test.ts index 848214ec532..db1c5cc3b56 100644 --- a/packages/qa/dogfood/test/public-form-read-back-masking.dogfood.test.ts +++ b/packages/qa/dogfood/test/public-form-read-back-masking.dogfood.test.ts @@ -33,7 +33,7 @@ import { describe, it, expect } from 'vitest'; import { bootStack } from '@objectstack/verify'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { definePermissionSet } from '@objectstack/spec/security'; @@ -62,21 +62,21 @@ const PfmaskTicket = ObjectSchema.create({ const data = { provider: 'object' as const, object: TICKET }; const PfmaskTicketViews = defineView({ list: { label: 'Tickets', type: 'grid', data, columns: [{ field: 'subject' }] }, - formViews: { - intake: { - type: 'simple', - data, - sections: [ - { - name: 'intake', - label: 'Intake', - columns: 1, - fields: [{ field: 'subject', required: true }, { field: 'pfmask_code' }], - }, - ], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`. */ +const PfmaskTicketIntakeForm = defineForm({ + name: `${TICKET}.intake`, + object: TICKET, + type: 'simple', + sections: [ + { + name: 'intake', + label: 'Intake', + columns: 1, + fields: [{ field: 'subject', required: true }, { field: 'pfmask_code' }], }, - }, + ], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, }); /** The guest set the form-submit route's grant context names, declared by the stack. */ @@ -99,12 +99,14 @@ const noGuestSetStack = defineStack({ manifest: manifest('no-guest-set', 'One object with two masked fields behind an anonymous form; no guest set.'), objects: [PfmaskTicket], views: [PfmaskTicketViews], + forms: [PfmaskTicketIntakeForm], }); const guestSetStack = defineStack({ manifest: manifest('guest-set', 'One object with two masked fields behind an anonymous form, and a guest set.'), objects: [PfmaskTicket], views: [PfmaskTicketViews], + forms: [PfmaskTicketIntakeForm], permissions: [PfmaskGuestSet], }); diff --git a/packages/qa/dogfood/test/public-form-submit-answer.dogfood.test.ts b/packages/qa/dogfood/test/public-form-submit-answer.dogfood.test.ts index 5050d847a3a..34d903bc248 100644 --- a/packages/qa/dogfood/test/public-form-submit-answer.dogfood.test.ts +++ b/packages/qa/dogfood/test/public-form-submit-answer.dogfood.test.ts @@ -33,7 +33,7 @@ import { describe, it, expect } from 'vitest'; import { bootStack } from '@objectstack/verify'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { definePermissionSet } from '@objectstack/spec/security'; @@ -77,21 +77,21 @@ const PfansRequest = ObjectSchema.create({ const data = { provider: 'object' as const, object: REQUEST }; const PfansRequestViews = defineView({ list: { label: 'Requests', type: 'grid', data, columns: [{ field: 'subject' }] }, - formViews: { - intake: { - type: 'simple', - data, - sections: [ - { - name: 'intake', - label: 'Intake', - columns: 1, - fields: [{ field: 'subject', required: true }, { field: 'email' }], - }, - ], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`. */ +const PfansRequestIntakeForm = defineForm({ + name: `${REQUEST}.intake`, + object: REQUEST, + type: 'simple', + sections: [ + { + name: 'intake', + label: 'Intake', + columns: 1, + fields: [{ field: 'subject', required: true }, { field: 'email' }], }, - }, + ], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, }); /** Look the submitted email up among existing contacts, elevated, and stamp the match. */ @@ -135,6 +135,7 @@ const noGuestSetStack = defineStack({ manifest: manifest('no-guest-set', 'An anonymous form whose elevated hook stamps a match from existing records; no guest set.'), objects: [PfansContact, PfansRequest], views: [PfansRequestViews], + forms: [PfansRequestIntakeForm], hooks: [matchExistingHook], } as any); @@ -142,6 +143,7 @@ const guestSetStack = defineStack({ manifest: manifest('guest-set', 'An anonymous form whose elevated hook stamps a match from existing records, and a guest set.'), objects: [PfansContact, PfansRequest], views: [PfansRequestViews], + forms: [PfansRequestIntakeForm], hooks: [matchExistingHook], permissions: [PfansGuestSet], } as any); diff --git a/packages/qa/dogfood/test/public-form-withdrawal-walled.dogfood.test.ts b/packages/qa/dogfood/test/public-form-withdrawal-walled.dogfood.test.ts index 03de40e5cef..a199d251026 100644 --- a/packages/qa/dogfood/test/public-form-withdrawal-walled.dogfood.test.ts +++ b/packages/qa/dogfood/test/public-form-withdrawal-walled.dogfood.test.ts @@ -29,13 +29,13 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; import { declaredOverride, ensurePair, inPair } from './customization-pair.js'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; const LEAD = 'walled_lead'; const SLUG = 'walled-lead-intake'; -const VIEW = `/meta/view/${LEAD}.intake`; +const FORM = `/meta/form/${LEAD}.intake`; const BASE = 'com.dogfood.walled-public-form'; const WalledLead = ObjectSchema.create({ @@ -52,14 +52,14 @@ const WalledLead = ObjectSchema.create({ const data = { provider: 'object' as const, object: LEAD }; const WalledLeadViews = defineView({ list: { label: 'Leads', type: 'grid', data, columns: [{ field: 'name' }] }, - formViews: { - intake: { - type: 'simple', - data, - sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, - }, - }, +}); +/** The public form, a `form` item (ADR-0159): `OBJECT.KEY`, bound by `object`, the body at its root. */ +const WalledLeadIntakeForm = defineForm({ + name: `${LEAD}.intake`, + object: LEAD, + type: 'simple', + sections: [{ name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'name', required: true }] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, }); const walledFormStack = defineStack({ @@ -73,6 +73,7 @@ const walledFormStack = defineStack({ }, objects: [WalledLead], views: [WalledLeadViews], + forms: [WalledLeadIntakeForm], }); const SYS = { isSystem: true } as const; @@ -114,20 +115,20 @@ describe('walled posture: withdrawing a public form from anonymous intake', () = /** PUT the form at the admin's current session scope. */ const put = async (body: Record) => { - const res = await stack.apiAs(admin, 'PUT', inPair(VIEW, BASE), declaredOverride(body, BASE, '0.0.0')); + const res = await stack.apiAs(admin, 'PUT', inPair(FORM, BASE), declaredOverride(body, BASE, '0.0.0')); const json = (await res.json()) as Record; return { status: res.status, json }; }; const withAnonymous = (allowAnonymous: boolean): Record => { const body = structuredClone(published); - body.config.sharing.allowAnonymous = allowAnonymous; + body.sharing.allowAnonymous = allowAnonymous; return body; }; /** The effective form as the admin's current scope reads it. */ const read = async (): Promise> => { - const res = await stack.apiAs(admin, 'GET', VIEW); + const res = await stack.apiAs(admin, 'GET', FORM); expect(res.status).toBe(200); const json = (await res.json()) as { item?: Record }; return (json.item ?? json) as Record; @@ -144,7 +145,7 @@ describe('walled posture: withdrawing a public form from anonymous intake', () = const item = await read(); // The editor's PUT body: the effective item without its read decorations. published = Object.fromEntries(Object.entries(item).filter(([k]) => !k.startsWith('_'))); - expect(published.config?.sharing?.allowAnonymous).toBe(true); + expect(published.sharing?.allowAnonymous).toBe(true); const created = await stack.apiAs(admin, 'POST', '/auth/organization/create', { name: 'Walled Tenant', slug: 'walled-tenant-form', @@ -221,7 +222,7 @@ describe('walled posture: withdrawing a public form from anonymous intake', () = it('withdrawn through `sharing.enabled: false` alone, by an org-active admin and env-wide: both doors 404 and nothing lands', async () => { const withEnabled = (enabled: boolean): Record => { const body = withAnonymous(true); - body.config.sharing.enabled = enabled; + body.sharing.enabled = enabled; return body; }; // [ADR-0131 D6] An org-active admin's withdrawal is environment-wide too. diff --git a/packages/qa/dogfood/test/view-container-default-form.dogfood.test.ts b/packages/qa/dogfood/test/view-container-default-form.dogfood.test.ts index c6854abde8e..c420cccea04 100644 --- a/packages/qa/dogfood/test/view-container-default-form.dogfood.test.ts +++ b/packages/qa/dogfood/test/view-container-default-form.dogfood.test.ts @@ -1,54 +1,56 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // -// [#21500] A view container that authors both a default `form` and named -// `formViews` serves its default `form` as THE default form on the object door, -// over a real boot, through `GET /api/v1/meta/view?object=OBJECT` — the read the -// console's create and edit surfaces are built from. +// [#21500] An object's forms are each served whole, under their own name, over +// a real boot — no form is collapsed into another that looks like it, and no +// form is promoted over another. // -// ## The contract (triage's ruling on the card) -// -// `ViewSchema.form` is the default form and `formViews` are additional. Create -// and edit render `form`; a named form is used only where it is asked for by -// name. At this door that is: the container's `form` is served as a form-family -// item carrying `isDefault: true`, and no named form carries it. The console's -// view merge (objectui `MetadataProvider.tsx`, `applyViewItem`) makes the -// `isDefault` form item the object's `.form`, else the first form item. -// -// ## The measurement this probe was written from +// ## Where this probe came from // // HotCRM's `crm_lead` container (objectstack-ai/hotcrm `0b2a9d4`, -// `src/sales/views/lead.view.ts`) authors a default `form` of type `simple` -// with no top-level `label`, a tabbed `formViews.detail_form`, and among its -// other named forms `formViews.web_to_lead` of type `simple`, also unlabelled. -// The fixture below reduces it to exactly those three forms. +// `src/sales/views/lead.view.ts`) authored, on protocol 18, a default `form` of +// type `simple` with no top-level `label`, a tabbed `formViews.detail_form`, +// and among its other named forms `formViews.web_to_lead` of type `simple`, +// also unlabelled. Measured at `origin/main` `85e29b8858`, the object door +// served `crm_lead.detail_form` flagged as the default and `crm_lead.web_to_lead`, +// and no item carried the default `form` at all: the container expansion +// collapsed the default `form` into the named form whose `{ type, label, +// columns }` signature it shared, then stamped the default on the FIRST named +// form. // -// Measured at `origin/main` `85e29b8858`, on this harness's unscoped kernel and -// on the CLI's standalone stack (`env_local`), the door served the same items -// for the package-shipped container: `crm_lead.detail_form` with -// `isDefault: true`, then `crm_lead.web_to_lead`; no item carries the default -// `form` at all. The cause is in `expandViewContainer` (`@objectstack/spec`): -// the form family collapses the default `form` into any named form whose -// `{ type, label, columns }` signature it shares — here `web_to_lead` — and then -// stamps `isDefault` on the FIRST named form, not on the one it matched. +// ## On protocol 19 (ADR-0159) // -// The two-form shape (`form` + `formViews.detail_form` only) and the -// `crm_account` control (a `form` and no `formViews`) are served correctly, and -// are kept here so the probe cannot pass by serving any one fixed answer. +// A form is its own metadata type, authored under `forms:` and named +// `OBJECT.KEY`; a `view` holds lists only, and a form item carries no +// `isDefault` (the record create and edit form is the object's `fieldGroups`). +// So the same three forms are authored here as `form` items and read through +// `GET /api/v1/meta/form`. What the probe still pins is the +// defect's observable half: every authored form is served under its own name +// with its own content (the default form's `intake` section is never lost into +// `web_to_lead`), none carries a default flag, and the view door serves no form +// at all. The two-form shape and the `crm_account` control are kept so the probe +// cannot pass by serving one fixed answer. The protocol-18 container shape +// itself is refused at parse, naming the `forms:` move; the last case pins that +// refusal, so the old fixture cannot come back as a silent pass. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; -import { defineStack } from '@objectstack/spec'; +import { defineStack, defineForm } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; -interface ViewRow { +interface FormRow { name: string; object?: string; - viewKind?: string; + type?: string; isDefault?: boolean; - config?: { type?: string; sections?: Array<{ name?: string }> }; + sections?: Array<{ name?: string }>; +} + +interface ViewRow { + name: string; + viewKind?: string; } -/** The default form's one section — the content only `form` authors. */ +/** The default form's one section — the content only `crm_lead.form` authors. */ const DEFAULT_FORM_SECTION = 'intake'; const defaultForm = { @@ -59,19 +61,18 @@ const defaultForm = { columns: 2, fields: [{ field: 'name' }, { field: 'need_type' }, { field: 'estimated_amount' }], }], -}; +} as const; const detailForm = { type: 'tabbed', sections: [ { name: 'general', label: 'General', fields: [{ field: 'name' }, { field: 'email' }] }, { name: 'address', label: 'Address', fields: [{ field: 'street' }] }, ], -}; -const webToLead = (object: string) => ({ +} as const; +const webToLead = { type: 'simple', - data: { provider: 'object', object }, sections: [{ name: 'contact_us', label: 'Contact us', fields: [{ field: 'name' }, { field: 'email' }] }], -}); +} as const; const object = (name: string) => ObjectSchema.create({ name, @@ -87,28 +88,39 @@ const object = (name: string) => ObjectSchema.create({ }, }); +const manifest = { + id: 'com.example.dogfood-default-form', + namespace: 'crm', + version: '0.0.1', + type: 'app', + name: 'Default form fixture', + engines: { protocol: '^19' }, +} as const; + +/** A `form` item of `obj` named `obj.key` with `body`. */ +const form = (obj: string, key: string, body: Record) => + defineForm({ name: `${obj}.${key}`, object: obj, ...body } as Parameters[0]); + const fixture = defineStack({ - manifest: { - id: 'com.example.dogfood-default-form', - namespace: 'crm', - version: '0.0.1', - type: 'app', - name: 'Default form fixture', - engines: { protocol: '^19' }, - }, + manifest, objects: [object('crm_lead'), object('crm_contact'), object('crm_account')], - views: [ - // HotCRM's form family: a default `form`, a tabbed named form, and a named - // form of the default form's own type. - { object: 'crm_lead', form: defaultForm, formViews: { detail_form: detailForm, web_to_lead: webToLead('crm_lead') } }, - // Both forms, of different types and nothing else. - { object: 'crm_contact', form: defaultForm, formViews: { detail_form: detailForm } }, - // The control: a default form and no `formViews`. - { object: 'crm_account', form: detailForm }, - ] as any, -}); + // One list, so the view door's answer for `crm_lead` is not empty by accident. + views: [{ object: 'crm_lead', list: { type: 'grid', label: 'All', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'] } }], + forms: [ + // HotCRM's form family: the former default form, a tabbed form, and a form + // of the former default form's own type. + form('crm_lead', 'form', defaultForm), + form('crm_lead', 'detail_form', detailForm), + form('crm_lead', 'web_to_lead', webToLead), + // Two forms of different types and nothing else. + form('crm_contact', 'form', defaultForm), + form('crm_contact', 'detail_form', detailForm), + // The control: one form. + form('crm_account', 'form', detailForm), + ], +} as Parameters[0]); -describe('dogfood: a container\'s default `form` is the default form on the object door (#21500)', () => { +describe('dogfood: an object\'s forms are each served whole under their own name (#21500)', () => { let stack: VerifyStack; let token: string; @@ -121,39 +133,78 @@ describe('dogfood: a container\'s default `form` is the default form on the obje await stack?.stop(); }); - /** The form-family items `GET /api/v1/meta/view?object=OBJECT` serves, in served order. */ - const formItems = async (obj: string): Promise => { - const res = await stack.apiAs(token, 'GET', `/meta/view?object=${obj}`); + /** + * The form items of `obj` that `GET /api/v1/meta/form` serves, in served + * order. The list is read whole and narrowed by each item's own `object`: + * the list's `?object=` filter is read for the `view` type only. + */ + const formItems = async (obj: string): Promise => { + const res = await stack.apiAs(token, 'GET', '/meta/form'); expect(res.status).toBe(200); - const body = (await res.json()) as { items?: ViewRow[] } | ViewRow[]; + const body = (await res.json()) as { items?: FormRow[] } | FormRow[]; const rows = Array.isArray(body) ? body : (body.items ?? []); - return rows.filter((r) => r.viewKind === 'form'); + return rows.filter((r) => r.object === obj); }; - const sectionsOf = (row: ViewRow | undefined) => (row?.config?.sections ?? []).map((s) => s.name); - const defaults = (rows: ViewRow[]) => rows.filter((r) => r.isDefault === true); + const sectionsOf = (rows: FormRow[], name: string) => + (rows.find((r) => r.name === name)?.sections ?? []).map((s) => s.name); + const defaults = (rows: FormRow[]) => rows.filter((r) => r.isDefault === true); - it('a container with a default `form` and named forms serves `form` as the one default form', async () => { + it('an object with a former default form and two named forms serves all three, each with its own content', async () => { const rows = await formItems('crm_lead'); - // Every authored form is served: the default and both named ones. + // Every authored form is served: the former default and both named ones. expect(rows.map((r) => r.name).sort()).toEqual( ['crm_lead.detail_form', 'crm_lead.form', 'crm_lead.web_to_lead'], ); - // Exactly one default, and it is the default form's own content. - expect(defaults(rows).map((r) => r.name)).toEqual(['crm_lead.form']); - expect(sectionsOf(defaults(rows)[0])).toEqual([DEFAULT_FORM_SECTION]); + // The former default form's content is its own — never folded into the + // `simple` form that shares its signature — and each other form keeps its own. + expect(sectionsOf(rows, 'crm_lead.form')).toEqual([DEFAULT_FORM_SECTION]); + expect(sectionsOf(rows, 'crm_lead.web_to_lead')).toEqual(['contact_us']); + expect(sectionsOf(rows, 'crm_lead.detail_form')).toEqual(['general', 'address']); + // No form is promoted to a default: a form item carries none. + expect(defaults(rows).map((r) => r.name)).toEqual([]); }); - it('a container with a default `form` and one named form of another type serves `form` as the default', async () => { + it('an object with two forms of different types serves both, each with its own content', async () => { const rows = await formItems('crm_contact'); expect(rows.map((r) => r.name).sort()).toEqual(['crm_contact.detail_form', 'crm_contact.form']); - expect(defaults(rows).map((r) => r.name)).toEqual(['crm_contact.form']); - expect(sectionsOf(defaults(rows)[0])).toEqual([DEFAULT_FORM_SECTION]); + expect(sectionsOf(rows, 'crm_contact.form')).toEqual([DEFAULT_FORM_SECTION]); + expect(sectionsOf(rows, 'crm_contact.detail_form')).toEqual(['general', 'address']); + expect(defaults(rows).map((r) => r.name)).toEqual([]); }); - it('control: a container with a default `form` and no `formViews` serves that form as the default', async () => { + it('control: an object with one form serves that form with its content', async () => { const rows = await formItems('crm_account'); expect(rows.map((r) => r.name)).toEqual(['crm_account.form']); - expect(defaults(rows).map((r) => r.name)).toEqual(['crm_account.form']); - expect(sectionsOf(defaults(rows)[0])).toEqual(['general', 'address']); + expect(sectionsOf(rows, 'crm_account.form')).toEqual(['general', 'address']); + expect(defaults(rows).map((r) => r.name)).toEqual([]); + }); + + it('the view door serves the object\'s list and no form', async () => { + const res = await stack.apiAs(token, 'GET', '/meta/view?object=crm_lead'); + expect(res.status).toBe(200); + const body = (await res.json()) as { items?: ViewRow[] } | ViewRow[]; + const rows = Array.isArray(body) ? body : (body.items ?? []); + // Positive control: the list is served, so the door answered for this object. + expect(rows.map((r) => r.name)).toContain('crm_lead.default'); + expect(rows.filter((r) => r.viewKind !== 'list').map((r) => r.name)).toEqual([]); + }); + + it('the protocol-18 container (a default `form` plus `formViews`) is refused at parse, naming the `forms:` move', () => { + let refusal: unknown; + try { + defineStack({ + manifest, + objects: [object('crm_lead')], + views: [{ object: 'crm_lead', form: defaultForm, formViews: { detail_form: detailForm, web_to_lead: webToLead } }], + } as unknown as Parameters[0]); + } catch (error) { + refusal = error; + } + const e = refusal as { code?: string; status?: number; issues?: Array<{ path: PropertyKey[]; message: string }> }; + expect({ code: e?.code, status: e?.status }).toEqual({ code: 'STACK_SCHEMA_INVALID', status: 422 }); + const issues = (e.issues ?? []).map((i) => ({ path: i.path.join('.'), message: i.message })); + // Each held form is refused by its own key, and each refusal names the `forms:` move. + expect(issues.map((i) => i.path).sort()).toEqual(['views.0.form', 'views.0.formViews']); + for (const issue of issues) expect(issue.message).toContain('`forms:`'); }); }); diff --git a/packages/rest/src/data-write-summary-recompute-other-doors.test.ts b/packages/rest/src/data-write-summary-recompute-other-doors.test.ts index 40d5cb4e8c2..adbdf2c206f 100644 --- a/packages/rest/src/data-write-summary-recompute-other-doors.test.ts +++ b/packages/rest/src/data-write-summary-recompute-other-doors.test.ts @@ -47,7 +47,6 @@ import { RestServer } from './rest-server'; import { installDefaultOrganization } from './default-organization.testkit.js'; // [#10126] Pay the first transform of this dist-resolved workspace dep at module load. -import { projectedFormsOf } from '@objectstack/spec/ui'; const PARENT = 'qsf_parent'; const CHILD = 'qsf_child'; @@ -75,15 +74,12 @@ const CHILD_OBJECT = { }, }; -const FORM_VIEW = { +/** [ADR-0159 D7] The public form as protocol 19 holds it: a `form` item, bound by `object`. */ +const FORM_ITEM = { name: 'qsf_child_form', object: CHILD, - viewKind: 'form', - config: { - data: { object: CHILD }, - sections: [{ fields: ['name', 'amount', 'parent'] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/qsf' }, - }, + sections: [{ fields: ['name', 'amount', 'parent'] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/qsf' }, }; function createMockServer() { @@ -134,15 +130,17 @@ beforeAll(async () => { }); const real = new ObjectStackProtocolImplementation(engine as any); - // The form door finds its form among the `view` items; everything else is the real protocol. + // The form door finds its form among the `form` items; everything else is the real protocol. const protocol = new Proxy(real as any, { get(target, prop, receiver) { if (prop === 'getMetaItemsPerPackage') return async () => []; - // [ADR-0159] No stored body and no `form` item: the door reads FORM_VIEW through the projection. + // [ADR-0159 D7] No stored body: the store is not provisioned, so the + // withdrawal layer's stored-row read answers none, like the other two. if (prop === 'getUnreadableFormBodies') return async () => []; + if (prop === 'getViewItemsWithStoredForms') return async () => []; if (prop === 'getMetaItems') { // The engine holds the objects; this harness registers no metadata service. - return async (req: any) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'form' ? projectedFormsOf([FORM_VIEW]) : req?.type === 'object' ? [CHILD_OBJECT, PARENT_OBJECT] : target.getMetaItems(req)); + return async (req: any) => (req?.type === 'view' ? [] : req?.type === 'form' ? [FORM_ITEM] : req?.type === 'object' ? [CHILD_OBJECT, PARENT_OBJECT] : target.getMetaItems(req)); } const v = Reflect.get(target, prop, receiver); return typeof v === 'function' ? v.bind(target) : v; diff --git a/packages/rest/src/form-old-shape-layers-38437.test.ts b/packages/rest/src/form-old-shape-layers-38437.test.ts index 501f82ff88e..c473adc33ae 100644 --- a/packages/rest/src/form-old-shape-layers-38437.test.ts +++ b/packages/rest/src/form-old-shape-layers-38437.test.ts @@ -27,6 +27,7 @@ import { SysMetadataCommitObject, SysMetadataHistoryObject, SysMetadataObject, + hashSpec, } from '@objectstack/metadata-core'; import { RestServer } from './rest-server'; @@ -138,6 +139,19 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { const install = async (id: string) => protocol.installPackage({ manifest: { id, name: id.split('.').join('-'), version: '0.1.0', type: 'app', namespace: 'fol_custom', dependencies: { [BASE]: '^1' } }, }); + /** + * A stored row as it exists at rest, written past every door: the shape a + * deployment upgraded from 18 may still store, which no save door admits + * on major 19 (ADR-0159 D7). + */ + const seedRow = async (type: string, packageId: string, item: Record) => { + const now = new Date().toISOString(); + await engine.insert('sys_metadata', { + id: `seed_${type}_${NAME}_${packageId}`, type, name: NAME, + package_id: packageId, state: 'active', metadata: JSON.stringify(item), checksum: hashSpec(item, type), + version: 1, created_at: now, updated_at: now, + }, { context: { isSystem: true } }); + }; const saveInto = async (type: 'view' | 'form', packageId: string, item: Record) => { await protocol.saveMetaItem({ type, name: NAME, item, mode: 'draft', packageId }); await protocol.publishMetaItem({ type, name: NAME, packageId }); @@ -155,7 +169,7 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[] }) { const layered = (packageId?: string) => protocol.getMetaItemLayered({ type: 'form', name: NAME, ...(packageId ? { packageId } : {}) }); const perPackage = async (packageId: string) => ((await protocol.getMetaItemsPerPackage({ type: 'form', packageId })).items as any[]) .filter((item) => item?.name === NAME); - return { protocol, get, post, records, install, saveInto, layers, layered, perPackage }; + return { protocol, get, post, records, install, seedRow, saveInto, layers, layered, perPackage }; } type Booted = Awaited>; @@ -191,7 +205,7 @@ describe('#38437 the form layered and per-package reads serve an old-shape base' // Ablation: the `form` arm of `getMetaItemLayered` removed → `code` and // `effective` read `null`; the `form` arm of `getMetaItemsPerPackage` // removed → the per-package layer reads `[]`. - it('pin 1: an old-shape base, no pair, reads as its projected form', async () => { + it('pin 1: an old-shape base, no pair, reads as its projected form; on 19 its doors serve no form (ADR-0159 D7)', async () => { const b = await boot({ views: [container('open')] }); for (const at of [BASE, undefined]) { const L = await b.layered(at); @@ -200,7 +214,9 @@ describe('#38437 the form layered and per-package reads serve an old-shape base' expect(L.overlay).toBeNull(); } expect((await b.perPackage(BASE)).map(form)).toEqual([projected('open')]); - await openOnBothDoors(b); + // [ADR-0159 D7] The projection serves no content on 19: no door serves an + // old-shape base's form. + await closedOnBothDoors(b); }); // Ablation: the arm removed → `code` reads `null` at both addresses. @@ -225,7 +241,8 @@ describe('#38437 the form layered and per-package reads serve an old-shape base' it('pin 3: a pre-card view override in the pair, no form row: effective is the override\'s projection', async () => { const b = await boot({ views: [container('open')] }); await b.install(PAIR); - await b.saveInto('view', PAIR, viewItem('closed', overrides)); + // The pre-card override is a stored old-shape row: the `view` door refuses the shape on 19. + await b.seedRow('view', PAIR, viewItem('closed', overrides)); const L = await b.layered(BASE); expect(form(L.code)).toEqual(projected('open')); expect(L.overlay).toBeNull(); diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index c2268c420f6..251d0dfad10 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -68,20 +68,16 @@ */ import { - anonymousFormIntakeCandidates, anonymousFormIntakePosture, anonymousFormIntakeUnavailability, - anonymousFormObjectName, } from '@objectstack/metadata-core'; import { isEmptyForRequired, isMissing } from '@objectstack/core'; import type { CreateDataRequest, GetMetaItemsRequest, PublicFormSubmitResponse } from '@objectstack/spec/api'; import { PUBLIC_FORM_SERVER_MANAGED_FIELDS } from '@objectstack/spec/security'; import { renderValidationMessage } from '@objectstack/spec/system'; import { - PROJECTED_FORM_SOURCE_KEY, formIntakeLayer, openFormAt, - projectViewForms, thankYouRecordFieldNames, type FormIntakeLayer, type UnreadableFormBody, @@ -215,12 +211,10 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // dependent package's same-named row, the base's form the override // removed — is not offered: that narrows intake, the direction a layer // may take. - // [ADR-0159 D6] Since card ②, over BOTH types. The candidates are the - // open forms of the effective `form` read — authored `form` items and the - // projection of the old shapes (a container's `form`, a `formViews` - // entry, a `viewKind: 'form'` item), resolved over both types, so a - // stored row that closes an address by replacing its base's body keeps - // closing it. The withdrawal layer is the effective lists AND the + // [ADR-0159 D6, D7] Over BOTH types. The candidates are the open forms of + // the effective `form` read, resolved over both types, so a stored row + // that closes an address by replacing its base's body keeps closing it + // (rule 11). The withdrawal layer is the effective lists AND the // per-package layers of both `form` and `view`, the old shapes passed // through the projection first (`formIntakeLayer`): narrowing only, in // both directions. Identity is the served name and, inside one name, the @@ -229,38 +223,19 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // different form. A stored body the projection cannot read closes the // links it names (rule 7, `getUnreadableFormBodies`). // - // A projected form whose served `view` item the effective `view` list - // still serves is answered through that item exactly as before (the same - // `form` object, the same label and translation), so an old-shape form - // answers byte-equal on the resolve door. + // [ADR-0159 D7] Since protocol 19 the candidates are `form` items only: + // the projection serves no content, so no candidate is answered through a + // `view` item. The stored old-shape bodies are read for the withdrawal + // layer alone (rule 10, the kept reader). const findPublicForm = ( forms: any[], - views: any[], layer: FormIntakeLayer, slug: string, - ): { view: any; form: any; object: string; formItem: any } | null => { + ): { form: any; object: string; formItem: any } | null => { const open = openFormAt(forms ?? [], layer, slug); if (!open) return null; const item = open.form; - if (item?.[PROJECTED_FORM_SOURCE_KEY] === 'view') { - const pkg = item?._packageId ?? undefined; - for (const view of views ?? []) { - if (!view || typeof view !== 'object') continue; - // The served item of that name, or (from a protocol that hands - // the doors a container) the container whose projection it is. - if (view.name !== item.name && !projectViewForms(view).forms.some((f) => f.name === item.name)) continue; - if ((view._packageId ?? undefined) !== pkg) continue; - const c = anonymousFormIntakeCandidates(view).find((candidate) => candidate.slug === slug); - if (!c) continue; - const objectName = anonymousFormObjectName(view, c.form); - if (objectName !== open.object) continue; - return { view, form: c.form, object: objectName, formItem: item }; - } - } - // An authored `form` item, or a projected one the `view` list does - // not serve at its address (a stored `view` row over a base that left - // the type): served as the form body, without its item envelope. - return { view: undefined, form: formBodyOf(item), object: open.object, formItem: item }; + return { form: formBodyOf(item), object: open.object, formItem: item }; }; // [ADR-0131 D6, C7] WHICH metadata an anonymous form request reads: @@ -292,7 +267,7 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo environmentId: string | undefined, req: any, slug: string, - ): Promise<{ view: any; form: any; object: string; formItem: any } | null> => { + ): Promise<{ form: any; object: string; formItem: any } | null> => { const p = await this.resolveProtocol(environmentId, req); if (typeof (p as any).getMetaItems !== 'function') return null; const tenancy = await this.resolveAnonymousFormTenancy(environmentId, req); @@ -314,8 +289,16 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo const inOneReading = (read: () => Promise): Promise => (typeof (p as any).readFormRequest === 'function' ? (p as any).readFormRequest(read) : read()); - const { forms, views, layer } = await inOneReading(async () => { - const views = listOf(await p.getMetaItems(viewsRequest)); + const { forms, layer } = await inOneReading(async () => { + // [ADR-0159 D7, D6 rule 10] The withdrawal layer reads every + // stored body the doors honoured, the form items of a stored + // old-shape row included, which the served `view` list leaves out + // since protocol 19 (`getViewItemsWithStoredForms`, a server-only + // extension, feature-detected). A protocol without it serves the + // whole `view` list on its own read. + const views = listOf(typeof (p as any).getViewItemsWithStoredForms === 'function' + ? await (p as any).getViewItemsWithStoredForms(viewsRequest) + : await p.getMetaItems(viewsRequest)); // [ADR-0159 D5, D6 rules 1 and 3] The candidates are the effective // `form` read, which projects the old shapes itself: ONE read, and no // second candidate source inside the door. A protocol that serves no @@ -333,14 +316,24 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo const unreadable: UnreadableFormBody[] = typeof (p as any).getUnreadableFormBodies === 'function' ? await (p as any).getUnreadableFormBodies() : []; + // [ADR-0146 D8, ADR-0159 D7] The base's own document of each + // candidate name, from the code layer: a declared override is + // served in its place, and the `form` per-package layer holds + // stored rows only, so without it a base whose own form is + // switched off (or not anonymous) would be judged by its + // override alone. Added to the layer, never a candidate: it can + // only close (a withdrawal layer only narrows). + const packagedBases = [...new Set(forms.map((f: any) => f?.name).filter((n: unknown) => typeof n === 'string'))] + .map((name) => this.packagedObjectBase(p, 'form', name)) + .filter((base: unknown) => base !== null && typeof base === 'object'); const layer = formIntakeLayer({ - forms: [...forms, ...(await perPackage(formsRequest))], + forms: [...forms, ...(await perPackage(formsRequest)), ...packagedBases], views: [...views, ...(await perPackage(viewsRequest))], unreadable, }); - return { forms, views, layer }; + return { forms, layer }; }); - const match = findPublicForm(forms, views, layer, slug); + const match = findPublicForm(forms, layer, slug); if (!match) return null; // [#21476] A form that cannot take intake on this posture is not // offered: `null` here IS the withdrawn form's answer on both @@ -407,12 +400,12 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // sections' `label` / `description` localized beside the // schema's field labels (see the translation block). let servedForm: any = match.form; - // The top-level `label`, served from the TRANSLATED view - // when the view authors one (see the translation block). A - // view that authors none keeps the route's own reading, so + // The top-level `label`, served from the TRANSLATED form + // when the form authors one (see the translation block). A + // form that authors none keeps the route's own reading, so // the console's `label ?? form.title ?? objectSchema.label` // still reaches the form's (translated) title. - let servedLabel: any = match.view !== undefined ? (match.view?.label ?? match.form?.label) : match.formItem?.label; + let servedLabel: any = match.formItem?.label; try { const p = await this.resolveProtocol(environmentId, req); if (typeof (p as any).getMetaItems === 'function') { @@ -470,7 +463,7 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // rank sits above it: an object is extended, // never replaced (ADR-0146 D10), so it never // answers `servedOverrideBaseOf` and this call - // passes no `pairBundle` (the view call below does). + // passes no `pairBundle` (the form call below does). const patchBundles = await patchTranslationBundlesOf(p, 'object', objectSchema?.name); objectSchema = translateMetadataDocument('object', objectSchema, bundle, { ...this.translateOptionsFor(i18n, locale), @@ -479,69 +472,28 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo }); // [#23497] The section headings. An anonymous // visitor cannot load the bundle client-side (the - // `/i18n` domain answers it 401), so a section's - // `objects.OBJECT._sections.NAME` copy reaches it - // here or not at all. ONE call into the spec's view - // translator, which owns every rule: the key is the - // section's `name` (a nameless section is returned - // as authored), a missing key keeps the authored - // text, only authored copy is translated, and an - // explicit override beats the catalog against the - // packaged view, handed over exactly as the object - // call above hands its own base. ⛔ No walk of - // `_sections` and no locale chain here. - // - // The protocol's view list serves view ITEMS only - // (a container is dropped and served as the - // `viewKind: 'form'` items it expands to), so the - // matched form is the item's `config`, the address - // `translateView` translates sections at. A form - // matched in any other slot is served as matched, - // never swapped for the item's `config`. It runs - // BEFORE the strip below and returns each section's - // `fields` untouched, so it cannot re-introduce a - // stripped field. The same call translates the - // form's `title` (`objects.OBJECT._views.VIEW.title`, - // at `config.title`), so the served form carries it. - // - // The top-level `label` is taken from the translated - // view only when the view AUTHORS one: the translator - // falls back to the view's machine name, which must - // never shadow the form's title in the console's - // `label ?? form.title ?? objectSchema.label`. + // `/i18n` domain answers it 401), so the form's copy + // reaches it here or not at all. ONE call into the + // spec's form translator, which owns every rule: + // `forms.NAME` first, `objects.OBJECT._sections` as + // a section's object-level default, a missing key + // keeps the authored text, and an explicit override + // beats the catalog against the packaged form. It + // runs BEFORE the strip below and returns each + // section's `fields` untouched, so it cannot + // re-introduce a stripped field. // - // A form view a `.custom` pair overrides (ADR-0146 - // D2) is also handed the pair's own translations, - // the first rank of a string the override changed - // (ruling record 6631250894): the same - // `pairTranslationBundleOf` question the `/meta/view` - // reads ask, of the view as the protocol served it - // (its envelope names the base). `undefined` keeps - // the override's own text, as before. - if (match.view !== undefined) { - const pairBundle = await pairTranslationBundleOf(p, 'view', match.view); - const view = translateMetadataDocument('view', match.view, bundle, { - ...this.translateOptionsFor(i18n, locale), - packagedBase: this.packagedObjectBase(p, 'view', match.view?.name), - ...(pairBundle !== undefined ? { pairBundle: pairBundle as any } : {}), - }); - if (match.form === match.view?.config) servedForm = view?.config; - if (match.view?.label !== undefined && view?.label !== undefined) { - servedLabel = view.label; - } - } else { - // [ADR-0159 D8] A `form` item: `forms.NAME` first, - // its old-shape `_views` tails as the fallback. - const pairBundle = await pairTranslationBundleOf(p, 'form', match.formItem); - const form = translateMetadataDocument('form', match.formItem, bundle, { - ...this.translateOptionsFor(i18n, locale), - packagedBase: this.packagedObjectBase(p, 'form', match.formItem?.name), - ...(pairBundle !== undefined ? { pairBundle: pairBundle as any } : {}), - }); - servedForm = formBodyOf(form); - if (match.formItem?.label !== undefined && form?.label !== undefined) { - servedLabel = form.label; - } + // [ADR-0159 D8] A `form` item, translated from `forms.NAME`; + // the `.custom` pair's own strings rank first (ADR-0146 D2). + const pairBundle = await pairTranslationBundleOf(p, 'form', match.formItem); + const form = translateMetadataDocument('form', match.formItem, bundle, { + ...this.translateOptionsFor(i18n, locale), + packagedBase: this.packagedObjectBase(p, 'form', match.formItem?.name), + ...(pairBundle !== undefined ? { pairBundle: pairBundle as any } : {}), + }); + servedForm = formBodyOf(form); + if (match.formItem?.label !== undefined && form?.label !== undefined) { + servedLabel = form.label; } } } catch (e: any) { diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index 7c858bfc364..9d3629c70a3 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -1863,9 +1863,9 @@ export function createMetaItemReadGate( if (metaType === 'form') { // [ADR-0159, card ② item 2] A `form` item's audience: the form's own - // `requiredPermissions` (a projected item carries its view item's gate - // too, `projectViewForms`). A caller refused a form's document at - // `/meta/view/NAME` is refused it at `/meta/form/NAME`, whole. + // `requiredPermissions`. [ADR-0159 D7] Since protocol 19 the served + // `form` read holds authored `form` items only, and no projection of + // a `view` item, so the gate judged here is always the form's own. return async (document) => { if (document == null) return serve(document); const ctx = await resolveCallerOnce(); @@ -3505,7 +3505,8 @@ const PACKAGED_BASE_ACCESSORS: ReadonlyMap = new Map { + const { data: _data, ...body } = config; + return { ...identity, ...body }; +}; + const FORM = { name: 'pf_file_supplier_form', object: OBJECT, @@ -113,17 +122,19 @@ describe('[#25572] POST /forms/:slug/submit: an anonymous submission carries no const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { - // [ADR-0159 D5] The `form` read, as the protocol serves it for the injected old shape: its projection. - if (request?.type === 'form') return projectedFormsOf([FORM]); - if (request?.type === 'view') return [FORM]; + // [ADR-0159 D7] The `form` read serves the injected form; the `view` read holds no list here. + if (request?.type === 'form') return [FORM].map(asFormItem); + if (request?.type === 'view') return []; if (request?.type === 'object') return [SUPPLIER]; return realGetMetaItems(request); }; // [#28409] The doors judge withdrawal against the effective list beside // the per-package layer: the injected list is that whole layer here. - protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'view' ? [FORM] : []); + protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'form' ? [FORM].map(asFormItem) : []); // [ADR-0159 D6 rule 7] No stored body here: the store is not provisioned, the injected lists are the layer. protocol.getUnreadableFormBodies = async () => []; + // [ADR-0159 D7, D6 rule 10] …and no stored old-shape row for the withdrawal layer to read. + protocol.getViewItemsWithStoredForms = async () => []; const realCreateData = protocol.createData.bind(protocol); createData = vi.fn(realCreateData); protocol.createData = createData; diff --git a/packages/rest/src/public-form-intake-availability.test.ts b/packages/rest/src/public-form-intake-availability.test.ts index 55fa54e60a0..bd7eea1c085 100644 --- a/packages/rest/src/public-form-intake-availability.test.ts +++ b/packages/rest/src/public-form-intake-availability.test.ts @@ -14,7 +14,6 @@ import { RestServer } from './rest-server'; // [#10126] Pay the first transform of these dist-resolved workspace deps at // MODULE LOAD rather than inside a clocked `it()` body. -import { projectedFormsOf } from '@objectstack/spec/ui'; // …and `@objectstack/objectql`, which `rest-server.ts`'s meta-object routes reach // through a dynamic import inside a handler (`check:test-source-alias`). import '@objectstack/objectql'; @@ -39,14 +38,11 @@ function mockRes() { return res; } -/** A flattened `viewKind: 'form'` item, as the protocol serves it. */ -const formView = (allowAnonymous = true) => ({ - name: 'contact', object: 'inquiry', viewKind: 'form', _diagnostics: { valid: true }, - config: { - data: { object: 'inquiry' }, - sections: [{ fields: ['name', 'email'] }], - sharing: { enabled: true, allowAnonymous, publicLink: `/forms/${SLUG}` }, - }, +/** [ADR-0159 D7] A `form` item, as the protocol serves it on 19: the body at the top level, bound by `object`. */ +const formItem = (allowAnonymous = true) => ({ + name: 'contact', object: 'inquiry', _diagnostics: { valid: true }, + sections: [{ fields: ['name', 'email'] }], + sharing: { enabled: true, allowAnonymous, publicLink: `/forms/${SLUG}` }, }); /** The bound object as the doors read it: the registry injects `organization_id`. */ @@ -72,20 +68,20 @@ interface Setup { tenancy: Tenancy; tenancyDisabled?: boolean; allowAnonymous?: function build(setup: Setup) { const createData = vi.fn().mockResolvedValue({ object: 'inquiry', id: 'rec_1', record: {} }); const getMetaItems = vi.fn(async (req: { type: string }) => { - if (req.type === 'view') return [formView(setup.allowAnonymous ?? true)]; - // [ADR-0159 D5] The `form` read, as the protocol serves it for an old-shape-only fixture: the projection of the views. - if (req.type === 'form') return projectedFormsOf([formView(setup.allowAnonymous ?? true)]); + // [ADR-0159 D7] A `view` read serves lists only, and this fixture holds none. + if (req.type === 'view') return []; + if (req.type === 'form') return [formItem(setup.allowAnonymous ?? true)]; if (req.type === 'object') return [inquiryObject(setup.tenancyDisabled ?? false)]; return []; }); const getMetaItemCached = vi.fn(async (_req: { cacheRequest: { ifNoneMatch?: string } }) => ({ - data: formView(setup.allowAnonymous ?? true), etag: { value: 'v1', weak: false }, notModified: false, + data: formItem(setup.allowAnonymous ?? true), etag: { value: 'v1', weak: false }, notModified: false, })); const protocol: any = { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems, - getMetaItem: vi.fn(async ({ type, name }: any) => ({ type, name, item: formView(setup.allowAnonymous ?? true) })), + getMetaItem: vi.fn(async ({ type, name }: any) => ({ type, name, ...(type === 'form' ? { item: formItem(setup.allowAnonymous ?? true) } : {}) })), getMetaItemCached: setup.cached ? getMetaItemCached : undefined, createData, }; @@ -122,7 +118,7 @@ function build(setup: Setup) { post: () => drive(find('POST', '/api/v1/forms/:slug/submit'), 'POST'), async adminRead(headers: Record = {}) { const res = mockRes(); - await find('GET', '/api/v1/meta/:type/:name').handler({ params: { type: 'view', name: 'contact' }, query: {}, headers } as any, res); + await find('GET', '/api/v1/meta/:type/:name').handler({ params: { type: 'form', name: 'contact' }, query: {}, headers } as any, res); return res; }, }; @@ -210,7 +206,7 @@ describe('[#21476] the administrator\'s read names why intake is unavailable', ( const diagnostics = res.body.item._diagnostics; expect(diagnostics.valid).toBe(true); expect(diagnostics.warnings).toHaveLength(1); - expect(diagnostics.warnings[0].path).toBe('config.sharing'); + expect(diagnostics.warnings[0].path).toBe('sharing'); const message: string = diagnostics.warnings[0].message; for (const named of [`/forms/${SLUG}`, "'inquiry'", "'organization_id'", "'isolated'", 'tenancy: { enabled: false }']) { expect(message).toContain(named); diff --git a/packages/rest/src/public-form-option-subset.test.ts b/packages/rest/src/public-form-option-subset.test.ts index 5a9aa476045..987c663b822 100644 --- a/packages/rest/src/public-form-option-subset.test.ts +++ b/packages/rest/src/public-form-option-subset.test.ts @@ -31,7 +31,6 @@ */ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; -import { projectedFormsOf } from '@objectstack/spec/ui'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; @@ -96,6 +95,16 @@ const form = (name: string, slug: string, sections: unknown[]) => ({ }, }); +/** + * [ADR-0159 D7] The injected form as protocol 19 serves it: a `form` item, the + * `config` body at the top level and bound by `object`. A `view` read serves + * lists only, so the injected lists hold the form under `form` alone. + */ +const asFormItem = ({ viewKind: _viewKind, config, ...identity }: any): any => { + const { data: _data, ...body } = config; + return { ...identity, ...body }; +}; + const FORM = form('pf_subset_case_form', SLUG, [ { name: 'case', @@ -172,17 +181,19 @@ describe('[#27606] POST /forms/:slug/submit: a form row\'s `options` subset is e const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { - // [ADR-0159 D5] The `form` read, as the protocol serves it for the injected old shape: its projection. - if (request?.type === 'form') return projectedFormsOf([FORM, WIDE_FORM, LOOSE_FORM]); - if (request?.type === 'view') return [FORM, WIDE_FORM, LOOSE_FORM]; + // [ADR-0159 D7] The `form` read serves the injected form; the `view` read holds no list here. + if (request?.type === 'form') return [FORM, WIDE_FORM, LOOSE_FORM].map(asFormItem); + if (request?.type === 'view') return []; if (request?.type === 'object') return [CASE]; return realGetMetaItems(request); }; // [#28409] The doors judge withdrawal against the effective list beside // the per-package layer: the injected list is that whole layer here. - protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'view' ? [FORM, WIDE_FORM, LOOSE_FORM] : []); + protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'form' ? [FORM, WIDE_FORM, LOOSE_FORM].map(asFormItem) : []); // [ADR-0159 D6 rule 7] No stored body here: the store is not provisioned, the injected lists are the layer. protocol.getUnreadableFormBodies = async () => []; + // [ADR-0159 D7, D6 rule 10] …and no stored old-shape row for the withdrawal layer to read. + protocol.getViewItemsWithStoredForms = async () => []; const realCreateData = protocol.createData.bind(protocol); createData = vi.fn(realCreateData); protocol.createData = createData; diff --git a/packages/rest/src/public-form-pair-translation.test.ts b/packages/rest/src/public-form-pair-translation.test.ts index 1948bf72e23..ecda14c9c64 100644 --- a/packages/rest/src/public-form-pair-translation.test.ts +++ b/packages/rest/src/public-form-pair-translation.test.ts @@ -1,18 +1,22 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // -// `GET /forms/:slug` translates a public form view that a `.custom` pair -// overrides (ADR-0146 D2) in the same label order the `/meta/view` reads serve +// `GET /forms/:slug` translates a public form that a `.custom` pair +// overrides (ADR-0146 D2) in the same label order the `/meta/form` reads serve // it in (ruling record 6631250894, restated by 6942920667): a translation the // pair ships, then the override's own text, then the base's translation. // // The ORDER is `@objectstack/spec/system`'s (`labelCatalogs`), and the pair's // translations are the protocol's to answer (`servedOverrideBaseOf` + // `getPairTranslationBundle`, asked through `pairTranslationBundleOf`). What is -// pinned here is the ROUTE's half: that the view it serves is handed the +// pinned here is the ROUTE's half: that the form it serves is handed the // pair's translations beside its packaged base, so the anonymous visitor reads // the text the authenticated `/meta` reader reads. // -// Every cell carries a CONTROL leg through `GET /meta/view/:name` on the same +// From protocol 19 the form is a `form` item (ADR-0159 D7) and its strings +// live under `forms.NAME` (ADR-0159 D8; the `objects.OBJECT._views` form tails +// are no longer read). +// +// Every cell carries a CONTROL leg through `GET /meta/form/:name` on the same // fixture. The pair rank needs the override envelope the read stamped on the // served document (`_packageId` = the base, `overrides.package` = the base); a // fixture that lost it would leave both surfaces on the override's own text, @@ -25,7 +29,6 @@ import { describe, it, expect, vi } from 'vitest'; import { SchemaRegistry, assertEngineFindOnePredicate } from '@objectstack/objectql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; -import { expandViewContainer } from '@objectstack/spec/ui'; import { RestServer } from './rest-server.js'; // Pay the first transform of the dist-resolved workspace dep the handlers reach @@ -62,47 +65,36 @@ const ticketObject = { }, }; -/** The `defineView` container as the code package ships it: one public form under `formViews.contact`. */ -const ticketContainer = () => ({ +/** The packaged form as the code package ships it (`forms:`): one public `form` item, `OBJECT.KEY`. */ +const shippedFormItem = (): any => ({ + name: VIEW, object: OBJ, - formViews: { - contact: { - type: 'simple', - title: TITLE_EN, - data: { provider: 'object', object: OBJ }, - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, - sections: [ - { name: 'about', label: ABOUT_EN, description: ABOUT_DESC_EN, fields: ['subject'] }, - { name: 'details', label: 'Details', fields: ['email'] }, - ], - }, - }, + type: 'simple', + title: TITLE_EN, + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, + sections: [ + { name: 'about', label: ABOUT_EN, description: ABOUT_DESC_EN, fields: ['subject'] }, + { name: 'details', label: 'Details', fields: ['email'] }, + ], }); -/** The packaged form item as the boot registers it (`expandViewContainer`). */ -const shippedFormItem = (): any => { - const item = expandViewContainer(OBJ, ticketContainer()).find((v) => v.name === VIEW); - if (!item) throw new Error(`fixture missing ${VIEW}`); - return item; -}; - /** The deployment's code catalog: `en` repeats the shipped strings, `zh-CN` translates them. */ const CODE_CATALOG: Record> = { en: { objects: { [OBJ]: { - _views: { contact: { title: TITLE_EN } }, _sections: { about: { label: ABOUT_EN, description: ABOUT_DESC_EN } }, }, }, + forms: { [VIEW]: { title: TITLE_EN } }, }, 'zh-CN': { objects: { [OBJ]: { - _views: { contact: { title: TITLE_ZH } }, _sections: { about: { label: ABOUT_ZH, description: ABOUT_DESC_ZH } }, }, }, + forms: { [VIEW]: { title: TITLE_ZH } }, }, }; @@ -110,10 +102,10 @@ const CODE_CATALOG: Record> = { const PAIR_ZH_DATA = { objects: { [OBJ]: { - _views: { contact: { title: TITLE_PAIR_ZH } }, _sections: { about: { label: ABOUT_PAIR_ZH } }, }, }, + forms: { [VIEW]: { title: TITLE_PAIR_ZH } }, }; /** Deep merge, `top` over `under`, of two translation-data groups. */ @@ -143,15 +135,15 @@ function createMockServer() { } interface Seed { - /** Seed the pair's declared override of the form view. */ + /** Seed the pair's declared override of the form. */ readonly override: boolean; /** Seed the pair's own zh-CN translation of the text its override wrote. */ readonly pairZh: boolean; } /** - * The REAL protocol over a real `SchemaRegistry`, the container registered the - * way the boot registers a `defineView` container, and the `.custom` pair's + * The REAL protocol over a real `SchemaRegistry`, the form registered the way + * the boot registers a package's `forms:`, and the `.custom` pair's * rows seeded the way Studio's Customize publishes them: the override row bound * to the pair (`package_id: .custom`) declaring * `overrides: { package: }`, and the pair's translation an active @@ -163,26 +155,31 @@ function makeHost(seed: Seed) { const registry = new SchemaRegistry({ multiTenant: false }); registry.logLevel = 'silent'; registry.registerObject(ticketObject as any, BASE_PKG); - const container = ticketContainer(); - registry.registerItem('view', { name: OBJ, ...container }, 'name', BASE_PKG); - for (const item of expandViewContainer(OBJ, container)) registry.registerItem('view', item, 'name', BASE_PKG); + // [ADR-0146 D3] The pair is read off the installed manifests: the base and its `.custom` pair. + registry.installPackage({ id: BASE_PKG, name: 'helpdesk', version: '1.0.0', type: 'app', namespace: 'helpdesk' } as never, 'code'); + registry.installPackage({ + id: PAIR_PKG, name: 'helpdesk (custom)', version: '0.1.0', type: 'module', namespace: 'helpdesk_custom', dependencies: { [BASE_PKG]: '^1' }, + } as never, 'authored'); + registry.registerItem('form', shippedFormItem(), 'name', BASE_PKG); const rows: Record[] = []; if (seed.override) { const shipped = shippedFormItem(); const overridden = { ...shipped, - config: { - ...shipped.config, - title: TITLE_OV, - sections: shipped.config.sections.map((s: any) => (s.name === 'about' ? { ...s, label: ABOUT_OV } : s)), - }, + title: TITLE_OV, + sections: shipped.sections.map((s: any) => (s.name === 'about' ? { ...s, label: ABOUT_OV } : s)), overrides: { package: BASE_PKG, basedOn: '1.0.0' }, }; rows.push({ - id: 'ov_form', type: 'view', name: VIEW, package_id: PAIR_PKG, organization_id: null, state: 'active', + id: 'ov_form', type: 'form', name: VIEW, package_id: PAIR_PKG, organization_id: null, state: 'active', metadata: JSON.stringify(overridden), }); + // A `form` is sealed (ADR-0131 D6): the reads serve a pair's declared + // override from the registry slot the read-side hydrator lays the + // published row into, wearing the base's envelope. This harness runs + // no hydrator, so the slot is laid here, as the hydrator lays it. + registry.registerItem('form', { ...overridden, _packageId: BASE_PKG }, 'name', PAIR_PKG); } if (seed.pairZh) { rows.push({ @@ -251,58 +248,58 @@ function makeHost(seed: Seed) { return body; }; /** The two strings a reader sees, plus the about section's description (a string the override left alone). */ - const strings = (config: any) => ({ - title: config?.title, - about: config?.sections?.find((s: any) => s?.name === 'about')?.label, - aboutDescription: config?.sections?.find((s: any) => s?.name === 'about')?.description, + const strings = (form: any) => ({ + title: form?.title, + about: form?.sections?.find((s: any) => s?.name === 'about')?.label, + aboutDescription: form?.sections?.find((s: any) => s?.name === 'about')?.description, }); return { protocol, /** `GET /forms/:slug` — the anonymous visitor's read. */ form: async (locale: string) => strings((await run('/api/v1/forms/:slug', { slug: SLUG }, locale))?.form), - /** `GET /meta/view/:name` — the CONTROL leg: the authenticated read of the same document. */ - meta: async (locale: string) => strings((await run('/api/v1/meta/:type/:name', { type: 'view', name: VIEW }, locale))?.item?.config), + /** `GET /meta/form/:name` — the CONTROL leg: the authenticated read of the same document. */ + meta: async (locale: string) => strings((await run('/api/v1/meta/:type/:name', { type: 'form', name: VIEW }, locale))?.item), }; } -describe('GET /forms/:slug serves a .custom pair override of the form view in the ruled label order', () => { - it('the view the route matches carries the override envelope the pair rank reads', async () => { - // The route matches its form in `getMetaItems({ type: 'view' })`; the pair +describe('GET /forms/:slug serves a .custom pair override of the form in the ruled label order', () => { + it('the form the route matches carries the override envelope the pair rank reads', async () => { + // The route matches its form in `getMetaItems({ type: 'form' })`; the pair // rank reads `servedOverrideBaseOf` off that served document. const { protocol } = makeHost({ override: true, pairZh: true }); - const views: any[] = ((await protocol.getMetaItems({ type: 'view' } as never)) as any).items; - const served = views.find((v) => v?.name === VIEW); + const forms: any[] = ((await protocol.getMetaItems({ type: 'form' } as never)) as any).items; + const served = forms.find((v) => v?.name === VIEW); expect(served?._packageId).toBe(BASE_PKG); expect(served?.overrides?.package).toBe(BASE_PKG); - expect(protocol.servedOverrideBaseOf('view', served)).toBe(BASE_PKG); + expect(protocol.servedOverrideBaseOf('form', served)).toBe(BASE_PKG); }); it('zh-CN: a translation the pair ships beats the override\'s own text, as /meta serves it', async () => { const host = makeHost({ override: true, pairZh: true }); const expected = { title: TITLE_PAIR_ZH, about: ABOUT_PAIR_ZH, aboutDescription: ABOUT_DESC_ZH }; // CONTROL: the authenticated read of the same document reads the pair's rank. - expect(await host.meta('zh-CN'), '/meta/view zh-CN').toEqual(expected); + expect(await host.meta('zh-CN'), '/meta/form zh-CN').toEqual(expected); expect(await host.form('zh-CN'), '/forms zh-CN').toEqual(expected); }); it('en: the pair ships no en row, so both surfaces serve the override\'s own text', async () => { const host = makeHost({ override: true, pairZh: true }); const expected = { title: TITLE_OV, about: ABOUT_OV, aboutDescription: ABOUT_DESC_EN }; - expect(await host.meta('en'), '/meta/view en').toEqual(expected); + expect(await host.meta('en'), '/meta/form en').toEqual(expected); expect(await host.form('en'), '/forms en').toEqual(expected); }); it('zh-CN with no pair translation: the override\'s own text beats the base\'s translation on both surfaces', async () => { const host = makeHost({ override: true, pairZh: false }); const expected = { title: TITLE_OV, about: ABOUT_OV, aboutDescription: ABOUT_DESC_ZH }; - expect(await host.meta('zh-CN'), '/meta/view zh-CN').toEqual(expected); + expect(await host.meta('zh-CN'), '/meta/form zh-CN').toEqual(expected); expect(await host.form('zh-CN'), '/forms zh-CN').toEqual(expected); }); it('zh-CN with no override: the base\'s form reads the base\'s translation on both surfaces', async () => { const host = makeHost({ override: false, pairZh: false }); const expected = { title: TITLE_ZH, about: ABOUT_ZH, aboutDescription: ABOUT_DESC_ZH }; - expect(await host.meta('zh-CN'), '/meta/view zh-CN').toEqual(expected); + expect(await host.meta('zh-CN'), '/meta/form zh-CN').toEqual(expected); expect(await host.form('zh-CN'), '/forms zh-CN').toEqual(expected); }); }); diff --git a/packages/rest/src/public-form-reads-once-37709.test.ts b/packages/rest/src/public-form-reads-once-37709.test.ts index cb81634433c..5ac5be7133c 100644 --- a/packages/rest/src/public-form-reads-once-37709.test.ts +++ b/packages/rest/src/public-form-reads-once-37709.test.ts @@ -54,10 +54,15 @@ const SLUG = 'contact-37709'; const body = { type: 'simple', sections: [{ fields: ['name'] }], sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` } }; const INQUIRY = { name: OBJECT, label: 'Inquiry', fields: { name: { name: 'name', type: 'text' as const, label: 'Name' } } }; -/** The two shapes a first-party form takes: an authored `form` item, an old-shape container's `formViews` entry. */ +/** + * The two shapes a first-party form takes: an authored `form` item, an + * old-shape container's `formViews` entry. [ADR-0159 D7] On 19 the projection + * serves no content, so the old shape's form is served by no read: the + * by-name `form` read answers no item and the door 404. + */ const SHAPES = { - 'an authored `form` item': { forms: [{ name: NAME, object: OBJECT, label: 'Contact us', ...body }] }, - 'an old-shape `formViews` entry': { views: [{ object: OBJECT, formViews: { contact: { ...body, data: { provider: 'object', object: OBJECT } } } }] }, + 'an authored `form` item': { ships: { forms: [{ name: NAME, object: OBJECT, label: 'Contact us', ...body }] }, served: true }, + 'an old-shape `formViews` entry': { ships: { views: [{ object: OBJECT, formViews: { contact: { ...body, data: { provider: 'object', object: OBJECT } } } }] }, served: false }, } as const; function mockServer() { @@ -163,13 +168,17 @@ describe('[ADR-0159 D5, D6] one form request reads the `view` list once and each return b; }; - describe.each(Object.entries(SHAPES))('the form is %s', (_shape, ships) => { + describe.each(Object.entries(SHAPES))('the form is %s', (_shape, { ships, served }) => { it('a by-name `form` read: the `view` list once, each type\'s stored rows once, and the rows of the name once', async () => { const b = await booted(ships); let answer: any; const reads = await b.counted(async () => { answer = await b.byName(); }); - expect(answer?.item?.name).toBe(NAME); - expect(answer?.item?._packageId).toBe(BASE); + if (served) { + expect(answer?.item?.name).toBe(NAME); + expect(answer?.item?._packageId).toBe(BASE); + } else { + expect(answer?.item).toBeUndefined(); + } expect(reads.lists).toEqual({ 'form:effective': 1, 'view:effective': 1 }); expect(reads.rows).toEqual(ONCE); // The generic by-name read: its own row read, predicated on the name. @@ -180,7 +189,7 @@ describe('[ADR-0159 D5, D6] one form request reads the `view` list once and each const b = await booted(ships); let answer: any; const reads = await b.counted(async () => { answer = await b.door(); }); - expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(answer.status, JSON.stringify(answer.body)).toBe(served ? 200 : 404); expect(reads.lists).toEqual({ 'view:effective': 1, 'form:effective': 1, 'form:per-package': 1, 'view:per-package': 1, }); @@ -200,7 +209,7 @@ describe('[ADR-0159 D5, D6] one form request reads the `view` list once and each b.protocol.readFormRequest = undefined; let answer: any; const reads = await b.counted(async () => { answer = await b.door(); }); - expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(answer.status, JSON.stringify(answer.body)).toBe(served ? 200 : 404); // The `view` list twice: the door's own read, and the `form` list's step 2. expect(reads.lists['view:effective']).toBe(2); // The `view` rows: the `view` list, the `form` list's scope, the unreadable bodies, the per-package diff --git a/packages/rest/src/public-form-required.test.ts b/packages/rest/src/public-form-required.test.ts index a217af3aff0..41ea75cc912 100644 --- a/packages/rest/src/public-form-required.test.ts +++ b/packages/rest/src/public-form-required.test.ts @@ -30,7 +30,6 @@ */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { projectedFormsOf } from '@objectstack/spec/ui'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; @@ -57,6 +56,16 @@ const LEAD = { }, }; +/** + * [ADR-0159 D7] The injected form as protocol 19 serves it: a `form` item, the + * `config` body at the top level and bound by `object`. A `view` read serves + * lists only, so the injected lists hold the form under `form` alone. + */ +const asFormItem = ({ viewKind: _viewKind, config, ...identity }: any): any => { + const { data: _data, ...body } = config; + return { ...identity, ...body }; +}; + const FORM = { name: 'pf_required_lead_form', object: OBJECT, @@ -135,17 +144,19 @@ describe('[#24131] POST /forms/:slug/submit enforces the form\'s own `required`' const protocol: any = new ObjectStackProtocolImplementation(engine as any); const realGetMetaItems = protocol.getMetaItems.bind(protocol); protocol.getMetaItems = async (request: any) => { - // [ADR-0159 D5] The `form` read, as the protocol serves it for the injected old shape: its projection. - if (request?.type === 'form') return projectedFormsOf([FORM]); - if (request?.type === 'view') return [FORM]; + // [ADR-0159 D7] The `form` read serves the injected form; the `view` read holds no list here. + if (request?.type === 'form') return [FORM].map(asFormItem); + if (request?.type === 'view') return []; if (request?.type === 'object') return [LEAD]; return realGetMetaItems(request); }; // [#28409] The doors judge withdrawal against the effective list beside // the per-package layer: the injected list is that whole layer here. - protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'view' ? [FORM] : []); + protocol.getMetaItemsPerPackage = async (request: any) => (request?.type === 'form' ? [FORM].map(asFormItem) : []); // [ADR-0159 D6 rule 7] No stored body here: the store is not provisioned, the injected lists are the layer. protocol.getUnreadableFormBodies = async () => []; + // [ADR-0159 D7, D6 rule 10] …and no stored old-shape row for the withdrawal layer to read. + protocol.getViewItemsWithStoredForms = async () => []; const rest = new RestServer(mockServer() as any, protocol, { api: { requireAuth: false } } as any); rest.registerRoutes(); const submit = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === '/api/v1/forms/:slug/submit'); diff --git a/packages/rest/src/public-form-routes.stored-row.test.ts b/packages/rest/src/public-form-routes.stored-row.test.ts index d5247cf434b..e0337417c8a 100644 --- a/packages/rest/src/public-form-routes.stored-row.test.ts +++ b/packages/rest/src/public-form-routes.stored-row.test.ts @@ -64,7 +64,6 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco // it reports TS7006 — one broken extension reading as two type errors in this // package's TEST_DEBT re-measure. import { RestServer } from './rest-server.js'; -import { projectedFormsOf } from '@objectstack/spec/ui'; // Pay the first transform of `@objectstack/objectql`, which the route source // reaches through a dynamic `import()`, at MODULE LOAD rather than inside a @@ -103,23 +102,24 @@ function stubEngine() { } /** - * Save a view through the real `saveMetaItem` and return the body the - * `sys_metadata` row holds — what a consumer of that row will read. + * Save a form through the real `saveMetaItem` and return the body the + * `sys_metadata` row holds — what a consumer of that row will read. From + * protocol 19 a form is its own type (ADR-0159 D7), so the save is a `form` + * save and the row is a `form` row. */ async function persistedBody(name: string, item: unknown): Promise { const { engine, rows } = stubEngine(); const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()) as any; - const result = await protocol.saveMetaItem({ type: 'view', name, item }); + const result = await protocol.saveMetaItem({ type: 'form', name, item }); expect(result.success, JSON.stringify(result)).toBe(true); - const row = rows.find((r) => r.type === 'view'); - expect(row, 'the save persisted no view row').toBeDefined(); + const row = rows.find((r) => r.type === 'form'); + expect(row, 'the save persisted no form row').toBeDefined(); return JSON.parse(row!.metadata); } // ─── the fixtures an author writes in Studio ──────────────────────────────── const SHARING = { enabled: true, allowAnonymous: true, publicLink: '/forms/contact' }; -const DATA = { provider: 'object', object: 'lead' }; /** The section every case declares. */ const SECTION = { @@ -128,17 +128,18 @@ const SECTION = { }; /** - * A public form saved from Studio as a `ViewItem` — `viewKind: 'form'` with the - * form config under `config`. This is the shape `findPublicFormView` resolves - * a stored public form through (its third branch), which is why the acceptance - * surface is spelled here rather than on the flattened overlay. + * A public form saved from Studio. From protocol 19 that is a `form` item + * (ADR-0159 D7): the form body at the top level, bound by `object`, named + * `OBJECT.KEY`. Before 19 Studio saved it as a `ViewItem` with + * `viewKind: 'form'`, which the `view` door now refuses. */ const studioForm = (sectionKey: 'groups' | 'sections') => ({ name: 'lead.contact', object: 'lead', - viewKind: 'form', label: 'Contact us', - config: { type: 'simple', data: DATA, sharing: SHARING, [sectionKey]: [SECTION] }, + type: 'simple', + sharing: SHARING, + [sectionKey]: [SECTION], }); const leadObject = { @@ -171,15 +172,16 @@ function mockRes() { return res; } -/** Mount the real routes over a protocol that serves the STORED view body. */ -function routesOver(storedView: any) { +/** Mount the real routes over a protocol that serves the STORED form body. */ +function routesOver(storedForm: any) { const createData = vi.fn().mockResolvedValue({ object: 'lead', id: 'rec_1', record: {} }); const protocol: any = { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { - if (type === 'form') return projectedFormsOf([storedView]); - if (type === 'view') return [storedView]; + // [ADR-0159 D7] The `form` read serves the stored form; the `view` read holds no list here. + if (type === 'form') return [storedForm]; + if (type === 'view') return []; if (type === 'object') return [leadObject]; return []; }), @@ -230,19 +232,16 @@ describe('#7134 a Studio-saved form authored with `groups` no longer degrades on // The claim under both routes above, stated directly: the fix is // that the ROW changed, not that `rest-server.ts` learned a second key. const stored = await persistedBody('lead.contact', studioForm('groups')); - expect(stored.config).not.toHaveProperty('groups'); - expect(stored.config.sections).toEqual([SECTION]); + expect(stored).not.toHaveProperty('groups'); + expect(stored.sections).toEqual([SECTION]); }); it('an EMPTY `groups` folds to an empty `sections` — a declaration, still empty', async () => { // The row half of the empty-declaration guard below. Evidence: on revert // the row carries `groups: []` and no `sections` at all. - const stored = await persistedBody('lead.contact', { - ...studioForm('groups'), - config: { type: 'simple', data: DATA, sharing: SHARING, groups: [] }, - }); - expect(stored.config.sections).toEqual([]); - expect(stored.config).not.toHaveProperty('groups'); + const stored = await persistedBody('lead.contact', { ...studioForm('groups'), groups: [] }); + expect(stored.sections).toEqual([]); + expect(stored).not.toHaveProperty('groups'); }); }); @@ -274,13 +273,10 @@ describe('#7134 GUARD — a form authored with canonical `sections` is unaffecte // GUARD, green in BOTH directions: #6601 / #6920's refusal must survive // the fold. An empty `groups` folds to an empty `sections`, and an empty // declaration is an empty declaration either way — so this asserts ROUTE - // behaviour only. (An `expect(stored.config.sections).toEqual([])` here + // behaviour only. (An `expect(stored.sections).toEqual([])` here // would be fix-evidence under a guard's label; it lives in the evidence // block above, where reverse verification can read it correctly.) - const stored = await persistedBody('lead.contact', { - ...studioForm('groups'), - config: { type: 'simple', data: DATA, sharing: SHARING, groups: [] }, - }); + const stored = await persistedBody('lead.contact', { ...studioForm('groups'), groups: [] }); const { resolve, submit, createData } = routesOver(stored); const readRes = mockRes(); diff --git a/packages/rest/src/public-form-section-i18n.test.ts b/packages/rest/src/public-form-section-i18n.test.ts index 56ded0e343f..f9ab12edef0 100644 --- a/packages/rest/src/public-form-section-i18n.test.ts +++ b/packages/rest/src/public-form-section-i18n.test.ts @@ -28,7 +28,7 @@ import { describe, it, expect, vi } from 'vitest'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SchemaRegistry } from '@objectstack/objectql'; -import { expandViewContainer, projectedFormsOf } from '@objectstack/spec/ui'; +import { expandViewContainer } from '@objectstack/spec/ui'; import { RestServer } from './rest-server'; // [#10126] Pay the first transform of the dist-resolved workspace dep the @@ -42,8 +42,8 @@ const ABOUT_ZH = '介绍一下你自己'; const ABOUT_DESC_ZH = '我们会在一天内回复你。'; /** - * The served form view, in the flattened registered shape the protocol - * enumerates (`viewKind: 'form'`, the form under `config`). Three sections: + * The served form: from protocol 19 a `form` item (ADR-0159 D7), its body at + * the top level. Three sections: * * - `about` — its label and description are in the zh-CN bundle; it also * declares a lookup field, which the anonymous route strips; @@ -56,17 +56,13 @@ function formView(aboutLabel = ABOUT_EN) { return { name: 'ticket_form', object: 'ticket', - viewKind: 'form', label: 'Contact us', - config: { - data: { object: 'ticket' }, - sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/test' }, - sections: [ - { name: 'about', label: aboutLabel, description: ABOUT_DESC_EN, fields: ['subject', 'contact_id'] }, - { name: 'details', label: 'Details', description: 'Anything else we should know.', fields: ['email'] }, - { label: 'More', fields: ['status'] }, - ], - }, + sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/test' }, + sections: [ + { name: 'about', label: aboutLabel, description: ABOUT_DESC_EN, fields: ['subject', 'contact_id'] }, + { name: 'details', label: 'Details', description: 'Anything else we should know.', fields: ['email'] }, + { label: 'More', fields: ['status'] }, + ], }; } @@ -130,37 +126,37 @@ function routeOver(protocol: unknown) { (rest as any).resolveExecCtx = async () => ({ userId: 'test-user' }); rest.registerRoutes(); const resolve = rest.getRoutes().find((r) => r.method === 'GET' && r.path.endsWith('/forms/:slug'))!; - return async (locale: string, slug = 'test') => { + return async (locale: string, slug = 'test', status = 200) => { const res: any = { statusCode: 200, body: undefined, headers: {} as Record }; res.status = vi.fn((c: number) => { res.statusCode = c; return res; }); res.json = vi.fn((b: any) => { res.body = b; return res; }); res.header = vi.fn((k: string, v: string) => { res.headers[k] = v; return res; }); await resolve.handler({ params: { slug }, query: {}, headers: { 'accept-language': locale } } as any, res); - expect(res.statusCode, JSON.stringify(res.body)).toBe(200); + expect(res.statusCode, JSON.stringify(res.body)).toBe(status); return res; }; } /** - * The route over a protocol double that serves `view` as the one view body. - * `packagedView`, when given, is what the protocol's `getPackagedViewBase` - * answers — the packaged view before any overlay, which the override rule - * compares the served strings against. + * The route over a protocol double that serves `view` as the one `form` item + * (the `view` list holds none). `packagedView`, when given, is what the + * protocol's `getPackagedFormBase` answers — the packaged form before any + * override, which the override rule compares the served strings against. */ function buildServer(view: Record, packagedView?: Record) { - const getPackagedViewBase = vi.fn((name: string) => (name === view.name ? packagedView : undefined)); + const getPackagedFormBase = vi.fn((name: string) => (name === view.name ? packagedView : undefined)); const protocol: any = { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { - if (type === 'form') return projectedFormsOf([view]); - if (type === 'view') return [view]; + if (type === 'form') return [view]; + if (type === 'view') return []; if (type === 'object') return [ticketObject]; return []; }), - ...(packagedView ? { getPackagedViewBase } : {}), + ...(packagedView ? { getPackagedFormBase } : {}), }; - return { get: routeOver(protocol), getPackagedViewBase }; + return { get: routeOver(protocol), getPackagedFormBase }; } const section = (res: any, index: number) => res.body.form.sections[index]; @@ -194,11 +190,11 @@ describe('[#23497] GET /forms/:slug — section headings are localized under Acc // the original. The catalog is the translation of the ORIGINAL, so it // must not overwrite the edit. const edited = 'Tell us about yourself (edited)'; - const { get, getPackagedViewBase } = buildServer(formView(edited), formView()); + const { get, getPackagedFormBase } = buildServer(formView(edited), formView()); const res = await get('zh-CN'); expect(section(res, 0)).toMatchObject({ name: 'about', label: edited, description: ABOUT_DESC_ZH }); - // Looked up by the served item's registry name, as the `/meta/view` reads do. - expect(getPackagedViewBase).toHaveBeenCalledWith('ticket_form'); + // Looked up by the served item's registry name, as the `/meta/form` reads do. + expect(getPackagedFormBase).toHaveBeenCalledWith('ticket_form'); }); it('CONTROL — en: every section is served its authored text', async () => { @@ -230,8 +226,8 @@ describe('[#23497] GET /forms/:slug — section headings are localized under Acc expect(Object.keys(res.body).sort()).toEqual(['form', 'label', 'object', 'objectSchema', 'slug']); expect(res.body).toMatchObject({ slug: 'test', object: 'ticket', label: 'Contact us' }); expect(res.headers.Vary).toBe('Accept-Language'); - expect(view.config.sections[0]).toMatchObject({ label: ABOUT_EN, description: ABOUT_DESC_EN }); - expect(view.config.sections[0].fields).toEqual(['subject', 'contact_id']); + expect(view.sections[0]).toMatchObject({ label: ABOUT_EN, description: ABOUT_DESC_EN }); + expect(view.sections[0].fields).toEqual(['subject', 'contact_id']); }); }); @@ -255,6 +251,14 @@ const containerForm = (slug: string) => ({ ], }); const ticketContainer = () => ({ object: 'ticket', form: containerForm('ticket-default'), formViews: { contact: containerForm('ticket-contact') } }); +/** [ADR-0159 D7] The same two forms as protocol 19 ships them: `form` items named `OBJECT.KEY`, no `data`. */ +const ticketForms = () => [ + ['ticket.contact', 'ticket-contact'], + ['ticket.form', 'ticket-default'], +].map(([name, slug]) => { + const { data: _data, ...body } = containerForm(slug); + return { name, object: 'ticket', ...body }; +}); const PKG = 'com.example.helpdesk'; @@ -288,28 +292,26 @@ function realProtocolSession() { }; const protocol: any = new ObjectStackProtocolImplementation(engine, undefined, 'env_test'); registry.registerObject(ticketObject as any, PKG); - const container = ticketContainer(); - registry.registerItem('view', { name: 'ticket', ...container }, 'name', PKG); - for (const item of expandViewContainer('ticket', container)) registry.registerItem('view', item, 'name', PKG); + for (const form of ticketForms()) registry.registerItem('form', form, 'name', PKG); return { protocol, rows, get: routeOver(protocol) }; } describe('[#23497] a container-authored form reaches the route as the item the protocol expands it to', () => { - it('the view list the route reads serves each container form only as a `viewKind: \'form\'` item, its form under `config`', async () => { + it('the `form` list the route reads serves each form as a `form` item, its body at the top level; the `view` list serves none', async () => { const { protocol } = realProtocolSession(); const views: any[] = (await protocol.getMetaItems({ type: 'view' })).items; - // No served body carries a container slot, so no candidate the route - // matches can come from `form` or `formViews`. - expect(views.filter((v) => v && ('form' in v || 'formViews' in v))).toEqual([]); - const forms = views.filter((v) => v?.viewKind === 'form'); - expect(forms.map((v) => [v.name, v.config?.sharing?.publicLink]).sort()).toEqual([ + // No served `view` carries a form, so no candidate the route matches + // can come from `form`, `formViews` or a `viewKind: 'form'` item. + expect(views.filter((v) => v && ('form' in v || 'formViews' in v || v.viewKind === 'form'))).toEqual([]); + const forms: any[] = (await protocol.getMetaItems({ type: 'form' })).items; + expect(forms.map((v) => [v.name, v.sharing?.publicLink]).sort()).toEqual([ ['ticket.contact', '/forms/ticket-contact'], ['ticket.form', '/forms/ticket-default'], ]); }); for (const slug of ['ticket-contact', 'ticket-default']) { - it(`zh-CN: the form authored at ${slug === 'ticket-contact' ? '`formViews.contact`' : 'the default `form`'} is served its translated headings`, async () => { + it(`zh-CN: the form ${slug === 'ticket-contact' ? '`ticket.contact`' : '`ticket.form`'} is served its translated headings`, async () => { const { get } = realProtocolSession(); const res = await get('zh-CN', slug); expect(res.body.form.sections.map((s: any) => [s.name, s.label, s.description])).toEqual([ @@ -323,8 +325,9 @@ describe('[#23497] a container-authored form reaches the route as the item the p }); } - it('zh-CN: a heading an environment overlay edited keeps the edit against the packaged view the real protocol answers', async () => { + it('a stored old-shape environment overlay of the form\'s name closes its address: the edited heading is not served (ADR-0159 D7)', async () => { const { rows, get, protocol } = realProtocolSession(); + // The overlay row as an 18 environment edit stored it: the old-shape item. const shipped: any = expandViewContainer('ticket', ticketContainer()).find((v) => v.name === 'ticket.contact'); const edited = 'Tell us about yourself (edited)'; const overlay = { @@ -339,28 +342,26 @@ describe('[#23497] a container-authored form reaches the route as the item the p state: 'active', metadata: JSON.stringify(overlay), }); // The packaged base is the item the package shipped, under the served item's own name. - expect((protocol.getPackagedViewBase('ticket.contact') as any)?.config?.sections?.[0]?.label).toBe(ABOUT_EN); - const res = await get('zh-CN', 'ticket-contact'); - expect(section(res, 0)).toMatchObject({ name: 'about', label: edited, description: ABOUT_DESC_ZH }); + expect((protocol.getPackagedFormBase('ticket.contact') as any)?.sections?.[0]?.label).toBe(ABOUT_EN); + // [ADR-0159 D6 rules 10 and 11] On 19 the stored old-shape row is the + // served row of the name and serves no content: the address answers + // 404, the edit is not served. + const res = await get('zh-CN', 'ticket-contact', 404); + expect(res.body?.code).toBe('FORM_NOT_FOUND'); + expect(JSON.stringify(res.body)).not.toContain(edited); }); }); describe('[#23497] a form matched outside `config` is served as matched', () => { - // No body the route reads carries a container slot (the pin above), but - // the route still answers one it is handed, from a protocol double or a - // row stored before the write door stored parsed bodies: its own sections, - // never the item's `config`, and as authored, because the spec's view - // translator localizes sections at `config` only. + // No body the route reads carries a container slot (the pin above). A + // container body the route is handed anyway, from a protocol double or a + // row stored before the write door stored parsed bodies, serves no form on + // 19: the door matches a `form` item's own body, never a container slot. for (const [where, slug] of [['form', 'ticket-default'], ['formViews.contact', 'ticket-contact']] as const) { - it(`a container's \`${where}\` is answered with its own sections, as authored`, async () => { - const res = await buildServer({ name: 'ticket', ...ticketContainer() }).get('zh-CN', slug); - expect(res.body.form.sharing.publicLink).toBe(`/forms/${slug}`); - expect(res.body.form.sections.map((s: any) => [s.name, s.label])).toEqual([ - ['about', ABOUT_EN], - ['details', 'Details'], - ]); - // The strip still ran over it. - expect(renderedFields(res)).toEqual([['subject'], ['email']]); + it(`a container body handed to the route serves no form at its \`${where}\`'s link: 404 (ADR-0159 D7)`, async () => { + const res = await buildServer({ name: 'ticket', ...ticketContainer() }).get('zh-CN', slug, 404); + expect(res.body?.code).toBe('FORM_NOT_FOUND'); + expect(JSON.stringify(res.body)).not.toContain(ABOUT_EN); }); } }); @@ -369,11 +370,11 @@ describe('GET /forms/:slug — a section entry\'s label, placeholder and helpTex /** The form view with an entry object overriding the `subject` field's copy in `about`, and one in `details` the bundle has no key for. */ const entryFormView = () => { const view = formView(); - view.config.sections[0].fields = [ + view.sections[0].fields = [ { field: 'subject', label: 'Your question', placeholder: 'One line, please', helpText: 'We route the ticket by it' }, 'contact_id', ] as any; - view.config.sections[1].fields = [{ field: 'email', label: 'Your email', placeholder: 'you@example.com' }] as any; + view.sections[1].fields = [{ field: 'email', label: 'Your email', placeholder: 'you@example.com' }] as any; return view; }; const entry = (res: any, index: number) => res.body.form.sections[index].fields[0]; @@ -413,8 +414,8 @@ describe('[#33952] GET /forms/:slug — a field label a code package\'s fieldPat getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { - if (type === 'form') return projectedFormsOf([formView()]); - if (type === 'view') return [formView()]; + if (type === 'form') return [formView()]; + if (type === 'view') return []; if (type === 'object') return [patchedTicket]; return []; }), diff --git a/packages/rest/src/public-form-title-i18n.test.ts b/packages/rest/src/public-form-title-i18n.test.ts index 6e30c8ea0b1..d5c62e07434 100644 --- a/packages/rest/src/public-form-title-i18n.test.ts +++ b/packages/rest/src/public-form-title-i18n.test.ts @@ -16,15 +16,16 @@ // `label` is still answered without one, so a form's title is not shadowed by // the view's machine name. // -// The RULES live in `@objectstack/spec/system` (`translateView`): the key is -// `objects.OBJECT._views.VIEW.title`, only an authored title is translated, a -// missing key keeps the authored text, and an explicit override beats the -// catalog against the packaged view. What is pinned here is the ROUTE's half. +// The RULES live in `@objectstack/spec/system` (`translateForm`): from +// protocol 19 a form is a `form` item and its key is `forms.NAME.title` +// (ADR-0159 D8; the `objects.OBJECT._views.VIEW.title` fallback left with the +// old shapes), only an authored title is translated, a missing key keeps the +// authored text, and an explicit override beats the catalog against the +// packaged form. What is pinned here is the ROUTE's half. import { describe, it, expect, vi } from 'vitest'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SchemaRegistry } from '@objectstack/objectql'; -import { expandViewContainer, projectedFormsOf } from '@objectstack/spec/ui'; import { RestServer } from './rest-server'; // [#10126] Pay the first transform of the dist-resolved workspace dep the @@ -46,25 +47,22 @@ const ticketObject = { const publicForm = (slug: string, title?: string) => ({ type: 'simple', - data: { provider: 'object', object: 'ticket' }, sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${slug}` }, ...(title !== undefined ? { title } : {}), sections: [{ name: 'about', label: 'About', fields: ['subject', 'email'] }], }); /** - * Three public forms on one container: `contact` authors a title the bundle + * Three public forms of one object: `contact` authors a title the bundle * translates, `untitled` authors none (the bundle carries a key for it that * must not apply), and `referral` authors a title the bundle has no key for. + * From protocol 19 each is a `form` item named `OBJECT.KEY` (ADR-0159 D7). */ -const ticketContainer = () => ({ - object: 'ticket', - formViews: { - contact: publicForm('contact-us', TITLE_EN), - untitled: publicForm('untitled'), - referral: publicForm('referral', 'Refer a friend'), - }, -}); +const ticketForms = () => [ + { name: 'ticket.contact', object: 'ticket', ...publicForm('contact-us', TITLE_EN) }, + { name: 'ticket.untitled', object: 'ticket', ...publicForm('untitled') }, + { name: 'ticket.referral', object: 'ticket', ...publicForm('referral', 'Refer a friend') }, +]; const BUNDLE: Record = { en: { objects: { ticket: { label: 'Ticket' } } }, @@ -73,13 +71,14 @@ const BUNDLE: Record = { ticket: { label: '工单', fields: { subject: { label: '主题' } }, - _views: { - contact: { title: TITLE_ZH }, - untitled: { title: 'MUST-NOT-APPLY' }, - labelled: { label: '工单表单', title: '提交工单' }, - }, }, }, + // [ADR-0159 D8] A form's strings live under `forms.NAME`. + forms: { + 'ticket.contact': { title: TITLE_ZH }, + 'ticket.untitled': { title: 'MUST-NOT-APPLY' }, + 'ticket.labelled': { label: '工单表单', title: '提交工单' }, + }, }, }; @@ -108,13 +107,13 @@ function routeOver(protocol: unknown) { (rest as any).resolveExecCtx = async () => ({ userId: 'test-user' }); rest.registerRoutes(); const resolve = rest.getRoutes().find((r) => r.method === 'GET' && r.path.endsWith('/forms/:slug'))!; - return async (locale: string, slug: string) => { + return async (locale: string, slug: string, status = 200) => { const res: any = { statusCode: 200, body: undefined, headers: {} as Record }; res.status = vi.fn((c: number) => { res.statusCode = c; return res; }); res.json = vi.fn((b: any) => { res.body = b; return res; }); res.header = vi.fn((k: string, v: string) => { res.headers[k] = v; return res; }); await resolve.handler({ params: { slug }, query: {}, headers: { 'accept-language': locale } } as any, res); - expect(res.statusCode, JSON.stringify(res.body)).toBe(200); + expect(res.statusCode, JSON.stringify(res.body)).toBe(status); return res; }; } @@ -129,10 +128,9 @@ const matchesWhere = (row: Record, where: Record) { +/** The route over a protocol double that serves `form` as the one form body. */ +function overDouble(form: Record) { const protocol: any = { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn(async ({ type }: { type: string }) => { - if (type === 'form') return projectedFormsOf([view]); - if (type === 'view') return [view]; + // [ADR-0159 D7] The `form` read serves the form; the `view` read holds no list here. + if (type === 'form') return [form]; + if (type === 'view') return []; if (type === 'object') return [ticketObject]; return []; }), @@ -170,7 +167,7 @@ function overDouble(view: Record) { } describe('GET /forms/:slug — the form title is localized under Accept-Language', () => { - it('zh-CN: a form whose title the bundle keys under `_views.VIEW.title` is served the translated title', async () => { + it('zh-CN: a form whose title the bundle keys under `forms.NAME.title` is served the translated title', async () => { const { get } = realProtocolSession(); const res = await get('zh-CN', 'contact-us'); expect(res.body.form.title).toBe(TITLE_ZH); @@ -194,7 +191,7 @@ describe('GET /forms/:slug — the form title is localized under Accept-Language const { get } = realProtocolSession(); const res = await get('zh-CN', 'untitled'); expect(res.body.form.title).toBeUndefined(); - // A container form item carries no `label`: the route answers none, so + // A form item that authors no `label`: the route answers none, so // the console's `payload.label ?? form.title ?? objectSchema.label` // reaches the object label, translated. expect(res.body.label).toBeUndefined(); @@ -208,30 +205,38 @@ describe('GET /forms/:slug — the form title is localized under Accept-Language expect(res.body.form.title).toBe(TITLE_ZH); }); - it('zh-CN: an environment overlay that edits the title keeps the edit against the packaged view', async () => { + it('a stored old-shape environment overlay of the form\'s name closes its address: no title is served (ADR-0159 D7)', async () => { const { rows, get } = realProtocolSession(); - const shipped: any = expandViewContainer('ticket', ticketContainer()).find((v) => v.name === 'ticket.contact'); + // The overlay row as an 18 environment edit stored it: the old-shape + // item the boot expanded the shipped container's `formViews.contact` to. + const shipped: any = { + name: 'ticket.contact', object: 'ticket', viewKind: 'form', + config: { ...publicForm('contact-us', TITLE_EN), data: { provider: 'object', object: 'ticket' } }, + }; const edited = 'Talk to us (edited)'; rows.push({ id: 'r_1', type: 'view', name: 'ticket.contact', package_id: null, organization_id: null, state: 'active', metadata: JSON.stringify({ ...shipped, config: { ...shipped.config, title: edited } }), }); - const res = await get('zh-CN', 'contact-us'); - expect(res.body.form.title).toBe(edited); + // [ADR-0159 D6 rules 10 and 11] On 19 the stored old-shape row is the + // served row of the name and serves no content: the address answers + // 404, the edit is not served (the kept reader's pins hold the rest). + const res = await get('zh-CN', 'contact-us', 404); + expect(res.body?.code).toBe('FORM_NOT_FOUND'); + expect(JSON.stringify(res.body)).not.toContain(edited); }); }); describe('GET /forms/:slug — the top-level `label` is served from the TRANSLATED view', () => { - /** A `viewKind: 'form'` item that authors both a `label` and a form `title`. */ + /** A `form` item that authors both a `label` and a form `title`. */ const labelledItem = () => ({ - name: 'labelled', + name: 'ticket.labelled', object: 'ticket', - viewKind: 'form', label: 'Ticket form', - config: publicForm('labelled', 'File a ticket'), + ...publicForm('labelled', 'File a ticket'), }); - it('zh-CN: an authored `label` with a `_views.VIEW.label` key is served translated, and so is the title', async () => { + it('zh-CN: an authored `label` with a `forms.NAME.label` key is served translated, and so is the title', async () => { const res = await overDouble(labelledItem())('zh-CN', 'labelled'); expect(res.body.label).toBe('工单表单'); expect(res.body.form.title).toBe('提交工单'); @@ -247,6 +252,6 @@ describe('GET /forms/:slug — the top-level `label` is served from the TRANSLAT const view = labelledItem(); await overDouble(view)('zh-CN', 'labelled'); expect(view.label).toBe('Ticket form'); - expect(view.config.title).toBe('File a ticket'); + expect(view.title).toBe('File a ticket'); }); }); diff --git a/packages/rest/src/public-form-two-type-withdrawal.test.ts b/packages/rest/src/public-form-two-type-withdrawal.test.ts index 4d61f07d49c..47b317ea24b 100644 --- a/packages/rest/src/public-form-two-type-withdrawal.test.ts +++ b/packages/rest/src/public-form-two-type-withdrawal.test.ts @@ -199,6 +199,14 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[]; objects?: unk version: 1, created_at: now, updated_at: now, }, { context: { isSystem: true } }); }; + /** + * A stored row as an 18 save left it, its history version included: written + * by the store's own put, past the save door that refuses the old shapes on + * 19 (ADR-0159 D7). The undo pins restore the version it records. + */ + const seedSavedRow = async (type: string, name: string, packageId: string, item: Record) => { + await protocol.getOverlayRepo().put({ type, name }, item, { parentVersion: null, actor: null, packageId }); + }; /** `GET /api/v1/meta/:type/:name` as `caller` (`systemPermissions`), or anonymous-free when `caller` is omitted. */ const meta = async (type: string, name: string, caller?: { systemPermissions: string[] }, headers: Record = {}): Promise => { (rest as any).resolveExecCtx = async () => (caller ? { userId: 'u_reader', ...caller } : undefined); @@ -215,7 +223,7 @@ async function boot(ships: { forms?: unknown[]; views?: unknown[]; objects?: unk await list.handler({ method: 'GET', path: `/api/v1/meta/${type}`, params: { type }, query: {}, body: {}, headers: {} } as any, res); return { status: res._status ?? 200, body: res._json }; }; - return { engine, protocol, rest, get, post, records, install, saveInto, saveBeforeTheGate, seedRow, meta, metaList }; + return { engine, protocol, rest, get, post, records, install, saveInto, saveBeforeTheGate, seedRow, seedSavedRow, meta, metaList }; } type Booted = Awaited>; @@ -283,21 +291,24 @@ describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either c await openOnBothDoors(b); }); - it('CONTROL: an old-shape form open in the base is served on both doors, and read as a `form` item', async () => { + it('an old-shape form open in the base\'s code is read as no `form` item, and its doors answer 404 (ADR-0159 D7)', async () => { const b = await booted({ views: [container(true)] }); + // [ADR-0159 D7] On 19 the projection serves no content: the old shape in + // booted code is served as no `form` item, and no door serves it. const forms = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.name === NAME); - expect(forms.map((f) => [f._packageId, f.object, f._formDefinedIn])).toEqual([[BASE, OBJECT, 'view']]); - await openOnBothDoors(b); + expect(forms).toEqual([]); + await closedOnBothDoors(b); }); - it('pin 1 — withdrawn by a `view` override in `.custom`, open as an authored `form` item: closed (ablate: the `view` half of the layer)', async () => { + it('pin 1 — withdrawn by a `view` override in `.custom`, open as an authored `form` item: closed three ways over (ablate together: the closed reading of a served old-shape row, the `form` half and the `view` half of the layer; any two of them alone leave it closed, and pin 3 carries the `view` half alone)', async () => { const b = await booted({ forms: [formItem(true)] }); await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + // [ADR-0159 D7] The `view` override is a stored old-shape row: no door admits the shape on 19. + await b.seedRow('view', NAME, PAIR, viewItem(false, overrides)); await closedOnBothDoors(b); }); - it('pin 2 — the mirror: withdrawn by a `form` override, open as an old-shape item in the base (ablate: the `form` half)', async () => { + it('pin 2 — the mirror on 19: a `form` override switched off over a base whose old-shape item serves no form stays closed (the `form` half is carried red by pin 5 for `form`, "narrowing only, the 19 twin" and "pin 2b, the 19 twin"; this pin stays green without it)', async () => { const b = await booted({ views: [container(true)] }); await b.install(PAIR); await b.saveInto('form', PAIR, formItem(false, overrides)); @@ -318,9 +329,11 @@ describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either c // lists serve it alone. A dependent package's row of the same name keeps // its link on ANOTHER slug, switched off: the body of the name withdraws // the form, whatever slug it points at (rule 6). - const b = await booted({ views: [container(true)] }); + // [ADR-0159 D7] The open definition is the base's `form` item (the form its + // code ships on 19); the dependent's row is a stored old-shape row. + const b = await booted({ forms: [formItem(true)] }); await b.install(DEPENDENT); - await b.saveBeforeTheGate('view', DEPENDENT, viewItem(false, {}, OTHER_SLUG)); + await b.seedRow('view', NAME, DEPENDENT, viewItem(false, {}, OTHER_SLUG)); const effective = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.name === NAME); expect(effective.map((f) => [f._packageId, f.sharing?.publicLink, f.sharing?.allowAnonymous])).toEqual([[BASE, `/forms/${SLUG}`, true]]); await closedOnBothDoors(b); @@ -330,10 +343,12 @@ describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either c // The base ships the name in the withdrawing row's own type, so the // effective list of that type serves the base's document alone and the // dependent's row sits in the per-package layer only. - const b = await booted(type === 'form' ? { forms: [formItem(true)] } : { views: [container(true)] }); + // [ADR-0159 D7] On 19 the base ships the form as a `form` item in both + // cases; the dependent's `view` row is a stored old-shape row. + const b = await booted({ forms: [formItem(true)] }); await b.install(DEPENDENT); if (type === 'form') await b.seedRow('form', NAME, DEPENDENT, formItem(false)); - else await b.saveBeforeTheGate('view', DEPENDENT, viewItem(false)); + else await b.seedRow('view', NAME, DEPENDENT, viewItem(false)); // The premise, for `view`: the effective read serves the base's open // form alone, and the withdrawing row sits in the per-package layer only. // (A dependent's `form` row under the base's name is sealed at the write @@ -369,7 +384,7 @@ describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either c it('pin 7 — replacement across the types: a `view` override with no link over an open authored `form` item closes the address (ablate: the cross-type resolution of D5)', async () => { const b = await booted({ forms: [formItem(true)] }); await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, viewItem(null, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(null, overrides)); await closedOnBothDoors(b); }); @@ -386,6 +401,18 @@ describe('[ADR-0159 D6] the form doors read both types: a withdrawal in either c await b.saveInto('form', PAIR, formItem(true, overrides)); await closedOnBothDoors(b); }); + + it('narrowing only, the 19 twin: a form the base\'s `form` item withdraws stays closed under an open `form` override (ablate: the `form` half)', async () => { + const b = await booted({ forms: [formItem(false)] }); + await closedOnBothDoors(b); + await b.install(PAIR); + await b.saveInto('form', PAIR, formItem(true, overrides)); + // The premise: the effective read serves the pair's open override at the + // base's address, so the base's own document alone keeps the form closed. + const served = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).filter((f) => f?.name === NAME); + expect(served.map((f) => [f._packageId, f.sharing?.allowAnonymous])).toEqual([[BASE, true]]); + await closedOnBothDoors(b); + }); }); describe('[ADR-0159 ruled question 3 = A] a `form` left open on an address another form holds is refused', () => { @@ -441,9 +468,10 @@ describe('[ADR-0159 D5] the `form` writes: the old-shape row goes with the save; }; it('a `form` save at a package removes that package\'s old-shape row of the name, in the same write', async () => { - const b = await booted({ views: [container(true)] }); + const b = await booted({ forms: [formItem(true)] }); await b.install(PAIR); - await b.saveInto('view', PAIR, viewItem(true, { ...overrides, label: 'Old shape' })); + // [ADR-0159 D7] The pair's old-shape row is stored as an 18 save left it. + await b.seedRow('view', NAME, PAIR, viewItem(true, { ...overrides, label: 'Old shape' })); expect((await storedViews(b)).length).toBe(1); await b.saveInto('form', PAIR, formItem(true, { ...overrides, label: 'New type' })); expect(await storedViews(b)).toEqual([]); @@ -574,12 +602,26 @@ describe('[ADR-0159 D6, D5] the `form` half of the layer, served rows only, and it('pin 2b — the `form` half alone: the base authors the form switched off with its link kept, and a dependent\'s old-shape row of the name stands open on that link (ablate: the `form` half of the layer)', async () => { const b = await booted({ forms: [formItem(false)] }); await b.install(DEPENDENT); - await b.saveBeforeTheGate('view', DEPENDENT, viewItem(true)); - // The premise: the open old shape is a candidate, and the only body that - // withdraws the name is the base's `form` item: no `view` body does. - expect(await servedAt(b)).toEqual(expect.arrayContaining([[BASE, false], [DEPENDENT, true]])); + await b.seedRow('view', NAME, DEPENDENT, viewItem(true)); + // The premise: the only body that withdraws the name is the base's `form` + // item: no `view` body does. [ADR-0159 D7] On 19 the projection serves no + // content, so the open old shape is no served `form` candidate, and the + // served `view` list holds lists only. + expect(await servedAt(b)).toEqual([[BASE, false]]); + const views = ((await b.protocol.getMetaItems({ type: 'view' })).items as any[]).filter((v) => v?.name === NAME); + expect(views).toEqual([]); + await closedOnBothDoors(b); + }); + + it('pin 2b, the 19 twin — the `form` half alone: the base authors the form switched off with its link kept, and a dependent\'s stored `form` row of the name stands open on that link (ablate: the `form` half of the layer)', async () => { + // [ADR-0159 D7] The original pin's open row is an old shape, which serves + // no form on 19; here the dependent's open row is a stored `form` row, so + // the base's `form` item is the only body that withdraws the name. + const b = await booted({ forms: [formItem(false)] }); + await b.install(DEPENDENT); + await b.seedRow('form', NAME, DEPENDENT, formItem(true)); const views = ((await b.protocol.getMetaItems({ type: 'view' })).items as any[]).filter((v) => v?.name === NAME); - expect(views.map((v) => v.config?.sharing?.allowAnonymous)).toEqual([true]); + expect(views).toEqual([]); await closedOnBothDoors(b); }); @@ -682,7 +724,7 @@ describe('[ADR-0159 D5, D6 rule 9, card ② items 2, 5 and 7] the `form` write d const THIRD = `${OBJECT}.third`; const failure = (p: Promise) => p.then(() => undefined, (e: any) => e); - it('rule 9 — an organization-scoped `form` save is refused as the same `view` save is, the withdrawal held in the other type, and nothing is written', async () => { + it('rule 9 — an organization-scoped `form` save is refused under every posture (here over a base whose old shape serves no form), as is the `view` save over a withdrawn `form` item: nothing is written, and both doors stay closed', async () => { // A form withdrawn in `form`, an organization-scoped `view` save that would leave it open… const a = await booted({ forms: [formItem(false)] }); const viewErr = await failure(a.protocol.saveMetaItem({ type: 'view', name: NAME, mode: 'draft', item: viewItem(true), organizationId: 'org_a' } as any)); @@ -714,11 +756,14 @@ describe('[ADR-0159 D5, D6 rule 9, card ② items 2, 5 and 7] the `form` write d await closedOnBothDoors(b); }); - it('an old-shape `view` write on a taken slug still saves as before', async () => { + it('an old-shape `view` write on a taken slug is refused for its shape, never as a taken address, and nothing is stored (ADR-0159 D7)', async () => { const b = await booted({ forms: [formItem(true)] }); await b.install(DEPENDENT); - await expect(b.saveInto('view', DEPENDENT, viewItem(true, { name: SECOND }, SLUG), SECOND)).resolves.toBeUndefined(); - expect((await rawRows(b, 'view', SECOND, DEPENDENT)).length).toBe(1); + // [ADR-0159 D7] On 19 the `view` door admits no form: the write is refused + // by the spec check, not by the address check a `form` write meets. + const err = await failure(b.protocol.saveMetaItem({ type: 'view', name: SECOND, packageId: DEPENDENT, mode: 'draft', item: viewItem(true, { name: SECOND }, SLUG) })); + expect([err?.status, err?.code]).toEqual([422, 'INVALID_METADATA']); + expect(await rawRows(b, 'view', SECOND, DEPENDENT)).toEqual([]); }); it('publish — a `form` draft left open on an address another form took after the draft was saved is refused 409 FORM_ADDRESS_TAKEN, naming both forms, and nothing is promoted', async () => { @@ -809,7 +854,7 @@ describe('[ADR-0159 D5] a `form` save, reset and delete: the old-shape row of th const b = await booted({ forms: [formItem(true)] }); await b.install(PAIR); await b.saveInto('form', PAIR, formItem(false, overrides)); - await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(false, overrides)); expect((await rawRows(b, 'view', NAME, PAIR)).length).toBe(1); await b.protocol.deleteMetaItem({ type: 'form', name: NAME, packageId: PAIR }); expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); @@ -818,10 +863,10 @@ describe('[ADR-0159 D5] a `form` save, reset and delete: the old-shape row of th }); it('a `form` delete at the pair removes the pair\'s old-shape row of the name', async () => { - const b = await booted({ views: [container(true)] }); + const b = await booted({ forms: [formItem(true)] }); await b.install(PAIR); await b.saveInto('form', PAIR, formItem(false, overrides)); - await b.saveInto('view', PAIR, viewItem(false, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(false, overrides)); expect((await rawRows(b, 'view', NAME, PAIR)).length).toBe(1); await b.protocol.deleteMetaItem({ type: 'form', name: NAME, packageId: PAIR }); expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); @@ -833,7 +878,7 @@ describe('[ADR-0159 D5] a `form` save, reset and delete: the old-shape row of th const b = await booted({}); await b.install(PAIR); await pairShipsNote(b); - await b.saveBeforeTheGate('view', PAIR, intakeContainer(NOTE_OBJECT, NOTE_SLUG), 'intake'); + await b.seedRow('view', 'intake', PAIR, intakeContainer(NOTE_OBJECT, NOTE_SLUG)); const [before] = await rawRows(b, 'view', 'intake', PAIR); expect(JSON.parse(before.metadata).formViews?.contact).toBeDefined(); await b.saveInto('form', PAIR, noteForm(false), NOTE_FORM); @@ -881,9 +926,9 @@ describe('[ADR-0159 D5] a `form` save, reset and delete: the old-shape row of th }); it('a `form` write that fails leaves both rows as they were', async () => { - const b = await booted({ views: [container(true)] }); + const b = await booted({ forms: [formItem(true)] }); await b.install(PAIR); - await b.saveInto('view', PAIR, viewItem(true, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(true, overrides)); const view = await rawRows(b, 'view', NAME, PAIR); await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(false, overrides) }); // The old-shape row's removal, the second write of the transaction, fails. @@ -936,27 +981,30 @@ describe('[ADR-0159 card ② item 2, D5, ADR-0029 D9.2a] the `/meta/form` read: // taken here, once, and each test's budget is for its own reads. beforeAll(async () => { const b = await booted({}); - await b.seedRow('view', NAME, null, viewItem(true)); + // A stored list: the served by-name `view` read serves lists only on 19 (ADR-0159 D7). + await b.seedRow('view', NAME, null, LIST); expect((await b.meta('view', NAME, holder)).status).toBe(200); }); - it('a caller refused a form\'s document at `/api/v1/meta/view/NAME` is refused it at `/api/v1/meta/form/NAME`; its holder is served both', async () => { + it('a stored old-shape item of the form\'s name, gated by an audience, is served on neither `/api/v1/meta/view/NAME` nor `/api/v1/meta/form/NAME`, to a stranger or to its holder (ADR-0159 D7)', async () => { // A view item's own audience gate travels with the form it projects. On // this tree only a row at rest carries one on a form (the `view` write // door refuses an item-level `requiredPermissions`, and a form body // declares none), so the row is seeded as stored. const b = await booted({}); await b.seedRow('view', NAME, null, viewItem(true, { requiredPermissions: [CAP] })); - const view = await b.meta('view', NAME, stranger); - const form = await b.meta('form', NAME, stranger); - expect(view.status, JSON.stringify(view.body)).toBe(403); - expect([form.status, form.body?.error?.code ?? form.body?.code]).toEqual([view.status, view.body?.error?.code ?? view.body?.code]); - expect(JSON.stringify(form.body)).not.toContain('Contact us'); - // CONTROL: the holder reads both. - expect((await b.meta('view', NAME, holder)).status).toBe(200); - const served = await b.meta('form', NAME, holder); - expect(served.status, JSON.stringify(served.body)).toBe(200); - expect(JSON.stringify(served.body)).toContain('Contact us'); + // [ADR-0159 D7] On 19 the served `view` read holds lists only and the + // projection serves no content: the stored item is served on neither read, + // and the stranger learns no more than the holder. + const code = (a: Answer) => a.body?.error?.code ?? a.body?.code; + for (const caller of [stranger, holder]) { + const view = await b.meta('view', NAME, caller); + const form = await b.meta('form', NAME, caller); + expect([view.status, code(view)], JSON.stringify(view.body)).toEqual([404, 'RESOURCE_NOT_FOUND']); + expect([form.status, code(form)]).toEqual([view.status, code(view)]); + expect(JSON.stringify(view.body)).not.toContain('Contact us'); + expect(JSON.stringify(form.body)).not.toContain('Contact us'); + } }); it('one definition per address: a package-less stored `form` row over a base that ships the form as an old shape is listed once, at the base\'s address, with the row\'s body (D5 served-row order)', async () => { @@ -1036,25 +1084,28 @@ describe('[ADR-0159 D5] the old shapes answer what they answered before the type for (const engine of engines) await engine.destroy().catch(() => {}); }); - it('a stack that authors the three old shapes: `GET /api/v1/meta/view` answers exactly the fixture, and each form is also served as a `form` item of the same name', async () => { + it('a stack that authors the three old shapes: `GET /api/v1/meta/view` serves the fixture\'s lists only, and no form is served as a `form` item (ADR-0159 D7)', async () => { const b = await boot(threeShapes()); engines.push(b.engine); - await b.saveInto('view', undefined, { ...viewItem(true, {}, 'standalone-37086'), name: STANDALONE }, STANDALONE); + // [ADR-0159 D7] The standalone item is a stored old-shape row: no door admits the shape on 19. + await b.seedRow('view', STANDALONE, null, { ...viewItem(true, {}, 'standalone-37086'), name: STANDALONE }); const list = await b.metaList('view'); - expect(JSON.stringify(wire(list))).toBe(JSON.stringify(wire(BEFORE['meta-view-list']))); - const forms = ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]).map((f) => [f.name, f._formDefinedIn]).sort(); - const viewForms = ((list.body?.items ?? list.body?.data?.items ?? list.body) as any[]) - .filter((v) => v?.viewKind === 'form').map((v) => [v.name, 'view']).sort(); - expect(viewForms.length).toBeGreaterThanOrEqual(3); - expect(forms).toEqual(viewForms); + // [ADR-0159 D7] On 19 the served `view` list holds lists only: the + // fixture's answer with its form items (all three of them) left out. + const fixture = BEFORE['meta-view-list']; + const fixtureForms = (fixture.body.items as any[]).filter((v) => v?.viewKind === 'form'); + expect(fixtureForms.map((v) => v.name).sort()).toEqual([NAME, `${OBJECT}.form`, STANDALONE].sort()); + expect(wire(list)).toEqual({ status: fixture.status, body: { type: fixture.body.type, items: (fixture.body.items as any[]).filter((v) => v?.viewKind !== 'form') } }); + // …and the projection serves no content: none of them is a `form` item. + expect((await b.protocol.getMetaItems({ type: 'form' })).items).toEqual([]); }); - it('an old-shape form whose `data.object` differs from its container\'s object answers both doors as before, byte-equal on the resolve door (ablate: parse projected items with FormSchema)', async () => { + it('an old-shape form in the base\'s code whose `data.object` differs from its container\'s object is served on neither door (ADR-0159 D7)', async () => { const b = await boot(otherObjectForm()); engines.push(b.engine); - expect(JSON.stringify(wire(await b.get()))).toBe(JSON.stringify(wire(BEFORE['data-object-resolve']))); - const submitted = await b.post(); - expect([submitted.status, submitted.body?.code]).toEqual([BEFORE['data-object-submit'].status, BEFORE['data-object-submit'].body?.code]); + // [ADR-0159 D7] On 19 the projection serves no content: the fixture's + // 200 resolve is not served, and nothing is written. + await closedOnBothDoors(b); }); }); @@ -1070,11 +1121,11 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba * stores its own old-shape row of the name with the form switched off. */ const pairWithItsOwnOldShapeRow = async (canRollBack: boolean): Promise => { - const b = await boot({ views: [container(true)] }, { canRollBack }); + const b = await boot({ forms: [formItem(true)] }, { canRollBack }); engines.push(b.engine); expect(engineCanRollBackOf(b)).toBe(canRollBack); await b.install(PAIR); - await b.saveInto('view', PAIR, viewItem(false, overrides)); + await b.seedSavedRow('view', NAME, PAIR, viewItem(false, overrides)); await closedOnBothDoors(b); return b; }; @@ -1149,12 +1200,12 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba ] as const; /** The pair over the base's open container, its own old-shape row of `kind` stored, and the form switched off published from a package draft. */ const publishedOverTheOldShape = async (shape: (typeof OLD_SHAPE_KINDS)[number]) => { - const b = await boot({ views: [container(true)] }, { canRollBack: shape.canRollBack }); + const b = await boot({ forms: [formItem(true)] }, { canRollBack: shape.canRollBack }); engines.push(b.engine); expect(engineCanRollBackOf(b)).toBe(shape.canRollBack); await b.install(PAIR); if (shape.ownObject) await pairShipsNote(b); - await b.saveBeforeTheGate('view', PAIR, shape.item(), shape.row); + await b.seedSavedRow('view', shape.row, PAIR, shape.item()); await closedOnBothDoors(b, shape.slug); const before = await rawRows(b, 'view', shape.row, PAIR); expect(before.length).toBe(1); @@ -1220,7 +1271,7 @@ describe('[ADR-0159 D5, ADR-0067 D2 and D3] the undo of a `form` publish puts ba } it('CONTROL: the revert of a `form` publish that removed no old-shape row removes the form and restores nothing else', async () => { - const b = await boot({ views: [container(true)] }, { canRollBack: false }); + const b = await boot({ forms: [formItem(true)] }, { canRollBack: false }); engines.push(b.engine); await b.install(PAIR); await b.protocol.saveMetaItem({ type: 'form', name: NAME, packageId: PAIR, mode: 'draft', item: formItem(false, overrides) }); @@ -1253,10 +1304,10 @@ describe('[ADR-0067 D2] a package publish refused part-way on an engine that can * the name with the form switched off. */ const pairOverTheBase = async (): Promise => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); engines.push(b.engine); await b.install(PAIR); - await b.saveInto('view', PAIR, viewItem(false, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(false, overrides)); await closedOnBothDoors(b); return b; }; @@ -1395,7 +1446,7 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', }); for (const listers of [0, 1, 2] as const) { - it(`a package-less form at the environment's own address is served today where the read seats it: with ${listers} package(s) shipping a list of the name, both doors serve it before --apply, it moves into the environment, and both doors serve it after (ablate: read the environment's own address only at the environment)`, async () => { + it(`a package-less form at the environment's own address: with ${listers} package(s) shipping a list of the name, both doors answer 404 before --apply (the stored old-shape overlay closes its address, ADR-0159 D7), it moves into the environment, and both doors serve it after (ablate: read the environment's own address only at the environment)`, async () => { const b = await booted({}); for (let i = 0; i < listers; i++) { b.engine.registerApp({ @@ -1406,27 +1457,29 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', await b.engine.syncSchemas(); await b.seedRow('view', NAME, null, viewItem(true)); const doors = async () => [answered(await b.get()), answered(await b.post())]; - const answers = await doors(); - expect(answers[0]![0]).toBe(200); - expect(answers[1]![0]).not.toBe(404); + // [ADR-0159 D6 rules 10 and 11, D7] On 19 the stored old-shape overlay of + // the name serves no content and closes the address. + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); const result = await apply(b); expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address, f.outcome, f.destination?.kind])).toEqual([ [{ kind: 'environment' }, 'move', 'environment_form'], ]); expect(result).toMatchObject({ applied: true }); expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId ?? null])).toEqual([[NAME, 'form', null]]); - expect(await doors()).toEqual(answers); + const after = await doors(); + expect(after[0]![0]).toBe(200); + expect(after[1]![0]).not.toBe(404); }); } - it('③ a pair held as booted code: its own old-shape row moves into the pair\'s own `form` row, the pair door is not asked, and both doors answer the same before and after (ablate: read the pair from the address kind)', async () => { + it('③ a pair held as booted code: its own old-shape row moves into the pair\'s own `form` row, the pair door is not asked, and both doors answer 404 before --apply and serve the form after it (ADR-0159 D7) (ablate: read the pair from the address kind)', async () => { const b = await booted({}); b.engine.registerApp({ id: PAIR, name: 'forms37086custom', version: '1.0.0', namespace: 'ftt_custom', dependencies: { [BASE]: '^1.0.0' } } as any); await b.engine.syncSchemas(); await b.seedRow('view', NAME, PAIR, viewItem(true)); const doors = async () => [answered(await b.get()), answered(await b.post())]; - const answers = await doors(); - expect(answers[0]![0]).toBe(200); + // [ADR-0159 D7] A stored old-shape row is served as no form until the ceremony moves it. + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], [404, 'FORM_NOT_FOUND']]); const result = await apply(b); expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.address, f.outcome, f.destination])).toEqual([ [{ kind: 'base', packageId: PAIR }, 'move', { kind: 'pair_form', base: BASE, pair: PAIR }], @@ -1435,7 +1488,9 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', expect(result.written.map((w: any) => [w.row.type, w.row.packageId])).toEqual([['form', PAIR]]); expect(await activeBodies(b, 'form', NAME, PAIR)).toEqual([expect.not.objectContaining({ overrides: expect.anything() })]); expect(await rawRows(b, 'view', NAME, PAIR)).toEqual([]); - expect(await doors()).toEqual(answers); + const after = await doors(); + expect(after[0]![0]).toBe(200); + expect(after[1]![0]).not.toBe(404); }); it('③ a pair held as booted code that ships the name itself: its own old-shape row over the pair\'s own form moves into the pair\'s own `form` row, the pair door is not asked, and both doors answer the same before and after (ablate: the pair read from the address kind where the pair ships the name)', async () => { @@ -1526,7 +1581,24 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', it('the switched-off form in a record-form slot, the stored twin: moved with its switch, not listed for removal, closed before and after (ablate: judge "public" by `sharing.enabled === true`)', async () => { const b = await booted({ views: [baseDefaultForm(sharing(true))] }); await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, slotItem(switchedOff, overrides), DFORM); + await b.seedRow('view', DFORM, PAIR, slotItem(switchedOff, overrides)); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.applied).toBe(true); + expect(result.removed).toEqual([]); + expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId])).toEqual([[DFORM, 'form', PAIR]]); + expect(await activeBodies(b, 'form', DFORM, PAIR)).toEqual([expect.objectContaining({ sharing: switchedOff, overrides: overrides.overrides })]); + await closedOnBothDoors(b); + }); + + it('the switched-off form in a record-form slot, the stored twin over a base whose `form` item in the slot declares no link: the row\'s own switched-off link alone keeps it a public form; moved with its switch, not listed for removal, closed before and after (ablate: judge "public" by `sharing.enabled === true`)', async () => { + // The existing twin's base declares a link in the slot, which classes the + // row as public on its own. Here the base's item declares none, so the + // only thing that keeps the row out of removal is its own link, kept with + // the switch off (D7-a: a link switched off is still a link). + const b = await booted({ forms: [{ name: DFORM, object: OBJECT, label: 'In the slot', ...fields }] }); + await b.install(PAIR); + await b.seedRow('view', DFORM, PAIR, slotItem(switchedOff, overrides)); await closedOnBothDoors(b); const result = await apply(b); expect(result.applied).toBe(true); @@ -1541,7 +1613,7 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', const b = await booted({ views: [baseDefaultForm(sharing(true))] }); if (shape === 'a `.custom` override') { await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, slotItem(null, overrides), DFORM); + await b.seedRow('view', DFORM, PAIR, slotItem(null, overrides)); } else { await b.seedRow('view', DFORM, null, slotItem(null)); } @@ -1560,7 +1632,7 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', const b = await booted({ views: [container(true)] }); if (shape === 'a `.custom` switch-only override') { await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(false, overrides)); } else { await b.seedRow('view', OBJECT, null, { name: OBJECT, ...container(false) }); } @@ -1581,7 +1653,7 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', it('a `.custom` view override that withdraws a form the base ships as a `form` item: moved into the pair as that form\'s declared override, written as the pair\'s own row and not as an edit of the shipped item, closed before and after (ablate: judge the declared override\'s write as an override of the shipped item)', async () => { const b = await booted({ forms: [formItem(true)] }); await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(false, overrides)); await closedOnBothDoors(b); const result = await apply(b); expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId, w.destination.kind])).toEqual([[NAME, 'form', PAIR, 'pair_override']]); @@ -1593,7 +1665,7 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', it('the fold keeps the served body and only narrows: an open override in the pair beside a package-less row that withdraws the form is closed before and after, and the destination keeps its link with the switch off (ablate: the carry of the folded row\'s switch)', async () => { const b = await booted({ views: [container(true)] }); await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, viewItem(true, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(true, overrides)); await b.seedRow('view', NAME, null, viewItem(false)); await closedOnBothDoors(b); const result = await apply(b); @@ -1615,12 +1687,12 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', await closedOnBothDoors(b); }); - it('the fold, the writable-base twin: a writable package\'s own open row beside a package-less row that withdraws the form is open before and closed after, and the report names it newly closed (ablate: the report\'s line for a newly closed form)', async () => { + it('the fold, the writable-base twin: a writable package\'s own open row beside a package-less row that withdraws the form is closed before (the stored old-shape overlay of the name closes the address, ADR-0159 D7) and after, and the report names it newly closed (ablate: the report\'s line for a newly closed form)', async () => { const b = await booted({}); await b.install(DEPENDENT); - await b.saveInto('view', DEPENDENT, viewItem(true)); + await b.seedRow('view', NAME, DEPENDENT, viewItem(true)); await b.seedRow('view', NAME, null, viewItem(false)); - await openOnBothDoors(b); + await closedOnBothDoors(b); const result = await apply(b); expect(result.census.forms.filter((f: any) => f.form === NAME)).toEqual([expect.objectContaining({ address: { kind: 'package', packageId: DEPENDENT }, outcome: 'move', newlyClosed: true, @@ -1645,25 +1717,29 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', }); it('the fold, a no-form row ahead of a form row: a list bound to the base, over its open form, beside an open package-less form row, is closed before and after, the pair holds no row of the name (ablate: find the served row among form rows only)', async () => { - const b = await booted({ views: [container(true)] }); + // [ADR-0159 D7] The base's open form is the `form` item its code ships on 19: + // open until the stored rows are written beside it. + const b = await booted({ forms: [formItem(true)] }); + await openOnBothDoors(b); await b.seedRow('view', NAME, BASE, LIST); await b.seedRow('view', NAME, null, viewItem(true)); const before = await allRows(b); await closedOnBothDoors(b); const result = await apply(b); expect(result.census.precheck.canSwitch).toBe(true); - expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => f.outcome)).toEqual(['left_in_place']); + // Left in place because the served row is the list, not because no door serves the form. + expect(result.census.forms.filter((f: any) => f.form === NAME).map((f: any) => [f.outcome, f.reason])).toEqual([['left_in_place', 'served_no_form']]); expect(await rawRows(b, 'form', NAME, PAIR)).toEqual([]); expect(await allRows(b)).toBe(before); await closedOnBothDoors(b); }); - it('the retired form and its successor on one address: both rows are moved as written, not through the `form` save door, the successor answers before and after, and the report names the pair (ablate: move the rows through the `form` save door)', async () => { + it('the retired form and its successor on one address: both rows are moved as written, not through the `form` save door, the successor answers 404 before (the stored old-shape overlay closes its address, ADR-0159 D7) and is served after, and the report names the pair (ablate: move the rows through the `form` save door)', async () => { const b = await booted({}); const RETIRED = `${OBJECT}.retired`; await b.seedRow('view', RETIRED, null, { ...viewItem(false), name: RETIRED, label: 'Retired' }); await b.seedRow('view', NAME, null, viewItem(true)); - await openOnBothDoors(b); + await closedOnBothDoors(b); const result = await apply(b); expect(result.census.sharedSlugs).toEqual([{ slug: SLUG, forms: [RETIRED, NAME].sort() }]); expect(result.written.map((w: any) => [w.form, w.row.type, w.row.packageId ?? null]).sort()).toEqual([[NAME, 'form', null], [RETIRED, 'form', null]].sort()); @@ -1676,7 +1752,7 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', it('all or nothing: with a row that holds the upgrade stored beside movable rows, --apply writes nothing, every stored row byte-equal, and both doors answer the same before and after (ablate: move what can be moved and report the rest)', async () => { const b = await booted({ views: [container(true)] }); await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, viewItem(false, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(false, overrides)); const BROKEN = `${OBJECT}.broken`; await b.seedRow('view', BROKEN, null, { name: BROKEN, viewKind: 'form', sharing: sharing(true) }); const before = await allRows(b); @@ -1689,7 +1765,8 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', }); it('internal record forms are removed, and only those: an unlinked default form in a stored container with a list goes, the container is re-saved with its list byte-equal, the report carries its body (ablate: the base half of the internal test)', async () => { - const b = await booted({ views: [{ object: OBJECT, form: fields, formViews: { contact: { ...body(true), data: { provider: 'object', object: OBJECT } } } }] }); + // [ADR-0159 D7] The open contact form ships as a `form` item; the base's container keeps its unlinked default `form`. + const b = await booted({ forms: [formItem(true)], views: [{ object: OBJECT, form: fields }] }); const LIST_BODY = { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }; await b.seedRow('view', OBJECT, null, { name: OBJECT, object: OBJECT, list: LIST_BODY, form: { ...fields, label: 'Edited' } }); await openOnBothDoors(b); @@ -1700,17 +1777,19 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', await openOnBothDoors(b); }); - it('the pair\'s own item (ruling 7250977204): a row bound to a read-only package that ships no form of the name moves into the pair declaring no `overrides`, and the public address answers byte-equal before and after', async () => { + it('the pair\'s own item (ruling 7250977204): a row bound to a read-only package that ships no form of the name moves into the pair declaring no `overrides`, and the public address answers 404 before --apply and serves the form after it (ADR-0159 D7)', async () => { const b = await booted({}); await b.seedRow('view', NAME, BASE, viewItem(true)); - const before = await b.get(); - expect(before.status).toBe(200); + // [ADR-0159 D7] A stored old-shape row is served as no form until the ceremony moves it. + expect(answered(await b.get())).toEqual([404, 'FORM_NOT_FOUND']); const result = await apply(b); expect(result.written).toEqual([expect.objectContaining({ destination: { kind: 'pair_form', base: BASE, pair: PAIR } })]); const [moved] = await activeBodies(b, 'form', NAME, PAIR); expect(moved).toBeDefined(); expect(moved).not.toHaveProperty('overrides'); - expect(JSON.stringify(await b.get())).toBe(JSON.stringify(before)); + const after = await b.get(); + expect(after.status, JSON.stringify(after.body)).toBe(200); + expect(after.body).toMatchObject({ slug: SLUG, label: 'Contact us' }); }); it('the census and the run agree where the store seals the destination: the pair\'s own item for a row bound to a read-only package that ships no form of the name, where another package ships the name as a `form` item, holds the upgrade in the census, and --apply writes nothing (ablate: the census read of the store\'s seal)', async () => { @@ -1815,7 +1894,7 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', it(`M3 through both doors: no package ships the name, a row bound to the read-only base beside the pair's declared override of it; ${shape}: one \`form\` row in the pair, the override's body kept, and both doors answer as before (ablate: plan the pair's override at the pair's own address)`, async () => { const b = await booted({}); await b.install(PAIR); - await b.saveBeforeTheGate('view', PAIR, viewItem(overrideOpen, overrides)); + await b.seedRow('view', NAME, PAIR, viewItem(overrideOpen, overrides)); await b.seedRow('view', NAME, BASE, viewItem(boundOpen)); await closedOnBothDoors(b); const result = await apply(b); @@ -1831,7 +1910,7 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', } for (const open of [false, true]) { - it(`a row the read serves at another address than the package it is bound to (ruling record 7254350842): a module ships the form on its own object, the row bound to its App is ${open ? 'open' : 'switched off'}; it moves into the pair as the module's declared override, and both doors answer as before (ablate: plan the row at the package it is bound to)`, async () => { + it(`a row the read serves at another address than the package it is bound to (ruling record 7254350842): a module ships the form on its own object, the row bound to its App is ${open ? 'open' : 'switched off'}; it moves into the pair as the module's declared override, and both doors answer 404 before --apply and as the moved row says after it (ADR-0159 D7) (ablate: plan the row at the package it is bound to)`, async () => { const b = await booted({}); const MODULE = `${BASE}.desk`; const TICKET = 'ftt_ticket'; @@ -1849,16 +1928,120 @@ describe('[ADR-0159 D7] the stored-form ceremony\'s --apply through both doors', await b.engine.syncSchemas(); await b.seedRow('view', TICKET_FORM, BASE, { name: TICKET_FORM, object: TICKET, viewKind: 'form', label: 'Stored', config: { ...body(open, TICKET_SLUG), data } }); const doors = async () => [answered(await b.get(TICKET_SLUG)), (await b.get(TICKET_SLUG)).body?.label ?? null]; - const before = await doors(); - expect(before).toEqual(open ? [[200, undefined], 'Stored'] : [[404, 'FORM_NOT_FOUND'], null]); + // [ADR-0159 D7] A stored old-shape row is served as no form until the ceremony moves it. + expect(await doors()).toEqual([[404, 'FORM_NOT_FOUND'], null]); const result = await apply(b); expect(result.census.forms.filter((f: any) => f.form === TICKET_FORM).map((f: any) => [f.address.packageId, f.outcome, f.destination?.kind])).toEqual([[MODULE, 'move', 'pair_override']]); const [moved] = await activeBodies(b, 'form', TICKET_FORM, PAIR); expect(moved).toMatchObject({ overrides: { package: MODULE } }); expect(await rawRows(b, 'view', TICKET_FORM, BASE)).toEqual([]); - expect(await doors()).toEqual(before); + expect(await doors()).toEqual(open ? [[200, undefined], 'Stored'] : [[404, 'FORM_NOT_FOUND'], null]); if (open) expect(answered(await b.post(TICKET_SLUG))).not.toEqual([404, 'FORM_NOT_FOUND']); else expect(answered(await b.post(TICKET_SLUG))).toEqual([404, 'FORM_NOT_FOUND']); }); } }); + +/** + * [ADR-0159 D7] From protocol 19 a stored row is read under the name its + * package's form is served under: at both doors, in the replacement check and + * in the stored-forms census, so the ceremony lands the row's withdrawal on + * that form. A row whose package cannot be told apart reads closed at every + * package that ships the name. Each pin asserts status, `code` and that no + * record was written (`closedOnBothDoors`), before `--apply` and after it. + * The ablation (the reading removed from `expandUnderOwnName`) is recorded on + * the PR. + */ +describe('[ADR-0159 D7] a stored row is read under the name its package\'s form is served under on protocol 19', () => { + const engines: ObjectQL[] = []; + const savedWritable = process.env.OS_METADATA_WRITABLE; + beforeAll(() => { delete process.env.OS_METADATA_WRITABLE; }); + beforeEach(() => { + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + }); + afterAll(async () => { + if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE; + else process.env.OS_METADATA_WRITABLE = savedWritable; + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: { forms?: unknown[]; views?: unknown[] }): Promise => { + const b = await boot(ships); + engines.push(b.engine); + return b; + }; + const OTHER = 'com.example.other37112'; + const OTHER_PAIR = `${OTHER}.custom`; + const list = { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }; + /** The stored row: the container an 18 package shipped its form in, the form switched off with its link kept. */ + const storedRow = (extra: Record = {}) => ({ name: OBJECT, ...container(false), ...extra }); + const apply = (b: Booted): Promise => applyStoredFormsOf(b.protocol, { actor: null }); + const written = (result: any) => result.written.map((w: any) => [w.form, w.row.type, w.row.packageId, w.destination.kind]); + /** The served `form` items of {@link NAME}: the package each is served at, and its anonymous switch. */ + const servedForms = async (b: Booted) => ((await b.protocol.getMetaItems({ type: 'form' })).items as any[]) + .filter((f) => f.name === NAME) + .map((f) => [f._packageId ?? null, f.sharing?.allowAnonymous ?? null]); + const withdrawalIn = async (b: Booted, pair: string) => + (await rawRows(b, 'form', NAME, pair)).map((r) => JSON.parse(r.metadata).sharing); + + it('CONTROL: with no stored row, the package\'s `form` item is open on both doors', async () => { + const b = await booted({ forms: [formItem(true)] }); + await openOnBothDoors(b); + }); + + it('the row closes its package\'s form: both doors answer 404 before --apply, the ceremony moves the withdrawal into the pair as that form\'s declared override, both doors answer 404 after it, and a second run finds nothing', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.seedRow('view', OBJECT, null, storedRow()); + await closedOnBothDoors(b); + expect(await servedForms(b)).toEqual([]); + const census = await listStoredFormsOf(b.protocol); + expect(census.forms.map((f: any) => [f.form, f.outcome])).toEqual([[NAME, 'move']]); + const result = await apply(b); + expect(result.applied).toBe(true); + expect(written(result)).toEqual([[NAME, 'form', PAIR, 'pair_override']]); + expect(await withdrawalIn(b, PAIR)).toEqual([sharing(false)]); + expect(await rawRows(b, 'view', OBJECT, null)).toEqual([]); + expect(await servedForms(b)).toEqual([[BASE, false]]); + await closedOnBothDoors(b); + expect(await apply(b)).toMatchObject({ applied: true, written: [], removed: [], rowsChanged: [] }); + await closedOnBothDoors(b); + }); + + it('a row whose package cannot be told apart reads closed: two packages ship the form, both doors answer 404 before --apply, the ceremony closes the form in each, and both doors answer 404 after it', async () => { + const b = await booted({ forms: [formItem(true)] }); + b.engine.registerApp({ id: OTHER, name: 'other37112', version: '1.0.0', namespace: 'fto', objects: [], forms: [formItem(true)] } as any); + await b.engine.syncSchemas(); + expect((await servedForms(b)).sort()).toEqual([[BASE, true], [OTHER, true]].sort()); + await openOnBothDoors(b); + await b.seedRow('view', OBJECT, null, storedRow()); + await closedOnBothDoors(b); + const result = await apply(b); + expect(result.applied).toBe(true); + expect(written(result).sort()).toEqual([[NAME, 'form', PAIR, 'pair_override'], [NAME, 'form', OTHER_PAIR, 'pair_override']].sort()); + expect(await withdrawalIn(b, PAIR)).toEqual([sharing(false)]); + expect(await withdrawalIn(b, OTHER_PAIR)).toEqual([sharing(false)]); + expect((await servedForms(b)).sort()).toEqual([[BASE, false], [OTHER, false]].sort()); + await closedOnBothDoors(b); + }); + + it('the row\'s list keeps the name it had, and the row stays for it: only the form is read under its package\'s name', async () => { + const b = await booted({ forms: [formItem(true)] }); + await b.seedRow('view', OBJECT, null, storedRow({ list })); + const lists = async () => ((await b.protocol.getMetaItems({ type: 'view' })).items as any[]).map((v) => [v.name, v._packageId ?? null]); + expect(await lists()).toEqual([[`${OBJECT}.${OBJECT}`, null]]); + await closedOnBothDoors(b); + expect(written(await apply(b))).toEqual([[NAME, 'form', PAIR, 'pair_override']]); + expect(await lists()).toEqual([[`${OBJECT}.${OBJECT}`, null]]); + await closedOnBothDoors(b); + }); + + it('CONTROL: the same row over a package that still ships a view of its name is closed before and after --apply', async () => { + const b = await booted({ forms: [formItem(true)], views: [{ name: OBJECT, object: OBJECT, list }] }); + await b.seedRow('view', OBJECT, null, storedRow({ list })); + await closedOnBothDoors(b); + expect(written(await apply(b))).toEqual([[NAME, 'form', PAIR, 'pair_override']]); + await closedOnBothDoors(b); + }); +}); diff --git a/packages/rest/src/public-form-withdrawal-effective-read.test.ts b/packages/rest/src/public-form-withdrawal-effective-read.test.ts index a35712940c0..c5cc2bb568a 100644 --- a/packages/rest/src/public-form-withdrawal-effective-read.test.ts +++ b/packages/rest/src/public-form-withdrawal-effective-read.test.ts @@ -39,6 +39,7 @@ import { SysMetadataCommitObject, SysMetadataHistoryObject, SysMetadataObject, + hashSpec, } from '@objectstack/metadata-core'; import { RestServer } from './rest-server'; @@ -51,17 +52,14 @@ const SLUG = 'contact-28409'; const sharing = (allowAnonymous: boolean) => ({ enabled: true, allowAnonymous, publicLink: `/forms/${SLUG}` }); +/** [ADR-0159 D7] The form as major 19 holds it: a `form` item named `OBJECT.KEY`, bound by `object`. */ const formView = (allowAnonymous: boolean, label = 'Contact us', extra: Record = {}) => ({ name: VIEW, object: OBJECT, - viewKind: 'form', label, - config: { - type: 'simple', - data: { provider: 'object', object: OBJECT }, - sections: [{ fields: ['name', 'email'] }], - sharing: sharing(allowAnonymous), - }, + type: 'simple', + sections: [{ fields: ['name', 'email'] }], + sharing: sharing(allowAnonymous), ...extra, }); @@ -107,20 +105,8 @@ async function boot(baseAllowsAnonymous = true) { // so a base with a pair declares one. namespace: 'pfw', objects: [INQUIRY], - // A shipped view is a container; its `formViews.contact` slot expands to - // the `.contact` form view the doors read. - views: [{ - object: OBJECT, - formViews: { - contact: { - label: 'Contact us', - type: 'simple', - data: { provider: 'object', object: OBJECT }, - sections: [{ fields: ['name', 'email'] }], - sharing: sharing(baseAllowsAnonymous), - }, - }, - }], + // [ADR-0159 D7] The base ships its public form as a `form` item. + forms: [formView(baseAllowsAnonymous)], } as any); await engine.syncSchemas(); const protocol: any = new ObjectStackProtocolImplementation(engine as any, () => new Map()); @@ -153,24 +139,25 @@ async function boot(baseAllowsAnonymous = true) { }, }); const saveInto = async (packageId: string, item: Record) => { - await protocol.saveMetaItem({ type: 'view', name: VIEW, item, mode: 'draft', packageId }); - await protocol.publishMetaItem({ type: 'view', name: VIEW, packageId }); + await protocol.saveMetaItem({ type: 'form', name: VIEW, item, mode: 'draft', packageId }); + await protocol.publishMetaItem({ type: 'form', name: VIEW, packageId }); }; // [#28410, ADR-0146 D2, ruling A on #28390] A dependent package's row under // a name the base ships is refused at the save door now (rename is its one // fix), so the withdrawing row this file pins is one stored BEFORE that gate: - // the door's refusal is asserted first, then the same body goes through the - // same draft save and per-item publish with the gate's verdict held at - // `not_concerned` for that one write, the row a pre-gate save left. + // the door's refusal is asserted first, then the same body is written as the + // active row a pre-gate save left. (A `form` write meets a second gate + // behind the first, the sealed packaged base, so the row is written past + // the door rather than through it with one verdict held.) const saveIntoBeforeTheGate = async (packageId: string, item: Record) => { - await expect(protocol.saveMetaItem({ type: 'view', name: VIEW, item, mode: 'draft', packageId })) + await expect(protocol.saveMetaItem({ type: 'form', name: VIEW, item, mode: 'draft', packageId })) .rejects.toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); - protocol.overrideWriteVerdict = () => ({ verdict: 'not_concerned' }); - try { - await saveInto(packageId, item); - } finally { - delete protocol.overrideWriteVerdict; - } + const now = new Date().toISOString(); + await engine.insert('sys_metadata', { + id: `seed_form_${VIEW}_${packageId}`, type: 'form', name: VIEW, + package_id: packageId, state: 'active', metadata: JSON.stringify(item), checksum: hashSpec(item, 'form'), + version: 1, created_at: now, updated_at: now, + }, { context: { isSystem: true } }); }; return { engine, protocol, get, post, install, saveInto, saveIntoBeforeTheGate }; } @@ -203,8 +190,8 @@ describe('[#28409] the form doors judge withdrawal against the effective read, n it('CONTROL: the base\'s public form is served by the real list', async () => { const { protocol, get } = await booted(); - const shipped = ((await protocol.getMetaItems({ type: 'view' })).items as any[]).filter((v) => v?.name === VIEW); - expect(shipped.map((v) => [v._packageId, v.config?.sharing?.allowAnonymous])).toEqual([[BASE, true]]); + const shipped = ((await protocol.getMetaItems({ type: 'form' })).items as any[]).filter((v) => v?.name === VIEW); + expect(shipped.map((v) => [v._packageId, v.sharing?.allowAnonymous])).toEqual([[BASE, true]]); const answer = await get(); expect(answer.status, JSON.stringify(answer.body)).toBe(200); }); @@ -217,10 +204,12 @@ describe('[#28409] the form doors judge withdrawal against the effective read, n // The premise: the effective list serves the base's (public) document // alone under the name, and the withdrawing row is the dependent's own // item in the per-package layer. - const effective = ((await protocol.getMetaItems({ type: 'view' })).items as any[]).filter((v) => v?.name === VIEW); - expect(effective.map((v) => v.config?.sharing?.allowAnonymous)).toEqual([true]); - const layer = ((await protocol.getMetaItemsPerPackage({ type: 'view' })).items as any[]).filter((v) => v?.name === VIEW); - expect(layer.map((v) => v.config?.sharing?.allowAnonymous).sort()).toEqual([false, true]); + const effective = ((await protocol.getMetaItems({ type: 'form' })).items as any[]).filter((v) => v?.name === VIEW); + expect(effective.map((v) => v.sharing?.allowAnonymous)).toEqual([true]); + const layer = ((await protocol.getMetaItemsPerPackage({ type: 'form' })).items as any[]).filter((v) => v?.name === VIEW); + // The `form` per-package layer holds the dependent's withdrawing row (its + // stored rows; the base's shipped item is the effective list's above). + expect(layer.map((v) => v.sharing?.allowAnonymous)).toContain(false); expect(closed(await get())).toEqual([404, 'FORM_NOT_FOUND']); expect(closed(await post())).toEqual([404, 'FORM_NOT_FOUND']); diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index af970df5780..344b3bacbbd 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -85,11 +85,8 @@ import { // [ADR-0131 D3 · D12 items 7–8] The walled refusal the same four doors ask // next, for every type they write. walledCatalogWriteVerdict, - // Which form candidates the anonymous form doors serve — the one rule the - // metadata protocol also judges organization-scoped `view` writes by. - anonymousFormIntakeCandidates, - // [ADR-0159 D6 rule 9] …and the slug a `form` item's own `sharing` opens: such - // an item is its own one candidate, on the doors, the write gate and the admin read. + // [ADR-0159 D6 rule 9] The slug a `form` item's own `sharing` opens: such an + // item is its own one candidate, on the doors, the write gate and the admin read. anonymousFormIntakeSlug, // `anonymousFormIntakeWithdrawnIn` (whether another body of the same view name withdraws a // candidate), read only by the anonymous form doors, moved with `registerFormEndpoints`' @@ -99,8 +96,6 @@ import { anonymousFormIntakePosture, anonymousFormIntakeUnavailability, anonymousFormIntakeUnavailableMessage, - anonymousFormObjectName, - anonymousFormSharingPath, // [#21476] `objectFieldVisibilityFingerprint`, the ADR-0106 fingerprint the admin // read folds the reason into — and [#22639] the list views the read gate // withheld — read only by the item read and its intake-reason helper, moved with @@ -6441,18 +6436,18 @@ export class RestServer { } /** - * [#21476] The administrator's read of a `view`: one warning per open - * public form that cannot take intake on this deployment, located at that - * form's `sharing` and naming why. Asked through the SAME predicate, the - * same tenancy read and the same object read as both anonymous doors - * (`registerFormEndpoints`), so the reason is shown exactly when the doors - * answer not-found. A view with no open public form reads nothing. - * - * [ADR-0159 D6 rule 9] …and of a `form` item, judged as the doors - * (`openFormAt`) and the write gate (`findPublicFormIntakeGaps`) judge it: - * the item itself is its one candidate, its own `sharing` opens the slug, - * its own `object` is what it submits into, and the warning sits at - * `sharing`, item-relative as the view's paths are. + * [#21476, ADR-0159 D6 rule 9] The administrator's read of a `form` item: + * a warning when it is an open public form that cannot take intake on this + * deployment, located at its `sharing` and naming why. Asked through the + * SAME predicate, the same tenancy read and the same object read as both + * anonymous doors (`registerFormEndpoints`), so the reason is shown exactly + * when the doors answer not-found. Judged as the doors (`openFormAt`) and + * the write gate (`findPublicFormIntakeGaps`) judge it: the item itself is + * its one candidate, its own `sharing` opens the slug and its own `object` + * is what it submits into. A form that is not open reads nothing. + * + * [ADR-0159 D7] A `view` is answered with no warning: it holds lists only + * since protocol 19, and the doors offer no form through a `view` body. */ private async anonymousFormIntakeWarnings( environmentId: string | undefined, @@ -6463,18 +6458,14 @@ export class RestServer { ): Promise> { if (!item || typeof item !== 'object' || typeof (p as any).getMetaItems !== 'function') return []; const body = item as Record; - let candidates: Array<{ object: string | undefined; slug: string; path: string }>; - if (type === 'form') { - const slug = anonymousFormIntakeSlug(body.sharing); - const object = typeof body.object === 'string' && body.object ? body.object : undefined; - candidates = slug === null ? [] : [{ object, slug, path: 'sharing' }]; - } else { - candidates = anonymousFormIntakeCandidates(body).map((candidate) => ({ - object: anonymousFormObjectName(body, candidate.form), - slug: candidate.slug, - path: anonymousFormSharingPath(body, candidate), - })); - } + // [ADR-0159 D7] A `view` states no reason: since protocol 19 a `view` + // read serves lists only and no door offers a form through a `view` + // body, so there is no open form of it for the posture to withhold. + if (type !== 'form') return []; + const slug = anonymousFormIntakeSlug(body.sharing); + const object = typeof body.object === 'string' && body.object ? body.object : undefined; + const candidates: Array<{ object: string | undefined; slug: string; path: string }> = + slug === null ? [] : [{ object, slug, path: 'sharing' }]; if (candidates.length === 0) return []; const tenancy = await this.resolveAnonymousFormTenancy(environmentId, req); const posture = anonymousFormIntakePosture(tenancy); @@ -6500,7 +6491,7 @@ export class RestServer { * Public forms are opt-in: a `FormView` becomes accessible to anonymous * visitors only when `sharing.enabled === true`, `sharing.allowAnonymous * === true` AND a `sharing.publicLink` slug is configured - * (`anonymousFormIntakeCandidates`, `@objectstack/metadata-core`). A form + * (`anonymousFormIntakeSlug`, `@objectstack/metadata-core`). A form * whose bound object cannot take an anonymous submission on this * deployment's posture is not offered either * ({@link anonymousFormIntakeUnavailability}): both routes answer it exactly @@ -6532,12 +6523,14 @@ export class RestServer { * masker over what the grant hands back (ADR-0138 records the name); the * submit answers the created id only (#22437). * - * The matched FormView's parent ViewSchema is found by scanning - * `protocol.getMetaItems({ type: 'view' })`. For each entry we inspect - * `form.sharing`, every entry in `formViews` and a flattened form item's - * `config.sharing`; the first open FormView whose `sharing.publicLink` - * matches `/forms/:slug` (or just `:slug`) wins. The response carries the matched form view under `form` and - * the inferred target object, matching what the frontend's + * [ADR-0159 D6, D7] The form is found in the effective `form` read + * (`protocol.getMetaItems({ type: 'form' })`): the open `form` item whose + * `sharing.publicLink` names `/forms/:slug` (or just `:slug`), unless a + * body of its name withdraws it. Since protocol 19 no form is answered + * through a `view` item; the stored bodies of the shapes a `view` held a + * form in before 19 are read for that withdrawal judgement alone + * (`form-routes.ts`). The response carries the matched form under `form` + * and its target object, matching what the frontend's * `mapViewSpecToEmbeddableConfig` expects. */ private registerFormEndpoints(basePath: string): void { diff --git a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts index b19e9306827..cecca57fbf0 100644 --- a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts +++ b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts @@ -66,7 +66,6 @@ import { REST_ROUTE_LEDGER } from './rest-route-ledger.js'; import { sandboxFaultAnswer } from './error-response.js'; import { isSandboxOwnFault } from '@objectstack/types'; import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; -import { projectedFormsOf } from '@objectstack/spec/ui'; const SENTENCE = 'Locked rows cannot be changed here.'; const WRAPPER = `hook 'mz_guard' threw: Error: ${SENTENCE}`; @@ -101,13 +100,11 @@ const WRITE_ROWS = REST_ROUTE_LEDGER.filter((row) => /^(POST|PUT|PATCH|DELETE) / // ─── the harness ──────────────────────────────────────────────────────────── const SCHEMA = { name: OBJECT, label: 'Locked', fields: { name: { name: 'name', type: 'text' } } }; -const FORM_VIEW = { - name: 'mz_form', object: OBJECT, viewKind: 'form', _diagnostics: { valid: true }, - config: { - data: { object: OBJECT }, - sections: [{ fields: ['name'] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/mz-form' }, - }, +/** [ADR-0159 D7] The public form as protocol 19 holds it: a `form` item, bound by `object`. */ +const FORM_ITEM = { + name: 'mz_form', object: OBJECT, _diagnostics: { valid: true }, + sections: [{ fields: ['name'] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/mz-form' }, }; type Fn = (...args: any[]) => any; @@ -130,10 +127,15 @@ const UNIT_CODE_FIELDS = { const READS: Record = { getDiscovery: async () => ({ version: 'v0', routes: {} }), getMetaTypes: async () => [], - // [ADR-0159 D5] No `form` item: the form door reads FORM_VIEW through the projection. - getMetaItems: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : req?.type === 'form' ? projectedFormsOf([FORM_VIEW]) : [SCHEMA]), + // [ADR-0159 D7] The form door reads FORM_ITEM off the `form` list; the `view` list holds no list here. + getMetaItems: async (req: { type?: string }) => (req?.type === 'view' ? [] : req?.type === 'form' ? [FORM_ITEM] : [SCHEMA]), // [#28409] The form doors' withdrawal layer beside the effective list. - getMetaItemsPerPackage: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : []), + getMetaItemsPerPackage: async (req: { type?: string }) => (req?.type === 'form' ? [FORM_ITEM] : []), + // [ADR-0159 D7, D6 rule 10] No stored old-shape row for the withdrawal layer to read. + getViewItemsWithStoredForms: async () => [], + // [ADR-0146 D8, ADR-0159 D7] No packaged base under the form: the door's base + // read is synchronous, so the rejecting fallback below must not answer it. + getPackagedFormBase: () => undefined, // [ADR-0159 D6 rule 7] No stored body the projection cannot read. getUnreadableFormBodies: async () => [], // [ADR-0159 D5, D6] The form doors' five reads run as one request reading. diff --git a/packages/rest/src/stored-forms-major19-kept-reader.test.ts b/packages/rest/src/stored-forms-major19-kept-reader.test.ts new file mode 100644 index 00000000000..6a028f0f441 --- /dev/null +++ b/packages/rest/src/stored-forms-major19-kept-reader.test.ts @@ -0,0 +1,414 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D5, D6 rules 10 and 11, D7; card ⑤b #37112] What both public form + * doors answer on a major-19 build for a stored row of the old shapes. + * + * Since @objectstack/spec 19 a `view` holds lists only: no door admits + * `view.form`, `view.formViews` or `viewKind: 'form'`, and no read serves form + * content from a `view` row. A deployment upgraded from 18 may still store + * such rows. They are read, never refused and never rewritten by a read, and + * these pins hold what `GET /api/v1/forms/:slug` and + * `POST /api/v1/forms/:slug/submit` answer at the address of a package's open + * `form` item while one stands: + * + * - a stored old-shape body whose form is switched off (the link kept); + * - a stored old-shape row of the form's name whose form names no link; + * - a stored row of the form's name that carries no form at all (a list), + * in each binding ADR-0159 D5 bounds the reading to. + * + * Every row is seeded as the store holds it at rest (the save door refuses the + * shapes; the last describe pins that refusal), and every pin reads status, + * `code` and the record count on both doors. The harness is the one of + * `stored-forms-switch-37112.test.ts`: the real protocol on a real `ObjectQL` + * engine and SQL store. + * + * Ablations (each run, rebuilt and restored; recorded in the PR): + * - describe 1: `oldShapeFormWithdrawals` answers no withdrawal; + * - describe 2: `readEffectiveFormList` serves the package's source item + * under a stored `view` row that holds a form; + * - describe 3: the same read serves it under a stored `view` row that holds + * no form; + * - describe 4: the address clash judges the served `form` list alone. + */ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { + ObjectStackProtocolImplementation, + resetEnvWritableMetadataTypes, +} from '@objectstack/metadata-protocol'; +import { + SysMetadataAuditObject, + SysMetadataCommitObject, + SysMetadataHistoryObject, + SysMetadataObject, + hashSpec, +} from '@objectstack/metadata-core'; +import { RestServer } from './rest-server'; + +const BASE = 'com.example.forms19'; +const PAIR = `${BASE}.custom`; +const DEPENDENT = 'com.default.acme-forms19'; +const OBJECT = 'fkr_inquiry'; +const NAME = `${OBJECT}.contact`; +const SLUG = 'contact-19'; + +const overrides = { overrides: { package: BASE, basedOn: '1.0.0' } }; +const sharing = (open: boolean) => ({ enabled: true, allowAnonymous: open, publicLink: `/forms/${SLUG}` }); +const body = (open: boolean | null) => ({ + type: 'simple', + sections: [{ fields: ['name', 'email'] }], + ...(open === null ? {} : { sharing: sharing(open) }), +}); +/** The major-19 shape: a `form` item, bound with `object`. */ +const formItem = (open: boolean | null, extra: Record = {}) => ({ + name: NAME, object: OBJECT, label: 'Contact us', ...body(open), ...extra, +}); +/** A stored old-shape item row: `viewKind: 'form'`, the body under `config`. */ +const oldShapeItem = (open: boolean | null, extra: Record = {}) => ({ + name: NAME, object: OBJECT, viewKind: 'form', label: 'Contact us', + config: { ...body(open), data: { provider: 'object', object: OBJECT } }, + ...extra, +}); +/** A stored old-shape container row: the form under `formViews.contact`, served as {@link NAME}. */ +const oldShapeContainer = (open: boolean | null) => ({ + name: OBJECT, object: OBJECT, + formViews: { contact: { ...body(open), data: { provider: 'object', object: OBJECT } } }, +}); +const listConfig = { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } }; +/** A stored list item of the form's name. */ +const LIST = { name: NAME, object: OBJECT, viewKind: 'list', label: 'A list', config: listConfig }; +/** A stored package-less container whose bare `list` expands to `OBJECT.CONTAINER`: a list at the form's name. */ +const LIST_CONTAINER = { name: 'contact', object: OBJECT, list: listConfig }; + +const INQUIRY = { + name: OBJECT, + label: 'Inquiry', + fields: { + name: { name: 'name', type: 'text' as const, label: 'Name' }, + email: { name: 'email', type: 'text' as const, label: 'Email' }, + }, +}; + +function mockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { + header: () => res, + setHeader: () => res, + send: (b: unknown) => { res._json = b; return res; }, + write: () => true, + end: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (b: unknown) => { res._json = b; return res; }, + }; + return res; +} + +interface Answer { status: number; body: any } + +const engines: ObjectQL[] = []; + +/** A deployment whose read-only package {@link BASE} ships the form OPEN, as a `form` item. */ +async function boot(ships: { forms?: unknown[] } = { forms: [formItem(true)] }) { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const engine = new ObjectQL(); + engines.push(engine); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + engine.registry.registerObject(o as any, 'test-package'); + } + engine.registerApp({ + id: BASE, name: 'forms19', version: '1.0.0', namespace: 'fkr', objects: [INQUIRY], + ...(ships.forms ? { forms: ships.forms } : {}), + } as any); + await engine.syncSchemas(); + const protocol: any = new ObjectStackProtocolImplementation(engine as any, () => new Map()); + const rest = new RestServer(mockServer() as any, protocol, { api: { requireAuth: false } } as any); + rest.registerRoutes(); + const route = (method: string, path: string) => rest.getRoutes().find((r: any) => r.method === method && r.path === path)!; + const resolve = route('GET', '/api/v1/forms/:slug'); + const submit = route('POST', '/api/v1/forms/:slug/submit'); + const get = async (): Promise => { + const res = makeRes(); + await resolve.handler({ params: { slug: SLUG }, query: {}, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + const post = async (): Promise => { + const res = makeRes(); + await submit.handler({ params: { slug: SLUG }, body: { name: 'Ada', email: 'ada@example.test' }, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + const records = async () => ((await engine.find(OBJECT, {}, { context: { isSystem: true } })) as unknown[]).length; + const install = async (id: string) => protocol.installPackage({ + manifest: { id, name: id.split('.').join('-'), version: '0.1.0', type: 'app', namespace: id === PAIR ? 'fkr_custom' : 'fkr_acme', dependencies: { [BASE]: '^1' } }, + }); + /** A stored row as it exists at rest, written past every door. */ + const seedRow = async (type: string, name: string, packageId: string | null, item: Record) => { + const now = new Date().toISOString(); + await engine.insert('sys_metadata', { + id: `seed_${type}_${name}_${packageId ?? 'unbound'}`, type, name, + package_id: packageId, state: 'active', metadata: JSON.stringify(item), checksum: hashSpec(item, type), + version: 1, created_at: now, updated_at: now, + }, { context: { isSystem: true } }); + }; + /** The forms of {@link NAME} the effective `form` list serves: `[package, open]` each. */ + const servedForms = async () => ((await protocol.getMetaItems({ type: 'form' })).items as any[]) + .filter((f) => f?.name === NAME) + .map((f) => [f._packageId ?? null, f.sharing?.allowAnonymous ?? null]); + /** Every stored row, as the store holds it. */ + const rows = async () => JSON.stringify(((await engine.find('sys_metadata', {}, { context: { isSystem: true } })) as any[]) + .map((r) => [r.type, r.name, r.package_id ?? null, r.state, typeof r.metadata === 'string' ? r.metadata : JSON.stringify(r.metadata), r.checksum]) + .sort((a, c) => JSON.stringify(a).localeCompare(JSON.stringify(c)))); + return { engine, protocol, get, post, records, install, seedRow, servedForms, rows }; +} + +type Booted = Awaited>; + +/** Both doors' answers — status and `code` — and the record count the pair left behind. */ +async function doors(b: Booted) { + const before = await b.records(); + const get = await b.get(); + const post = await b.post(); + const wrote = (await b.records()) - before; + return { get: [get.status, get.body?.code ?? null], post: [post.status, post.body?.code ?? null], wrote }; +} + +const CLOSED = { get: [404, 'FORM_NOT_FOUND'], post: [404, 'FORM_NOT_FOUND'], wrote: 0 }; +/** + * The package's form as it answers with no stored row over it: served, and the + * submit reaches the object's own rules. This harness composes no tenancy + * service, so the insert is refused for its `organization_id`; a closed + * address answers 404 before any of that is read. + */ +const OPEN = { get: [200, null], post: [400, 'VALIDATION_FAILED'], wrote: 0 }; + +/** The binding a stored row is seeded in, and the package it needs installed first. */ +const BINDINGS = [ + { binding: 'the package\'s declared override', packageId: PAIR, extra: overrides }, + { binding: 'the read-only package itself', packageId: BASE, extra: {} }, + { binding: 'no package', packageId: null, extra: {} }, +] as const; + +describe('#37112 a stored old-shape row on a major-19 build, at a package\'s open `form` item', () => { + const savedWritable = process.env.OS_METADATA_WRITABLE; + beforeAll(() => { delete process.env.OS_METADATA_WRITABLE; }); + beforeEach(() => { + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + }); + afterAll(async () => { + if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE; + else process.env.OS_METADATA_WRITABLE = savedWritable; + ObjectStackProtocolImplementation.resetEnvWritableCache(); + resetEnvWritableMetadataTypes(); + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + + it('the premise: with no stored row over it, the package\'s `form` item is served and its submit reaches the object', async () => { + const b = await boot(); + expect(await b.servedForms()).toEqual([[BASE, true]]); + expect(await doors(b)).toEqual(OPEN); + }); + + describe('a stored old-shape body that switches the form off answers 404 at its link', () => { + it('an item row of the name in a dependent package: the `form` list still serves the package\'s open item, and both doors answer 404', async () => { + const b = await boot(); + await b.install(DEPENDENT); + await b.seedRow('view', NAME, DEPENDENT, oldShapeItem(false)); + const stored = await b.rows(); + // The effective `form` list serves the package's open item alone: the + // stored body is the only thing that closes the address. + expect(await b.servedForms()).toEqual([[BASE, true]]); + expect(await doors(b)).toEqual(CLOSED); + // A read rewrites nothing. + expect(await b.rows()).toBe(stored); + }); + + it('an item row beside an open stored `form` row of the name, both in the package\'s declared override: the `form` row is served, and both doors answer 404', async () => { + const b = await boot(); + await b.install(PAIR); + await b.seedRow('form', NAME, PAIR, formItem(true, overrides)); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', NAME, PAIR, oldShapeItem(false, overrides)); + const stored = await b.rows(); + // The stored `form` row is the served row of the address, open: the + // stored old-shape body is the only thing that closes it. + expect((await b.servedForms()).map(([, open]) => open)).toEqual([true]); + expect(await doors(b)).toEqual(CLOSED); + expect(await b.rows()).toBe(stored); + }); + + it('an item row beside an open stored `form` row of the name, both in no package: the `form` row is served, and both doors answer 404', async () => { + const b = await boot({}); + await b.seedRow('form', NAME, null, formItem(true)); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', NAME, null, oldShapeItem(false)); + expect(await b.servedForms()).toEqual([[null, true]]); + expect(await doors(b)).toEqual(CLOSED); + }); + + it('a container row bound to the package whose `formViews` entry of the name is switched off: both doors answer 404', async () => { + const b = await boot(); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', OBJECT, BASE, oldShapeContainer(false)); + const stored = await b.rows(); + expect(await doors(b)).toEqual(CLOSED); + expect(await b.rows()).toBe(stored); + }); + + it.each(BINDINGS)('an item row of the name in $binding: both doors answer 404', async ({ packageId, extra }) => { + const b = await boot(); + if (packageId === PAIR) await b.install(PAIR); + await b.seedRow('view', NAME, packageId, oldShapeItem(false, extra)); + expect(await doors(b)).toEqual(CLOSED); + }); + }); + + describe('a stored old-shape row of the name whose form names no link answers 404 at the package\'s link', () => { + it.each(BINDINGS)('in $binding: nothing of the name is served, and both doors answer 404', async ({ packageId, extra }) => { + const b = await boot(); + if (packageId === PAIR) await b.install(PAIR); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', NAME, packageId, oldShapeItem(null, extra)); + const stored = await b.rows(); + expect(await b.servedForms()).toEqual([]); + expect(await doors(b)).toEqual(CLOSED); + expect(await b.rows()).toBe(stored); + }); + }); + + describe('a stored row of the name that carries no form answers 404 at the package\'s link', () => { + it.each(BINDINGS)('a list item in $binding: nothing of the name is served, and both doors answer 404', async ({ packageId, extra }) => { + const b = await boot(); + if (packageId === PAIR) await b.install(PAIR); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', NAME, packageId, { ...LIST, ...extra }); + expect(await b.servedForms()).toEqual([]); + expect(await doors(b)).toEqual(CLOSED); + }); + + it('a package-less container whose expansion writes a list at the name: both doors answer 404', async () => { + const b = await boot(); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', LIST_CONTAINER.name, null, LIST_CONTAINER); + expect(await b.servedForms()).toEqual([]); + expect(await doors(b)).toEqual(CLOSED); + }); + }); + + describe('a stored old-shape form still holds the public address its link names (ruled question 3 = A)', () => { + const OTHER = `${OBJECT}.other`; + /** A `form` of another name, saved open on {@link SLUG}: the refusal, or `undefined` once saved. */ + const saveOther = (b: Booted) => b.protocol + .saveMetaItem({ type: 'form', name: OTHER, packageId: DEPENDENT, mode: 'draft', item: { ...formItem(true), name: OTHER } }) + .then(() => undefined, (e: any) => e); + + it.each([ + { row: 'an item row in no package that switches the form off', name: NAME, packageId: null, item: oldShapeItem(false) }, + { row: 'a container row bound to the package whose `formViews` entry is switched off', name: OBJECT, packageId: BASE, item: oldShapeContainer(false) }, + ])('$row: a `form` of another name left open on that address is refused 409 FORM_ADDRESS_TAKEN, and nothing is written', async ({ name, packageId, item }) => { + const b = await boot({}); + await b.install(DEPENDENT); + await b.seedRow('view', name, packageId, item); + const stored = await b.rows(); + // No read serves the stored form, and it still holds its address. + expect(await b.servedForms()).toEqual([]); + const err = await saveOther(b); + expect([err?.code, err?.status]).toEqual(['FORM_ADDRESS_TAKEN', 409]); + expect(err?.holder).toEqual({ name: NAME, packageId }); + expect(await b.rows()).toBe(stored); + expect(await doors(b)).toEqual(CLOSED); + }); + + it('CONTROL: with no stored row on the address, the same save is admitted', async () => { + const b = await boot({}); + await b.install(DEPENDENT); + expect(await saveOther(b)).toBeUndefined(); + }); + }); + + describe('the served `view` reads hold lists only, and the stored row stays as stored', () => { + it('a stored old-shape item row is in no `view` list and answers no item by name; a stored list of another name is served by both', async () => { + const OTHER = `${OBJECT}.all`; + const b = await boot(); + await b.seedRow('view', NAME, null, oldShapeItem(false)); + await b.seedRow('view', OTHER, null, { ...LIST, name: OTHER }); + const stored = await b.rows(); + const listed = ((await b.protocol.getMetaItems({ type: 'view' })).items as any[]).map((v) => v?.name); + expect(listed).toContain(OTHER); + expect(listed).not.toContain(NAME); + expect((await b.protocol.getMetaItem({ type: 'view', name: OTHER })).item?.name).toBe(OTHER); + expect((await b.protocol.getMetaItem({ type: 'view', name: NAME })).item).toBeUndefined(); + // …and the row is still there, byte-equal, and still closes the form. + expect(await b.rows()).toBe(stored); + expect(await doors(b)).toEqual(CLOSED); + }); + + it('a save-back of an old-shape container is refused, so no stored state is lost: the by-name `view` read serves the stored container whole, the same body saved back through the `view` door answers 422, and the row and both doors stay as they were', async () => { + const b = await boot(); + expect(await doors(b)).toEqual(OPEN); + await b.seedRow('view', OBJECT, BASE, oldShapeContainer(false)); + const stored = await b.rows(); + expect(await doors(b)).toEqual(CLOSED); + // The console's read-merge-write: the served body, its read envelope dropped. + const served = (await b.protocol.getMetaItem({ type: 'view', name: OBJECT })).item; + expect(served?.formViews?.contact?.sharing).toEqual(sharing(false)); + const { _packageId, _provenance, _diagnostics, ...body } = served; + const err: any = await b.protocol.saveMetaItem({ type: 'view', name: OBJECT, item: body }).then(() => undefined, (e: unknown) => e); + expect([err?.code, err?.status]).toEqual(['INVALID_METADATA', 422]); + expect(((err?.issues ?? []) as any[]).map((i) => (Array.isArray(i.path) ? i.path.join('.') : String(i.path ?? '')))).toContain('formViews'); + expect(await b.rows()).toBe(stored); + expect(await doors(b)).toEqual(CLOSED); + }); + }); +}); + +describe('#37112 the save door refuses the three old shapes with their prescription', () => { + afterAll(async () => { + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + + const refusal = async (item: Record, name: string) => { + const b = await boot(); + await b.install(DEPENDENT); + const stored = await b.rows(); + const err: any = await b.protocol.saveMetaItem({ type: 'view', name, item, mode: 'draft', packageId: DEPENDENT }).then( + () => undefined, + (e: unknown) => e, + ); + return { + code: err?.code, + status: err?.status, + paths: ((err?.issues ?? []) as any[]).map((i) => (Array.isArray(i.path) ? i.path.join('.') : String(i.path ?? ''))), + messages: ((err?.issues ?? []) as any[]).map((i) => String(i.message)), + wrote: (await b.rows()) !== stored, + }; + }; + + it('`view.form`: 422 INVALID_METADATA located at `form`, and no row is written', async () => { + const r = await refusal({ name: OBJECT, object: OBJECT, list: listConfig, form: { ...body(true), data: { provider: 'object', object: OBJECT } } }, OBJECT); + expect([r.code, r.status, r.wrote]).toEqual(['INVALID_METADATA', 422, false]); + expect(r.paths).toContain('form'); + expect(r.messages.find((m) => m.startsWith('`view.form` was removed in @objectstack/spec 19.0.0'))).toBeDefined(); + }); + + it('`view.formViews`: 422 INVALID_METADATA located at `formViews`, and no row is written', async () => { + const r = await refusal({ ...oldShapeContainer(true), list: listConfig }, OBJECT); + expect([r.code, r.status, r.wrote]).toEqual(['INVALID_METADATA', 422, false]); + expect(r.paths).toContain('formViews'); + expect(r.messages.find((m) => m.startsWith('`view.formViews` was removed in @objectstack/spec 19.0.0'))).toBeDefined(); + }); + + it('`viewKind: \'form\'`: 422 INVALID_METADATA located at `viewKind`, and no row is written', async () => { + const r = await refusal(oldShapeItem(true), NAME); + expect([r.code, r.status, r.wrote]).toEqual(['INVALID_METADATA', 422, false]); + expect(r.paths).toContain('viewKind'); + expect(r.messages.find((m) => m.startsWith("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0"))).toBeDefined(); + }); +}); diff --git a/packages/rest/src/stored-forms-switch-37112.test.ts b/packages/rest/src/stored-forms-switch-37112.test.ts index 5775f4f3122..0ccbab9aa4d 100644 --- a/packages/rest/src/stored-forms-switch-37112.test.ts +++ b/packages/rest/src/stored-forms-switch-37112.test.ts @@ -222,7 +222,7 @@ describe('#37112 the protocol-19 switch through both doors', () => { // Ablation: count an unreadable body as nothing to move → the switch is // recorded over a row whose links are closed only by its unreadability. it('a stored body the projection cannot read', async () => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', NAME, BASE, { name: NAME, object: OBJECT, viewKind: 'form', config: 'not-a-form', sharing: sharing(false) }); const rows = await allRows(b); const before = await doors(b); @@ -240,7 +240,7 @@ describe('#37112 the protocol-19 switch through both doors', () => { describe('a kind the rulings do not count does not stop the switch', () => { // Ablation: count a draft as a hold → the switch is refused. it('an old-shape draft row: neither moved nor deleted, and the switch is recorded', async () => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', NAME, BASE, viewItem(false), 'draft'); const before = await doors(b); expect(before.get[0]).toBe(200); @@ -255,8 +255,8 @@ describe('#37112 the protocol-19 switch through both doors', () => { describe('a deployment that can switch is switched, and both doors answer as before', () => { // Ablation: skip the ceremony and record the switch → the re-run census // still plans the move, and the verdict is false. - it('⛔ a stored withdrawal over a base\'s open old-shape form moves, and the form stays closed', async () => { - const b = await boot({ views: [container(true)] }); + it('⛔ a stored withdrawal over a base\'s open form moves, and the form stays closed', async () => { + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', NAME, BASE, viewItem(false)); const before = await doors(b); // The "before" reading: the stored switch-off closes the base's form. @@ -270,7 +270,7 @@ describe('#37112 the protocol-19 switch through both doors', () => { }); it('an internal record form is removed, and nothing a door answers changes', async () => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', DFORM, BASE, { name: DFORM, object: OBJECT, viewKind: 'form', isDefault: true, config: { ...body(null), data: { provider: 'object', object: OBJECT } } }); const before = await doors(b); expect(before.get[0]).toBe(200); @@ -282,7 +282,7 @@ describe('#37112 the protocol-19 switch through both doors', () => { }); it('a second run finds nothing to move: the switch is idempotent', async () => { - const b = await boot({ views: [container(true)] }); + const b = await boot({ forms: [formItem(true)] }); await b.seedRow('view', NAME, BASE, viewItem(false)); expect((await runSwitch(b)).switched).toBe(true); const rows = await allRows(b); @@ -292,4 +292,129 @@ describe('#37112 the protocol-19 switch through both doors', () => { expect(await allRows(b)).toBe(rows); }); }); + + // [ADR-0159 D5, D6 rule 11, D7; rulings of record 7136809727 and 7142585849] + // The card's pin, verbatim: "the precheck does not hold the two ruled kinds, + // and their addresses stay closed". A row that carries no form, and a form + // row left behind such a row, are left as stored: the precheck counts + // neither, the switch is recorded with every stored row byte-equal, and both + // doors answer 404 at the address before it and after it. + describe('the precheck does not hold the two ruled kinds, and their addresses stay closed', () => { + const WRITABLE = 'com.default.acme-forms37112'; + const LIST = { name: NAME, object: OBJECT, viewKind: 'list', label: 'A list', config: { type: 'grid', columns: ['name'], data: { provider: 'object', object: OBJECT } } }; + /** A package the environment writes, which depends on {@link BASE} and takes a namespace of its own. */ + const installWritable = (b: Booted) => b.protocol.installPackage({ + manifest: { id: WRITABLE, name: 'acme-forms37112', version: '0.1.0', type: 'app', namespace: 'fsw_acme', dependencies: { [BASE]: '^1' } }, + }); + /** Another package holds the namespace {@link BASE}'s pair would take: the pair cannot be ensured. */ + const squatPairNamespace = async (b: Booted) => { + await b.protocol.installPackage({ manifest: { id: 'com.default.squatter37112', name: 'squatter', version: '0.1.0', type: 'app', namespace: 'fsw_custom' } }); + const ensured = await b.protocol.ensureCustomizationPackage({ basePackageId: BASE }).then(() => 'ensured', (e: any) => e?.status ?? 'refused'); + expect(ensured).not.toBe('ensured'); + }; + + const KINDS = [ + { + kind: 'a row that carries no form over a linked base, bound to the read-only base', + ships: { forms: [formItem(true)] }, + seed: async (b: Booted) => { await b.seedRow('view', NAME, BASE, LIST); }, + }, + { + kind: 'a row that carries no form over a linked base, bound to no package', + ships: { forms: [formItem(true)] }, + seed: async (b: Booted) => { await b.seedRow('view', NAME, null, LIST); }, + }, + { + kind: 'a row that carries no form over a linked base, in the base\'s declared override', + ships: { forms: [formItem(true)] }, + seed: async (b: Booted) => { + await b.install(PAIR); + await b.seedRow('view', NAME, PAIR, { ...LIST, overrides: { package: BASE, basedOn: '1.0.0' } }); + }, + }, + { + kind: 'a package-less form row behind a writable package\'s list', + ships: {}, + seed: async (b: Booted) => { + await installWritable(b); + await b.seedRow('view', NAME, WRITABLE, LIST); + await b.seedRow('view', NAME, null, viewItem(true)); + }, + }, + { + kind: 'a form row left behind a no-form row bound to a read-only base', + ships: { forms: [formItem(true)] }, + seed: async (b: Booted) => { + await b.seedRow('view', NAME, BASE, LIST); + await b.seedRow('view', NAME, null, viewItem(true)); + }, + }, + ] as const; + + // Ablation: the kept replacement check serves the package's source item + // under a stored row that carries no form → the base's address answers 200. + it.each(KINDS)('$kind: not counted, the switch is recorded with every stored row byte-equal, and both doors answer 404 before and after', async ({ ships, seed }) => { + const b = await boot(ships as { forms?: unknown[] }); + await seed(b); + const rows = await allRows(b); + // The "before" reading: the address is closed. + expect(await doors(b)).toEqual(CLOSED); + const run = await runSwitch(b); + expect(run.before.precheck.canSwitch).toBe(true); + expect(run.before.precheck.holds).toEqual([]); + expect(run.before.precheck.counts).toMatchObject({ move: 0, remove: 0, hold: 0 }); + expect(run.switched).toBe(true); + expect(run.ceremony?.written).toEqual([]); + expect(await allRows(b)).toBe(rows); + expect(await doors(b)).toEqual(CLOSED); + }); + + // The fourth fixture, for the address: "not counted" is asked per package + // address. Ablation: ask it by name → the row passed over at the writable + // package's address is passed over at the base's too, and the switch is + // recorded over a row the read-only base's address is closed by. + it('⛔ a package-less row passed over at a writable package\'s address and served at a read-only base\'s address whose pair cannot be ensured still stops the switch', async () => { + const b = await boot({ forms: [formItem(true)] }); + await installWritable(b); + await squatPairNamespace(b); + await b.seedRow('view', NAME, WRITABLE, LIST); + await b.seedRow('view', NAME, null, viewItem(false)); + const rows = await allRows(b); + const before = await doors(b); + // The "before" reading: the package-less switch-off closes the base's form. + expect(before).toEqual(CLOSED); + const run = await runSwitch(b); + expect(run.switched).toBe(false); + expect(run.before.precheck.canSwitch).toBe(false); + expect(run.before.precheck.holds.map((h) => h.base)).toEqual([BASE]); + const plans = run.before.forms.filter((f) => f.form === NAME).map((f) => [(f.address as { packageId?: string }).packageId ?? null, f.outcome]); + expect(plans).toEqual(expect.arrayContaining([[WRITABLE, 'left_in_place'], [BASE, 'hold']])); + expect(run.ceremony).toBeUndefined(); + expect(await allRows(b)).toBe(rows); + expect(await doors(b)).toEqual(CLOSED); + }); + }); + + // [ADR-0159 D6 rules 10 and 11, D7] A stored old-shape container is a stored + // old-shape row like any other: its form members are read wherever a stored + // form is read, before the switch and after it. + describe('a stored container\'s form members are read as stored forms', () => { + it('⛔ a switched-off form member of a stored container keeps the base\'s open `form` item closed on both doors', async () => { + const b = await boot({ forms: [formItem(true)] }); + expect((await doors(b)).get[0]).toBe(200); + await b.seedRow('view', OBJECT, BASE, { name: OBJECT, ...container(false) }); + expect(await doors(b)).toEqual(CLOSED); + }); + + it('the census counts an open form member of a package-less stored container, and the switch moves it', async () => { + const MEMBER = `${OBJECT}.intake.contact`; + const b = await boot({}); + await b.seedRow('view', 'intake', null, { name: 'intake', ...container(true) }); + const run = await runSwitch(b); + expect(run.before.forms.filter((f) => f.form === MEMBER).map((f) => f.outcome)).toEqual(['move']); + expect(run.before.precheck.counts.move).toBe(1); + expect(run.switched).toBe(true); + expect(run.after?.forms.filter((f) => f.form === MEMBER).map((f) => f.outcome)).toEqual(['keep']); + }); + }); }); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index cbd94e44fb0..fd861a3b8f3 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -193,6 +193,11 @@ export class AppPlugin implements Plugin { * plugin's `start()`, which loads the inline seed, runs only after the guard * has judged. Order-if-present: every other kernel is unchanged. * + * The protocol-19 boot guard (ADR-0159 D7; the guard module's + * `FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME`, a literal for the same + * reason): it judges after the ownership guard, and the inline seed loads + * only once both have judged. Order-if-present. + * * The host's package-state store (`PACKAGE_STATE_STORE_PLUGIN_NAME`, * `./package-state-host-store.ts`, spelled as a literal for the same * reason): `init()` seeds the registry's disabled set from it, so it must @@ -202,6 +207,7 @@ export class AppPlugin implements Plugin { optionalDependencies = [ 'com.objectstack.engine.objectql', 'com.objectstack.organization-ownership-boot-guard', + 'com.objectstack.form-type-switch-boot-guard', 'com.objectstack.auth', 'com.objectstack.auth.identity-objects', 'com.objectstack.package-state-store', diff --git a/packages/runtime/src/form-save-legacy-organization-transaction.integration.test.ts b/packages/runtime/src/form-save-legacy-organization-transaction.integration.test.ts new file mode 100644 index 00000000000..141041c20b7 --- /dev/null +++ b/packages/runtime/src/form-save-legacy-organization-transaction.integration.test.ts @@ -0,0 +1,132 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A published `form` save runs in one engine transaction: the `form` row and + * the removal of the old-shape row that carried the form commit together + * (ADR-0159 D5). On SQLite that transaction holds the pool's one connection. + * On a database the organization-ownership ceremony has not migrated + * (`sys_metadata` still carries the physical `organization_id` column), the + * reads inside it leave the legacy organization's rows out, off that column, + * through the driver directly (`readLegacyOrganizationRows`). Those reads + * must join the save's transaction: a read that asks the pool for a second + * connection waits for one a single-connection pool never grants, and the + * save hangs until the pool's acquire timeout refuses it. + * + * Pinned on a real engine over a real SQLite file (this package may import + * both the engine and the protocol; `@objectstack/metadata-protocol` may not + * import the engine): + * + * 1. a published `form` save into a `.custom` pair, while a legacy + * organization's row is stored, completes and stores the pair's row; + * 2. a `form` draft saved into a pair and then published, with the + * organization column on disk, completes and stores the active row. + * + * Each case runs at the suite's default timeout, far under the pool's acquire + * timeout: a save that waits for a second connection fails the case. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { + SysMetadataObject, + SysMetadataHistoryObject, + SysMetadataAuditObject, +} from '@objectstack/metadata-core'; + +const BASE = 'com.example.lgtx'; +const PAIR = `${BASE}.custom`; +const OBJECT = 'lgtx_task'; +const FORM = `${OBJECT}.intake`; + +let cleanup: Array<() => Promise | void> = []; +afterEach(async () => { + for (const c of cleanup.reverse()) await c(); + cleanup = []; +}); + +const taskObject = { + name: OBJECT, + label: 'Task', + fields: { title: { type: 'text', label: 'Title' } }, +}; + +const formBody = (label: string) => ({ + name: FORM, + label, + object: OBJECT, + sections: [{ name: 'main', label: 'Main', fields: ['title'] }], +}); + +/** + * A real engine over a SQLite file shaped like v17: the physical + * `organization_id` column added raw, outside the declared object, and the + * given legacy rows written into it the way a 17.x runtime stored them. + */ +async function boot(legacyRows: Array<{ id: string; type: string; name: string; organization_id: string }>) { + const dir = mkdtempSync(join(tmpdir(), 'os-lgtx-')); + cleanup.push(() => rmSync(dir, { recursive: true, force: true })); + const driver = new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: join(dir, 'data.sqlite') }, + useNullAsDefault: true, + }); + const objects = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, taskObject] as any[]; + await driver.initObjects(objects); + const k = (driver as any).knex; + await k.raw('ALTER TABLE sys_metadata ADD COLUMN organization_id TEXT'); + const now = new Date().toISOString(); + for (const row of legacyRows) { + await k('sys_metadata').insert({ + id: row.id, type: row.type, name: row.name, organization_id: row.organization_id, package_id: PAIR, + state: 'active', version: 1, checksum: `sha256:seed_${row.id}`, created_at: now, updated_at: now, + metadata: JSON.stringify({ name: row.name, label: row.name, object: OBJECT, type: 'grid', columns: ['title'] }), + }); + } + const engine = new ObjectQL(); + engine.registerDriver(driver as any, true); + await engine.init(); + for (const o of objects) engine.registry.registerObject(o, '@objectstack/platform-objects'); + // The pair: a writable package the deployment holds (authored, no manifest + // booted it), beside the read-only base it customizes. + engine.registry.installPackage({ id: BASE, name: 'lgtx', version: '1.0.0', type: 'app' } as any, 'code'); + engine.registry.installPackage({ id: PAIR, name: 'lgtx-custom', version: '0.1.0', type: 'app', dependencies: { [BASE]: '1.0.0' } } as any, 'authored'); + cleanup.push(() => engine.destroy()); + const protocol = new ObjectStackProtocolImplementation(engine as any, undefined, undefined, 'package-author'); + const rows = async (type: string) => + ((await k('sys_metadata').select('id', 'type', 'name', 'state', 'package_id', 'organization_id', 'metadata').where({ type })) as any[]) + .map((r) => ({ ...r, metadata: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata })); + return { protocol, rows }; +} + +describe('a form save on SQLite joins its own transaction when legacy organization rows are read', () => { + it('a published form save into a pair completes while a legacy organization row is stored', async () => { + const { protocol, rows } = await boot([{ id: 'org_view', type: 'view', name: `${OBJECT}_grid`, organization_id: 'org_a' }]); + + const saved: any = await (protocol as any).saveMetaItem({ type: 'form', name: FORM, item: formBody('Intake'), packageId: PAIR }); + + expect(saved).toMatchObject({ success: true }); + const forms = await rows('form'); + expect(forms.map((r) => [r.name, r.state, r.package_id, r.organization_id ?? null, r.metadata.label])) + .toEqual([[FORM, 'active', PAIR, null, 'Intake']]); + // The legacy organization's row is read past, never rewritten. + expect((await rows('view')).map((r) => [r.id, r.organization_id])).toEqual([['org_view', 'org_a']]); + }); + + it('a form draft saved into a pair and then published completes with the organization column on disk', async () => { + const { protocol, rows } = await boot([]); + + const drafted: any = await (protocol as any).saveMetaItem({ type: 'form', name: FORM, item: formBody('Drafted'), packageId: PAIR, mode: 'draft' }); + expect(drafted).toMatchObject({ success: true, state: 'draft' }); + const published: any = await (protocol as any).publishMetaItem({ type: 'form', name: FORM, packageId: PAIR }); + + expect(published).toMatchObject({ success: true }); + const active = (await rows('form')).filter((r) => r.state === 'active'); + expect(active.map((r) => [r.name, r.package_id, r.organization_id ?? null, r.metadata.label])) + .toEqual([[FORM, PAIR, null, 'Drafted']]); + }); +}); diff --git a/packages/runtime/src/form-type-switch-boot-guard.kernel.test.ts b/packages/runtime/src/form-type-switch-boot-guard.kernel.test.ts new file mode 100644 index 00000000000..14526a77eda --- /dev/null +++ b/packages/runtime/src/form-type-switch-boot-guard.kernel.test.ts @@ -0,0 +1,437 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D7; ruling records 7303149461 and 7308112533] The protocol-19 boot + * refusal and its birth half on a REAL kernel: the guard's throw must stop + * `bootstrap()`, and "created from empty" must be the driver's own + * observation, which no hand-called plugin can show. + * + * The composition is `os serve`'s data spine: a driver, ObjectQL, the platform + * objects, plus the guard. Each case prepares the store before the boot, the + * way an earlier release or the switch command left it: + * + * 1. a database an earlier release created (its tables there, no switch + * record) is refused, naming the command, and the kernel never runs; + * 2. the same database with the switch recorded boots; + * 3. a database created from empty boots, the guard writing the birth marker + * (`details.birth`), and boots again on that marker; + * 4. a store with any table already there is not born here: refused; + * 5. a record that is not verified is refused; + * 6. a refused boot loads no seed: `AppPlugin`, `use()`d ahead of the guard + * (the hostile slot), starts only after it judged; + * 7. the birth half alone (what every CLI data and schema boot composes) + * writes the marker on a store it created and never refuses; + * 8. beside the organization-ownership guard: a database that owes both acts + * hears of the older one first, and a fresh store carries both markers; + * 9. the guard is not limited to a store that names a SQL dialect: one that + * names none boots when born here and is refused when it holds rows; + * 10. a composition that stores metadata and registers no ledger is refused; + * 11. a plugin that takes the guard's name replaces it on the kernel, which is + * why the host refuses that composition before it starts. + */ + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; +import { FORM_TYPE_SWITCH_MIGRATION_ID } from '@objectstack/spec/system'; +import { createIdentityObjectsPlugin } from '@objectstack/plugin-auth'; +// The real plugin chain loads `@objectstack/metadata` lazily (AppPlugin); paid +// here, at collection, so no case's clocked window pays the first load. +import '@objectstack/metadata'; +import { AppPlugin } from './app-plugin.js'; +import { DriverPlugin } from './driver-plugin.js'; +import { + assertFormTypeSwitchGuardNotReplaced, + FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME, + FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE, + FORM_TYPE_SWITCH_PROTOCOL_MAJOR, + FormTypeSwitchBirthMarkerPlugin, + FormTypeSwitchBootGuardPlugin, + formTypeSwitchRefusalMessage, + isFormTypeSwitchBootRefusal, + type FormTypeSwitchBootRefusal, +} from './form-type-switch-boot-guard.js'; +import { + isOrganizationOwnershipBootRefusal, + OrganizationOwnershipBootGuardPlugin, +} from './organization-ownership-boot-guard.js'; + +const dirs: string[] = []; +const kernels: ObjectKernel[] = []; +const MARKER = FORM_TYPE_SWITCH_MIGRATION_ID; +const COMMAND = `os migrate protocol --to ${FORM_TYPE_SWITCH_PROTOCOL_MAJOR}`; + +/** + * The refusal a failed boot carries. The guard refuses from its `start()`, and + * the kernel reports a failed `start()` as its own error with the plugin's as + * the `cause`: the shape a host that composes the guard reads. + */ +function refusalIn(error: unknown): FormTypeSwitchBootRefusal | undefined { + for (let e = error, depth = 0; !!e && typeof e === 'object' && depth < 8; e = (e as { cause?: unknown }).cause, depth++) { + if (isFormTypeSwitchBootRefusal(e)) return e; + } + return undefined; +} + +function databaseFile(): string { + const dir = mkdtempSync(join(tmpdir(), 'os-form-switch-guard-')); + dirs.push(dir); + return join(dir, 'data.db'); +} + +/** + * The same file store behind a driver that names no SQL dialect, the way a + * document or key-value driver presents itself: no `dialectName`, no knex + * `client`. Every call still lands on the real driver, so the schema sync + * counts the guard reads are the store's own. The organization-ownership guard + * is inert on such a driver by design; this one is not. + */ +function dialectLess(file: string): unknown { + const real = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }); + return new Proxy(real, { + get(target, key) { + if (key === 'dialectName') return undefined; + if (key === 'config') return {}; + const value = Reflect.get(target, key, target); + return typeof value === 'function' ? value.bind(target) : value; + }, + has(target, key) { + return key !== 'dialectName' && Reflect.has(target, key); + }, + }); +} + +function sql>(file: string, statement: string): T[] { + const db = new DatabaseSync(file); + try { + return db.prepare(statement).all() as T[]; + } finally { + db.close(); + } +} + +interface MarkerRow { verified_at: string | null; applied_at: string | null; blocking: number; details: string | null } +const markerRows = (file: string): MarkerRow[] => + sql(file, `SELECT verified_at, applied_at, blocking, details FROM sys_migration WHERE id = '${MARKER}'`); + +/** The switch's record as `os migrate protocol --to 19 --apply` writes it; `verifiedAt: null` is a run that did not verify. */ +function recordSwitch(file: string, verifiedAt: string | null): void { + const db = new DatabaseSync(file); + try { + db.prepare('INSERT INTO sys_migration (id, last_run_at, verified_at, applied_at, blocking, details) VALUES (?, ?, ?, ?, ?, ?)') + .run(MARKER, '2026-12-01T00:00:00.000Z', verifiedAt, '2026-12-01T00:00:00.000Z', 0, JSON.stringify({ protocol: 19 })); + } finally { + db.close(); + } +} + +/** An app whose inline seed writes two rows. */ +const seededApp = () => new AppPlugin({ + id: 'com.test.switch_seed', + name: 'switch_seed', + version: '1.0.0', + type: 'app', + objects: [{ name: 'switch_event', label: 'Event', fields: { subject: { name: 'subject', type: 'text', label: 'Subject' } } }], + data: [{ object: 'switch_event', mode: 'upsert', externalId: 'subject', records: [{ subject: 'one' }, { subject: 'two' }] }], +}); + +interface BootOptions { + /** What judges the store: `os serve`'s guard, the CLI boots' birth half, or nothing (an earlier release). */ + guard?: 'serve' | 'birth' | 'none'; + /** + * The seeding app and the identity objects its seed rows are stamped with, + * `use()`d first, so only the app's declared ordering holds its seed back. + */ + seed?: boolean; + /** The organization-ownership guard too, `use()`d after this one, so only the declared ordering judges it first. */ + ownership?: boolean; + /** Leave the platform objects out: a composition with no `sys_migration` ledger. */ + noLedger?: boolean; + /** Plugins `use()`d last, as a stack's own `plugins` are. */ + late?: unknown[]; + driver?: unknown; +} + +async function boot(file: string | null, opts: BootOptions = {}): Promise<{ kernel: ObjectKernel; error: unknown }> { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + kernels.push(kernel); + if (opts.seed) { + await kernel.use(seededApp()); + await kernel.use(createIdentityObjectsPlugin() as never); + } + await kernel.use(new DriverPlugin((opts.driver ?? new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: file as string }, + useNullAsDefault: true, + })) as never)); + await kernel.use(new ObjectQLPlugin()); + const guard = opts.guard ?? 'serve'; + if (guard === 'serve') await kernel.use(new FormTypeSwitchBootGuardPlugin()); + if (guard === 'birth') await kernel.use(new FormTypeSwitchBirthMarkerPlugin()); + if (opts.ownership) await kernel.use(new OrganizationOwnershipBootGuardPlugin()); + if (!opts.noLedger) await kernel.use(new PlatformObjectsPlugin() as never); + for (const plugin of opts.late ?? []) await kernel.use(plugin as never); + try { + await kernel.bootstrap(); + return { kernel, error: null }; + } catch (error) { + return { kernel, error }; + } +} + +/** + * A database an earlier release created: this composition booted over it with + * no guard and no birth half, so every table is there and no switch record is. + */ +async function earlierReleaseDatabase(): Promise { + const file = databaseFile(); + const { kernel, error } = await boot(file, { guard: 'none' }); + expect(error).toBeNull(); + await kernel.shutdown(); + expect(markerRows(file)).toEqual([]); + return file; +} + +afterEach(async () => { + for (const kernel of kernels.splice(0)) { + if (kernel.getState() === 'running') await kernel.shutdown(); + } + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +describe('the protocol-19 boot refusal on a real kernel (ADR-0159 D7)', () => { + it('a database an earlier release created stops the boot with the refusal, naming the command, before the kernel runs', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file); + const refusal = refusalIn(error); + expect(refusal?.name, String(error)).toBe('FormTypeSwitchBootRefusal'); + // The registered machine code, by value: what a host discriminates the refusal by. + expect(refusal?.code).toBe('FORM_TYPE_SWITCH_REQUIRED'); + expect(FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE).toBe('FORM_TYPE_SWITCH_REQUIRED'); + expect(refusal?.reason).toBe('absent'); + expect(refusal?.message).toContain(`'${COMMAND}'`); + expect(refusal?.message).toContain(`'${COMMAND} --apply --yes'`); + // Refused in `start()`: the kernel's start-failure error carries it as its cause. + expect((error as Error).cause).toBe(refusal); + expect(kernel.getState()).not.toBe('running'); + // A refusal records nothing: the store is still one the command has not run on. + expect(markerRows(file)).toEqual([]); + }); + + it('the same database, its switch recorded and verified, boots', async () => { + const file = await earlierReleaseDatabase(); + recordSwitch(file, '2026-12-01T00:00:01.000Z'); + const { kernel, error } = await boot(file); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + }); + + it('a record that is not verified is refused', async () => { + const file = await earlierReleaseDatabase(); + recordSwitch(file, null); + const { kernel, error } = await boot(file); + expect(refusalIn(error)?.reason, String(error)).toBe('unverified'); + expect(kernel.getState()).not.toBe('running'); + }); + + it('a database created from empty boots, the guard writing the birth marker; the next boot reads it and boots', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + const [row, ...rest] = markerRows(file); + expect(rest).toEqual([]); + expect(row?.verified_at).toBeTruthy(); + expect(row?.applied_at).toBeNull(); + expect(Number(row?.blocking)).toBe(0); + const details = JSON.parse(String(row!.details)) as { birth?: Record }; + expect(details.birth).toMatchObject({ protocol: FORM_TYPE_SWITCH_PROTOCOL_MAJOR, createdAt: row!.verified_at }); + expect(typeof details.birth?.platformVersion).toBe('string'); + await kernel.shutdown(); + // The same store, found this time: the marker carries it, and is not written again. + expect((await boot(file)).error).toBeNull(); + expect(markerRows(file)).toEqual([row]); + }); + + it('a store with one table already there was not created from empty: refused, and no birth marker is written', async () => { + const file = databaseFile(); + const db = new DatabaseSync(file); + // Any table of the composition that an earlier boot left: here the journal's. + db.exec('CREATE TABLE sys_migration_journal (id TEXT PRIMARY KEY)'); + db.close(); + const { kernel, error } = await boot(file); + expect(refusalIn(error)?.reason, String(error)).toBe('absent'); + expect(kernel.getState()).not.toBe('running'); + expect(markerRows(file)).toEqual([]); + }); +}); + +describe('a refused boot loads no seed (the guard judges before AppPlugin starts)', () => { + it('AppPlugin, use()d ahead of the guard: its own declaration holds the inline seed back', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file, { seed: true }); + expect(refusalIn(error)?.reason, String(error)).toBe('absent'); + expect(kernel.getState()).not.toBe('running'); + // The engine's schema sync ran before the refusal; the seed did not. + expect(sql(file, 'SELECT id FROM switch_event')).toEqual([]); + }); + + it('control: the same composition over a fresh file loads the seed', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { seed: true }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + expect(sql<{ subject: string }>(file, 'SELECT subject FROM switch_event ORDER BY subject').map((r) => r.subject)).toEqual(['one', 'two']); + }); + + it('AppPlugin names the guard in its optionalDependencies, by the guard\'s own name', () => { + expect(new FormTypeSwitchBootGuardPlugin().name).toBe(FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME); + expect(new AppPlugin({}).optionalDependencies).toContain(FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME); + }); +}); + +describe('the birth half alone, as every CLI data and schema boot composes it', () => { + it('writes the birth marker on a store this boot created from empty', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { guard: 'birth' }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + const [row] = markerRows(file); + expect(row?.verified_at).toBeTruthy(); + expect(JSON.parse(String(row!.details)).birth).toMatchObject({ protocol: FORM_TYPE_SWITCH_PROTOCOL_MAJOR }); + await kernel.shutdown(); + // The served boot that follows a CLI-created store reads that marker. + expect((await boot(file)).error).toBeNull(); + }); + + it('never refuses and never marks a store it found: an earlier release\'s database boots and stays unrecorded', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file, { guard: 'birth' }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + expect(markerRows(file)).toEqual([]); + }); +}); + +describe('beside the organization-ownership guard, as os serve composes both', () => { + it('a fresh store carries both birth markers and boots', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { ownership: true }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + expect(sql<{ id: string }>(file, 'SELECT id FROM sys_migration ORDER BY id').map((r) => r.id)) + .toEqual(expect.arrayContaining(['adr-0131-organization-ownership', MARKER])); + }); + + it('a database that owes both acts hears of the older one first', async () => { + const file = await earlierReleaseDatabase(); + const { error } = await boot(file, { ownership: true }); + expect(refusalIn(error)).toBeUndefined(); + expect(isOrganizationOwnershipBootRefusal((error as Error).cause), String(error)).toBe(true); + }); +}); + +describe('not limited to stores that name a SQL dialect: a stored form is a sys_metadata row on whatever driver persists it', () => { + it('a store that names no dialect, born at this boot, boots with its birth marker written', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { driver: dialectLess(file) }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + const engine = kernel.getService<{ findOne: (o: string, q: unknown) => Promise<{ verified_at?: unknown; details?: unknown } | null> }>('objectql'); + const row = await engine.findOne('sys_migration', { where: { id: MARKER }, context: { isSystem: true } }); + expect(row?.verified_at).toBeTruthy(); + expect(markerRows(file)).toHaveLength(1); + }); + + it('a store that names no dialect and already holds rows was not created here: refused', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file, { driver: dialectLess(file) }); + expect(refusalIn(error)?.reason, String(error)).toBe('absent'); + expect(kernel.getState()).not.toBe('running'); + expect(markerRows(file)).toEqual([]); + }); +}); + +describe('what the guard can and cannot judge', () => { + it('a composition that stores metadata and registers no ledger has no switch record to read: refused', async () => { + const file = databaseFile(); + const { kernel, error } = await boot(file, { noLedger: true }); + expect(refusalIn(error)?.reason, String(error)).toBe('no-ledger'); + expect(kernel.getState()).not.toBe('running'); + }); + + it('a kernel with no engine has no database to judge: the guard and the birth half do nothing', async () => { + const noEngine = { getService: () => { throw new Error('service objectql is not registered'); } } as never; + await expect(new FormTypeSwitchBootGuardPlugin().start(noEngine)).resolves.toBeUndefined(); + await expect(new FormTypeSwitchBirthMarkerPlugin().start(noEngine)).resolves.toBeUndefined(); + }); +}); + +describe('the guard is the host\'s own: no plugin replaces it', () => { + /** A stack plugin that carries the guard's name and judges nothing. */ + const impostor = () => ({ name: FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME, version: '9.9.9', init: async () => {}, start: async () => {} }); + + it('control: on the kernel, a later plugin under the guard\'s name replaces it, and an unswitched database boots', async () => { + const file = await earlierReleaseDatabase(); + const { kernel, error } = await boot(file, { late: [impostor()] }); + expect(error).toBeNull(); + expect(kernel.getState()).toBe('running'); + }); + + it('so the host refuses a composition that carries the name on another plugin, before it starts', () => { + const guard = new FormTypeSwitchBootGuardPlugin(); + const refused = (() => { + try { + assertFormTypeSwitchGuardNotReplaced(guard, [{ name: 'com.example.other' }, impostor()]); + return undefined; + } catch (error) { + return error; + } + })(); + expect(isFormTypeSwitchBootRefusal(refused)).toBe(true); + expect((refused as FormTypeSwitchBootRefusal).reason).toBe('guard-replaced'); + }); + + it('the guard itself, and plugins under other names, pass', () => { + const guard = new FormTypeSwitchBootGuardPlugin(); + expect(() => assertFormTypeSwitchGuardNotReplaced(guard, [guard, { name: 'com.example.other' }, null, 'a-specifier'])).not.toThrow(); + }); +}); + +describe('the refusal names the command as the refused boot was started', () => { + it('a development boot names it with --dev, a preset boot with its preset', () => { + expect(formTypeSwitchRefusalMessage('absent', { dev: true })).toContain(`'${COMMAND} --dev'`); + expect(formTypeSwitchRefusalMessage('absent', { preset: 'minimal' })).toContain(`'${COMMAND} --preset minimal --apply --yes'`); + }); + + it('a database the command would not find by default is named, so the command switches the database that was refused', () => { + const message = formTypeSwitchRefusalMessage('absent', { databaseUrl: 'file:/srv/app/data.db' }); + expect(message).toContain(`'${COMMAND} --database-url file:/srv/app/data.db'`); + }); + + it('a credential is never printed: the URL, the auth token and the auth secret are read from the shell', () => { + const message = formTypeSwitchRefusalMessage('absent', { + databaseUrl: 'postgres://app:s3cret@db.internal/app', + databaseDriver: 'postgres', + databaseAuthTokenFromFlag: true, + authSecretFile: '/srv/app/home/auth-secret', + }); + expect(message).not.toContain('s3cret'); + expect(message).toContain('--database-url "${OS_DATABASE_URL:?'); + expect(message).toContain('OS_DATABASE_DRIVER=postgres '); + expect(message).toContain('OS_DATABASE_AUTH_TOKEN="${OS_DATABASE_AUTH_TOKEN:?'); + expect(message).toContain('OS_AUTH_SECRET="$(cat /srv/app/home/auth-secret)" '); + }); + + it('every refusing state names the command', () => { + for (const state of ['absent', 'unverified', 'unreadable', 'no-ledger'] as const) { + expect(formTypeSwitchRefusalMessage(state), state).toContain(`'${COMMAND} --apply --yes'`); + } + }); +}); diff --git a/packages/runtime/src/form-type-switch-boot-guard.ts b/packages/runtime/src/form-type-switch-boot-guard.ts new file mode 100644 index 00000000000..fbf9091ab0d --- /dev/null +++ b/packages/runtime/src/form-type-switch-boot-guard.ts @@ -0,0 +1,614 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { Plugin, PluginContext } from '@objectstack/core'; +import { + isDataMigrationFlagVerified, + DATA_MIGRATION_FLAG_OBJECT, + FORM_TYPE_SWITCH_MIGRATION_ID, + type DataMigrationFlag, +} from '@objectstack/spec/system'; +import { resolveRuntimeVersion } from './runtime-version.js'; + +/** + * FormTypeSwitchBootGuardPlugin — the protocol-19 boot refusal (ADR-0159 D7; + * ruling record 7303149461) and its birth half (ruling record 7308112533). + * + * On protocol 19 `view` holds lists only, and a form is a `form` item. A + * database an earlier release left may still store forms in an old shape: a + * view container's form, a `formViews` entry, a `viewKind: 'form'` item. The + * act that moves them, `os migrate protocol --to 19 --apply`, is an + * operator's: it previews, moves all or nothing, checks again, and only then + * records the switch. It is never a boot step. So a served boot refuses to + * start until the switch is recorded, and says which command to run. + * + * ## What is refused + * + * The guard reads the switch's `sys_migration` row + * ({@link FORM_TYPE_SWITCH_MIGRATION_ID}) and decides on one question, the + * spec's own (`isDataMigrationFlagVerified`): is it there and verified. It + * never compares versions and never reads a stored form: counting what is left + * to move is the command's census, not a boot's. + * + * 1. A VERIFIED row boots: the command's record, or the birth marker below. + * 2. No row, on a datastore this boot observed being CREATED FROM EMPTY: the + * guard writes the BIRTH MARKER (verified, `details.birth` = + * {@link FormTypeSwitchBirthMarker}) exactly once and boots. A store with + * no prior data holds no stored form, so no switch is owed. The observation + * is the stores' own schema-sync counts, the one that holds the ledger and + * the one that holds `sys_metadata` (the same store on every composition + * this repository builds), never the sum over every driver. + * 3. No row on any other store, which is every database an earlier release + * created: refused until the command has run on it. A database with no + * stored form runs it once too: it finds nothing to move and records the + * switch, and the refusal says so. + * 4. A row that is not verified, or one that could not be read, is refused. + * 5. A composition that serves `sys_metadata` from a store and registers no + * ledger to read the switch from is refused: where the stored forms are + * and the record is not, there is nothing to boot on. + * + * - A read that fails is refused, never passed: "I could not check" is not + * "the switch is recorded". + * - A birth marker that cannot be written refuses the boot: a store left + * without one would be taken, at its next boot, for a database an earlier + * release created. + * - ⛔ No way round: no `OS_ALLOW_*` / `OS_SKIP_*` variable, no flag and no + * config key skips the check (ruling record 7303149461). + * + * ## When it judges: in `start()` + * + * Ordered after the engine (whose `start()` connects the drivers and runs the + * schema sync the "created from empty" observation is read off), the platform + * objects (`sys_migration`) and the organization-ownership guard, so a + * database that owes both acts is told the older one first. `AppPlugin`, + * whose `start()` loads the inline seed, and `@objectstack/plugin-auth`'s + * `AuthPlugin` and `IdentityObjectsPlugin`, whose `start()` writes identity + * rows, name this guard in their `optionalDependencies` + * ({@link FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME}). A `start()` + * that throws stops the kernel before the next plugin starts; the kernel + * hands the refusal on as the `cause` of its own start-failure error, so a + * host that inspects the boot error asks {@link isFormTypeSwitchBootRefusal} + * of each `cause` down the chain. + * + * ## Where it runs, and where it must not + * + * Composed by `os serve` (and so `os dev` and `os start`) only. ⛔ Never in + * `createStandaloneStack`'s own list: every CLI data and schema boot shares + * that builder, `os migrate protocol`'s own boot among them, and a guard there + * would refuse the one command that clears it. That builder composes the birth + * half alone ({@link FormTypeSwitchBirthMarkerPlugin}), which writes the + * marker on a store it created from empty and never refuses. + * + * Unlike the organization-ownership guard this one is not limited to SQL + * stores: a stored form is a `sys_metadata` row on whatever driver persists + * it. A composition with no engine, or one where no store serves either + * `sys_migration` or `sys_metadata`, has nothing to judge and the guard is + * inert there. + */ + +/** + * The machine code a host discriminates this refusal by, across module + * instances. Registered in `@objectstack/spec`'s error-code ledger under this + * package; the refusal is thrown at boot, before any socket opens, so no + * request ever carries it. + */ +export const FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE = 'FORM_TYPE_SWITCH_REQUIRED' as const; + +/** + * The `name` every refusal carries: what a log line and a stack trace show. + * Not exported: a host discriminates on the code above, never on this. + */ +const FORM_TYPE_SWITCH_BOOT_REFUSAL_NAME = 'FormTypeSwitchBootRefusal' as const; + +/** + * The guard's kernel plugin name: a plugin that writes rows in its `start()` + * names it in `optionalDependencies`, so on a kernel that composes the guard it + * starts only once the guard has judged the database (ADR-0116 ordering). + * Each writer spells the name as a string literal (`check:init-service-contract` + * reads `optionalDependencies` as literals only), and the guard's tests pin the + * declaration against this constant. + */ +export const FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME = 'com.objectstack.form-type-switch-boot-guard' as const; + +/** The birth-marker plugin's kernel name. */ +export const FORM_TYPE_SWITCH_BIRTH_MARKER_PLUGIN_NAME = 'com.objectstack.form-type-switch-birth-marker' as const; + +/** The protocol major whose switch this guard reads, and the one a birth marker names. */ +export const FORM_TYPE_SWITCH_PROTOCOL_MAJOR = 19 as const; + +/** The object whose rows hold every stored form: where an old shape would be. */ +const METADATA_OBJECT = 'sys_metadata'; + +/** + * What the guard writes into `details.birth` of the + * {@link FORM_TYPE_SWITCH_MIGRATION_ID} row on a datastore created from empty. + * Provenance only: the guard decides on the row being verified, never on + * these fields. + */ +export interface FormTypeSwitchBirthMarker { + /** The protocol major the store was born on. */ + protocol: number; + /** The exact platform version that created the store (never compared). */ + platformVersion: string; + /** When the boot observed the store created from empty (ISO 8601). */ + createdAt: string; +} + +/** How the boot that runs the guard was started: what the refusal's command must match. */ +export interface FormTypeSwitchBootGuardOptions { + /** A development boot (`os dev` / `os serve --dev`): the named command carries `--dev`, as the command's own flag asks. */ + dev?: boolean; + /** The tier preset this boot was given (`os serve --preset`): the named command carries it, so it composes the same stack. */ + preset?: string; + /** + * The file this production boot read its auth secret from because the + * operator set none (`os start`'s `/auth-secret`). The command + * composes the deployment as this server does only with that secret, and the + * operator's shell does not hold it, so on a boot that is not a development + * boot the named commands export it from this file. + */ + authSecretFile?: string; + /** + * The database this boot serves, when the command run bare in the + * operator's shell would reach another one (`os start -d`, a `--home` home, + * `os dev -d`). The named commands then carry `--database-url`, so run + * verbatim they switch the database that was refused. A URL that carries a + * credential is not printed: the commands read it from `OS_DATABASE_URL` and + * stop if it is unset. + */ + databaseUrl?: string; + /** The driver `--database-driver` chose for this boot: set in front of the named commands as `OS_DATABASE_DRIVER`. */ + databaseDriver?: string; + /** + * Whether this boot's database auth token came from `--database-auth-token`. + * The value never reaches the guard: the named commands read + * `OS_DATABASE_AUTH_TOKEN` from the operator's shell and stop when it is + * unset, so the token is never printed. + */ + databaseAuthTokenFromFlag?: boolean; +} + +/** What the guard read of the switch's `sys_migration` row, when that reading refuses the boot. */ +export type FormTypeSwitchMarkerState = 'absent' | 'unverified' | 'unreadable' | 'no-ledger'; + +/** + * Why a boot was refused: what the guard read of the marker + * ({@link FormTypeSwitchMarkerState}), `birth-unwritten` when the store was + * created from empty and its birth marker could not be written, or + * `guard-replaced` when another plugin took the guard's name + * ({@link assertFormTypeSwitchGuardNotReplaced}). + */ +export type FormTypeSwitchRefusalReason = FormTypeSwitchMarkerState | 'birth-unwritten' | 'guard-replaced'; + +export class FormTypeSwitchBootRefusal extends Error { + readonly code = FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE; + override readonly name = FORM_TYPE_SWITCH_BOOT_REFUSAL_NAME; + constructor( + message: string, + /** Why the boot was refused. */ + readonly reason: FormTypeSwitchRefusalReason, + ) { + super(message); + } +} + +/** Structural, not `instanceof`: a host may hold two module instances. */ +export function isFormTypeSwitchBootRefusal(error: unknown): error is FormTypeSwitchBootRefusal { + return !!error && typeof error === 'object' && (error as { code?: unknown }).code === FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE; +} + +/** + * What a shell running a printed command without `OS_DATABASE_URL` says, and + * stops at, when the boot's database URL carries a credential. + */ +export const FORM_TYPE_SWITCH_CREDENTIAL_URL_UNSET = + 'export OS_DATABASE_URL as the database URL this server was started with'; + +/** What a shell says, and stops at, when the boot's auth token came from a flag and the variable is unset. */ +const AUTH_TOKEN_UNSET = 'export OS_DATABASE_AUTH_TOKEN as the database auth token this server was started with'; + +/** + * A value as one POSIX shell word: bare when it holds only characters no shell + * reads specially, otherwise double-quoted with the four characters a double + * quote still interprets escaped. + */ +function shellWord(value: string): string { + if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value)) return value; + return '"' + value.replace(/[\\"$\x60]/g, (c) => '\\' + c) + '"'; +} + +/** + * Whether a database URL holds a secret: a password in its user-info, or a + * query parameter whose name says token, password, secret or key. A value that + * does not parse as a URL is treated as holding one: a refusal never guesses a + * credential away. + */ +function carriesCredential(url: string): boolean { + if (/^file:/i.test(url)) return false; + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return true; + } + if (parsed.password !== '') return true; + return [...parsed.searchParams.keys()].some((key) => /token|password|passwd|secret|key/i.test(key)); +} + +/** + * The switch command the refusal names, spelled for the boot that refused, so + * that run verbatim it composes the same deployment over the same database: + * `--dev` and `--preset` as the boot had them, `--database-url` when the + * command's own default would reach another database (by reference when the + * URL carries a credential), and in front of it the variables the command + * reads a driver, an auth token or a file-held auth secret from. + */ +function switchCommand(opts: FormTypeSwitchBootGuardOptions): string { + let front = ''; + if (opts.databaseDriver) front += `OS_DATABASE_DRIVER=${shellWord(opts.databaseDriver)} `; + if (opts.databaseAuthTokenFromFlag) front += `OS_DATABASE_AUTH_TOKEN="\${OS_DATABASE_AUTH_TOKEN:?${AUTH_TOKEN_UNSET}}" `; + if (!opts.dev && opts.authSecretFile) front += `OS_AUTH_SECRET="$(cat ${shellWord(opts.authSecretFile)})" `; + let flags = ''; + if (opts.dev) flags += ' --dev'; + if (opts.preset) flags += ` --preset ${shellWord(opts.preset)}`; + if (opts.databaseUrl) { + flags += carriesCredential(opts.databaseUrl) + ? ` --database-url "\${OS_DATABASE_URL:?${FORM_TYPE_SWITCH_CREDENTIAL_URL_UNSET}}"` + : ` --database-url ${shellWord(opts.databaseUrl)}`; + } + return `${front}os migrate protocol --to ${FORM_TYPE_SWITCH_PROTOCOL_MAJOR}${flags}`; +} + +/** Why a named command reads a value from the shell instead of printing it. */ +function referenceNotes(opts: FormTypeSwitchBootGuardOptions): string { + let notes = ''; + if (!opts.dev && opts.authSecretFile) { + notes += ` Both commands export the auth secret this server read from ${opts.authSecretFile}, so they compose the ` + + 'deployment as this server does.'; + } + if (opts.databaseUrl && carriesCredential(opts.databaseUrl)) { + notes += ' The database URL this server was started with carries a credential, so it is not printed: export it as ' + + 'OS_DATABASE_URL in the shell that runs both commands, which read it from there and stop if it is unset.'; + } + if (opts.databaseAuthTokenFromFlag) { + notes += ' The database auth token this server was started with (--database-auth-token) is not printed: export it ' + + 'as OS_DATABASE_AUTH_TOKEN in the shell that runs both commands, which read it from there and stop if it is unset.'; + } + return notes; +} + +/** + * The refusal text: what was found, that the server refuses to start, and the + * command, first as its preview and then as the run that switches. + */ +export function formTypeSwitchRefusalMessage( + marker: FormTypeSwitchMarkerState, + opts: FormTypeSwitchBootGuardOptions = {}, +): string { + const command = switchCommand(opts); + const major = FORM_TYPE_SWITCH_PROTOCOL_MAJOR; + const run = + `Run '${command}' to see what the switch does with every stored form in an old shape, take a backup, then run ` + + `'${command} --apply --yes', and start again.${referenceNotes(opts)}`; + if (marker === 'absent') { + return ( + `This database has not been switched to protocol ${major}: it carries no switch record (sys_migration ` + + `'${FORM_TYPE_SWITCH_MIGRATION_ID}'), so an earlier release created it. On protocol ${major} a view holds lists ` + + 'only and a form is a form item, and the switch is what moves the forms this database stores in an old shape. ' + + `The server refuses to start rather than serve it unswitched. ${run} A database that stores no form runs the ` + + 'command once too: it finds nothing to move and records the switch.' + ); + } + if (marker === 'unreadable') { + return ( + `The protocol ${major} switch record (sys_migration '${FORM_TYPE_SWITCH_MIGRATION_ID}') of this database could ` + + 'not be read, and an unread answer is never taken for a switched database. The server refuses to start. Fix the ' + + `read, or run the switch: ${run}` + ); + } + if (marker === 'no-ledger') { + return ( + `This composition stores metadata (sys_metadata) and registers no ${DATA_MIGRATION_FLAG_OBJECT} ledger to read ` + + `the protocol ${major} switch record from, so the server cannot tell whether this database was switched and ` + + 'refuses to start. Compose the platform objects plugin (@objectstack/platform-objects), which os serve mounts ' + + `by default, then start again; on a database an earlier release created: ${run}` + ); + } + return ( + `The protocol ${major} switch has not finished on this database: its record (sys_migration ` + + `'${FORM_TYPE_SWITCH_MIGRATION_ID}') is not verified. The server refuses to start rather than serve it ` + + `unswitched. ${run}` + ); +} + +interface GuardDriver { + getSchemaSyncStats?: () => { created: number; existing: number } | undefined; +} + +interface GuardEngine { + getDriverForObject?: (object: string) => unknown; + findOne?: (object: string, query: Record) => Promise; + insert?: (object: string, data: Record, options?: Record) => Promise; + getObject?: (name: string) => unknown; + wasDatastoreCreatedFromEmpty?: () => boolean; + invalidateDataMigrationFlags?: () => void; +} + +/** What the guard read of the switch's `sys_migration` row. */ +type MarkerReading = + /** No store serves the ledger or `sys_metadata` on this composition: nothing to judge. */ + | { state: 'inert' } + | { state: 'no-ledger' } + | { state: 'absent' } + | { state: 'unreadable' } + | { state: 'unverified' } + | { state: 'verified' }; + +/** The driver that serves `object` when the composition registers it, or `undefined`. */ +function storeOf(engine: GuardEngine, object: string): GuardDriver | undefined { + if (typeof engine.getDriverForObject !== 'function') return undefined; + try { + if (typeof engine.getObject === 'function' && !engine.getObject(object)) return undefined; + return (engine.getDriverForObject(object) as GuardDriver | undefined) ?? undefined; + } catch { + return undefined; + } +} + +/** + * The switch's row. `inert` when no store serves the ledger and none serves + * `sys_metadata` either (`os serve` with no database), or the engine offers no + * read. `no-ledger` when a store serves `sys_metadata` and none serves the + * ledger. `unreadable` only when a store serves the ledger and its read threw. + */ +async function readMarker(engine: GuardEngine): Promise { + if (typeof engine.findOne !== 'function') return { state: 'inert' }; + if (!storeOf(engine, DATA_MIGRATION_FLAG_OBJECT)) { + return storeOf(engine, METADATA_OBJECT) ? { state: 'no-ledger' } : { state: 'inert' }; + } + try { + const row = (await engine.findOne(DATA_MIGRATION_FLAG_OBJECT, { + where: { id: FORM_TYPE_SWITCH_MIGRATION_ID }, + context: { isSystem: true }, + })) as DataMigrationFlag | null; + if (!row) return { state: 'absent' }; + const flag = { ...row, blocking: Number((row as { blocking?: unknown }).blocking) } as DataMigrationFlag; + return isDataMigrationFlagVerified(flag) ? { state: 'verified' } : { state: 'unverified' }; + } catch { + return { state: 'unreadable' }; + } +} + +/** + * Did THIS boot observe the store being created from empty? Judged on the + * store that holds the ledger and on the one that holds `sys_metadata` (one + * driver wherever they share a datasource): each one's own schema-sync counts + * (`getSchemaSyncStats`) must say every table it synced it created, and none + * it found. A driver that cannot report answers through the engine's + * all-driver reading, and "cannot say" is no. + */ +function storesCreatedFromEmpty(engine: GuardEngine): boolean { + const stores = new Set(); + for (const object of [DATA_MIGRATION_FLAG_OBJECT, METADATA_OBJECT]) { + const store = storeOf(engine, object); + if (store) stores.add(store); + } + if (stores.size === 0) return false; + for (const store of stores) { + let stats: { created: number; existing: number } | undefined; + try { + stats = store.getSchemaSyncStats?.(); + } catch { + return false; + } + if (stats) { + if ((Number(stats.existing) || 0) !== 0 || !((Number(stats.created) || 0) > 0)) return false; + continue; + } + try { + if (engine.wasDatastoreCreatedFromEmpty?.() !== true) return false; + } catch { + return false; + } + } + return true; +} + +/** + * Write the birth marker: the switch's row, verified, with `details.birth` + * naming the protocol major the store was created on. Only where no row exists. + */ +async function writeBirthMarker(engine: GuardEngine, now: Date): Promise { + if (typeof engine.insert !== 'function') throw new Error('the engine offers no insert'); + const at = now.toISOString(); + const birth: FormTypeSwitchBirthMarker = { + protocol: FORM_TYPE_SWITCH_PROTOCOL_MAJOR, + platformVersion: resolveRuntimeVersion(), + createdAt: at, + }; + await engine.insert( + DATA_MIGRATION_FLAG_OBJECT, + { + id: FORM_TYPE_SWITCH_MIGRATION_ID, + last_run_at: at, + verified_at: at, + applied_at: null, + blocking: 0, + advisory: 0, + details: JSON.stringify({ birth }), + created_at: at, + updated_at: at, + }, + { context: { isSystem: true } }, + ); + engine.invalidateDataMigrationFlags?.(); + return birth; +} + +function birthLine(birth: FormTypeSwitchBirthMarker): string { + return ( + `[form-type-switch] a datastore created from empty: birth marker written (protocol ${birth.protocol}, ` + + `platform ${birth.platformVersion}).` + ); +} + +/** + * Write the birth marker when, and only when, this boot created the store + * from empty and no switch row is there. The marker written, or `null` when + * none was owed. Throws when the write fails. + */ +export async function recordFormTypeSwitchBirth( + engine: GuardEngine, + logger?: { info?: (msg: string) => void }, + now: () => Date = () => new Date(), +): Promise { + if (!storesCreatedFromEmpty(engine)) return null; + if ((await readMarker(engine)).state !== 'absent') return null; + const birth = await writeBirthMarker(engine, now()); + logger?.info?.(birthLine(birth)); + return birth; +} + +/** + * The check itself, for the plugin and for a host that composes its own boot: + * resolves when the database may be served (writing the birth marker on a + * store created from empty), throws {@link FormTypeSwitchBootRefusal} when it + * may not. + */ +export async function assertFormTypeSwitched( + engine: GuardEngine, + logger?: { info?: (msg: string) => void }, + opts: FormTypeSwitchBootGuardOptions & { now?: () => Date } = {}, +): Promise { + const marker = await readMarker(engine); + if (marker.state === 'inert' || marker.state === 'verified') return; + if (marker.state === 'absent' && storesCreatedFromEmpty(engine)) { + let birth: FormTypeSwitchBirthMarker; + try { + birth = await writeBirthMarker(engine, (opts.now ?? (() => new Date()))()); + } catch (error) { + throw new FormTypeSwitchBootRefusal( + `The server refuses to start: this datastore was created from empty, and its protocol ` + + `${FORM_TYPE_SWITCH_PROTOCOL_MAJOR} birth marker (sys_migration '${FORM_TYPE_SWITCH_MIGRATION_ID}') could ` + + `not be written (${error instanceof Error ? error.message : String(error)}). Without it the next boot would ` + + `take this store for a database an earlier release created. Fix the write and start again, or run ` + + `'${switchCommand(opts)} --apply --yes'.`, + 'birth-unwritten', + ); + } + logger?.info?.(birthLine(birth)); + return; + } + throw new FormTypeSwitchBootRefusal(formTypeSwitchRefusalMessage(marker.state, opts), marker.state); +} + +/** + * Refuse a composition in which another plugin carries the guard's name. + * + * Duplicate registration by name is last-one-wins on the kernel, by declared + * contract: a plugin mounted after the guard under its name replaces it, the + * guard never starts, and the boot goes unjudged. That would be a config key + * that boots an unswitched database anyway, which the ruling excludes (record + * 7303149461), so the host that composes the guard hands the plugins it + * mounted from the stack here before any of them initializes. Throws + * {@link FormTypeSwitchBootRefusal} (`guard-replaced`). + */ +export function assertFormTypeSwitchGuardNotReplaced(guard: unknown, composed: Iterable): void { + for (const plugin of composed) { + if (plugin === guard) continue; + if ((plugin as { name?: unknown } | null | undefined)?.name !== FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME) continue; + throw new FormTypeSwitchBootRefusal( + `Refusing to boot: a plugin of this stack is named '${FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME}', the name of the ` + + `server's own protocol ${FORM_TYPE_SWITCH_PROTOCOL_MAJOR} boot guard, and a later registration under one name ` + + 'replaces the earlier one. The guard is not replaceable: remove that plugin from the stack, or give it a ' + + 'name of its own.', + 'guard-replaced', + ); + } +} + +export class FormTypeSwitchBootGuardPlugin implements Plugin { + readonly name = FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME; + readonly type = 'standard'; + readonly version = '1.0.0'; + readonly dependencies: string[] = []; + /** + * Started after the engine (its `start()` connects the drivers and runs the + * schema sync), after the platform objects, which register `sys_migration`, + * and after the organization-ownership guard: a database that owes both acts + * hears of the older one first, and a store created from empty has that + * guard's birth marker before this one's. Order-if-present: the guard still + * loads (inert) on a kernel with no engine. + */ + readonly optionalDependencies: string[] = [ + 'com.objectstack.engine.objectql', + 'com.objectstack.platform-objects', + 'com.objectstack.organization-ownership-boot-guard', + ]; + + constructor(private readonly options: FormTypeSwitchBootGuardOptions = {}) {} + + async init(_ctx: PluginContext): Promise {} + + /** [ADR-0159 D7] Judges here, not at `kernel:ready`: a `start()` that throws stops the boot before the next plugin starts. */ + async start(ctx: PluginContext): Promise { + let engine: GuardEngine | undefined; + try { + engine = (ctx as any).getService?.('objectql'); + } catch { + return; // no engine: no database to judge + } + if (!engine || typeof engine.getDriverForObject !== 'function') return; + await assertFormTypeSwitched(engine, (ctx as any)?.logger, this.options); + } +} + +/** + * [Ruling record 7308112533] The birth half alone, for a boot that composes no + * guard: every CLI data and schema boot (`createStandaloneStack`), which can + * be the boot that creates a fresh install's store (`os migrate apply`, + * `os seed` before the first `os serve`). It writes the birth marker under + * exactly the guard's conditions and never refuses: judging the database stays + * the served boot's. Without it, the first `os serve` of an install whose + * store a CLI boot created would find no marker on a store it did not create, + * and refuse a fresh install. + * + * A boot that holds its DDL back (`deferSchemaDdl`) or skips schema sync + * reports nothing created, so the plugin writes nothing there: the switch + * command's own boots never trip it. A deferred boot that then creates the + * tables calls {@link recordFormTypeSwitchBirth} itself once they exist (the + * CLI's `flushSchemaDdl`), judged on the same counts. + */ +export class FormTypeSwitchBirthMarkerPlugin implements Plugin { + readonly name = FORM_TYPE_SWITCH_BIRTH_MARKER_PLUGIN_NAME; + readonly type = 'standard'; + readonly version = '1.0.0'; + readonly dependencies: string[] = []; + /** As the guard: after the engine's schema sync and the ledger's registration. */ + readonly optionalDependencies: string[] = ['com.objectstack.engine.objectql', 'com.objectstack.platform-objects']; + + async init(_ctx: PluginContext): Promise {} + + async start(ctx: PluginContext): Promise { + let engine: GuardEngine | undefined; + try { + engine = (ctx as any).getService?.('objectql'); + } catch { + return; + } + if (!engine || typeof engine.getDriverForObject !== 'function') return; + const logger = (ctx as any)?.logger as { info?: (msg: string) => void; error?: (msg: string) => void } | undefined; + try { + await recordFormTypeSwitchBirth(engine, logger); + } catch (error) { + // Durability: the store keeps looking healthy, and its first served boot + // will refuse it as one an earlier release created. + logger?.error?.( + `[form-type-switch] this store was created from empty and its birth marker (sys_migration ` + + `'${FORM_TYPE_SWITCH_MIGRATION_ID}') could not be written ` + + `(${error instanceof Error ? error.message : String(error)}): the first 'os serve' will refuse it as a ` + + `database an earlier release created. Fix the write and run this command again, or run 'os migrate ` + + `protocol --to ${FORM_TYPE_SWITCH_PROTOCOL_MAJOR} --apply --yes' on it.`, + ); + } + } +} diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 482c5f515b6..ccd80a96165 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -159,6 +159,28 @@ export { organizationOwnershipRefusalMessage, } from './organization-ownership-boot-guard.js'; export type { OrganizationOwnershipBootGuardOptions, OrganizationOwnershipMarkerState } from './organization-ownership-boot-guard.js'; +// [ADR-0159 D7] The protocol-19 boot refusal `os serve` composes, and the birth +// half every CLI data and schema boot composes beside it. +export { + FormTypeSwitchBootGuardPlugin, + FormTypeSwitchBirthMarkerPlugin, + FORM_TYPE_SWITCH_BOOT_GUARD_PLUGIN_NAME, + FORM_TYPE_SWITCH_BIRTH_MARKER_PLUGIN_NAME, + FORM_TYPE_SWITCH_PROTOCOL_MAJOR, + recordFormTypeSwitchBirth, + FormTypeSwitchBootRefusal, + FORM_TYPE_SWITCH_BOOT_REFUSAL_CODE, + assertFormTypeSwitched, + assertFormTypeSwitchGuardNotReplaced, + isFormTypeSwitchBootRefusal, + formTypeSwitchRefusalMessage, +} from './form-type-switch-boot-guard.js'; +export type { + FormTypeSwitchBirthMarker, + FormTypeSwitchBootGuardOptions, + FormTypeSwitchMarkerState, + FormTypeSwitchRefusalReason, +} from './form-type-switch-boot-guard.js'; export { DefaultDatasourcePlugin } from './default-datasource-plugin.js'; export type { DefaultDatasourceDefinition, DefaultDatasourcePluginOptions } from './default-datasource-plugin.js'; export { AppPlugin, collectBundleHooks, collectBundleFunctions, collectBundleFunctionEntries, collectBundleActions } from './app-plugin.js'; diff --git a/packages/runtime/src/standalone-stack.ts b/packages/runtime/src/standalone-stack.ts index d810dea2a51..44e92ac9cc4 100644 --- a/packages/runtime/src/standalone-stack.ts +++ b/packages/runtime/src/standalone-stack.ts @@ -81,6 +81,7 @@ import { makeDirectorySync } from './make-directory.js'; import { loadTursoDriverFactory } from './turso-driver-factory.js'; import { devAutoMigrateConfig } from './dev-auto-migrate.js'; import { OrganizationOwnershipBirthMarkerPlugin } from './organization-ownership-boot-guard.js'; +import { FormTypeSwitchBirthMarkerPlugin } from './form-type-switch-boot-guard.js'; import { namesRetiredMemoryEngine, resolveProjectDatabaseUrl, @@ -1178,6 +1179,13 @@ export async function createStandaloneStack(config?: StandaloneStackConfig): Pro // by its first `os serve`. It never refuses — the served boot's guard // judges (⛔ the guard itself stays out of this list). new OrganizationOwnershipBirthMarkerPlugin(), + // [ADR-0159 D7; ruling record 7308112533] The same for the protocol-19 + // switch: a store this boot creates from empty holds no stored form, + // so its switch record is written here as a birth marker and the + // first `os serve` does not refuse a fresh install. It never refuses + // (⛔ the guard itself stays out of this list: `os migrate protocol`'s + // own boot shares it). + new FormTypeSwitchBirthMarkerPlugin(), ]; if (artifactBundle) { plugins.push(new AppPlugin(artifactBundle, undefined, { diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index ea90b9c7a32..586f1dfb752 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -595,6 +595,7 @@ "GetTranslationsRequestSchema (const)", "GetTranslationsResponse (type)", "GetTranslationsResponseSchema (const)", + "GetUiViewFormScaffold (type)", "GetUiViewRequest (type)", "GetUiViewRequestSchema (const)", "GetUiViewResponse (type)", diff --git a/packages/spec/api-surface/root.json b/packages/spec/api-surface/root.json index 5ae86b2dc59..aaac8b3f738 100644 --- a/packages/spec/api-surface/root.json +++ b/packages/spec/api-surface/root.json @@ -131,6 +131,7 @@ "STACK_DEFINITION_KEYS (const)", "STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS (const)", + "ServedViewItem (type)", "Skill (type)", "StackDefinitionKey (type)", "StoredConversionOptions (type)", @@ -177,6 +178,7 @@ "defineViewItem (function)", "defineWebhook (function)", "deriveViewContainerObject (function)", + "expandServedViewContainer (function)", "expandViewContainer (function)", "expandViewContainerWithDiagnostics (function)", "expression (function)", @@ -188,6 +190,7 @@ "hasStackProvenance (function)", "isAggregatedViewContainer (function)", "isKnownPlatformCapability (function)", + "isServedViewItem (function)", "isViewContainerShaped (function)", "lintUnknownAuthoringKeys (function)", "lintUnknownKeysAgainstSchema (function)", diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index a3b73edd4fe..2b859dfd0e2 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -477,6 +477,7 @@ "SelectionConfig (type)", "SelectionConfigParsed (type)", "SelectionConfigSchema (const)", + "ServedViewItem (type)", "SharingConfig (type)", "SharingConfigParsed (type)", "SharingConfigSchema (const)", @@ -610,6 +611,7 @@ "deriveColumnSummary (function)", "deriveViewContainerObject (function)", "diagnoseViewMetadata (function)", + "expandServedViewContainer (function)", "expandViewContainer (function)", "expandViewContainerWithDiagnostics (function)", "expressionBindableTextKeysFor (function)", @@ -622,6 +624,7 @@ "isExpressionBindableTextKey (function)", "isKnownComponentType (function)", "isRecordContextBlockType (function)", + "isServedViewItem (function)", "isViewContainerShaped (function)", "isViewFilterOrGroup (function)", "listViewGroupKeyPredicate (function)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 90a03916edb..3cbbf1b9108 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -993,8 +993,8 @@ "api/GetUiViewResponse:_packageId", "api/GetUiViewResponse:_packageVersion", "api/GetUiViewResponse:_provenance", - "api/GetUiViewResponse:form", - "api/GetUiViewResponse:formViews", + "api/GetUiViewResponse:form [RETIRED]", + "api/GetUiViewResponse:formViews [RETIRED]", "api/GetUiViewResponse:label", "api/GetUiViewResponse:list", "api/GetUiViewResponse:listViews", diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index 30b0daf0c68..ffc4faa8c3b 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -1436,8 +1436,8 @@ "ui/View:_packageId", "ui/View:_packageVersion", "ui/View:_provenance", - "ui/View:form", - "ui/View:formViews", + "ui/View:form [RETIRED]", + "ui/View:formViews [RETIRED]", "ui/View:label", "ui/View:list", "ui/View:listViews", diff --git a/packages/spec/docs/references/api/automation-api.md b/packages/spec/docs/references/api/automation-api.md index 143fe482586..5ab357e2ee9 100644 --- a/packages/spec/docs/references/api/automation-api.md +++ b/packages/spec/docs/references/api/automation-api.md @@ -419,7 +419,7 @@ const result = AutomationApiErrorCode.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +385 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +386 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | | **message** | `string` | ✅ | The inner refusal's own diagnostic text, verbatim, without the node and operation prefixes the run's failure text adds | ### Allowed Values: `FlowInnerRefusal.code` @@ -612,6 +612,7 @@ const result = AutomationApiErrorCode.parse(data); * `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` +* `FORM_TYPE_SWITCH_REQUIRED` * `HOOK_ABORTED` * `HOOK_UNSCOPED_DATA_ACCESS` * `IMPORT_JOB_CREATE_FAILED` diff --git a/packages/spec/docs/references/api/contract.md b/packages/spec/docs/references/api/contract.md index ac280168ff1..82ea52bb12d 100644 --- a/packages/spec/docs/references/api/contract.md +++ b/packages/spec/docs/references/api/contract.md @@ -22,7 +22,7 @@ const result = ApiErrorSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +385 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +386 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -222,6 +222,7 @@ const result = ApiErrorSchema.parse(data); * `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` +* `FORM_TYPE_SWITCH_REQUIRED` * `HOOK_ABORTED` * `HOOK_UNSCOPED_DATA_ACCESS` * `IMPORT_JOB_CREATE_FAILED` diff --git a/packages/spec/docs/references/api/error-code-ledger.md b/packages/spec/docs/references/api/error-code-ledger.md index 2a7ae6b030c..2335a1050a8 100644 --- a/packages/spec/docs/references/api/error-code-ledger.md +++ b/packages/spec/docs/references/api/error-code-ledger.md @@ -389,6 +389,7 @@ const result = ErrorCode.parse(data); * `FORM_ADDRESS_TAKEN` * `FORM_NOT_FOUND` * `FORM_RESOLVE_FAILED` +* `FORM_TYPE_SWITCH_REQUIRED` * `HOOK_ABORTED` * `HOOK_UNSCOPED_DATA_ACCESS` * `IMPORT_JOB_CREATE_FAILED` diff --git a/packages/spec/docs/references/api/protocol.md b/packages/spec/docs/references/api/protocol.md index 5e818e11a89..2ad2339e726 100644 --- a/packages/spec/docs/references/api/protocol.md +++ b/packages/spec/docs/references/api/protocol.md @@ -5,8 +5,8 @@ > This reference is split into 3 files, each small enough for GitHub to show as a document. - Part 1: [AiAgentCapabilities](#aiagentcapabilities), [AiAgentChatRequest](#aiagentchatrequest), [AiAgentSummary](#aiagentsummary), [AiAgentsResponse](#aiagentsresponse), [AiChatRequest](#aichatrequest), [AiChatResponse](#aichatresponse), [AiCompleteRequest](#aicompleterequest), [AiConversation](#aiconversation), [AiConversationMessage](#aiconversationmessage), [AiMessage](#aimessage), [AiModelsResponse](#aimodelsresponse), [AiPendingAction](#aipendingaction), [AiPendingActionStatus](#aipendingactionstatus), [AiStreamChunk](#aistreamchunk), [ApproveAiPendingActionResponse](#approveaipendingactionresponse), [AuditMetaItemRequest](#auditmetaitemrequest), [AuditMetaItemResponse](#auditmetaitemresponse), [AutomationActionsResponse](#automationactionsresponse), [AutomationTriggerRequest](#automationtriggerrequest), [AutomationTriggerResponse](#automationtriggerresponse), [BatchDataRequest](#batchdatarequest), [BatchDataResponse](#batchdataresponse), [BuildProbeReport](#buildprobereport), [CheckPermissionRequest](#checkpermissionrequest), [CheckPermissionResponse](#checkpermissionresponse), [CloneDataResponse](#clonedataresponse), [CreateAiConversationRequest](#createaiconversationrequest), [CreateDataRequest](#createdatarequest), [CreateDataResponse](#createdataresponse), [CreateManyDataRequest](#createmanydatarequest), [CreateManyDataResponse](#createmanydataresponse), [DeleteDataRequest](#deletedatarequest), [DeleteDataResponse](#deletedataresponse), [DeleteManyDataRequest](#deletemanydatarequest), [DeleteManyDataResponse](#deletemanydataresponse), [DeleteMetaItemRequest](#deletemetaitemrequest), [DeleteMetaItemResponse](#deletemetaitemresponse), [DestructiveChangeIssue](#destructivechangeissue), [DiffMetaItemRequest](#diffmetaitemrequest), [DiffMetaItemResponse](#diffmetaitemresponse), [DisablePackageRequest](#disablepackagerequest), [DisablePackageResponse](#disablepackageresponse), [EnablePackageRequest](#enablepackagerequest), [EnablePackageResponse](#enablepackageresponse), [FieldStillShownBy](#fieldstillshownby), [FindDataRequest](#finddatarequest), [FindDataResponse](#finddataresponse), [FindReferencesToMetaResponse](#findreferencestometaresponse), [FlowRegistration](#flowregistration), [FlowRegistrationRefusal](#flowregistrationrefusal), [GetDataRequest](#getdatarequest), [GetDataResponse](#getdataresponse), [GetDiscoveryRequest](#getdiscoveryrequest), [GetDiscoveryResponse](#getdiscoveryresponse), [GetEffectivePermissionsRequest](#geteffectivepermissionsrequest), [GetEffectivePermissionsResponse](#geteffectivepermissionsresponse), [GetFieldLabelsRequest](#getfieldlabelsrequest), [GetFieldLabelsResponse](#getfieldlabelsresponse), [GetLocalesRequest](#getlocalesrequest), [GetLocalesResponse](#getlocalesresponse), [GetMetaDiagnosticsResponse](#getmetadiagnosticsresponse), [GetMetaItemCachedRequest](#getmetaitemcachedrequest), [GetMetaItemCachedResponse](#getmetaitemcachedresponse), [GetMetaItemLayeredRequest](#getmetaitemlayeredrequest), [GetMetaItemLayeredResponse](#getmetaitemlayeredresponse), [GetMetaItemRequest](#getmetaitemrequest) -- Part 2: [GetMetaItemResponse](protocol.part-2.md#getmetaitemresponse), [GetMetaItemsRequest](protocol.part-2.md#getmetaitemsrequest), [GetMetaItemsResponse](protocol.part-2.md#getmetaitemsresponse), [GetMetaTypesRequest](protocol.part-2.md#getmetatypesrequest), [GetMetaTypesResponse](protocol.part-2.md#getmetatypesresponse), [GetNotificationPreferencesRequest](protocol.part-2.md#getnotificationpreferencesrequest), [GetNotificationPreferencesResponse](protocol.part-2.md#getnotificationpreferencesresponse), [GetObjectPermissionsRequest](protocol.part-2.md#getobjectpermissionsrequest), [GetObjectPermissionsResponse](protocol.part-2.md#getobjectpermissionsresponse), [GetPackageRequest](protocol.part-2.md#getpackagerequest), [GetPackageResponse](protocol.part-2.md#getpackageresponse), [GetPresenceRequest](protocol.part-2.md#getpresencerequest), [GetPresenceResponse](protocol.part-2.md#getpresenceresponse), [GetPublishedMetaItemResponse](protocol.part-2.md#getpublishedmetaitemresponse), [GetRecordFieldAccessResponse](protocol.part-2.md#getrecordfieldaccessresponse), [GetTranslationsRequest](protocol.part-2.md#gettranslationsrequest), [GetTranslationsResponse](protocol.part-2.md#gettranslationsresponse), [GetUiViewRequest](protocol.part-2.md#getuiviewrequest), [GetUiViewResponse](protocol.part-2.md#getuiviewresponse), [HistoryMetaItemRequest](protocol.part-2.md#historymetaitemrequest), [HistoryMetaItemResponse](protocol.part-2.md#historymetaitemresponse), [HttpFindQueryParams](protocol.part-2.md#httpfindqueryparams), [InstallPackageRequest](protocol.part-2.md#installpackagerequest), [InstallPackageResponse](protocol.part-2.md#installpackageresponse), [ListAiConversationsRequest](protocol.part-2.md#listaiconversationsrequest), [ListAiConversationsResponse](protocol.part-2.md#listaiconversationsresponse), [ListAiPendingActionsRequest](protocol.part-2.md#listaipendingactionsrequest), [ListAiPendingActionsResponse](protocol.part-2.md#listaipendingactionsresponse), [ListDraftsResponse](protocol.part-2.md#listdraftsresponse), [ListNotificationsRequest](protocol.part-2.md#listnotificationsrequest), [ListNotificationsResponse](protocol.part-2.md#listnotificationsresponse), [ListPackagesRequest](protocol.part-2.md#listpackagesrequest), [ListPackagesResponse](protocol.part-2.md#listpackagesresponse), [MarkAllNotificationsReadRequest](protocol.part-2.md#markallnotificationsreadrequest), [MarkAllNotificationsReadResponse](protocol.part-2.md#markallnotificationsreadresponse), [MarkNotificationsReadRequest](protocol.part-2.md#marknotificationsreadrequest), [MarkNotificationsReadResponse](protocol.part-2.md#marknotificationsreadresponse), [MetadataAuthoringClient](protocol.part-2.md#metadataauthoringclient), [MetadataAuthoringSurface](protocol.part-2.md#metadataauthoringsurface), [MetadataConflictError](protocol.part-2.md#metadataconflicterror), [Notification](protocol.part-2.md#notification), [NotificationPreferences](protocol.part-2.md#notificationpreferences), [PublicFormSubmitResponse](protocol.part-2.md#publicformsubmitresponse), [PublishMetaItemRequest](protocol.part-2.md#publishmetaitemrequest), [PublishMetaItemResponse](protocol.part-2.md#publishmetaitemresponse), [PublishPackageDraftsRequest](protocol.part-2.md#publishpackagedraftsrequest) -- Part 3: [PublishPackageDraftsResponse](protocol.part-3.md#publishpackagedraftsresponse), [RealtimeConnectRequest](protocol.part-3.md#realtimeconnectrequest), [RealtimeConnectResponse](protocol.part-3.md#realtimeconnectresponse), [RealtimeDisconnectRequest](protocol.part-3.md#realtimedisconnectrequest), [RealtimeDisconnectResponse](protocol.part-3.md#realtimedisconnectresponse), [RealtimeSubscribeRequest](protocol.part-3.md#realtimesubscriberequest), [RealtimeSubscribeResponse](protocol.part-3.md#realtimesubscriberesponse), [RealtimeUnsubscribeRequest](protocol.part-3.md#realtimeunsubscriberequest), [RealtimeUnsubscribeResponse](protocol.part-3.md#realtimeunsubscriberesponse), [RegisterDeviceRequest](protocol.part-3.md#registerdevicerequest), [RegisterDeviceResponse](protocol.part-3.md#registerdeviceresponse), [RejectAiPendingActionResponse](protocol.part-3.md#rejectaipendingactionresponse), [RollbackMetaItemRequest](protocol.part-3.md#rollbackmetaitemrequest), [RollbackMetaItemResponse](protocol.part-3.md#rollbackmetaitemresponse), [RuntimeAuthoringIssue](protocol.part-3.md#runtimeauthoringissue), [RuntimeBuildIssue](protocol.part-3.md#runtimebuildissue), [SaveMetaItemRequest](protocol.part-3.md#savemetaitemrequest), [SaveMetaItemResponse](protocol.part-3.md#savemetaitemresponse), [SearchAllHit](protocol.part-3.md#searchallhit), [SearchAllPageHit](protocol.part-3.md#searchallpagehit), [SearchAllResponse](protocol.part-3.md#searchallresponse), [SeedAppliedIdList](protocol.part-3.md#seedappliedidlist), [SeedAppliedLanded](protocol.part-3.md#seedappliedlanded), [SetPresenceRequest](protocol.part-3.md#setpresencerequest), [SetPresenceResponse](protocol.part-3.md#setpresenceresponse), [UninstallPackageRequest](protocol.part-3.md#uninstallpackagerequest), [UninstallPackageResponse](protocol.part-3.md#uninstallpackageresponse), [UnregisterDeviceRequest](protocol.part-3.md#unregisterdevicerequest), [UnregisterDeviceResponse](protocol.part-3.md#unregisterdeviceresponse), [UpdateAiConversationRequest](protocol.part-3.md#updateaiconversationrequest), [UpdateDataRequest](protocol.part-3.md#updatedatarequest), [UpdateDataResponse](protocol.part-3.md#updatedataresponse), [UpdateManyDataRequest](protocol.part-3.md#updatemanydatarequest), [UpdateManyDataResponse](protocol.part-3.md#updatemanydataresponse), [UpdateNotificationPreferencesRequest](protocol.part-3.md#updatenotificationpreferencesrequest), [UpdateNotificationPreferencesResponse](protocol.part-3.md#updatenotificationpreferencesresponse), [ValidateDataIssue](protocol.part-3.md#validatedataissue), [ValidateDataRequest](protocol.part-3.md#validatedatarequest), [ValidateDataResponse](protocol.part-3.md#validatedataresponse) +- Part 2: [GetMetaItemResponse](protocol.part-2.md#getmetaitemresponse), [GetMetaItemsRequest](protocol.part-2.md#getmetaitemsrequest), [GetMetaItemsResponse](protocol.part-2.md#getmetaitemsresponse), [GetMetaTypesRequest](protocol.part-2.md#getmetatypesrequest), [GetMetaTypesResponse](protocol.part-2.md#getmetatypesresponse), [GetNotificationPreferencesRequest](protocol.part-2.md#getnotificationpreferencesrequest), [GetNotificationPreferencesResponse](protocol.part-2.md#getnotificationpreferencesresponse), [GetObjectPermissionsRequest](protocol.part-2.md#getobjectpermissionsrequest), [GetObjectPermissionsResponse](protocol.part-2.md#getobjectpermissionsresponse), [GetPackageRequest](protocol.part-2.md#getpackagerequest), [GetPackageResponse](protocol.part-2.md#getpackageresponse), [GetPresenceRequest](protocol.part-2.md#getpresencerequest), [GetPresenceResponse](protocol.part-2.md#getpresenceresponse), [GetPublishedMetaItemResponse](protocol.part-2.md#getpublishedmetaitemresponse), [GetRecordFieldAccessResponse](protocol.part-2.md#getrecordfieldaccessresponse), [GetTranslationsRequest](protocol.part-2.md#gettranslationsrequest), [GetTranslationsResponse](protocol.part-2.md#gettranslationsresponse), [GetUiViewRequest](protocol.part-2.md#getuiviewrequest), [GetUiViewResponse](protocol.part-2.md#getuiviewresponse), [HistoryMetaItemRequest](protocol.part-2.md#historymetaitemrequest), [HistoryMetaItemResponse](protocol.part-2.md#historymetaitemresponse), [HttpFindQueryParams](protocol.part-2.md#httpfindqueryparams), [InstallPackageRequest](protocol.part-2.md#installpackagerequest), [InstallPackageResponse](protocol.part-2.md#installpackageresponse), [ListAiConversationsRequest](protocol.part-2.md#listaiconversationsrequest), [ListAiConversationsResponse](protocol.part-2.md#listaiconversationsresponse), [ListAiPendingActionsRequest](protocol.part-2.md#listaipendingactionsrequest), [ListAiPendingActionsResponse](protocol.part-2.md#listaipendingactionsresponse), [ListDraftsResponse](protocol.part-2.md#listdraftsresponse), [ListNotificationsRequest](protocol.part-2.md#listnotificationsrequest), [ListNotificationsResponse](protocol.part-2.md#listnotificationsresponse), [ListPackagesRequest](protocol.part-2.md#listpackagesrequest), [ListPackagesResponse](protocol.part-2.md#listpackagesresponse), [MarkAllNotificationsReadRequest](protocol.part-2.md#markallnotificationsreadrequest), [MarkAllNotificationsReadResponse](protocol.part-2.md#markallnotificationsreadresponse), [MarkNotificationsReadRequest](protocol.part-2.md#marknotificationsreadrequest), [MarkNotificationsReadResponse](protocol.part-2.md#marknotificationsreadresponse), [MetadataAuthoringClient](protocol.part-2.md#metadataauthoringclient), [MetadataAuthoringSurface](protocol.part-2.md#metadataauthoringsurface), [MetadataConflictError](protocol.part-2.md#metadataconflicterror), [Notification](protocol.part-2.md#notification), [NotificationPreferences](protocol.part-2.md#notificationpreferences), [PublicFormSubmitResponse](protocol.part-2.md#publicformsubmitresponse), [PublishMetaItemRequest](protocol.part-2.md#publishmetaitemrequest), [PublishMetaItemResponse](protocol.part-2.md#publishmetaitemresponse), [PublishPackageDraftsRequest](protocol.part-2.md#publishpackagedraftsrequest), [PublishPackageDraftsResponse](protocol.part-2.md#publishpackagedraftsresponse), [RealtimeConnectRequest](protocol.part-2.md#realtimeconnectrequest), [RealtimeConnectResponse](protocol.part-2.md#realtimeconnectresponse), [RealtimeDisconnectRequest](protocol.part-2.md#realtimedisconnectrequest), [RealtimeDisconnectResponse](protocol.part-2.md#realtimedisconnectresponse), [RealtimeSubscribeRequest](protocol.part-2.md#realtimesubscriberequest), [RealtimeSubscribeResponse](protocol.part-2.md#realtimesubscriberesponse), [RealtimeUnsubscribeRequest](protocol.part-2.md#realtimeunsubscriberequest), [RealtimeUnsubscribeResponse](protocol.part-2.md#realtimeunsubscriberesponse), [RegisterDeviceRequest](protocol.part-2.md#registerdevicerequest), [RegisterDeviceResponse](protocol.part-2.md#registerdeviceresponse), [RejectAiPendingActionResponse](protocol.part-2.md#rejectaipendingactionresponse), [RollbackMetaItemRequest](protocol.part-2.md#rollbackmetaitemrequest) +- Part 3: [RollbackMetaItemResponse](protocol.part-3.md#rollbackmetaitemresponse), [RuntimeAuthoringIssue](protocol.part-3.md#runtimeauthoringissue), [RuntimeBuildIssue](protocol.part-3.md#runtimebuildissue), [SaveMetaItemRequest](protocol.part-3.md#savemetaitemrequest), [SaveMetaItemResponse](protocol.part-3.md#savemetaitemresponse), [SearchAllHit](protocol.part-3.md#searchallhit), [SearchAllPageHit](protocol.part-3.md#searchallpagehit), [SearchAllResponse](protocol.part-3.md#searchallresponse), [SeedAppliedIdList](protocol.part-3.md#seedappliedidlist), [SeedAppliedLanded](protocol.part-3.md#seedappliedlanded), [SetPresenceRequest](protocol.part-3.md#setpresencerequest), [SetPresenceResponse](protocol.part-3.md#setpresenceresponse), [UninstallPackageRequest](protocol.part-3.md#uninstallpackagerequest), [UninstallPackageResponse](protocol.part-3.md#uninstallpackageresponse), [UnregisterDeviceRequest](protocol.part-3.md#unregisterdevicerequest), [UnregisterDeviceResponse](protocol.part-3.md#unregisterdeviceresponse), [UpdateAiConversationRequest](protocol.part-3.md#updateaiconversationrequest), [UpdateDataRequest](protocol.part-3.md#updatedatarequest), [UpdateDataResponse](protocol.part-3.md#updatedataresponse), [UpdateManyDataRequest](protocol.part-3.md#updatemanydatarequest), [UpdateManyDataResponse](protocol.part-3.md#updatemanydataresponse), [UpdateNotificationPreferencesRequest](protocol.part-3.md#updatenotificationpreferencesrequest), [UpdateNotificationPreferencesResponse](protocol.part-3.md#updatenotificationpreferencesresponse), [ValidateDataIssue](protocol.part-3.md#validatedataissue), [ValidateDataRequest](protocol.part-3.md#validatedatarequest), [ValidateDataResponse](protocol.part-3.md#validatedataresponse) > **Source:** `packages/spec/src/api/protocol.zod.ts` diff --git a/packages/spec/docs/references/api/protocol.part-2.md b/packages/spec/docs/references/api/protocol.part-2.md index 9ff4b0da30f..ec258a8ebd3 100644 --- a/packages/spec/docs/references/api/protocol.part-2.md +++ b/packages/spec/docs/references/api/protocol.part-2.md @@ -419,9 +419,9 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **label** | `string \| Record` | optional | Human-readable label shown in metadata lists. | | **object** | `string` | optional | Object this container binds to — how a stack-level `views: [...]` entry says which object its views belong to; read by `getViewsByObject()` / `GET /meta/view?object=`. | | **list** | `{ name?: string; label?: string \| Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }` | optional | | -| **form** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | optional | | +| **form** | `never` | optional | [REMOVED] `view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and a `view` holds lists only. Move the form to the stack's `forms:` as a `form` item named `OBJECT.form` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); a record's New and Edit dialogs lay out by the object's `fieldGroups` and read no form, so a create or edit form that nothing else opens is deleted, not moved. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047) | -| **formViews** | `Record; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }>` | optional | Additional named form views | +| **formViews** | `never` | optional | [REMOVED] `view.formViews` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and a `view` holds lists only. Move each entry to the stack's `forms:` as a `form` item named `OBJECT.KEY` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); the name stays the one it is served under, so a `type: 'form'` action and a public link keep reaching it. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -483,34 +483,6 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | | **userFilters** | `{ element?: Enum<'dropdown' \| 'toggle'>; fields?: object[] }` | optional | | -### Nested Shape: `GetUiViewResponse.form` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - ### Nested Shape: `GetUiViewResponse.listViews[string]` | Property | Type | Required | Description | @@ -563,34 +535,6 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **aria** | `{ ariaLabel?: string \| Record; ariaDescribedBy?: string; role?: string }` | optional | ARIA accessibility attributes for the list view | | **userFilters** | `{ element?: Enum<'dropdown' \| 'toggle'>; fields?: object[] }` | optional | | -### Nested Shape: `GetUiViewResponse.formViews[string]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `Enum<'simple' \| 'tabbed' \| 'wizard'>` | optional (default: `"simple"`) | Form layout: 'simple' (stacked sections, the default), 'tabbed' (one tab per section) or 'wizard' (one gated step per section). Where the form opens is the caller's choice, not the form's | -| **layout** | `Enum<'vertical' \| 'horizontal'>` | optional | Field layout direction — 'vertical' (the renderer default) or 'horizontal'. Multi-column is not a layout value: set `columns` | -| **columns** | `integer` | optional | Number of columns for the form body | -| **title** | `string` | optional | Form title | -| **description** | `string` | optional | Form description | -| **defaultTab** | `string` | optional | Initially active tab (tabbed forms) | -| **tabPosition** | `Enum<'top' \| 'bottom' \| 'left' \| 'right'>` | optional | Tab strip position (tabbed forms) | -| **allowSkip** | `boolean` | optional | Wizard step-gate opt-out: allow entering a later step without submitting the one before it. Navigation freedom, NOT a validation exemption — the final submit still re-validates every step and returns to the first failing one. Default (absent/false): steps unlock in array order as each prior step submits validly. UI admission only, never authorization. | -| **showStepIndicator** | `boolean` | optional | Show the wizard step indicator (renderer default: shown). Step progress (completed/current/upcoming/invalid) is derived from the step gate — this boolean is the only authorable progress surface. | -| **splitDirection** | `never` | optional | [REMOVED] `view.form.splitDirection` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it set the pane orientation of a split form, and the split form renderer retired in the same release, so no form draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitSize** | `never` | optional | [REMOVED] `view.form.splitSize` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it sized the primary pane of a `type: 'split'` form, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **splitResizable** | `never` | optional | [REMOVED] `view.form.splitResizable` was removed in @objectstack/spec 18.3.0 (ADR-0050) — it made the panes of a `type: 'split'` form resizable, and `split` left the form view `type` in the same release, so no form view draws panes. Delete the key. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerSide** | `never` | optional | [REMOVED] `view.form.drawerSide` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it. Delete the key: an object's list opens a record in its drawer from the hover icon, and the React `ObjectForm` block keeps its own `drawerSide` prop for the drawer it opens with `formType='drawer'`. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **drawerWidth** | `never` | optional | [REMOVED] `view.form.drawerWidth` was removed in @objectstack/spec 18.3.0 (ADR-0049) — no form view opens in a drawer, so no form view ever read it, and a pixel width cannot be chosen without knowing the client viewport. Delete the key: a list's record drawer takes its starting width from the `navigation.size` bucket, and the React `ObjectForm` block keeps its own `drawerWidth` prop for the drawer it opens. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **modalSize** | `never` | optional | [REMOVED] `view.form.modalSize` was removed in @objectstack/spec 19.0.0 (ADR-0049) — no form view opens in a dialog, so nothing reads it from a form view. Delete the key: the console's New and Edit dialogs lay a record out by the object's `fieldGroups` and choose their own size, a form opened by name gets a page of its own, and the React `ObjectForm` block keeps its own `modalSize` prop for the modal it opens with `formType='modal'`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | -| **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | -| **sections** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | | -| **groups** | `{ name?: string; label?: string \| Record; description?: string; collapsible?: boolean; … }[]` | optional | [LEGACY ALIAS → `sections`] Accepted for back-compat and folded onto `sections` at parse; `sections` wins when both are present. Prefer `sections`. | -| **subforms** | `{ childObject: string; relationshipField?: string; columns?: object[]; amountField?: string; … }[]` | optional | Inline master-detail child collections | -| **sharing** | `{ enabled?: boolean; publicLink?: string; password?: string; allowedDomains?: string[]; … }` | optional | Public sharing configuration for this form | -| **submitBehavior** | `{ kind: 'thank-you'; title?: string; message?: string } \| { kind: 'redirect'; url: string; delayMs?: integer } \| { kind: 'continue' } \| { kind: 'next-record' }` | optional | Post-submit behavior. On the `redirect` arm, `url` is relative-only and interpolates only declared record fields as `{{record.field_name}}`, URL-escaped. | -| **buttons** | `{ submit?: object; cancel?: object }` | optional | Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm. | -| **defaults** | `Record` | optional | Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values;). | - ### Nested Shape: `GetUiViewResponse.protection` | Property | Type | Required | Description | @@ -1184,3 +1128,247 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' --- +## PublishPackageDraftsResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | True only when every pending draft promoted (`failed` empty) AND at least one item published. A pre-flight refusal or an ADR-0067 D2 rollback answers false on a 200 — but so does a publish with nothing to promote, so false alone is NOT a refusal: read `outcome`, not this boolean or the HTTP status. Always equal to `outcome === 'published'` (pinned), so it is also false on `published_unregistered`, where the drafts landed but an object is not served. It does NOT cover the best-effort receipts below, each of which reports its own `success`. | +| **outcome** | `Enum<'published' \| 'published_unregistered' \| 'refused' \| 'nothing_to_publish'>` | ✅ | First-class discriminant for WHICH exit answered — the fact `success` compresses into one boolean. `published`: at least one draft promoted, none refused, and the runtime registry took every promoted object. `published_unregistered`: the drafts landed exactly as on `published` — the metadata is live and stays live — but the runtime registry refused at least one promoted object, so that object is not served: until something registers it, data reads, writes and seed loads against it answer OBJECT_NOT_FOUND. `unregistered[]` names each such object; do not seed or read it before it is registered (publish it again, or restart). `refused`: the batch was refused — a pre-flight violation or the ADR-0067 D2 all-or-nothing rollback; the per-item story is in `failed[]`, which is non-empty exactly on this outcome (the invariant consumers previously had to reverse-engineer, now stated by the producer). `nothing_to_publish`: the package had no pending drafts — nothing landed AND nothing was refused; `success` stays false (a no-op is not a successful publish), which before this field made that answer indistinguishable from a refusal. Producer invariants, pinned in the conformance suites: `success === (outcome === 'published')`; `refused` if and only if `failed.length > 0`; `nothing_to_publish` if and only if `published.length === 0 && failed.length === 0`; `published_unregistered` if and only if `unregistered` is present. Values are lowercase snake, matching the `sys_metadata_audit` outcome vocabulary. | +| **publishedCount** | `integer` | ✅ | Number of drafts promoted to active — `published.length`. 0 on every refusal path (the batch is all-or-nothing, ADR-0067 D2). | +| **failedCount** | `integer` | ✅ | Number of items that did not publish — `failed.length`. On a rollback this counts the WHOLE batch: the causal item plus every sibling marked BATCH_ABORTED. | +| **published** | `{ type: string; name: string; version: string; advisories?: object[] }[]` | ✅ | Every draft promoted to active, in publish order. Empty on every refusal path. | +| **failed** | `{ type: string; name: string; error: string; code?: string; … }[]` | ✅ | Items that did not publish. Because the batch is all-or-nothing (ADR-0067 D2), a non-empty list means NOTHING landed: `published: []`, `publishedCount: 0`. | +| **unregistered** | `{ type: string; name: string; rule: Enum<'object-registry-refused'> }[]` | optional | Present ONLY on `outcome: 'published_unregistered'`, and then non-empty: each promoted object the runtime registry refused, in publish order. Every entry also appears in `published[]` — its metadata IS live, nothing was rolled back (ADR-0067 D2 runs the registration after the metadata commit) — but the object is not served until something registers it, so a caller about to seed or read it should publish it again or restart first. Absent on every other outcome; an empty array is never emitted. | +| **seedApplied** | `{ success: boolean; inserted?: integer; updated?: integer; error?: string; … }` | optional | Aggregate outcome of materializing EVERY published `seed` body in one multi-pass loader run (cross-seed references need the whole set). Present ONLY when the batch published at least one seed. Two producers, one key: the batch itself self-applies (`applySeedBodies`), and the REST door back-fills the same key for custom protocols that do not — never both (an externalId-less seed would double-insert). Best-effort: a seed problem is surfaced here, never thrown. | +| **materializeApplied** | `{ success: boolean; inserted: integer; updated: integer; failures: object[] }` | optional | ADR-0086 P2 — aggregate result of publish-time materializers across the batch (e.g. `flow`, whose draft credentials become the live ones), including side-effect failures surfaced by the per-item effects loop. Present ONLY when at least one published item had a registered materializer or a side-effect failure. Best-effort, same contract as `seedApplied`. | +| **probes** | `{ issues: object[]; checked: object }` | optional | ADR-0038 L3 post-publish runtime probe report — one real read per published artifact (seeded objects have rows, views are readable, widget dataset selections execute and return data, an object's own field-name lists resolve). `issues[]` carries the findings, each with the agent-facing `message` / `fix` and the `userMessage` sentence for the person who published; `checked` counts the probes that ran per plane. Present only when something was publishable; probes never fail the publish. | +| **commitId** | `string` | optional | ADR-0067 — id of the commit this publish recorded. Absent when nothing published. | +| **backfillApplied** | `{ success: boolean; fields: object[] }` | optional | The opt-in `backfill` request key's receipt: the literal `defaultValue` of each named field this publish added, written into the object's existing rows whose value is absent, page by page, as the caller (permissions, RLS/FLS and record hooks apply as on their own edit). Present ONLY when the request named at least one field and the batch published; absent means nothing was asked. A request that names a field this publish does not add, or one without a literal default, is refused with a 400 before anything is published, so this key never reports a refusal. | +| **unhiddenApps** | `string[]` | optional | ADR-0045 §3 — names of the apps whose `_unpublished` gate this publish cleared (publish = live AND visible; a materialized additive build has no drafts, only this flip). Attached by the REST door, not the protocol helper. Present ONLY when at least one app flipped — on a mid-loop failure it names the apps that DID persist, beside `unhideError` ('s split report). Spelling is a permanent wire contract (see the door's note). | +| **unhideError** | `string` | optional | Present when the ADR-0045 visibility flip failed (wholly or partway): the drafts ARE published, but apps still stored `_unpublished: true` stay externally unobservable. Client-facing text only — undeclared driver text is withheld per ADR-0112; the full cause is in the server log. The route is idempotent: re-run it once the cause is resolved. | +| **rebindError** | `string` | optional | Present when the post-publish `metadata:reloaded` announce failed: everything is published and stored, but boot-cached consumers keep the pre-publish view until re-run or restart (a newly published record-triggered flow does not bind its trigger). Client-facing text only, same ADR-0112 withhold as `unhideError`. | + +### Nested Shape: `PublishPackageDraftsResponse.published[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the promoted draft (canonical singular). | +| **name** | `string` | ✅ | Item name of the promoted draft. | +| **version** | `string` | ✅ | Version token of the promoted row — the same keyed ADR-0008 optimistic-concurrency token the single-item doors return: echo it back as `If-Match` on the next write to this item. A keyed digest of the stored content hash, never the hash itself. Opaque to callers; currently `hmac-sha256:` plus 64 hex characters, but the format is not part of this contract. | +| **advisories** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | Non-gating findings the runtime authoring gate raised against THIS draft's promotion (the same element shape and the same omitted-when-empty discipline as `PublishMetaItemResponseSchema.advisories`, riding each element rather than a parallel top-level map). Present ONLY when at least one finding was raised — an empty array is never emitted, so an advisory-free batch's response bytes are unchanged. Advisory by construction: every entry is `warning`/`info`, because an `error` finding refuses the promotion and — the batch being all-or-nothing — aborts the whole batch as `failed[]` instead; `failed[]` elements never carry this key. | + +### Nested Shape: `PublishPackageDraftsResponse.failed[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the item that did not publish. | +| **name** | `string` | ✅ | Item name. | +| **error** | `string` | ✅ | What refused it. On a rollback, the causal item carries its real error and every sibling carries the all-or-nothing explanation. A refusal that produced structured findings states a one-sentence HEADLINE here (what failed, where, which rules, how many); the per-path detail rides `issues[]` instead of being restated in this string (consumers rendering both channels were showing every finding twice). | +| **code** | `string` | optional | Machine code for the refusal class (SCREAMING_SNAKE, ADR-0112 vocabulary) — e.g. a pre-flight violation code, or BATCH_ABORTED on the non-causal items of a rolled-back batch. | +| **issues** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | The structured findings behind the refusal, when the refusing error carried them — today the author-time gate's INVALID_METADATA refusal on the causal item. The producer has emitted this key; declaring it is what lets a typed consumer read it back, and what lets `error` stay a headline without losing the per-path detail. Same element shape as `published[].advisories` and the single-item 422's `issues[]` (— one dialect, declared once). Present ONLY on the causal item and only when the refusal produced structured findings; BATCH_ABORTED siblings never carry it. Absent means "this refusal carried no structured findings", never "no problems". | + +### Nested Shape: `PublishPackageDraftsResponse.unregistered[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the published item the registry refused (`object`). | +| **name** | `string` | ✅ | Name of the object that is published but not served. | +| **rule** | `Enum<'object-registry-refused'>` | ✅ | Why it is not served, as a stable rule id: the same id as the warning on this object's `published[]` element, whose `message` and `hint` say what happened and how to fix it. | + +### Nested Shape: `PublishPackageDraftsResponse.seedApplied` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | False when the seed rows did not fully land. The publish itself still succeeded — check this rather than assuming data went live. | +| **inserted** | `integer` | optional | Rows created by the externalId-keyed upsert. Optional ONLY because the route-level fallback producer (custom protocols that do not self-apply) reports early failures without counters; the in-batch producer always emits both counters. | +| **updated** | `integer` | optional | Rows updated by the externalId-keyed upsert. Same optionality rationale as `inserted`. | +| **error** | `string` | optional | Single failure message, present when the apply failed before the loader ran (including "no readable seed bodies"). When the failure is the seed bodies' own schema refusal, this is a one-sentence headline and the per-path detail rides `issues[]`. | +| **errors** | `any[]` | optional | Per-record failures reported by the seed loader, plus any seed-body read failures. May be present and empty on a clean load. | +| **issues** | `{ path: string; message: string; code?: string }[]` | optional | Structured spec-validation findings behind `error`, present when the apply was refused by the seed bodies' own schema — the declared 422 `seedRequestValidationError` mints. The per-path detail lives HERE, once; `error` stays a one-sentence headline. Absent on non-validation failures (driver faults, unreadable bodies), whose whole story is `error` / `errors[]`. | +| **landed** | `{ object: string; inserted: object; matched: object }[]` | optional | Per object, the stored rows the seed landed on: `inserted` (created by this publish) and `matched` (pre-existing rows a seed key matched), each capped at `SEED_APPLIED_LANDED_IDS_CAP` (200) ids with `total` and `truncated` stating any cut. One entry per object the loader ran, empty lists included. When the load threw part-way (`success: false` with `error`), it lists only the datasets that FINISHED before the throw, and is EMPTY when none had; the dataset that threw is not listed (its rows are in the counts, its object in `error`). ABSENT means "not reported" — the apply failed before any load ran (see `error`), or the producer reports no ids — never "no rows landed". | + +### Nested Shape: `PublishPackageDraftsResponse.materializeApplied` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | False when any item's materializer failed; the publish still succeeded. | +| **inserted** | `integer` | ✅ | Data-plane rows created across the batch. | +| **updated** | `integer` | ✅ | Data-plane rows updated across the batch. | +| **failures** | `{ type: string; name: string; error: string }[]` | ✅ | Each item whose data-plane projection did NOT land — named per-item, unlike the single-item door's scalar `error`, because one aggregate boolean over N items would hide WHICH ones never went live. | + +### Nested Shape: `PublishPackageDraftsResponse.probes` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **issues** | `{ layer: 'runtime'; severity: Enum<'error' \| 'warning'>; artifact: object; ref?: object; … }[]` | ✅ | The findings, in probe order (seeds, views, objects, dashboard widgets). Empty when every probe passed. | +| **checked** | `{ seeds: integer; views: integer; widgets: integer; objects: integer }` | ✅ | How many probes actually ran, per plane. A 0 means nothing of that kind was probed, never that something was probed and passed: read it beside `issues`, so that "no object was inspected" and "every object was clean" are different numbers. | + +### Nested Shape: `PublishPackageDraftsResponse.backfillApplied` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | False when any field stopped short (its entry carries `error`). The publish itself still succeeded and is not undone. | +| **fields** | `{ object: string; field: string; updated: integer; error?: string; … }[]` | ✅ | One element per requested field, in request order. | + + +--- + +## RealtimeConnectRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **transport** | `Enum<'websocket' \| 'sse' \| 'polling'>` | optional | Preferred transport protocol | +| **channels** | `string[]` | optional | Channels to subscribe to on connect | +| **token** | `string` | optional | Authentication token | + + +--- + +## RealtimeConnectResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **connectionId** | `string` | ✅ | Unique connection identifier | +| **transport** | `Enum<'websocket' \| 'sse' \| 'polling'>` | ✅ | Negotiated transport protocol | +| **url** | `string` | optional | WebSocket/SSE endpoint URL | + + +--- + +## RealtimeDisconnectRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **connectionId** | `string` | optional | Connection ID to disconnect | + + +--- + +## RealtimeDisconnectResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | Whether disconnection succeeded | + + +--- + +## RealtimeSubscribeRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **channel** | `string` | ✅ | Channel name to subscribe to | +| **events** | `string[]` | optional | Specific event types to listen for | +| **filter** | `Record` | optional | Event filter criteria | + + +--- + +## RealtimeSubscribeResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **subscriptionId** | `string` | ✅ | Unique subscription identifier | +| **channel** | `string` | ✅ | Subscribed channel name | + + +--- + +## RealtimeUnsubscribeRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **subscriptionId** | `string` | ✅ | Subscription ID to cancel | + + +--- + +## RealtimeUnsubscribeResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | Whether unsubscription succeeded | + + +--- + +## RegisterDeviceRequest + +Register or refresh a push device for the signed-in user + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **token** | `string` | ✅ | Device push notification token | +| **platform** | `Enum<'ios' \| 'android' \| 'web'>` | ✅ | Device platform | +| **deviceId** | `string` | optional | Client-held device id, stable per app install. Re-registering the same deviceId refreshes that device; absent, the server mints one and answers it, and the client keeps it for later registrations and unregister | +| **name** | `string` | optional | Device friendly name | +| **vendor** | `Enum<'apns' \| 'fcm'>` | optional | Push vendor the token belongs to: apns or fcm. Absent, the server derives it from platform: ios means apns, android means fcm. web has no default vendor: a web registration names apns or fcm, and one without vendor is refused | +| **appId** | `string` | optional | App the token was issued to: the iOS bundle ID or the Android application ID | +| **locale** | `string` | optional | Device locale (BCP 47, for example zh-CN). Stored on the device row; no push renders by it: a push arrives in the recipient's language (sys_user.locale, then the deployment default) | +| **origin** | `string` | optional | The origin the Console was loaded from (window.location.origin, for example https://crm.example.com): the address the mobile shell saved for this server. The Console writes it; the server stores it on the device row and every push to the device carries it back, so a shell with several saved servers opens the push on the one that sent it. http or https, a lowercase host and an optional port; a path, another scheme or a bare host is refused | + + +--- + +## RegisterDeviceResponse + +Answer to a device registration: the device id the client keeps + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **deviceId** | `string` | ✅ | Registered device ID | +| **success** | `boolean` | ✅ | Whether registration succeeded | + + +--- + +## RejectAiPendingActionResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **status** | `'rejected'` | ✅ | Always "rejected" | +| **id** | `string` | ✅ | The rejected action id | + + +--- + +## RollbackMetaItemRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type name | +| **name** | `string` | ✅ | Item name | +| **toVersion** | `integer` | ✅ | The history version whose body is restored as the new live row: a whole number of at least 1, as the history lists it. The rollback door reads this declaration and refuses anything else `400`. | +| **message** | `string` | optional | Rollback note, recorded on the new history row. | +| **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder, except where the read naming no package serves the row-held base (a bundled type's member of a name no package ships in code, whose active rows a base package and one or more packages declaring it hold, with no package-unbound row beside them): there the base's slot is addressed, as naming the base addresses it. Two packages neither of which declares the other are still refused. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | + + +--- + diff --git a/packages/spec/docs/references/api/protocol.part-3.md b/packages/spec/docs/references/api/protocol.part-3.md index 2ba9f948afe..a085e7ddee6 100644 --- a/packages/spec/docs/references/api/protocol.part-3.md +++ b/packages/spec/docs/references/api/protocol.part-3.md @@ -4,250 +4,6 @@ > Part 3 of [Protocol schema — API Protocol reference](protocol.md), which lists every part. ---- - -## PublishPackageDraftsResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | True only when every pending draft promoted (`failed` empty) AND at least one item published. A pre-flight refusal or an ADR-0067 D2 rollback answers false on a 200 — but so does a publish with nothing to promote, so false alone is NOT a refusal: read `outcome`, not this boolean or the HTTP status. Always equal to `outcome === 'published'` (pinned), so it is also false on `published_unregistered`, where the drafts landed but an object is not served. It does NOT cover the best-effort receipts below, each of which reports its own `success`. | -| **outcome** | `Enum<'published' \| 'published_unregistered' \| 'refused' \| 'nothing_to_publish'>` | ✅ | First-class discriminant for WHICH exit answered — the fact `success` compresses into one boolean. `published`: at least one draft promoted, none refused, and the runtime registry took every promoted object. `published_unregistered`: the drafts landed exactly as on `published` — the metadata is live and stays live — but the runtime registry refused at least one promoted object, so that object is not served: until something registers it, data reads, writes and seed loads against it answer OBJECT_NOT_FOUND. `unregistered[]` names each such object; do not seed or read it before it is registered (publish it again, or restart). `refused`: the batch was refused — a pre-flight violation or the ADR-0067 D2 all-or-nothing rollback; the per-item story is in `failed[]`, which is non-empty exactly on this outcome (the invariant consumers previously had to reverse-engineer, now stated by the producer). `nothing_to_publish`: the package had no pending drafts — nothing landed AND nothing was refused; `success` stays false (a no-op is not a successful publish), which before this field made that answer indistinguishable from a refusal. Producer invariants, pinned in the conformance suites: `success === (outcome === 'published')`; `refused` if and only if `failed.length > 0`; `nothing_to_publish` if and only if `published.length === 0 && failed.length === 0`; `published_unregistered` if and only if `unregistered` is present. Values are lowercase snake, matching the `sys_metadata_audit` outcome vocabulary. | -| **publishedCount** | `integer` | ✅ | Number of drafts promoted to active — `published.length`. 0 on every refusal path (the batch is all-or-nothing, ADR-0067 D2). | -| **failedCount** | `integer` | ✅ | Number of items that did not publish — `failed.length`. On a rollback this counts the WHOLE batch: the causal item plus every sibling marked BATCH_ABORTED. | -| **published** | `{ type: string; name: string; version: string; advisories?: object[] }[]` | ✅ | Every draft promoted to active, in publish order. Empty on every refusal path. | -| **failed** | `{ type: string; name: string; error: string; code?: string; … }[]` | ✅ | Items that did not publish. Because the batch is all-or-nothing (ADR-0067 D2), a non-empty list means NOTHING landed: `published: []`, `publishedCount: 0`. | -| **unregistered** | `{ type: string; name: string; rule: Enum<'object-registry-refused'> }[]` | optional | Present ONLY on `outcome: 'published_unregistered'`, and then non-empty: each promoted object the runtime registry refused, in publish order. Every entry also appears in `published[]` — its metadata IS live, nothing was rolled back (ADR-0067 D2 runs the registration after the metadata commit) — but the object is not served until something registers it, so a caller about to seed or read it should publish it again or restart first. Absent on every other outcome; an empty array is never emitted. | -| **seedApplied** | `{ success: boolean; inserted?: integer; updated?: integer; error?: string; … }` | optional | Aggregate outcome of materializing EVERY published `seed` body in one multi-pass loader run (cross-seed references need the whole set). Present ONLY when the batch published at least one seed. Two producers, one key: the batch itself self-applies (`applySeedBodies`), and the REST door back-fills the same key for custom protocols that do not — never both (an externalId-less seed would double-insert). Best-effort: a seed problem is surfaced here, never thrown. | -| **materializeApplied** | `{ success: boolean; inserted: integer; updated: integer; failures: object[] }` | optional | ADR-0086 P2 — aggregate result of publish-time materializers across the batch (e.g. `flow`, whose draft credentials become the live ones), including side-effect failures surfaced by the per-item effects loop. Present ONLY when at least one published item had a registered materializer or a side-effect failure. Best-effort, same contract as `seedApplied`. | -| **probes** | `{ issues: object[]; checked: object }` | optional | ADR-0038 L3 post-publish runtime probe report — one real read per published artifact (seeded objects have rows, views are readable, widget dataset selections execute and return data, an object's own field-name lists resolve). `issues[]` carries the findings, each with the agent-facing `message` / `fix` and the `userMessage` sentence for the person who published; `checked` counts the probes that ran per plane. Present only when something was publishable; probes never fail the publish. | -| **commitId** | `string` | optional | ADR-0067 — id of the commit this publish recorded. Absent when nothing published. | -| **backfillApplied** | `{ success: boolean; fields: object[] }` | optional | The opt-in `backfill` request key's receipt: the literal `defaultValue` of each named field this publish added, written into the object's existing rows whose value is absent, page by page, as the caller (permissions, RLS/FLS and record hooks apply as on their own edit). Present ONLY when the request named at least one field and the batch published; absent means nothing was asked. A request that names a field this publish does not add, or one without a literal default, is refused with a 400 before anything is published, so this key never reports a refusal. | -| **unhiddenApps** | `string[]` | optional | ADR-0045 §3 — names of the apps whose `_unpublished` gate this publish cleared (publish = live AND visible; a materialized additive build has no drafts, only this flip). Attached by the REST door, not the protocol helper. Present ONLY when at least one app flipped — on a mid-loop failure it names the apps that DID persist, beside `unhideError` ('s split report). Spelling is a permanent wire contract (see the door's note). | -| **unhideError** | `string` | optional | Present when the ADR-0045 visibility flip failed (wholly or partway): the drafts ARE published, but apps still stored `_unpublished: true` stay externally unobservable. Client-facing text only — undeclared driver text is withheld per ADR-0112; the full cause is in the server log. The route is idempotent: re-run it once the cause is resolved. | -| **rebindError** | `string` | optional | Present when the post-publish `metadata:reloaded` announce failed: everything is published and stored, but boot-cached consumers keep the pre-publish view until re-run or restart (a newly published record-triggered flow does not bind its trigger). Client-facing text only, same ADR-0112 withhold as `unhideError`. | - -### Nested Shape: `PublishPackageDraftsResponse.published[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of the promoted draft (canonical singular). | -| **name** | `string` | ✅ | Item name of the promoted draft. | -| **version** | `string` | ✅ | Version token of the promoted row — the same keyed ADR-0008 optimistic-concurrency token the single-item doors return: echo it back as `If-Match` on the next write to this item. A keyed digest of the stored content hash, never the hash itself. Opaque to callers; currently `hmac-sha256:` plus 64 hex characters, but the format is not part of this contract. | -| **advisories** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | Non-gating findings the runtime authoring gate raised against THIS draft's promotion (the same element shape and the same omitted-when-empty discipline as `PublishMetaItemResponseSchema.advisories`, riding each element rather than a parallel top-level map). Present ONLY when at least one finding was raised — an empty array is never emitted, so an advisory-free batch's response bytes are unchanged. Advisory by construction: every entry is `warning`/`info`, because an `error` finding refuses the promotion and — the batch being all-or-nothing — aborts the whole batch as `failed[]` instead; `failed[]` elements never carry this key. | - -### Nested Shape: `PublishPackageDraftsResponse.failed[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of the item that did not publish. | -| **name** | `string` | ✅ | Item name. | -| **error** | `string` | ✅ | What refused it. On a rollback, the causal item carries its real error and every sibling carries the all-or-nothing explanation. A refusal that produced structured findings states a one-sentence HEADLINE here (what failed, where, which rules, how many); the per-path detail rides `issues[]` instead of being restated in this string (consumers rendering both channels were showing every finding twice). | -| **code** | `string` | optional | Machine code for the refusal class (SCREAMING_SNAKE, ADR-0112 vocabulary) — e.g. a pre-flight violation code, or BATCH_ABORTED on the non-causal items of a rolled-back batch. | -| **issues** | `{ rule: string; path: string; where: string; message: string; … }[]` | optional | The structured findings behind the refusal, when the refusing error carried them — today the author-time gate's INVALID_METADATA refusal on the causal item. The producer has emitted this key; declaring it is what lets a typed consumer read it back, and what lets `error` stay a headline without losing the per-path detail. Same element shape as `published[].advisories` and the single-item 422's `issues[]` (— one dialect, declared once). Present ONLY on the causal item and only when the refusal produced structured findings; BATCH_ABORTED siblings never carry it. Absent means "this refusal carried no structured findings", never "no problems". | - -### Nested Shape: `PublishPackageDraftsResponse.unregistered[number]` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type of the published item the registry refused (`object`). | -| **name** | `string` | ✅ | Name of the object that is published but not served. | -| **rule** | `Enum<'object-registry-refused'>` | ✅ | Why it is not served, as a stable rule id: the same id as the warning on this object's `published[]` element, whose `message` and `hint` say what happened and how to fix it. | - -### Nested Shape: `PublishPackageDraftsResponse.seedApplied` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | False when the seed rows did not fully land. The publish itself still succeeded — check this rather than assuming data went live. | -| **inserted** | `integer` | optional | Rows created by the externalId-keyed upsert. Optional ONLY because the route-level fallback producer (custom protocols that do not self-apply) reports early failures without counters; the in-batch producer always emits both counters. | -| **updated** | `integer` | optional | Rows updated by the externalId-keyed upsert. Same optionality rationale as `inserted`. | -| **error** | `string` | optional | Single failure message, present when the apply failed before the loader ran (including "no readable seed bodies"). When the failure is the seed bodies' own schema refusal, this is a one-sentence headline and the per-path detail rides `issues[]`. | -| **errors** | `any[]` | optional | Per-record failures reported by the seed loader, plus any seed-body read failures. May be present and empty on a clean load. | -| **issues** | `{ path: string; message: string; code?: string }[]` | optional | Structured spec-validation findings behind `error`, present when the apply was refused by the seed bodies' own schema — the declared 422 `seedRequestValidationError` mints. The per-path detail lives HERE, once; `error` stays a one-sentence headline. Absent on non-validation failures (driver faults, unreadable bodies), whose whole story is `error` / `errors[]`. | -| **landed** | `{ object: string; inserted: object; matched: object }[]` | optional | Per object, the stored rows the seed landed on: `inserted` (created by this publish) and `matched` (pre-existing rows a seed key matched), each capped at `SEED_APPLIED_LANDED_IDS_CAP` (200) ids with `total` and `truncated` stating any cut. One entry per object the loader ran, empty lists included. When the load threw part-way (`success: false` with `error`), it lists only the datasets that FINISHED before the throw, and is EMPTY when none had; the dataset that threw is not listed (its rows are in the counts, its object in `error`). ABSENT means "not reported" — the apply failed before any load ran (see `error`), or the producer reports no ids — never "no rows landed". | - -### Nested Shape: `PublishPackageDraftsResponse.materializeApplied` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | False when any item's materializer failed; the publish still succeeded. | -| **inserted** | `integer` | ✅ | Data-plane rows created across the batch. | -| **updated** | `integer` | ✅ | Data-plane rows updated across the batch. | -| **failures** | `{ type: string; name: string; error: string }[]` | ✅ | Each item whose data-plane projection did NOT land — named per-item, unlike the single-item door's scalar `error`, because one aggregate boolean over N items would hide WHICH ones never went live. | - -### Nested Shape: `PublishPackageDraftsResponse.probes` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **issues** | `{ layer: 'runtime'; severity: Enum<'error' \| 'warning'>; artifact: object; ref?: object; … }[]` | ✅ | The findings, in probe order (seeds, views, objects, dashboard widgets). Empty when every probe passed. | -| **checked** | `{ seeds: integer; views: integer; widgets: integer; objects: integer }` | ✅ | How many probes actually ran, per plane. A 0 means nothing of that kind was probed, never that something was probed and passed: read it beside `issues`, so that "no object was inspected" and "every object was clean" are different numbers. | - -### Nested Shape: `PublishPackageDraftsResponse.backfillApplied` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | False when any field stopped short (its entry carries `error`). The publish itself still succeeded and is not undone. | -| **fields** | `{ object: string; field: string; updated: integer; error?: string; … }[]` | ✅ | One element per requested field, in request order. | - - ---- - -## RealtimeConnectRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **transport** | `Enum<'websocket' \| 'sse' \| 'polling'>` | optional | Preferred transport protocol | -| **channels** | `string[]` | optional | Channels to subscribe to on connect | -| **token** | `string` | optional | Authentication token | - - ---- - -## RealtimeConnectResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **connectionId** | `string` | ✅ | Unique connection identifier | -| **transport** | `Enum<'websocket' \| 'sse' \| 'polling'>` | ✅ | Negotiated transport protocol | -| **url** | `string` | optional | WebSocket/SSE endpoint URL | - - ---- - -## RealtimeDisconnectRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **connectionId** | `string` | optional | Connection ID to disconnect | - - ---- - -## RealtimeDisconnectResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | Whether disconnection succeeded | - - ---- - -## RealtimeSubscribeRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **channel** | `string` | ✅ | Channel name to subscribe to | -| **events** | `string[]` | optional | Specific event types to listen for | -| **filter** | `Record` | optional | Event filter criteria | - - ---- - -## RealtimeSubscribeResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **subscriptionId** | `string` | ✅ | Unique subscription identifier | -| **channel** | `string` | ✅ | Subscribed channel name | - - ---- - -## RealtimeUnsubscribeRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **subscriptionId** | `string` | ✅ | Subscription ID to cancel | - - ---- - -## RealtimeUnsubscribeResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **success** | `boolean` | ✅ | Whether unsubscription succeeded | - - ---- - -## RegisterDeviceRequest - -Register or refresh a push device for the signed-in user - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **token** | `string` | ✅ | Device push notification token | -| **platform** | `Enum<'ios' \| 'android' \| 'web'>` | ✅ | Device platform | -| **deviceId** | `string` | optional | Client-held device id, stable per app install. Re-registering the same deviceId refreshes that device; absent, the server mints one and answers it, and the client keeps it for later registrations and unregister | -| **name** | `string` | optional | Device friendly name | -| **vendor** | `Enum<'apns' \| 'fcm'>` | optional | Push vendor the token belongs to: apns or fcm. Absent, the server derives it from platform: ios means apns, android means fcm. web has no default vendor: a web registration names apns or fcm, and one without vendor is refused | -| **appId** | `string` | optional | App the token was issued to: the iOS bundle ID or the Android application ID | -| **locale** | `string` | optional | Device locale (BCP 47, for example zh-CN). Stored on the device row; no push renders by it: a push arrives in the recipient's language (sys_user.locale, then the deployment default) | -| **origin** | `string` | optional | The origin the Console was loaded from (window.location.origin, for example https://crm.example.com): the address the mobile shell saved for this server. The Console writes it; the server stores it on the device row and every push to the device carries it back, so a shell with several saved servers opens the push on the one that sent it. http or https, a lowercase host and an optional port; a path, another scheme or a bare host is refused | - - ---- - -## RegisterDeviceResponse - -Answer to a device registration: the device id the client keeps - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **deviceId** | `string` | ✅ | Registered device ID | -| **success** | `boolean` | ✅ | Whether registration succeeded | - - ---- - -## RejectAiPendingActionResponse - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **status** | `'rejected'` | ✅ | Always "rejected" | -| **id** | `string` | ✅ | The rejected action id | - - ---- - -## RollbackMetaItemRequest - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | Metadata type name | -| **name** | `string` | ✅ | Item name | -| **toVersion** | `integer` | ✅ | The history version whose body is restored as the new live row: a whole number of at least 1, as the history lists it. The rollback door reads this declaration and refuses anything else `400`. | -| **message** | `string` | optional | Rollback note, recorded on the new history row. | -| **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | -| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder, except where the read naming no package serves the row-held base (a bundled type's member of a name no package ships in code, whose active rows a base package and one or more packages declaring it hold, with no package-unbound row beside them): there the base's slot is addressed, as naming the base addresses it. Two packages neither of which declares the other are still refused. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | - - --- ## RollbackMetaItemResponse diff --git a/packages/spec/docs/references/system/translation.md b/packages/spec/docs/references/system/translation.md index e24a4358521..58712ea1155 100644 --- a/packages/spec/docs/references/system/translation.md +++ b/packages/spec/docs/references/system/translation.md @@ -88,7 +88,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | @@ -115,8 +115,8 @@ Translation data for a single field | :--- | :--- | :--- | :--- | | **label** | `string` | optional | Translated view label | | **description** | `string` | optional | Translated view description | -| **title** | `string` | optional | Translated form view title — overlays a form view's own `title` (`FormViewSchema.title`); only a form that authors one is translated | -| **submitBehavior** | `{ title?: string; message?: string }` | optional | Translated thank-you panel copy — overlays a form view's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'`; only copy the form authors is translated | +| **title** | `never` | optional | [REMOVED] `translation.objects.OBJECT._views.KEY.title` was removed in @objectstack/spec 19.0.0 (ADR-0159 D8) — a form is a `form` item, and no view carries a heading. Move the string to `forms['OBJECT.KEY'].title`, the address the translator reads a form's heading from. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **submitBehavior** | `never` | optional | [REMOVED] `translation.objects.OBJECT._views.KEY.submitBehavior` was removed in @objectstack/spec 19.0.0 (ADR-0159 D8) — a form is a `form` item, and no view has a thank-you panel. Move the `title` and `message` to `forms['OBJECT.KEY'].submitBehavior`, the address the translator reads a form's panel from. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **emptyState** | `{ title?: string; message?: string }` | optional | Translated empty-state copy shown when the view has no rows | | **bulkActions** | `Record }>` | optional | Selection-bar translations keyed by bulk-action def name (`BulkActionDefSchema.name`) | @@ -221,7 +221,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | @@ -432,7 +432,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | @@ -706,7 +706,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | @@ -949,7 +949,7 @@ Translation data for a single object | **pluralLabel** | `string` | optional | Translated plural label | | **description** | `string` | optional | Translated object description | | **fields** | `Record; … }>` | optional | Field-level translations | -| **_views** | `Record` | optional | View translations keyed by view name | +| **_views** | `Record }>` | optional | View translations keyed by view name | | **_actions** | `Record` | optional | Action translations keyed by action name | | **_sections** | `Record }>` | optional | Section translations keyed by section name | | **_tabs** | `Record` | optional | Filter-preset tab translations keyed by tab name | diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index eb97e8de57f..4f0ac8131fd 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -3,7 +3,7 @@ "measured": { "zod": "4.4.3", "publishedSchemasWithDroppedRefinements": 284, - "droppedRefinementSites": 1262, + "droppedRefinementSites": 1242, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -249,7 +249,6 @@ "manifest.translations.element.valueType.flows.valueType.screens.valueType.description", "manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "manifest.translations.element.valueType.flows.valueType.successMessage", - "manifest.views.element.form", "manifest.views.element.list", "manifest.views.element.list.bulkActionDefs.element", "manifest.views.element.list.emptyState.link.url", @@ -448,7 +447,6 @@ "data.options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.description", "data.options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "data.options[1].manifest.translations.element.valueType.flows.valueType.successMessage", - "data.options[1].manifest.views.element.form", "data.options[1].manifest.views.element.list", "data.options[1].manifest.views.element.list.bulkActionDefs.element", "data.options[1].manifest.views.element.list.emptyState.link.url", @@ -502,10 +500,6 @@ }, "api/GetUiViewResponse": { "sites": [ - "form", - "form.sections.element", - "form.subforms.element.columns.element", - "form.submitBehavior.options[1].url", "list", "list.bulkActionDefs.element", "list.emptyState.link.url", @@ -634,7 +628,6 @@ "options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.description", "options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "options[1].manifest.translations.element.valueType.flows.valueType.successMessage", - "options[1].manifest.views.element.form", "options[1].manifest.views.element.list", "options[1].manifest.views.element.list.bulkActionDefs.element", "options[1].manifest.views.element.list.emptyState.link.url", @@ -744,7 +737,6 @@ "data.packages.element.options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.description", "data.packages.element.options[1].manifest.translations.element.valueType.flows.valueType.screens.valueType.title", "data.packages.element.options[1].manifest.translations.element.valueType.flows.valueType.successMessage", - "data.packages.element.options[1].manifest.views.element.form", "data.packages.element.options[1].manifest.views.element.list", "data.packages.element.options[1].manifest.views.element.list.bulkActionDefs.element", "data.packages.element.options[1].manifest.views.element.list.emptyState.link.url", @@ -2315,10 +2307,6 @@ }, "ui/View": { "sites": [ - "form", - "form.sections.element", - "form.subforms.element.columns.element", - "form.submitBehavior.options[1].url", "list", "list.bulkActionDefs.element", "list.emptyState.link.url", @@ -2356,11 +2344,7 @@ "options[0].config.gantt.groupByField", "options[0].config.grouping.fields.element.field", "options[0].config.kanban.groupByField", - "options[0].config.timeline.groupByField", - "options[1].config", - "options[1].config.sections.element", - "options[1].config.subforms.element.columns.element", - "options[1].config.submitBehavior.options[1].url" + "options[0].config.timeline.groupByField" ] }, "ui/ViewItemWire": { @@ -2373,11 +2357,7 @@ "options[0].config.gantt.groupByField", "options[0].config.grouping.fields.element.field", "options[0].config.kanban.groupByField", - "options[0].config.timeline.groupByField", - "options[1].config", - "options[1].config.sections.element", - "options[1].config.subforms.element.columns.element", - "options[1].config.submitBehavior.options[1].url" + "options[0].config.timeline.groupByField" ] }, "ui/ViewTab": { diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index f218331770b..e68495b75a7 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -575,6 +575,7 @@ "GetTranslationsRequestSchema": "src/api/protocol.zod.ts#GetTranslationsRequestSchema (const)", "GetTranslationsResponse": "src/api/protocol.zod.ts#GetTranslationsResponse (type)", "GetTranslationsResponseSchema": "src/api/protocol.zod.ts#GetTranslationsResponseSchema (const)", + "GetUiViewFormScaffold": "src/api/protocol.zod.ts#GetUiViewFormScaffold (type)", "GetUiViewRequest": "src/api/protocol.zod.ts#GetUiViewRequest (type)", "GetUiViewRequestSchema": "src/api/protocol.zod.ts#GetUiViewRequestSchema (const)", "GetUiViewResponse": "src/api/protocol.zod.ts#GetUiViewResponse (type)", diff --git a/packages/spec/export-origins/root.json b/packages/spec/export-origins/root.json index 14a1c341671..e853c4b68da 100644 --- a/packages/spec/export-origins/root.json +++ b/packages/spec/export-origins/root.json @@ -130,6 +130,7 @@ "STACK_DEFINITION_KEYS": "src/stack.zod.ts#STACK_DEFINITION_KEYS (const)", "STACK_KEY_GUIDANCE": "src/data/authoring-key-lint.ts#STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS": "src/data/authoring-key-lint.ts#STACK_RUNTIME_MEMBERS (const)", + "ServedViewItem": "src/ui/view.zod.ts#ServedViewItem (type)", "Skill": "src/ai/skill.zod.ts#Skill (type)", "StackDefinitionKey": "src/stack.zod.ts#StackDefinitionKey (type)", "StoredConversionOptions": "src/conversions/stored.ts#StoredConversionOptions (type)", @@ -176,6 +177,7 @@ "defineViewItem": "src/ui/view.zod.ts#defineViewItem (function)", "defineWebhook": "src/automation/webhook.zod.ts#defineWebhook (function)", "deriveViewContainerObject": "src/ui/view-container-object.ts#deriveViewContainerObject (function)", + "expandServedViewContainer": "src/ui/view.zod.ts#expandServedViewContainer (function)", "expandViewContainer": "src/ui/view.zod.ts#expandViewContainer (function)", "expandViewContainerWithDiagnostics": "src/ui/view.zod.ts#expandViewContainerWithDiagnostics (function)", "expression": "src/shared/expression.zod.ts#expression (function)", @@ -187,6 +189,7 @@ "hasStackProvenance": "src/stack-provenance.ts#hasStackProvenance (function)", "isAggregatedViewContainer": "src/ui/view.zod.ts#isAggregatedViewContainer (function)", "isKnownPlatformCapability": "src/kernel/platform-capabilities.ts#isKnownPlatformCapability (function)", + "isServedViewItem": "src/ui/view.zod.ts#isServedViewItem (function)", "isViewContainerShaped": "src/ui/assembled-views.zod.ts#isViewContainerShaped (function)", "lintUnknownAuthoringKeys": "src/kernel/metadata-authoring-lint.ts#lintUnknownAuthoringKeys (function)", "lintUnknownKeysAgainstSchema": "src/kernel/metadata-authoring-lint.ts#lintUnknownKeysAgainstSchema (function)", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index 8cb354427ed..af3e866500e 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -460,6 +460,7 @@ "SelectionConfig": "src/ui/view.zod.ts#SelectionConfig (type)", "SelectionConfigParsed": "src/ui/view.zod.ts#SelectionConfigParsed (type)", "SelectionConfigSchema": "src/ui/view.zod.ts#SelectionConfigSchema (const)", + "ServedViewItem": "src/ui/view.zod.ts#ServedViewItem (type)", "SharingConfig": "src/ui/sharing.zod.ts#SharingConfig (type)", "SharingConfigParsed": "src/ui/sharing.zod.ts#SharingConfigParsed (type)", "SharingConfigSchema": "src/ui/sharing.zod.ts#SharingConfigSchema (const)", @@ -593,6 +594,7 @@ "deriveColumnSummary": "src/ui/view-grouping-query.ts#deriveColumnSummary (function)", "deriveViewContainerObject": "src/ui/view-container-object.ts#deriveViewContainerObject (function)", "diagnoseViewMetadata": "src/ui/view.zod.ts#diagnoseViewMetadata (function)", + "expandServedViewContainer": "src/ui/view.zod.ts#expandServedViewContainer (function)", "expandViewContainer": "src/ui/view.zod.ts#expandViewContainer (function)", "expandViewContainerWithDiagnostics": "src/ui/view.zod.ts#expandViewContainerWithDiagnostics (function)", "expressionBindableTextKeysFor": "src/ui/expression-bindable-text-keys.zod.ts#expressionBindableTextKeysFor (function)", @@ -605,6 +607,7 @@ "isExpressionBindableTextKey": "src/ui/expression-bindable-text-keys.zod.ts#isExpressionBindableTextKey (function)", "isKnownComponentType": "src/ui/component-type-vocabulary.ts#isKnownComponentType (function)", "isRecordContextBlockType": "src/ui/react-blocks.ts#isRecordContextBlockType (function)", + "isServedViewItem": "src/ui/view.zod.ts#isServedViewItem (function)", "isViewContainerShaped": "src/ui/assembled-views.zod.ts#isViewContainerShaped (function)", "isViewFilterOrGroup": "src/ui/view.zod.ts#isViewFilterOrGroup (function)", "listViewGroupKeyPredicate": "src/ui/view-grouping-query.ts#listViewGroupKeyPredicate (function)", diff --git a/packages/spec/liveness/README.md b/packages/spec/liveness/README.md index 62a83bb31de..62929099bce 100644 --- a/packages/spec/liveness/README.md +++ b/packages/spec/liveness/README.md @@ -995,7 +995,7 @@ marker where the Notes cell goes, never a guess at what belongs there. | skill | `permissions` REMOVED 2026-07 (#3704); `triggerPhrases` REMOVED 2026-07-30 (#3896 close-out sweep — phrases were never matched; activation is `triggerConditions` + the agent's `skills[]` + /skill-name pinning) | | dataset | `measures.certified` (declared-but-unenforced governance flag) REMOVED in 16.0 (#2377) | | page | live, plus the one dead tombstone below. The `print` declaration (#22158, 2026-10-08: the container, its eight keys and the four `margins` sides) was declared spec-first by card ① of the #8346 ruling (B′) — its REFUSALS live (the parse's `checkPagePrintComposition`, lint's `validatePrintPageBlocks`), its keys `planned` with `authorWarn` on the container — and flipped `live` 2026-10-16 (#23710) once card ②, the console's print rendering, reached the `.objectui-sha` pin: `PageRenderer` mounts objectui's `buildPagePrintStylesheet`, which reads every key. `authorWarn` went with the flip, so an author who writes `print` is no longer told the layout is not applied. Its earlier `planned` row, `requires`, flipped `live` 2026-10-02 (#20871): the save door refuses an html page whose written list disagrees with its source and stores the derived one, and boot hydration reports a stored page whose list names a plugin the deployment's SDUI manifest does not carry. Dead `assignedProfiles` REMOVED 2026-09-12 (ADR-0090 D2 + ADR-0049 — a per-page audience list named for the concept D2 deleted, with zero readers in either repo, so the page was open to everyone who could reach it). The row stays because `retiredKey` keeps the key in the walked shape (the `rls.priority` precedent). Its prior `live` verdict is the #12516 class twice over: the objectui bridge it cited never existed (lit control — two sibling objectui citations in the same file resolve), and the entry carried no `verifiedAt`, so nothing ever re-asked | -| view | list/form drilled via `children` (#2998 Track B); list.{responsive,performance} + form.{defaultSort,aria} REMOVED 2026-07-30 (#3896 close-out sweep — list aria/data stay live); **form.data was that sweep's one CORRECTION** — the removal attempt broke the build (`defineMetadataForm` writes `data.provider='schema'` onto every metadata form, `metadata-protocol` serves it), so it stands `live` with re-verified evidence; form.{buttons,defaults} live (framework#1894 / #2998); audit-era DEAD lines superseded by re-verification. **The dead set is six, not the four removals above**: #4534 (the last #4001 batch, batch 6e) declared three CONTAINER-level keys this row had never classified — `name` and `label`, both `dead`, and `object`, `live`. All three are properties of the `views: [...]` *container*, not of a view: `name` is dead because authoring it changes nothing — an authored value restates the key the container already registers under or contradicts it — and `label` is container display metadata with no reader. Neither is `authorWarn`'d and both are deliberately KEPT — the metadata door itself stamps the save name into every saved view body (`normalizeViewMetadata`) and its overlay paths key on that copy, so tombstoning `name` would reject the platform's own saves (re-measured 2026-10-02, #20301 stage 2: the earlier attribution to artifact-shipped containers and the metadata-validation sweep was the door's stamp misread; neither carries one). `object` is the container's object binding, and it was *stripped on every parse* until #4534 declared it. Separately, the level-2 dead residue (userActions.buttons, tabs[].order; addRecord.mode/formView until their #24692 removal) is noted on parents and is **not** in the counts — one drill level only **#9340**: `list.map` declared — the eighth visualization block (`ListMapConfigSchema`), keys mirroring objectui plugin-map's documented read set. FLIPPED `planned` → `live` 2026-08-24 (#11442): objectui#5908 landed `resolveListMapConfig`, which merges the view-level `map` block over the legacy `options.map` bag before `ListView.tsx`'s `case 'map'` forwards it into `ObjectMap`, with the same merged config also feeding the visualization-switcher's capability gate so a view binding coordinates only in the spec block is no longer filtered out of `allowedVisualizations` either (objectui#5042) **#22611** (2026-10-10): `list.requiredPermissions` is this type's only `planned` row (the `list.map` precedent above flipped `live`) — the audience gate (a list of capabilities, all required), declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier). The warning reaches a container's `list` only: the lint flattens one level of `children`, so a named `listViews` entry is not walked, and the key's describe carries the not-enforced clause for that door | +| view | list drilled via `children` (#2998 Track B; `form` was drilled the same way until its tombstone, the last note of this row); list.{responsive,performance} + form.{defaultSort,aria} REMOVED 2026-07-30 (#3896 close-out sweep — list aria/data stay live); **form.data was that sweep's one CORRECTION** — the removal attempt broke the build (`defineMetadataForm` writes `data.provider='schema'` onto every metadata form, `metadata-protocol` serves it), so it stands `live` with re-verified evidence; form.{buttons,defaults} live (framework#1894 / #2998); audit-era DEAD lines superseded by re-verification. **The dead set is six, not the four removals above**: #4534 (the last #4001 batch, batch 6e) declared three CONTAINER-level keys this row had never classified — `name` and `label`, both `dead`, and `object`, `live`. All three are properties of the `views: [...]` *container*, not of a view: `name` is dead because authoring it changes nothing — an authored value restates the key the container already registers under or contradicts it — and `label` is container display metadata with no reader. Neither is `authorWarn`'d and both are deliberately KEPT — the metadata door itself stamps the save name into every saved view body (`normalizeViewMetadata`) and its overlay paths key on that copy, so tombstoning `name` would reject the platform's own saves (re-measured 2026-10-02, #20301 stage 2: the earlier attribution to artifact-shipped containers and the metadata-validation sweep was the door's stamp misread; neither carries one). `object` is the container's object binding, and it was *stripped on every parse* until #4534 declared it. Separately, the level-2 dead residue (userActions.buttons, tabs[].order; addRecord.mode/formView until their #24692 removal) is noted on parents and is **not** in the counts — one drill level only **#9340**: `list.map` declared — the eighth visualization block (`ListMapConfigSchema`), keys mirroring objectui plugin-map's documented read set. FLIPPED `planned` → `live` 2026-08-24 (#11442): objectui#5908 landed `resolveListMapConfig`, which merges the view-level `map` block over the legacy `options.map` bag before `ListView.tsx`'s `case 'map'` forwards it into `ObjectMap`, with the same merged config also feeding the visualization-switcher's capability gate so a view binding coordinates only in the spec block is no longer filtered out of `allowedVisualizations` either (objectui#5042) **#22611** (2026-10-10): `list.requiredPermissions` is this type's only `planned` row (the `list.map` precedent above flipped `live`) — the audience gate (a list of capabilities, all required), declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier). The warning reaches a container's `list` only: the lint flattens one level of `children`, so a named `listViews` entry is not walked, and the key's describe carries the not-enforced clause for that door **ADR-0159 D7** (2026-12-01): `form` and `formViews` are tombstones in protocol 19, because a form is its own metadata type (`form`, under the stack's `forms:`) and a `view` holds lists only. Both rows are `dead` and stay, since `retiredKey` keeps each key in the walked shape; `form`'s drilled `children` left this ledger with the container (the walk does not drill a tombstone), so every `form.*` sentence above is the record of what those rows said and no longer names a row here. A form's keys are classified in the `form` row's ledger, which was seeded from those rows. `viewKind: 'form'` left as a VALUE (`enumWithRetiredValues`), so it adds no row and no `RETIRED_KEYS_BY_MAJOR` entry | | report | dataset-bound (ADR-0021); the aria/performance LEDGER entries were stale — the keys left the schema in the report-liveness close-out; deleted 2026-07-30 as hygiene. Audit-era `chart` DEAD superseded (framework#1890 / #3441) — live on non-joined reports only: a `joined` report's container `chart` is refused and `blocks[].chart` was removed (#20161, 2026-09-27; nothing drew either) | | dashboard | ADR-0021 dataset widgets (#3251; DashboardWidgetSchema `.strict()`); `aria`/`performance` (and widget `performance` + PerformanceConfigSchema) REMOVED 2026-07-30 (#3896 close-out sweep — no renderer applied any of them); audit-era `globalFilters`/`dateRange` DEAD superseded (framework#2501) **#4956**: `widgets` DRILLED — the row jumps 20 → 41 classified because all 22 widget-level keys enter the count at once. They had never been classified at all: the entry carried one blanket `live` plus a `note` asserting they were classified "in the DashboardWidgetSchema subtree", and no such subtree existed in any of the 28 ledger files. That gap, not any evidence, is what carried `widgets[].responsive` through the #3896 sweep that removed both its sibling `widgets[].performance` and its literal namesake `view.responsive` — `view` is drilled, so `list.responsive` got asked and went out. New dead 6 = `responsive` (retired #4876/#4995, tombstone keeps the row) + `colorVariant` + `actionUrl`/`actionType`/`actionIcon` + `aria`. The action trio is the sharpest: no renderer draws a per-widget action button at all (every `actionUrl` read in DashboardRenderer is scoped to `header.actions[]`), yet `validate-dashboard-action-refs.ts` enforces reference integrity on it and its docblock calls it "the per-widget button" — a lint guarding an affordance that does not exist. `requiresService` is the counter-example worth remembering: dead by every objectui measurement, and LIVE server-side (`filterDashboardForUser`, ADR-0057 D10) — judging a widget key from the renderer repo alone would have retired an enforced gate. `compareTo` is `live` on ONE path only (inline object-provider charts); on the ADR-0021 dataset path the string arms are dropped and `{ offset }` throws in the executor. **#6774** moves the row 33/8 → 34/7: `colorVariant` CORRECTED dead → live 2026-08-09, the enforce leg of #5010 ruling B landing from the renderer side (objectui#3359 / PR objectui#3799, absorbed by pin `09987b68`). Worth reading beside `requiresService` above, because it is the same lesson from the other end — that row warns against judging a widget key from the renderer repo alone, and this one is a `dead` verdict that was correct in this repo AND correct in the renderer repo on the day it was measured, and stopped being either when a cross-repo decision was implemented. A ledger row is a claim with a timestamp; `verifiedAt` is what makes the claim re-askable. It also empties the dashboard warn set, so the author-side lint now says nothing about any widget key — `dashboard` stays in the lint's TYPE_COLLECTIONS all the same (the `webhook`/`email_template` resolved state). **#17385** DRILLS `widgets.chartConfig` — 14 per-key verdicts where the row had carried one blanket `live`, re-measured against `.objectui-sha` pin `53ded82bf7a4`: 12 live (the nine chrome keys `chartConfigPresentation` lowers, plus `xAxis`/`yAxis`/`series`, whose PRESENTATION merges onto the derived bindings while `ChartAxis.field` and `ChartSeries.name` are dropped so membership stays with the dataset) and dead 2 — `type`, which parses and does nothing because the widget's own `type` owns the chart family, and `aria`, which has no reader on either face. Both are pinned as NEGATIVES in objectui, which is what makes them re-askable rather than merely asserted. ⚠️ The drill made SIX containers one level further down visible for the first time (`xAxis`/`yAxis`/`series`/`annotations`/`interaction`/`aria`, 39 child keys); they are RECORDED, not drilled — fanning this row's verdicts down over them would manufacture verdicts, and the evidence work is a separate measurement. Note the cell's previous last stated position (`34/7`) had already drifted one `dead` behind the generated artifact before this change; the counts columns are generated and are the authority **#22611** (2026-10-10): `requiredPermissions` is this type's only `planned` row — the audience gate (a list of capabilities, all required) shared word for word with the list view's, declared spec-first under the ruling of record 6095014058, letter A, with `authorWarn` and an `authorHint` because no server reads it until the `/meta` read gate applies it (#22639, the carrier) | | query | **not a metadata type** — the REQUEST surface (`QuerySchema`: client SDK QueryBuilder output; the `POST /data/:object/query` body), governed via `SPEC_ONLY_SCHEMAS` (#4286). The gate resolves 1 experimental at the depth this ledger drills; the 7 marker-experimental search affordances sit one level deeper, below what this ledger declares (the walk recurses since #17424, but only where a `children` map is written, and none is written here) — resolved from `[EXPERIMENTAL — not enforced]` describe markers, not ledger entries (search `fuzzy`/`operator`/`boost`/`minScore`/`language`/`highlight` + `aggregations[].filter` — declared engine affordances no executor receives). The #4286 sweep closed out same-release: `having` ENFORCED 2026-07-31 (engine-side post-aggregation filter, both paths; was finding 1); dead 4 = the tombstoned removals `joins`/`windowFunctions`/`cursor`/`distinct` — REMOVED 2026-07-31 (retiredKey keeps each in the walked shape so the rows stay; protocol-17 semantic migrations; the JoinNode + WindowFunctionNode clusters and the `QueryBuilder.cursor()`/`.distinct()` producers deleted with their keys; `distinct`'s mis-wired REST count suppression deleted too — finding 2). **#6815** adds the 5th dead: `aggregations[].distinct` REMOVED 2026-08-09 (live → dead, `-1` live). It is the one member of this ledger the #4286 sweep could not have caught with the question it asked — that sweep looked for keys NO executor reads, and this one had a reader: the objectql in-memory fallback deduplicated before applying the function while all five other faces (driver-sql, driver-turso, driver-mongodb, driver-memory, service-analytics' `AGGREGATE_SQL`) ignored it, so one query answered two plausible NUMBERS depending on which backend served it. The lesson for the next audit is the question, not the key: a per-key `live` verdict is only as good as the count of faces it was measured across, and this row's 2026-07-31 evidence (`in-memory-aggregation.ts:167,204-206`) was TRUE and still the wrong verdict. `count_distinct` is the surviving spelling (enforce leg, #6409) | @@ -1009,7 +1009,7 @@ marker where the Notes cell goes, never a guess at what belongs there. | mapping | seeded 2026-08-01 (#4488) at 8/11 live; **0 dead since #4509** retired the three that were not. The import half (#2611) is loudly enforced — unsupported transforms/formats are 400s, `mode`/`upsertKey` default the request, the wizard picker renders `label`. RETIRED 17.0.0: `extractQuery` (authorWarn — "for export only" promised an export path no exporter implements) + `errorPolicy`/`batchSize`, which were dead AND **unwarnable** (schema defaults materialize at parse, so presence ≠ authored — `_authorWarnSkipped`, the non-boolean instance of the default(true) rule). That unwarnability is why they went out in the 17.0.0 window rather than after a deprecation cycle: removal was the only channel that could ever reach the author. Rows DELETED, not tombstoned — MappingSchema is strict, so the keys left the walked shape. `connectorSource` (2026-09-30) is this type's first `planned` row: the pull binding the connector-attached sync family MOVED here when the connector's `syncConfig` / `fieldMappings` retired to tombstones, seeded contract-first with `authorWarn` (its seven drilled rows — five children and `watermark`'s two — `planned` with it) because the pull executor is the next stage. **Live since 2026-10-01 (#20919)**: the connector sync executor reads every key. The container's `authorWarn` left with that re-grade (#21127) — kept at first, it made the author-side lint throw, so `os validate` / `os lint` exited 1 on every stack that authored the binding; the caveat it carried (nothing schedules a pull until the `job` stage lands) is on the key's description | | picklist | seeded 2026-09-30 (#19518) with every key `planned`, ahead of its runtime reader by ruling; **live since the runtime layer (#19519)**: the ObjectQL registry merges `picklistExtensions` into the list (additive only, a repeated value refused) and resolves it onto every field that names it, the write door judges against that set, and a field naming an undeclared list fails the boot. `field.picklist` left `authorWarn` with it. Display keys (`label`, `description`, `options.color`) are graded by their served form. | | seed | seeded 2026-08-01 (#4488). Fully live via SeedLoaderService on both doors (boot/per-org replay + runtime-draft publish). `records` is the z.record walk boundary: the keys an author writes are the target object's fields, governed by that object's own definitions — recorded in the entry, not silently skipped | -| translation | seeded 2026-08-01 (#4488) — after fixing the walker: the registered schema is a z.preprocess pipe (#3778 retired-dialect guard) whose transform side the unwrap always took, so the type was literally unwalkable. 11 of 12 groups live across spec resolvers, REST localization, objectui client resolvers and plugin-audit (whose composed-key `t()` calls make `messages` easy to mis-verify as dead) — `flows` was the one that was not, and was `planned` at seeding. **#14253** added the twelfth, `datasets`, seeded LIVE and DRILLED (label / description / dimensions / measures) with its reader in the same change: `translateDataset` in the dispatch table, which is what `TRANSLATABLE_METADATA_TYPES` is derived from, so the REST boundary followed with nothing else to remember. The same change gave `objects.._views..bulkActions` and `objects.._validations..message` their first keys — both beneath the walk boundary, so neither adds a row here. Dead 1 = `validationMessages` (authorWarn) at seeding: nothing resolved it, and #3778's own legacy-key migration table steered `errors:` authors into it — a shipped false signpost, the capabilities.readOnly shape. **#4667**: `validationMessages` REMOVED (row deleted) — removed from the shared translationDataShape(), so it retired at BOTH doors at once, closing the item-only asymmetry #3778's original guard had. #3778's own `errors` guidance was rewritten in the same change: it had been steering authors INTO this dead group. ⚠️ **What that left behind is this table's own worked example of the defect it warns about** (#7377): the same commit that deleted the `validationMessages` row wrote a count column of `dead 2` beside a sentence that named exactly one dead key — and that one was the key it had just removed. The real two were `name` and `label`, which the cell never mentioned. Measured at that commit, not inferred: the ledger's dead set there is `{name, label}` and `validationMessages` is absent from `props`. The number was right and the prose was false, in the same cell, on the day it was written — which is why the counts are now generated and this cell holds prose only. **#7131** (PR #7425) resolves it: `name` and `label` re-grade `dead` → `live` under the designer-previews-count-as-consumers ruling (objectui `TranslationPreview.tsx:67` reads `label` first and falls back to `name`, both rendering at `:100`), so the dead set is empty and there is no dead-set sentence left to keep true. As on `job`, the ADR-0033 docs-shaped exemption is untouched — nothing about enforce-or-remove moved. **#19620** (ruling batch #210 item 2 letter B): `settings` row DELETED — the strict-delete route, because `TranslationItemSchema` no longer declares the key and refuses it by name (the item door now takes the per-app face, as the file door has since #15178). ⚠️ The deleted row read `live`, and that verdict was TRUE and stays true of the platform: its evidence read the SERVED tree, which the platform bundle feeds, so the deletion retires the key from the application-authored item and nothing else — the capability lives on `PlatformTranslationDataSchema`, outside this ledger. **#20296**: `flows` is now half-read. `flows.screens` re-graded `planned` → `live`: objectui's FlowRunner reads each screen's `title` and each field's `label` / `placeholder` at the `.objectui-sha` pin f8a9d0fb. `flows.label` stays `planned` because nothing reads it yet (#20318), and so does the container's `authorWarn`, whose `authorHint` now names the read half and the unread one. **#23710**: the terminal toasts `flows.successMessage` / `flows.errorMessage` (child rows added `planned` by #22507) re-graded `live`: objectui's `translatedFlowMessage` asks `translateFlow` for both at the `.objectui-sha` pin daeb77fc84dd. **#24979**: `flows.approvals` and its one drilled key `label` (added `planned` as the spec half of #24863) re-graded `live`: plugin-approvals' `reader-locale-labels.ts` (commit ba69b168be) serves an approval request's step label from `flows..approvals..label` in the reader's locale, falling back to the stored snapshot, so the type's planned set is empty. | +| translation | seeded 2026-08-01 (#4488) — after fixing the walker: the registered schema is a z.preprocess pipe (#3778 retired-dialect guard) whose transform side the unwrap always took, so the type was literally unwalkable. 11 of 12 groups live across spec resolvers, REST localization, objectui client resolvers and plugin-audit (whose composed-key `t()` calls make `messages` easy to mis-verify as dead) — `flows` was the one that was not, and was `planned` at seeding. **#14253** added the twelfth, `datasets`, seeded LIVE and DRILLED (label / description / dimensions / measures) with its reader in the same change: `translateDataset` in the dispatch table, which is what `TRANSLATABLE_METADATA_TYPES` is derived from, so the REST boundary followed with nothing else to remember. The same change gave `objects.._views..bulkActions` and `objects.._validations..message` their first keys — both beneath the walk boundary, so neither adds a row here. Dead 1 = `validationMessages` (authorWarn) at seeding: nothing resolved it, and #3778's own legacy-key migration table steered `errors:` authors into it — a shipped false signpost, the capabilities.readOnly shape. **#4667**: `validationMessages` REMOVED (row deleted) — removed from the shared translationDataShape(), so it retired at BOTH doors at once, closing the item-only asymmetry #3778's original guard had. #3778's own `errors` guidance was rewritten in the same change: it had been steering authors INTO this dead group. ⚠️ **What that left behind is this table's own worked example of the defect it warns about** (#7377): the same commit that deleted the `validationMessages` row wrote a count column of `dead 2` beside a sentence that named exactly one dead key — and that one was the key it had just removed. The real two were `name` and `label`, which the cell never mentioned. Measured at that commit, not inferred: the ledger's dead set there is `{name, label}` and `validationMessages` is absent from `props`. The number was right and the prose was false, in the same cell, on the day it was written — which is why the counts are now generated and this cell holds prose only. **#7131** (PR #7425) resolves it: `name` and `label` re-grade `dead` → `live` under the designer-previews-count-as-consumers ruling (objectui `TranslationPreview.tsx:67` reads `label` first and falls back to `name`, both rendering at `:100`), so the dead set is empty and there is no dead-set sentence left to keep true. As on `job`, the ADR-0033 docs-shaped exemption is untouched — nothing about enforce-or-remove moved. **#19620** (ruling batch #210 item 2 letter B): `settings` row DELETED — the strict-delete route, because `TranslationItemSchema` no longer declares the key and refuses it by name (the item door now takes the per-app face, as the file door has since #15178). ⚠️ The deleted row read `live`, and that verdict was TRUE and stays true of the platform: its evidence read the SERVED tree, which the platform bundle feeds, so the deletion retires the key from the application-authored item and nothing else — the capability lives on `PlatformTranslationDataSchema`, outside this ledger. **#20296**: `flows` is now half-read. `flows.screens` re-graded `planned` → `live`: objectui's FlowRunner reads each screen's `title` and each field's `label` / `placeholder` at the `.objectui-sha` pin f8a9d0fb. `flows.label` stays `planned` because nothing reads it yet (#20318), and so does the container's `authorWarn`, whose `authorHint` now names the read half and the unread one. **#23710**: the terminal toasts `flows.successMessage` / `flows.errorMessage` (child rows added `planned` by #22507) re-graded `live`: objectui's `translatedFlowMessage` asks `translateFlow` for both at the `.objectui-sha` pin daeb77fc84dd. **#24979**: `flows.approvals` and its one drilled key `label` (added `planned` as the spec half of #24863) re-graded `live`: plugin-approvals' `reader-locale-labels.ts` (commit ba69b168be) serves an approval request's step label from `flows..approvals..label` in the reader's locale, falling back to the stored snapshot, so the type's planned set is empty. **ADR-0159 D8** (2026-12-01): the two form tails under a view's translations, `objects.._views..title` and `.submitBehavior`, are tombstones in protocol 19 (a form's heading and thank-you panel are `forms..title` / `.submitBehavior`, and the translator's fallback read of the tails left with them). Both sit beneath the walk boundary, like the `_views` keys #14253 added, so neither adds a row here; the `forms` row carries the record | | qa | seeded 2026-08-10 (#6247) — **not a metadata type**: `TestSuiteSchema` is the FILE surface of the shipped `os test` command (`qa/*.test.json`), governed through the same `SPEC_ONLY_SCHEMAS` override as `query`/`webhook`/`validation`. It is in the table as the clearest worked example of a **false `dead` measurement**: #6247 reported the whole domain declared-but-inert on a grep that scanned only `*Schema` identifiers, and every consumer here reads the **type** names (`QA.TestSuite`, `QA.TestStep`, `QA.TestAction`) — so an entire execution chain (core's `TestRunner` + `HttpTestAdapter`, published via `export * as QA`, driven by a documented CLI command) read as zero consumers, and a retire ruling was issued on it before being withdrawn. The `evidenceScope` table one section up says no amount of specifier matching is sufficient for a negative claim; this is the same lesson for **identifier** matching. What was really wrong was narrower and real: the type was the contract and the schema had no `parse` site, so the CLI's `JSON.parse(content) as QA.TestSuite` cast admitted anything — ENFORCED in the same change (`TestSuiteSchema.safeParse` at the load site, pinned). The seeding recorded Dead 5 — `name`, `scenarios.name`, `scenarios.description`, `scenarios.tags` and `scenarios.requires` — and #20289 (family `qa-runner`, verdict ENFORCE) made all FIVE live: the suite `name` heads the suite in `os test`'s report and is stamped as `suiteName` on every TestResult the suite produces; `scenarios.name` is printed beside the id and carried as `scenarioName`; `scenarios.description` is carried and printed under a failed scenario; `scenarios.tags` is read by `os test --tags` (any-of, exact; deselected scenarios are counted and never passed); and `scenarios.requires` is judged by the TestRunner before a scenario's first step — `params` against the environment of the process running `os test`, `services` against the target's discovery `services` (enabled and `available`) — so an unmet entry SKIPS the scenario with its reason, counted apart and never passed. `requires` was put to the maintainer first rather than guessed (ruled B): over HTTP no server surface lists the loaded plugins, so `requires.plugins` is a `retiredKey()` tombstone inside the block whose prescription names `requires.services`. It does not carry `authorWarn` and the omission is deliberate (`_authorWarnSkipped`): the lint walks stack **collections**, a QA suite is a loose file in no stack, so a warn flag here would emit nothing — a silent no-op inside the mechanism built to catch silent no-ops | | validation | seeded 2026-08-01 (#4488). The ADR-0020 carrier: the evaluator honors active/events/priority/severity/type/condition/message (the zod header's "only reads type/condition/…" prose is STALE — trust the ledger). Dead 3 = label/description/tags, declared governance metadata, kept unmarked. Union walk boundary recorded: only base + `script` keys walked; per-variant keys are governed by the evaluator's tests, not ledger rows. **No longer a registered metadata kind** — #4509 retired it under ADR-0088 (a standalone rule had no object-binding key and every variant is `.strict()`, so it bound to nothing and gated no write; a state machine authored that way saved cleanly and did nothing). The rule VOCABULARY is untouched and fully live via `object.validations[]`, so the ledger keeps governing it through the gate's spec-only override, alongside `webhook` and `query`. The contrast with the two bridges in the same batch is the point: enforce-or-remove picked ENFORCE where the feature existed and only the wiring was missing, and REMOVE where the shape itself could not carry the feature | | api | seeded 2026-08-04 (#5271, part of #5206; PR #5312) — **not a metadata type until that same change made it one**, which is the row's point: governance and registration landed together, the treatment `datasource` did not get (#4487) and paid for with six inert keys found by hand. What #5206 measured before the fix: `api` was in neither `DEFAULT_METADATA_TYPE_REGISTRY` nor `BUILTIN_METADATA_TYPE_SCHEMAS`, so `saveMetaItem`'s `resolveOverlaySchema('api', …)` → `getMetadataTypeSchema('api')` returned `undefined` and took its own documented branch — an unregistered type is stored **unvalidated** — while `getMetaTypes()` could not enumerate the type at all, so Studio rendered neither list nor form. That issue names the shape precisely and it is the inverse of this ledger's usual one: **enforced but undeclared** (the matcher was already indexing these entries, #5089), where `dead` is declared-but-unenforced. The seeding pass classified 27 keys — live 25 / planned 2 / dead 0 — each cited `file:line` at the consumer layer that reads it: the MATCHER (`packages/metadata/src/endpoint-matcher.ts`) indexes `name`/`path`/`method`; the EXECUTOR (`packages/runtime/src/endpoint-executor.ts`) dispatches on `type` and reads `target`/`objectParams`; the POLICY chain (`packages/runtime/src/endpoint-policy.ts` + `security/inbound-rate-limit.ts`) enforces `authRequired`/`rateLimit`/`cacheTtl`; the MAPPING layer (`packages/runtime/src/api-mapping.ts`) applies `inputMapping`/`outputMapping`; and OpenAPI enrichment (`packages/rest/src/openapi-endpoints.ts`) emits `summary`/`description`. Timing was the reason it was cheap: #5040's E-series had built every one of those consumers and all of it was on main, so each key had a real evidence path rather than a promise. **Planned 2 = `inputMapping.transform` + `outputMapping.transform`, and `planned` rather than `dead` is load-bearing**: `dead` here means parsed with no consumer — a silent no-op — and these are the opposite, parsed and then LOUDLY REFUSED at publish (`endpoint-publish-gate.ts` mappingGate) and again at runtime, because no transformation-function registry exists anywhere in the platform. An author who writes one is told so and told what to do instead, so there is nothing for enforce-or-remove to chase; they stay in the vocabulary because admitting them needs a function registry **and** a sandbox ruling (#5040 §3.4), which is a design decision, not a key to quietly delete. Zero dead | @@ -1028,7 +1028,7 @@ marker where the Notes cell goes, never a guess at what belongs there. | assignment_rule | seeded 2026-10-26 with the type itself (#25769, ADR-0142 D5): registered governed. Declared only — organization-authored rules are deferred (ADR-0142 merge question 11) — and read on every insert by the engine's `AssignmentRuleEvaluator`, after every `beforeInsert` hook, for a row whose `owner_id` and `queue` are both still empty. All rows `live`, and `entries.assignTo` is drilled (`type`, `value`) rather than inherited. `name` and `entries.name` key the round-robin cursor (`sys_assignment_cursor`, per rule, entry and organization), so a rename restarts a rotation; `object` gates evaluation to objects carrying the platform `queue` column; `entries.load` is the `least_loaded` count predicate, required with that strategy and refused otherwise. `kernel:ready` refuses a stack that declares rules or queues with no `ownership-queue` service registered, so no row is inert by a missing service. | | template_manifest | seeded 2026-11-06 with the marketplace taxonomy, through `SPEC_ONLY_SCHEMAS` (the sixth category: a package-listing file surface — `objectstack.manifest.json`, read by `os package publish` and create-objectstack, never by a boot). The facet keys `businessFunctions` / `industries` / `maturity` are `planned`: the CLI judges and forwards them, and their consumers are the cloud catalog (objectstack-ai/cloud#3661, which drops them until it lands) and the console marketplace card. `solutionType` is `live` through the publish cross-check. `category` is the tombstone. The other `dead` rows are what entering the denominator measured: `name`, `specVersion`, `skills`, `scaffold` and the warned-and-unsent `visibility` were then retired as tombstones (ADR-0049); `publisher` / `isStarter`, which publish named in a warning and did not send but a first-party publish script did, were then retired too (maintainer ruling: a trust claim does not belong in an author-editable file). | | ai_context | seeded 2026-11-25 with the type itself (#37140, ADR-0160 D1): registered governed, never a `PENDING_GOVERNANCE` debt. Every key is read by the one `get_record_context` executor (`@objectstack/service-record-context`), served over the MCP door on HTTP and stdio; `name`, `object`, `fields`, `related.*` and `body.field` are `live` there, and `label` is the answer's pack header. | -| form | seeded 2026-11-26 with the type itself (#37086, ADR-0159 card ②): registered governed, never a `PENDING_GOVERNANCE` debt. `name`, `object` and `label` are the item's own rows, each `live` on the effective `form` read and the anonymous doors. The body rows carry view.json `form.*`'s verdicts, because the body IS `FormViewSchema`'s shape by reference and the doors serve it to the same public renderer an old-shape form reaches; each row says so and names card ③ (#37087) as the re-verification, the card that lets the console open a `form` item from an action. `overrides` is the planned ADR-0146 row every overridable type carries. The ADR-0010 envelope is auto-live (`null`). | +| form | seeded 2026-11-26 with the type itself (#37086, ADR-0159 card ②): registered governed, never a `PENDING_GOVERNANCE` debt. `name`, `object` and `label` are the item's own rows, each `live` on the effective `form` read and the anonymous doors. The body rows were seeded with view.json `form.*`'s verdicts, because the body IS `FormViewSchema`'s shape by reference and the doors serve it to the public renderer an old-shape form reached until protocol 19; each row says so and names card ③ (#37087) as the re-verification, the card that lets the console open a `form` item from an action. **ADR-0159 D7** (2026-12-01): view.json's `form.*` rows left with the container's tombstone, so these rows are the one classification of a form's keys; `columns` and `sections`, which view.json had re-cited after the seed, were brought level before its rows left. `overrides` is the planned ADR-0146 row every overridable type carries. The ADR-0010 envelope is auto-live (`null`). | | knowledge_source | seeded 2026-11-26 with the type itself (#37304, ADR-0161 K4): registered governed, never a `PENDING_GOVERNANCE` debt. Every key that parses is read by the knowledge service (`@objectstack/service-knowledge`), whose loader registers the published items: `name` is the source's slot and index key, `label` / `description` / `aiExposed` are read by `search_knowledge`, `adapter`, `source.*` and `refresh.onRecordChange` by the build, the event sync and the reap guard. The 6 `dead` keys are ADR-0161 K6's tombstones, removed in the same PR: `id`, `source.contentFields`, `adapterConfig`, `embedding`, `vectorStore`, `refresh.cron`. | The `dead` set across types is the enforce-or-remove worklist (ADR-0049); a `dead` diff --git a/packages/spec/liveness/form.json b/packages/spec/liveness/form.json index 883519689ec..2705290d569 100644 --- a/packages/spec/liveness/form.json +++ b/packages/spec/liveness/form.json @@ -1,6 +1,6 @@ { "type": "form", - "_note": "FormSchema (ADR-0159 D2) — the `form` metadata type: `name` (`OBJECT.KEY`), `object`, `label`, a form view's body at the top level (FormViewSchema's keys by reference, less `data`), the override declaration and the ADR-0010 envelope. Seeded 2026-11-26 with the type itself (card ②, #37086). The body rows carry view.json `form.*`'s verdicts, because the body IS that schema and the doors serve it to the same renderer; each says so and names the re-verification card.", + "_note": "FormSchema (ADR-0159 D2) — the `form` metadata type: `name` (`OBJECT.KEY`), `object`, `label`, a form view's body at the top level (FormViewSchema's keys by reference, less `data`), the override declaration and the ADR-0010 envelope. Seeded 2026-11-26 with the type itself (card ②, #37086). The body rows were seeded with view.json `form.*`'s verdicts, because the body IS that schema and the doors serve it to the same renderer; each says so and names the re-verification card. 2026-12-01 (ADR-0159 D7): the view container's `form` and `formViews` are tombstones in protocol 19, so view.json's `form.*` rows left with them and these rows are the one classification of a form's keys. The two rows view.json had re-cited after the seed were brought level the same day, before its rows left: `columns` (re-cited 2026-11-26) and `sections` (re-read 2026-11-27).", "props": { "name": { "status": "live", @@ -23,115 +23,116 @@ "status": "live", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. NARROWED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) to the form's LAYOUT: simple / tabbed / wizard. The key stays live — ui/packages/plugin-form/src/ObjectForm.tsx routes tabbed and wizard to TabbedForm / WizardForm and simple to its own arm; ui/apps/console/src/components/FormPage.tsx forwards it for a named or public form (since #36425 the record create / edit surfaces load no internal form view, so RecordFormPage and the record dialog no longer read it). `split`, `drawer` and `modal` are refused by name (enumWithRetiredValues carries each prescription; a value-level narrowing, so this row stays and no RETIRED_KEYS_BY_MAJOR entry exists for them) and deleted from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which lands the form on the `simple` default. Where a form opens is the caller's open mode. The renderer's split / drawer / modal arms for a form view leave on #27159." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. NARROWED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) to the form's LAYOUT: simple / tabbed / wizard. The key stays live — ui/packages/plugin-form/src/ObjectForm.tsx routes tabbed and wizard to TabbedForm / WizardForm and simple to its own arm; ui/apps/console/src/components/FormPage.tsx forwards it for a named or public form (since #36425 the record create / edit surfaces load no internal form view, so RecordFormPage and the record dialog no longer read it). `split`, `drawer` and `modal` are refused by name (enumWithRetiredValues carries each prescription; a value-level narrowing, so this row stays and no RETIRED_KEYS_BY_MAJOR entry exists for them) and deleted from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which lands the form on the `simple` default. Where a form opens is the caller's open mode. The renderer's split / drawer / modal arms for a form view leave on #27159." }, "layout": { "status": "live", "verifiedAt": "2026-09-27", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui @ f8a9d0fb0: plugin-form ObjectForm.tsx:1408 (simple arm) and :463/:499 (drawer/modal hand-off), DrawerForm.tsx:575, ModalForm.tsx:597 — each reads vertical/horizontal only. The enum was narrowed to those two arms 2026-09-27 (#20221, ADR-0049 enforce-or-remove): every arm folded 'inline' and 'grid' to vertical, so both were a declared value the renderer threw away; multi-column is the sibling `columns` key. The key itself stays live." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui @ f8a9d0fb0: plugin-form ObjectForm.tsx:1408 (simple arm) and :463/:499 (drawer/modal hand-off), DrawerForm.tsx:575, ModalForm.tsx:597 — each reads vertical/horizontal only. The enum was narrowed to those two arms 2026-09-27 (#20221, ADR-0049 enforce-or-remove): every arm folded 'inline' and 'grid' to vertical, so both were a declared value the renderer threw away; multi-column is the sibling `columns` key. The key itself stays live." }, "columns": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:247-258 / DrawerForm.tsx:478 applyAutoLayout column count." + "verifiedAt": "2026-12-01", + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. RE-CITED 2026-11-26 (#37665, ruling A on #37638): the form view's `columns` is the grid width of a sectioned form, capping each section's count; an undeclared section takes it. Reader: ui/apps/console/src/components/FormPage.tsx#buildSections, the named (`/forms/:name`) and public (`/f/:slug`) form page, resolving through ui/packages/plugin-form/src/autoLayout.ts#sectionedGridLayout. RE-CITED 2026-12-01 (ADR-0159 D7): the Setup preview canvas this row also cited, the `view` editor's form canvas (ViewPreview's buildFormPreviewSchema), was removed with the view-held form; the `form` item editor's live preview passes no `columns`, so the console form page is the one reader. The previous ModalForm / DrawerForm citation was stale: those hosts no longer receive a stored form view." }, "title": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:662 / DrawerForm.tsx:528 header; ObjectView form adapter (audit L25)." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:662 / DrawerForm.tsx:528 header; ObjectView form adapter (audit L25)." }, "description": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:662-681 / DrawerForm.tsx:528-558 render it under the title." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ModalForm.tsx:662-681 / DrawerForm.tsx:528-558 render it under the title." }, "defaultTab": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx:185 → tabbed variant." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx:185 → tabbed variant." }, "tabPosition": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx:186 → tabbed variant." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx:186 → tabbed variant." }, "allowSkip": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:397-444 (step navigation gating)." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:397-444 (step navigation gating)." }, "showStepIndicator": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:438." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:438." }, "splitDirection": { "status": "dead", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27159, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which #27159 widened before 18.3.0 shipped. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It oriented the split form's panes. Its form-view reader left with `type: 'split'` on #27155; its last reader, ui/packages/plugin-form/src/SplitForm.tsx behind the React `ObjectForm` block's `formType='split'`, was deleted with that value on #27159 (the `object-form` block's own splitDirection is tombstoned in the same change); nothing to write instead — a `tabbed` form gives each section its own tab." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27159, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which #27159 widened before 18.3.0 shipped. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It oriented the split form's panes. Its form-view reader left with `type: 'split'` on #27155; its last reader, ui/packages/plugin-form/src/SplitForm.tsx behind the React `ObjectForm` block's `formType='split'`, was deleted with that value on #27159 (the `object-form` block's own splitDirection is tombstoned in the same change); nothing to write instead — a `tabbed` form gives each section its own tab." }, "splitSize": { "status": "dead", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It sized the split form's primary pane. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It sized the split form's primary pane. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." }, "splitResizable": { "status": "dead", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It made the split form's panes resizable. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It made the split form's panes resizable. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." }, "drawerSide": { "status": "dead", "verifiedAt": "2026-11-02", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its form-view reader sat behind `type: 'drawer'`, which left the enum on #27155; measured at origin/main 104cd1a5, no metadata form-view surface reads it (ui/packages/plugin-form/src/ObjectFormContainer.tsx is the only caller that hands it to DrawerForm.tsx, and it serves the `object-form` block's `formType='drawer'`, which a form view's `type` cannot reach). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — a list opens a clicked record in its drawer (`navigation.mode`)." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its form-view reader sat behind `type: 'drawer'`, which left the enum on #27155; measured at origin/main 104cd1a5, no metadata form-view surface reads it (ui/packages/plugin-form/src/ObjectFormContainer.tsx is the only caller that hands it to DrawerForm.tsx, and it serves the `object-form` block's `formType='drawer'`, which a form view's `type` cannot reach). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — a list opens a clicked record in its drawer (`navigation.mode`)." }, "drawerWidth": { "status": "dead", "verifiedAt": "2026-11-02", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was already DEPRECATED (#2578 → size buckets) with no size-bucket conversion of its own, and inert on a form view since `type: 'drawer'` left the enum on #27155: the only reader, DrawerForm.tsx, is reached only through the `object-form` block's `formType='drawer'` (ObjectFormContainer.tsx). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts); nothing to write on a form view instead — a list's record drawer takes its starting width from `navigation.size`." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was already DEPRECATED (#2578 → size buckets) with no size-bucket conversion of its own, and inert on a form view since `type: 'drawer'` left the enum on #27155: the only reader, DrawerForm.tsx, is reached only through the `object-form` block's `formType='drawer'` (ObjectFormContainer.tsx). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts); nothing to write on a form view instead — a list's record drawer takes its starting width from `navigation.size`." }, "modalSize": { "status": "dead", "verifiedAt": "2026-11-28", "evidenceScope": "in-repo", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-28 (#36544, ADR-0049 enforce-or-remove, seat ruling on the card: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms, the flattened form overlay and the `form` item) and stripped from stored rows and sources by the protocol-19 form-view-modal-size-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its one form-view reader was the console's New / Edit record dialog, which copied it from the object's internal form view until #36425 retired that read. Measured at origin/main 0e361201, no form-view surface reads it: ui/apps/console/src/components/FormPage.tsx, the page a named or public form opens on, names every other form key it draws and never this one; ui/packages/app-shell/src/utils/recordFormNavigation.ts#resolveRecordFormModalLayout writes `modalSize: 'full'` only from the surface the host derived; ui/packages/app-shell/src/hooks/useActionModal.tsx takes it from the action's own descriptor; and packages/rest, packages/runtime, packages/objectql and packages/metadata* never name it. ui/packages/plugin-form/src/ModalForm.tsx still reads a `modalSize`, the `object-form` block's own prop (ObjectFormContainer.tsx hands it over for `formType='modal'`), which a form view cannot reach. The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — the record dialog chooses its own size from the fields it draws." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. REMOVED 2026-11-28 (#36544, ADR-0049 enforce-or-remove, seat ruling on the card: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms, the flattened form overlay and the `form` item) and stripped from stored rows and sources by the protocol-19 form-view-modal-size-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its one form-view reader was the console's New / Edit record dialog, which copied it from the object's internal form view until #36425 retired that read. Measured at origin/main 0e361201, no form-view surface reads it: ui/apps/console/src/components/FormPage.tsx, the page a named or public form opens on, names every other form key it draws and never this one; ui/packages/app-shell/src/utils/recordFormNavigation.ts#resolveRecordFormModalLayout writes `modalSize: 'full'` only from the surface the host derived; ui/packages/app-shell/src/hooks/useActionModal.tsx takes it from the action's own descriptor; and packages/rest, packages/runtime, packages/objectql and packages/metadata* never name it. ui/packages/plugin-form/src/ModalForm.tsx still reads a `modalSize`, the `object-form` block's own prop (ObjectFormContainer.tsx hands it over for `formType='modal'`), which a form view cannot reach. The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — the record dialog chooses its own size from the fields it draws." }, "sections": { "status": "live", "verifiedAt": "2026-08-11", "evidenceScope": "cross-repo", "evidence": "objectui: form renderers + spec-bridge form-view.ts:169 (audit L17); packages/rest/src/form-routes.ts registerFormEndpoints (the two /forms/:slug routes walk sections: resolve strips every lookup/master_detail/user field from the anonymous rendering, submit builds allowedFields from them)", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. This row carries the blanket verdict for the whole FormField subtree beneath it (undrilled inheritance). [#7467] had added the anonymous public-form picker block to that subtree, read only by the anonymous lookup route; [#21180] REMOVED it 2026-10-01 (ADR-0087 D2, ruling E on #21079): the key is now a retiredKey() tombstone in FormFieldBaseSchema carrying the prescription, the route is deleted, and the resolve route strips lookup/master_detail/user fields from the anonymous rendering unconditionally. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormField:publicPicker in RETIRED_KEYS_BY_MAJOR[18]. [#12174] drills the six FormField constraint keys out of the blanket verdict — maxLength/minLength/min/max/precision/scale are all LIVE, measured at objectui@f7c52e2 (2026-08-26): two independent spec-to-runtime routes copy all six onto the runtime field (packages/react/src/spec-bridge/bridges/form-view.ts mapField, objectui#5898; packages/plugin-form/src/sectionFields.ts normalizeSectionField), the console FormPage merges override.maxLength ?? def.maxLength onto the rendered input (apps/console/src/components/FormPage.tsx:548, objectui#5595), packages/fields buildValidationRules turns minLength/maxLength/min/max into react-hook-form rules, ObjectForm.tsx:691 derives the number input step from precision, and NumberField.tsx:21 reads scale; server-side, GET /forms/:slug (packages/rest/src/rest-server.ts) serves the rows verbatim to anonymous renderers (a conduit, no key-level read). On that measurement the four count-shaped keys tightened to the #11566/#11949/#8321 value shapes (lengths int>=1, precision/scale int>=0; min/max stay bare numbers — they are values, not counts). Form-row `span` / `scale` read points (FormFieldBaseSchema in packages/spec/src/ui/view.zod.ts; moved out of spec source, #23434), re-read at objectui @b9814b334 on 2026-10-14: objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#resolveColSpan resolves 'full' to the grid's full column count and sizes 'auto' from the widget type, objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#WIDE_FIELD_TYPES makes textarea, markdown, html, richtext and repeater (via the wide `field:grid` widget) span the full count, and objectui @b9814b334 packages/components/src/renderers/form/form.tsx#spanLadderFor emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid; the widest-tier-only under-span of #17328 ended with objectui#9244 / objectui#9253). A form row's `scale` reaches `Intl.NumberFormat` through plugin-form (see field.json row `scale`). [#27155] The section key `pane` (split-pane placement) is REMOVED 2026-10-28 with `type: 'split'` (ADR-0050): a retiredKey() tombstone in FormSectionSchema carrying the prescription, stripped by the protocol-18 form-view-presentation-types-removed conversion. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormSection:pane in RETIRED_KEYS_BY_MAJOR[18]." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. This row carries the blanket verdict for the whole FormField subtree beneath it (undrilled inheritance). [#7467] had added the anonymous public-form picker block to that subtree, read only by the anonymous lookup route; [#21180] REMOVED it 2026-10-01 (ADR-0087 D2, ruling E on #21079): the key is now a retiredKey() tombstone in FormFieldBaseSchema carrying the prescription, the route is deleted, and the resolve route strips lookup/master_detail/user fields from the anonymous rendering unconditionally. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormField:publicPicker in RETIRED_KEYS_BY_MAJOR[18]. [#12174] drills the six FormField constraint keys out of the blanket verdict — maxLength/minLength/min/max/precision/scale are all LIVE, measured at objectui@f7c52e2 (2026-08-26): two independent spec-to-runtime routes copy all six onto the runtime field (packages/react/src/spec-bridge/bridges/form-view.ts mapField, objectui#5898; packages/plugin-form/src/sectionFields.ts normalizeSectionField), the console FormPage merges override.maxLength ?? def.maxLength onto the rendered input (apps/console/src/components/FormPage.tsx:548, objectui#5595), packages/fields buildValidationRules turns minLength/maxLength/min/max into react-hook-form rules, ObjectForm.tsx:691 derives the number input step from precision, and NumberField.tsx:21 reads scale; server-side, GET /forms/:slug (packages/rest/src/rest-server.ts) serves the rows verbatim to anonymous renderers (a conduit, no key-level read). On that measurement the four count-shaped keys tightened to the #11566/#11949/#8321 value shapes (lengths int>=1, precision/scale int>=0; min/max stay bare numbers — they are values, not counts). Form-row `span` / `scale` read points (FormFieldBaseSchema in packages/spec/src/ui/view.zod.ts; moved out of spec source, #23434), re-read at objectui @b9814b334 on 2026-10-14: objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#resolveColSpan resolves 'full' to the grid's full column count and sizes 'auto' from the widget type, objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#WIDE_FIELD_TYPES makes textarea, markdown, html, richtext and repeater (via the wide `field:grid` widget) span the full count (re-read 2026-11-27, #37677: since objectui#11448 repeater maps to the shared `field:object` JSON editor, so autoLayout.ts#WIDE_DECLARED_FIELD_TYPES widens it by its object-field type, read in both form renderers), and objectui @b9814b334 packages/components/src/renderers/form/form.tsx#spanLadderFor emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid; the widest-tier-only under-span of #17328 ended with objectui#9244 / objectui#9253). A form row's `scale` reaches `Intl.NumberFormat` through plugin-form (see field.json row `scale`). [#27155] The section key `pane` (split-pane placement) is REMOVED 2026-10-28 with `type: 'split'` (ADR-0050): a retiredKey() tombstone in FormSectionSchema carrying the prescription, stripped by the protocol-18 form-view-presentation-types-removed conversion. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormSection:pane in RETIRED_KEYS_BY_MAJOR[18]." }, "groups": { "status": "live", "verifiedAt": "2026-08-09", "evidenceScope": "in-repo", "evidence": "packages/spec/src/ui/view.zod.ts (foldFormGroupsIntoSections + the .overwrite on FormViewSchema — the PRODUCER fold, #6926: groups-only folds onto sections, sections wins when both are present, and groups is absent from every parsed form); ui/packages/plugin-form/src/ObjectForm.tsx (:129-142 at objectui @7b3e048) (objectui @7b3e048 — the pre-existing boundary folds, now redundant for parsed forms and retiring in a later cross-repo lap)", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. WHERE THE FOLD LIVES: at the producer, as of #6926 — a `.overwrite()` on FormViewSchema, inherited by every parse door (ViewSchema.form/.formViews.*, both ViewItemSchema form arms, and ViewMetadataSchema's container AND flattened form-overlay members, which picks it up through .extend()). Before #6926 the alias was declared but folded NOWHERE in this repo: it was honored one boundary downstream in objectui (alias-at-one-boundary, objectui#2545, after a groups-only spec rendered nothing), while the framework's REST public-form routes read `sections` only — so the same authored form rendered in the console and degraded on GET /forms/:slug, POST /forms/:slug/submit and GET /forms/:slug/lookup/:field. That omission is what let #6926 be filed reading a live key as dead; it is recorded here so the next reader cannot repeat it. STILL NOT FOLDED (measured 2026-08-09, #6926): a RUNTIME-saved sys_metadata row — saveMetaItem validates through ViewMetadataSchema and then deliberately discards parsed.data to keep Studio round-trip keys, and the read replays the ADR-0087 stored-row conversion chain, which is not a zod parse. Code-authored views (defineView/defineMetadataForm → registry) DO reach REST folded. Pre-parse consumers still read the authored key and are right to: packages/lint's view rules walk authored sources. Audit L24 drift resolved by alias-at-one-boundary; superseded by the producer fold. 2026-10-26 (#25712, objectui merged into this repo as ui/): the spec-bridge clause (`form-view.ts:169`) was dropped, not repointed: objectui#6632 retired the spec-bridge. ObjectForm's line range is kept as the @7b3e048 reading; it does not match today's file." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. WHERE THE FOLD LIVES: at the producer, as of #6926 — a `.overwrite()` on FormViewSchema, inherited by every parse door (ViewSchema.form/.formViews.*, both ViewItemSchema form arms, and ViewMetadataSchema's container AND flattened form-overlay members, which picks it up through .extend()). Before #6926 the alias was declared but folded NOWHERE in this repo: it was honored one boundary downstream in objectui (alias-at-one-boundary, objectui#2545, after a groups-only spec rendered nothing), while the framework's REST public-form routes read `sections` only — so the same authored form rendered in the console and degraded on GET /forms/:slug, POST /forms/:slug/submit and GET /forms/:slug/lookup/:field. That omission is what let #6926 be filed reading a live key as dead; it is recorded here so the next reader cannot repeat it. STILL NOT FOLDED (measured 2026-08-09, #6926): a RUNTIME-saved sys_metadata row — saveMetaItem validates through ViewMetadataSchema and then deliberately discards parsed.data to keep Studio round-trip keys, and the read replays the ADR-0087 stored-row conversion chain, which is not a zod parse. Code-authored views (defineView/defineMetadataForm → registry) DO reach REST folded. Pre-parse consumers still read the authored key and are right to: packages/lint's view rules walk authored sources. Audit L24 drift resolved by alias-at-one-boundary; superseded by the producer fold. 2026-10-26 (#25712, objectui merged into this repo as ui/): the spec-bridge clause (`form-view.ts:169`) was dropped, not repointed: objectui#6632 retired the spec-bridge. ObjectForm's line range is kept as the @7b3e048 reading; it does not match today's file." }, "subforms": { "status": "live", "verifiedAt": "2026-08-10", "evidenceScope": "in-repo", "evidence": "ui/packages/plugin-form/src/ObjectForm.tsx (:175 at objectui @11c1e71e) branches on schema.subforms and :197 hands it to MasterDetailForm as `details`; the plugin-form master-detail form (:315 at objectui @11c1e71e) reads it as schema.details and :240 renders one panel per entry, with :227 summing their amount fields; ui/packages/plugin-form/src/ModalForm.tsx:1080 and ui/packages/plugin-form/src/DrawerForm.tsx:909 take the same key through their own envelopes (ModalForm applies at :1117/:1153, DrawerForm at :921) — measured objectui @11c1e71e", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. RE-CITED 2026-08-10 (#7133/#7142): the old citation named deriveMasterDetail.ts:338 and LineItemsPanel.tsx:45, and neither file mentions `subforms` at objectui @11c1e71e. deriveMasterDetail DERIVES master-detail panels from relationship metadata — its output is merged with the authored key one level up, in app-shell MetadataProvider.tsx:304-307 — and LineItemsPanel.tsx:41-55 is the per-panel schema, one hop past the rename to `details`. The form renderers are the readers that branch on the authored key. Verdict unchanged: LIVE, master-detail fully wired (audit L17)." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. RE-CITED 2026-08-10 (#7133/#7142): the old citation named deriveMasterDetail.ts:338 and LineItemsPanel.tsx:45, and neither file mentions `subforms` at objectui @11c1e71e. deriveMasterDetail DERIVES master-detail panels from relationship metadata — its output is merged with the authored key one level up, in app-shell MetadataProvider.tsx:304-307 — and LineItemsPanel.tsx:41-55 is the per-panel schema, one hop past the rename to `details`. The form renderers are the readers that branch on the authored key. Verdict unchanged: LIVE, master-detail fully wired (audit L17)." }, "sharing": { "status": "live", - "verifiedAt": "2026-11-26", - "evidence": "packages/rest/src/form-routes.ts#findPublicForm (`const open = openFormAt(forms ?? [], layer, slug);` — the public form doors serve only an open form of the effective `form` list whose slug matches, an old shape among them as the `form` item it projects); packages/spec/src/ui/form-intake-layer.ts#openFormAt (`if (layer.closedLinks.has(slug)) return null;`, then `if (anonymousFormIntakeSlug(form.sharing) !== slug) continue;` and `if (name === undefined || layer.withdrawn.has(name)) continue;` — a `form` item's own `sharing` decides its address, under the withdrawal layer); packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlug (the slug rule reads all three keys: `if (s.enabled !== true) return null;`, `if (s.allowAnonymous !== true) return null;`, `if (typeof s.publicLink !== 'string' || !s.publicLink) return null;`); packages/rest/src/form-routes.ts#resolveFormBySlug (both doors resolve the match through it, and the submit door grants `publicFormGrant: { object: match.object }` for the matched form's object)", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. Framework-side consumer: public (anonymous) form endpoints opt in via FormView.sharing — /forms/:slug resolves sharing.publicLink across form + formViews (rest-server.ts:1716, :4366-4405) and grants publicFormGrant. Renderer-side the config is not read (audit L20) — the public form is served, not re-parsed client-side. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:4384` had rotted onto a comment about `api`-only route enumeration, ~4,020 lines above the form endpoints; the note's own inline pointers (`:1716`, `:4366-4405`) had gone with it and are superseded by the anchors. Re-closed by hand against 8cb96ec41." + "verifiedAt": "2026-12-01", + "evidence": "packages/rest/src/form-routes.ts#findPublicForm (`const open = openFormAt(forms ?? [], layer, slug);` — the public form doors serve only an open form of the effective `form` list whose slug matches; since protocol 19 that list holds `form` items only, and no form is answered out of a `view` body, ADR-0159 D7); packages/spec/src/ui/form-intake-layer.ts#openFormAt (`if (layer.closedLinks.has(slug)) return null;`, then `if (anonymousFormIntakeSlug(form.sharing) !== slug) continue;` and `if (name === undefined || layer.withdrawn.has(name)) continue;` — a `form` item's own `sharing` decides its address, under the withdrawal layer); packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlug (the slug rule reads all three keys: `if (s.enabled !== true) return null;`, `if (s.allowAnonymous !== true) return null;`, `if (typeof s.publicLink !== 'string' || !s.publicLink) return null;`); packages/rest/src/form-routes.ts#resolveFormBySlug (both doors resolve the match through it, and the submit door grants `publicFormGrant: { object: match.object }` for the matched form's object)", + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. Framework-side consumer: public (anonymous) form endpoints opt in via FormView.sharing — /forms/:slug resolves sharing.publicLink across form + formViews (rest-server.ts:1716, :4366-4405) and grants publicFormGrant. Renderer-side the config is not read (audit L20) — the public form is served, not re-parsed client-side. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:4384` had rotted onto a comment about `api`-only route enumeration, ~4,020 lines above the form endpoints; the note's own inline pointers (`:1716`, `:4366-4405`) had gone with it and are superseded by the anchors. Re-closed by hand against 8cb96ec41." }, "submitBehavior": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:315-316 + ObjectForm.tsx dispatch thank-you/redirect/continue/next-record; covered by ObjectForm.submitBehavior.test.tsx / WizardForm.successBehavior.test.tsx. Supersedes the 2026-06 audit's DEAD line (L20) — wiring landed with the objectui#2545/#2552 reconciliation." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: WizardForm.tsx:315-316 + ObjectForm.tsx dispatch thank-you/redirect/continue/next-record; covered by ObjectForm.submitBehavior.test.tsx / WizardForm.successBehavior.test.tsx. Supersedes the 2026-06 audit's DEAD line (L20) — wiring landed with the objectui#2545/#2552 reconciliation." }, "buttons": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx foldFormButtons() reads schema.buttons and folds submit/cancel {show,label} onto the flat showSubmit/submitText/showCancel/cancelText props (framework#1894 / #2998); ObjectView forwards it, and every console form entry point resolves submit/cancel through resolveFormViewChrome / readFormButton (#26843). Flat keys kept as deprecated back-compat (explicit flat key wins). SUB-KEY buttons.reset REMOVED 2026-10-28 (#27153, ADR-0049 enforce-or-remove, ruled retire): measured at origin/main fbe344b3, six button bars (components form.tsx, console FormPage, ModalForm, DrawerForm, WizardForm, MasterDetailForm) drew submit/cancel and none drew reset; reset.label had no reader; the one fold of reset.show landed on ObjectForm showReset, which means clear-after-save (resetOnSubmit), not a button. Tombstoned inside the buttons block (retiredKey carries the prescription) and stripped from stored rows and sources by the protocol-18 form-view-buttons-reset-removed conversion; the fold was removed in the same change. Sub-keys cannot be drilled (one level only), so the removal is recorded here; submit and cancel keep this row live." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx foldFormButtons() reads schema.buttons and folds submit/cancel {show,label} onto the flat showSubmit/submitText/showCancel/cancelText props (framework#1894 / #2998); ObjectView forwards it, and every console form entry point resolves submit/cancel through resolveFormViewChrome / readFormButton (#26843). Flat keys kept as deprecated back-compat (explicit flat key wins). SUB-KEY buttons.reset REMOVED 2026-10-28 (#27153, ADR-0049 enforce-or-remove, ruled retire): measured at origin/main fbe344b3, six button bars (components form.tsx, console FormPage, ModalForm, DrawerForm, WizardForm, MasterDetailForm) drew submit/cancel and none drew reset; reset.label had no reader; the one fold of reset.show landed on ObjectForm showReset, which means clear-after-save (resetOnSubmit), not a button. Tombstoned inside the buttons block (retiredKey carries the prescription) and stripped from stored rows and sources by the protocol-18 form-view-buttons-reset-removed conversion; the fold was removed in the same change. Sub-keys cannot be drilled (one level only), so the removal is recorded here; submit and cancel keep this row live." }, "defaults": { "status": "live", - "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the same public form renderer an old-shape form reaches (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row carries view.json `form.`'s verdict. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx foldFormButtons() reads schema.defaults and folds it into create-mode initialValues (framework#1894 / #2998); an explicit initialValues (URL prefill) still wins." + "note": "Inherited verdict (2026-11-26, ADR-0159 card ②): a `form` item's body keys ARE `FormViewSchema`'s shape, taken by reference (packages/spec/src/ui/view.zod.ts#FormSchema), and the anonymous doors serve the item's body to the public form renderer an old-shape form reached until protocol 19 (packages/rest/src/form-routes.ts#resolveFormBySlug), so this row was seeded with view.json `form.`'s verdict; that row left view.json with the container's tombstone (2026-12-01, ADR-0159 D7), and this row is the one classification of the key. Until card ③ (#37087) the console opens no `form` item from an action; re-verify this row with that card. objectui: ObjectForm.tsx foldFormButtons() reads schema.defaults and folds it into create-mode initialValues (framework#1894 / #2998); an explicit initialValues (URL prefill) still wins." }, "protection": null, "_lock": null, diff --git a/packages/spec/liveness/state-counts/view.md b/packages/spec/liveness/state-counts/view.md index f13052fddda..2de50457f18 100644 --- a/packages/spec/liveness/state-counts/view.md +++ b/packages/spec/liveness/state-counts/view.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `view` | 74 | 0 | 0 | 12 | 0 | 86 | +| `view` | 56 | 0 | 0 | 8 | 0 | 64 | diff --git a/packages/spec/liveness/translation.json b/packages/spec/liveness/translation.json index bdad54f3bfc..a57122a25ce 100644 --- a/packages/spec/liveness/translation.json +++ b/packages/spec/liveness/translation.json @@ -28,7 +28,7 @@ "status": "live", "verifiedAt": "2026-08-28", "evidence": "packages/spec/src/system/i18n-resolver.ts#lookupObjectField (`objects..label` / `pluralLabel` / `description`); packages/spec/src/system/i18n-resolver.ts#lookupObjectFieldAttr (`objects..fields..`); packages/spec/src/system/i18n-resolver.ts#resolveViewLabel (`objects.._views..label`); packages/spec/src/system/i18n-resolver.ts#actionTranslationNode (`objects.._actions`, the one address of a bound action — never followed by globalActions); packages/spec/src/system/i18n-resolver.ts#lookupTabLabel (`objects.._tabs`); packages/spec/src/system/i18n-resolver.ts#lookupRelatedListLabel (`objects.._relatedLists`, read by translateObject); ui/packages/i18n/src/useObjectLabel.ts (:397-400 at objectui @940ba24)", - "note": "the largest group, fully live: label/pluralLabel/description (translateObject), fields.{label,help,placeholder,options}, _views (resolveViewLabel + empty-state copy), _actions (label/description/confirmText/successMessage/outcomeMessages/params/resultDialog — a bound action's only address; it never falls back to globalActions), _sections (objectui record:details section labels). Served through REST translateMetaItem(s) and the /api/v1/i18n endpoints; objectui re-resolves client-side via the spec-translations transform. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — this entry named SIX positions in i18n-resolver.ts and only the first, `:735`, was parsable as a citation at all; it had rotted onto `widgets?: WidgetLike[]` in the `DashboardLike` INTERFACE. The other five (`:751`, `:159`, `:197`, `:873`, `:900`) were bare line suffixes with no path in front of them, so they were never resolved, bounded or key-checked by anything — the largest instance in this batch of the class `flow.status` and `dashboard.widgets.suppressWarnings` also carried. The five anchors above are the five distinct group readers, named. Re-closed by hand against 8cb96ec41." + "note": "the largest group, fully live: label/pluralLabel/description (translateObject), fields.{label,help,placeholder,options}, _views (resolveViewLabel + empty-state copy; a list's strings only since protocol 19 — a form's `title` / `submitBehavior` tails are tombstoned there and live under `forms`, ADR-0159 D8), _actions (label/description/confirmText/successMessage/outcomeMessages/params/resultDialog — a bound action's only address; it never falls back to globalActions), _sections (objectui record:details section labels). Served through REST translateMetaItem(s) and the /api/v1/i18n endpoints; objectui re-resolves client-side via the spec-translations transform. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — this entry named SIX positions in i18n-resolver.ts and only the first, `:735`, was parsable as a citation at all; it had rotted onto `widgets?: WidgetLike[]` in the `DashboardLike` INTERFACE. The other five (`:751`, `:159`, `:197`, `:873`, `:900`) were bare line suffixes with no path in front of them, so they were never resolved, bounded or key-checked by anything — the largest instance in this batch of the class `flow.status` and `dashboard.widgets.suppressWarnings` also carried. The five anchors above are the five distinct group readers, named. Re-closed by hand against 8cb96ec41." }, "picklists": { "status": "live", @@ -154,9 +154,9 @@ }, "forms": { "status": "live", - "verifiedAt": "2026-11-26", - "evidence": "packages/spec/src/system/i18n-resolver.ts#translateForm (`forms..{label,description,title,submitBehavior.title,submitBehavior.message}` first; `title` and `submitBehavior` fall back to the `_views.` tails; `_views..label` is never read); packages/lint/src/i18n-walk.ts#walkForms (the extractor emits the `forms..*` keys and no `_views` tail)", - "note": "ADR-0159 card ② item 8: the `form` metadata type's translation family.", + "verifiedAt": "2026-12-01", + "evidence": "packages/spec/src/system/i18n-resolver.ts#translateForm (`forms..{label,description,title,submitBehavior.title,submitBehavior.message}`, the one address of a form's own strings since protocol 19: the fallback read of the `_views..title` / `.submitBehavior` tails left with their tombstones, ADR-0159 D8; `_views..label` was never read for a form); packages/lint/src/i18n-walk.ts#walkForms (the extractor emits the `forms..*` keys and no `_views` tail)", + "note": "ADR-0159 card ② item 8: the `form` metadata type's translation family. 2026-12-01 (ADR-0159 D8): the one address of a form's heading and thank-you panel. The two form tails a form defined in a view had under `objects.._views.` (`title`, `submitBehavior`) are tombstoned in protocol 19 (retiredKey carries the prescription naming `forms['OBJECT.KEY']`) and moved by the protocol-19 conversion translation-view-form-tails-to-forms. Both sit under a record's value shape, beneath this ledger's walk boundary and the authorable-surface walk alike, so the tombstones add no row here and no RETIRED_KEYS_BY_MAJOR entry: the D3 semantic entry translation-form-tails-move-to-forms is their registration.", "children": { "label": { "status": "live", diff --git a/packages/spec/liveness/view.json b/packages/spec/liveness/view.json index 52ad1580820..c49e33afe72 100644 --- a/packages/spec/liveness/view.json +++ b/packages/spec/liveness/view.json @@ -1,6 +1,6 @@ { "type": "view", - "_note": "ViewSchema (object view container: list/form/listViews/formViews). Seeded from docs/audits/archive/2026-06/2026-06-viewschema-property-liveness.md (objectui consumer cross-reference) and re-verified against objectui@fb35e48 (2026-07-16) — several audit-era DEAD findings have since gone LIVE (submitBehavior, sharing.lockedBy, ViewData providers on the list path) and are classified from the current reads, not the stale audit lines. objectui paths cited as 'objectui: ' prose (not resolved against this repo). Sub-sub-key divergences (userActions.buttons, addRecord.mode/formView, tabs[].order) can't be drilled (one level only) — captured in the parent entry's note and tracked in the enforce-or-remove worklist (#2998 Track B / ADR-0049). 2026-07-30 (#3896 close-out sweep): the dead authoring keys were REMOVED — tombstoned at the schema with prescriptions (retiredKey) and stripped by the protocol-17 close-out conversions; entries deleted per the #3715 precedent. widget.performance (no ledger file of its own) was verified dead the corrected way — zero readers in either repo; objectui virtual scrolling reads the LIVE top-level virtualScroll — and removed with them. 2026-08-28 (commit 8f10a79f7): all five `path:NNN` citations in this file were re-anchored to their consuming symbols, and all five were wrong. Two pairs shared one wrong line each — `list.name`/`listViews` on a schema declaration, `form.sharing`/`formViews` on a comment about API routes — and `object` was falsified in PROSE as well as position, naming a function that lives in another package.", + "_note": "ViewSchema (object view container: list/listViews; form/formViews REMOVED in 19, ADR-0159 D7). Seeded from docs/audits/archive/2026-06/2026-06-viewschema-property-liveness.md (objectui consumer cross-reference) and re-verified against objectui@fb35e48 (2026-07-16) — several audit-era DEAD findings have since gone LIVE (submitBehavior, sharing.lockedBy, ViewData providers on the list path) and are classified from the current reads, not the stale audit lines. objectui paths cited as 'objectui: ' prose (not resolved against this repo). Sub-sub-key divergences (userActions.buttons, addRecord.mode/formView, tabs[].order) can't be drilled (one level only) — captured in the parent entry's note and tracked in the enforce-or-remove worklist (#2998 Track B / ADR-0049). 2026-07-30 (#3896 close-out sweep): the dead authoring keys were REMOVED — tombstoned at the schema with prescriptions (retiredKey) and stripped by the protocol-17 close-out conversions; entries deleted per the #3715 precedent. widget.performance (no ledger file of its own) was verified dead the corrected way — zero readers in either repo; objectui virtual scrolling reads the LIVE top-level virtualScroll — and removed with them. 2026-08-28 (commit 8f10a79f7): all five `path:NNN` citations in this file were re-anchored to their consuming symbols, and all five were wrong. Two pairs shared one wrong line each — `list.name`/`listViews` on a schema declaration, `form.sharing`/`formViews` on a comment about API routes — and `object` was falsified in PROSE as well as position, naming a function that lives in another package.", "props": { "name": { "status": "dead", @@ -278,129 +278,9 @@ } }, "form": { - "children": { - "data": { - "status": "live", - "verifiedAt": "2026-07-30", - "evidence": "packages/spec/src/ui/view.zod.ts defineMetadataForm (writes data.provider=schema + schemaId onto every metadata form); packages/metadata-protocol/src/protocol.ts:1580,1598 (serves schemaId with the form to the metadata-admin pipeline)", - "note": "CORRECTED 2026-07-30: the #3896 sweep attempted removal on the prior dead verdict and the build itself refuted it — defineMetadataForm authors the key on every *.metadata-form.ts. The record-form provider VALUES (object/value) may still lack readers; that is a value-subset audit, not a key removal. 2026-10-13: the `api` value is RETIRED on the union itself (see `list.data`'s retirement record) — a form's `data` no longer admits a request block; a submit-to-endpoint is not a view concern." - }, - "type": { - "status": "live", - "verifiedAt": "2026-10-28", - "evidenceScope": "in-repo", - "note": "NARROWED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) to the form's LAYOUT: simple / tabbed / wizard. The key stays live — ui/packages/plugin-form/src/ObjectForm.tsx routes tabbed and wizard to TabbedForm / WizardForm and simple to its own arm; ui/apps/console/src/components/FormPage.tsx forwards it for a named or public form (since #36425 the record create / edit surfaces load no internal form view, so RecordFormPage and the record dialog no longer read it). `split`, `drawer` and `modal` are refused by name (enumWithRetiredValues carries each prescription; a value-level narrowing, so this row stays and no RETIRED_KEYS_BY_MAJOR entry exists for them) and deleted from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which lands the form on the `simple` default. Where a form opens is the caller's open mode. The renderer's split / drawer / modal arms for a form view leave on #27159." - }, - "layout": { - "status": "live", - "verifiedAt": "2026-09-27", - "note": "objectui @ f8a9d0fb0: plugin-form ObjectForm.tsx:1408 (simple arm) and :463/:499 (drawer/modal hand-off), DrawerForm.tsx:575, ModalForm.tsx:597 — each reads vertical/horizontal only. The enum was narrowed to those two arms 2026-09-27 (#20221, ADR-0049 enforce-or-remove): every arm folded 'inline' and 'grid' to vertical, so both were a declared value the renderer threw away; multi-column is the sibling `columns` key. The key itself stays live." - }, - "columns": { - "status": "live", - "verifiedAt": "2026-11-26", - "note": "RE-CITED 2026-11-26 (#37665, ruling A on #37638): the form view's `columns` is the grid width of a sectioned form, capping each section's count; an undeclared section takes it. Readers: ui/apps/console/src/components/FormPage.tsx#buildSections, the named (`/forms/:name`) and public (`/f/:slug`) form page, and the Setup preview canvas, ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.tsx#buildFormPreviewSchema handing it to ui/packages/plugin-form/src/ObjectForm.tsx; both resolve through ui/packages/plugin-form/src/autoLayout.ts#sectionedGridLayout. The previous ModalForm / DrawerForm citation was stale: those hosts no longer receive a stored form view." - }, - "title": { - "status": "live", - "note": "objectui: ModalForm.tsx:662 / DrawerForm.tsx:528 header; ObjectView form adapter (audit L25)." - }, - "description": { - "status": "live", - "note": "objectui: ModalForm.tsx:662-681 / DrawerForm.tsx:528-558 render it under the title." - }, - "defaultTab": { - "status": "live", - "note": "objectui: ObjectForm.tsx:185 → tabbed variant." - }, - "tabPosition": { - "status": "live", - "note": "objectui: ObjectForm.tsx:186 → tabbed variant." - }, - "allowSkip": { - "status": "live", - "note": "objectui: WizardForm.tsx:397-444 (step navigation gating)." - }, - "showStepIndicator": { - "status": "live", - "note": "objectui: WizardForm.tsx:438." - }, - "splitDirection": { - "status": "dead", - "verifiedAt": "2026-10-28", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-10-28 (#27159, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion, which #27159 widened before 18.3.0 shipped. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It oriented the split form's panes. Its form-view reader left with `type: 'split'` on #27155; its last reader, ui/packages/plugin-form/src/SplitForm.tsx behind the React `ObjectForm` block's `formType='split'`, was deleted with that value on #27159 (the `object-form` block's own splitDirection is tombstoned in the same change); nothing to write instead — a `tabbed` form gives each section its own tab." - }, - "splitSize": { - "status": "dead", - "verifiedAt": "2026-10-28", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It sized the split form's primary pane. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." - }, - "splitResizable": { - "status": "dead", - "verifiedAt": "2026-10-28", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-10-28 (#27155, ADR-0050 Accepted by ruling 6464210455 on #27032, letter A′) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-presentation-types-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It made the split form's panes resizable. Its only reader was ui/packages/plugin-form/src/SplitForm.tsx, reached through ObjectForm's `split` arm and RecordFormPage's split hand-off, both behind `type: 'split'`, which left the enum in the same change; nothing to write instead — a `tabbed` form gives each section its own tab." - }, - "drawerSide": { - "status": "dead", - "verifiedAt": "2026-11-02", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms and the flattened form overlay) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its form-view reader sat behind `type: 'drawer'`, which left the enum on #27155; measured at origin/main 104cd1a5, no metadata form-view surface reads it (ui/packages/plugin-form/src/ObjectFormContainer.tsx is the only caller that hands it to DrawerForm.tsx, and it serves the `object-form` block's `formType='drawer'`, which a form view's `type` cannot reach). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — a list opens a clicked record in its drawer (`navigation.mode`)." - }, - "drawerWidth": { - "status": "dead", - "verifiedAt": "2026-11-02", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-11-02 (#29012, ADR-0049 enforce-or-remove, triage ruling 6571544001: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape) and stripped from stored rows and sources by the protocol-18 form-view-drawer-keys-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was already DEPRECATED (#2578 → size buckets) with no size-bucket conversion of its own, and inert on a form view since `type: 'drawer'` left the enum on #27155: the only reader, DrawerForm.tsx, is reached only through the `object-form` block's `formType='drawer'` (ObjectFormContainer.tsx). The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts); nothing to write on a form view instead — a list's record drawer takes its starting width from `navigation.size`." - }, - "modalSize": { - "status": "dead", - "verifiedAt": "2026-11-28", - "evidenceScope": "in-repo", - "note": "REMOVED 2026-11-28 (#36544, ADR-0049 enforce-or-remove, seat ruling on the card: retire) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error at every form-view door built from the shape: FormViewSchema, the container's form / formViews, both ViewItem form arms, the flattened form overlay and the `form` item) and stripped from stored rows and sources by the protocol-19 form-view-modal-size-removed conversion. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its one form-view reader was the console's New / Edit record dialog, which copied it from the object's internal form view until #36425 retired that read. Measured at origin/main 0e361201, no form-view surface reads it: ui/apps/console/src/components/FormPage.tsx, the page a named or public form opens on, names every other form key it draws and never this one; ui/packages/app-shell/src/utils/recordFormNavigation.ts#resolveRecordFormModalLayout writes `modalSize: 'full'` only from the surface the host derived; ui/packages/app-shell/src/hooks/useActionModal.tsx takes it from the action's own descriptor; and packages/rest, packages/runtime, packages/objectql and packages/metadata* never name it. ui/packages/plugin-form/src/ModalForm.tsx still reads a `modalSize`, the `object-form` block's own prop (ObjectFormContainer.tsx hands it over for `formType='modal'`), which a form view cannot reach. The React `ObjectForm` block keeps the prop in its own overlay (packages/spec/src/ui/react-blocks.ts), and the `object-form` page block declares it in ObjectFormPropsSchema; nothing to write on a form view instead — the record dialog chooses its own size from the fields it draws." - }, - "sections": { - "status": "live", - "verifiedAt": "2026-08-11", - "evidenceScope": "cross-repo", - "evidence": "objectui: form renderers + spec-bridge form-view.ts:169 (audit L17); packages/rest/src/form-routes.ts registerFormEndpoints (the two /forms/:slug routes walk sections: resolve strips every lookup/master_detail/user field from the anonymous rendering, submit builds allowedFields from them)", - "note": "This row carries the blanket verdict for the whole FormField subtree beneath it (undrilled inheritance). [#7467] had added the anonymous public-form picker block to that subtree, read only by the anonymous lookup route; [#21180] REMOVED it 2026-10-01 (ADR-0087 D2, ruling E on #21079): the key is now a retiredKey() tombstone in FormFieldBaseSchema carrying the prescription, the route is deleted, and the resolve route strips lookup/master_detail/user fields from the anonymous rendering unconditionally. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormField:publicPicker in RETIRED_KEYS_BY_MAJOR[18]. [#12174] drills the six FormField constraint keys out of the blanket verdict — maxLength/minLength/min/max/precision/scale are all LIVE, measured at objectui@f7c52e2 (2026-08-26): two independent spec-to-runtime routes copy all six onto the runtime field (packages/react/src/spec-bridge/bridges/form-view.ts mapField, objectui#5898; packages/plugin-form/src/sectionFields.ts normalizeSectionField), the console FormPage merges override.maxLength ?? def.maxLength onto the rendered input (apps/console/src/components/FormPage.tsx:548, objectui#5595), packages/fields buildValidationRules turns minLength/maxLength/min/max into react-hook-form rules, ObjectForm.tsx:691 derives the number input step from precision, and NumberField.tsx:21 reads scale; server-side, GET /forms/:slug (packages/rest/src/rest-server.ts) serves the rows verbatim to anonymous renderers (a conduit, no key-level read). On that measurement the four count-shaped keys tightened to the #11566/#11949/#8321 value shapes (lengths int>=1, precision/scale int>=0; min/max stay bare numbers — they are values, not counts). Form-row `span` / `scale` read points (FormFieldBaseSchema in packages/spec/src/ui/view.zod.ts; moved out of spec source, #23434), re-read at objectui @b9814b334 on 2026-10-14: objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#resolveColSpan resolves 'full' to the grid's full column count and sizes 'auto' from the widget type, objectui @b9814b334 packages/plugin-form/src/autoLayout.ts#WIDE_FIELD_TYPES makes textarea, markdown, html, richtext and repeater (via the wide `field:grid` widget) span the full count (re-read 2026-11-27, #37677: since objectui#11448 repeater maps to the shared `field:object` JSON editor, so autoLayout.ts#WIDE_DECLARED_FIELD_TYPES widens it by its object-field type, read in both form renderers), and objectui @b9814b334 packages/components/src/renderers/form/form.tsx#spanLadderFor emits one clamped col-span class per multi-column tier (`@md:col-span-2 @2xl:col-span-3` for a 3-column grid; the widest-tier-only under-span of #17328 ended with objectui#9244 / objectui#9253). A form row's `scale` reaches `Intl.NumberFormat` through plugin-form (see field.json row `scale`). [#27155] The section key `pane` (split-pane placement) is REMOVED 2026-10-28 with `type: 'split'` (ADR-0050): a retiredKey() tombstone in FormSectionSchema carrying the prescription, stripped by the protocol-18 form-view-presentation-types-removed conversion. The subtree has no per-key rows, so the tombstone adds none; the retirement is registered as ui/FormSection:pane in RETIRED_KEYS_BY_MAJOR[18]." - }, - "groups": { - "status": "live", - "verifiedAt": "2026-08-09", - "evidenceScope": "in-repo", - "evidence": "packages/spec/src/ui/view.zod.ts (foldFormGroupsIntoSections + the .overwrite on FormViewSchema — the PRODUCER fold, #6926: groups-only folds onto sections, sections wins when both are present, and groups is absent from every parsed form); ui/packages/plugin-form/src/ObjectForm.tsx (:129-142 at objectui @7b3e048) (objectui @7b3e048 — the pre-existing boundary folds, now redundant for parsed forms and retiring in a later cross-repo lap)", - "note": "WHERE THE FOLD LIVES: at the producer, as of #6926 — a `.overwrite()` on FormViewSchema, inherited by every parse door (ViewSchema.form/.formViews.*, both ViewItemSchema form arms, and ViewMetadataSchema's container AND flattened form-overlay members, which picks it up through .extend()). Before #6926 the alias was declared but folded NOWHERE in this repo: it was honored one boundary downstream in objectui (alias-at-one-boundary, objectui#2545, after a groups-only spec rendered nothing), while the framework's REST public-form routes read `sections` only — so the same authored form rendered in the console and degraded on GET /forms/:slug, POST /forms/:slug/submit and GET /forms/:slug/lookup/:field. That omission is what let #6926 be filed reading a live key as dead; it is recorded here so the next reader cannot repeat it. STILL NOT FOLDED (measured 2026-08-09, #6926): a RUNTIME-saved sys_metadata row — saveMetaItem validates through ViewMetadataSchema and then deliberately discards parsed.data to keep Studio round-trip keys, and the read replays the ADR-0087 stored-row conversion chain, which is not a zod parse. Code-authored views (defineView/defineMetadataForm → registry) DO reach REST folded. Pre-parse consumers still read the authored key and are right to: packages/lint's view rules walk authored sources. Audit L24 drift resolved by alias-at-one-boundary; superseded by the producer fold. 2026-10-26 (#25712, objectui merged into this repo as ui/): the spec-bridge clause (`form-view.ts:169`) was dropped, not repointed: objectui#6632 retired the spec-bridge. ObjectForm's line range is kept as the @7b3e048 reading; it does not match today's file." - }, - "subforms": { - "status": "live", - "verifiedAt": "2026-08-10", - "evidenceScope": "in-repo", - "evidence": "ui/packages/plugin-form/src/ObjectForm.tsx (:175 at objectui @11c1e71e) branches on schema.subforms and :197 hands it to MasterDetailForm as `details`; ui/packages/plugin-form/src/MasterDetailForm.tsx (:315 at objectui @11c1e71e) reads schema.details and :240 renders one panel per entry, with :227 summing their amount fields; ui/packages/plugin-form/src/ModalForm.tsx:1080 and ui/packages/plugin-form/src/DrawerForm.tsx:909 take the same key through their own envelopes (ModalForm applies at :1117/:1153, DrawerForm at :921) — measured objectui @11c1e71e", - "note": "RE-CITED 2026-08-10 (#7133/#7142): the old citation named deriveMasterDetail.ts:338 and LineItemsPanel.tsx:45, and neither file mentions `subforms` at objectui @11c1e71e. deriveMasterDetail DERIVES master-detail panels from relationship metadata — its output is merged with the authored key one level up, in app-shell MetadataProvider.tsx:304-307 — and LineItemsPanel.tsx:41-55 is the per-panel schema, one hop past the rename to `details`. The form renderers are the readers that branch on the authored key. Verdict unchanged: LIVE, master-detail fully wired (audit L17)." - }, - "sharing": { - "status": "live", - "verifiedAt": "2026-08-28", - "evidence": "packages/rest/src/form-routes.ts#findPublicForm (`for (const c of anonymousFormIntakeCandidates(view))` then `if (c.slug !== slug) continue;` — the public form doors serve only a candidate whose slug matches); packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeCandidates (hands each form's `sharing` to `anonymousFormIntakeSlug`, across the nested `form`, every `formViews` entry and the flattened `config` of a `viewKind: 'form'` item); packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlug (the slug rule reads all three keys: `if (s.enabled !== true) return null;`, `if (s.allowAnonymous !== true) return null;`, `if (typeof s.publicLink !== 'string' || !s.publicLink) return null;`); packages/rest/src/form-routes.ts#resolveFormBySlug (both doors resolve the match through it, and the submit door grants `publicFormGrant: { object: match.object }` for the matched form's object)", - "note": "Framework-side consumer: public (anonymous) form endpoints opt in via FormView.sharing — /forms/:slug resolves sharing.publicLink across form + formViews (rest-server.ts:1716, :4366-4405) and grants publicFormGrant. Renderer-side the config is not read (audit L20) — the public form is served, not re-parsed client-side. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:4384` had rotted onto a comment about `api`-only route enumeration, ~4,020 lines above the form endpoints; the note's own inline pointers (`:1716`, `:4366-4405`) had gone with it and are superseded by the anchors. Re-closed by hand against 8cb96ec41." - }, - "submitBehavior": { - "status": "live", - "note": "objectui: WizardForm.tsx:315-316 + ObjectForm.tsx dispatch thank-you/redirect/continue/next-record; covered by ObjectForm.submitBehavior.test.tsx / WizardForm.successBehavior.test.tsx. Supersedes the 2026-06 audit's DEAD line (L20) — wiring landed with the objectui#2545/#2552 reconciliation." - }, - "buttons": { - "status": "live", - "note": "objectui: ObjectForm.tsx foldFormButtons() reads schema.buttons and folds submit/cancel {show,label} onto the flat showSubmit/submitText/showCancel/cancelText props (framework#1894 / #2998); ObjectView forwards it, and every console form entry point resolves submit/cancel through resolveFormViewChrome / readFormButton (#26843). Flat keys kept as deprecated back-compat (explicit flat key wins). SUB-KEY buttons.reset REMOVED 2026-10-28 (#27153, ADR-0049 enforce-or-remove, ruled retire): measured at origin/main fbe344b3, six button bars (components form.tsx, console FormPage, ModalForm, DrawerForm, WizardForm, MasterDetailForm) drew submit/cancel and none drew reset; reset.label had no reader; the one fold of reset.show landed on ObjectForm showReset, which means clear-after-save (resetOnSubmit), not a button. Tombstoned inside the buttons block (retiredKey carries the prescription) and stripped from stored rows and sources by the protocol-18 form-view-buttons-reset-removed conversion; the fold was removed in the same change. Sub-keys cannot be drilled (one level only), so the removal is recorded here; submit and cancel keep this row live." - }, - "defaults": { - "status": "live", - "note": "objectui: ObjectForm.tsx foldFormButtons() reads schema.defaults and folds it into create-mode initialValues (framework#1894 / #2998); an explicit initialValues (URL prefill) still wins." - } - } + "status": "dead", + "verifiedAt": "2026-12-01", + "note": "REMOVED 2026-12-01 (ADR-0159 D7) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and moved out of sources by the protocol-19 conversion view-forms-to-form-items. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent); a form is its own metadata type, authored under the stack's `forms:` as a `form` item named `OBJECT.form`, and its keys are classified in liveness/form.json. The per-key `children` this row carried went with the container: the walk no longer drills a tombstone. Stored rows are not rewritten: a view read serves lists only and drops the form member, and the kept withdrawal reader still reads a stored row's form through the projection (ADR-0159 D6 rules 10 and 11)." }, "listViews": { "status": "live", @@ -409,10 +289,9 @@ "note": "Named list views. Framework: expandViewContainer flattens container views into per-object view items (collision diagnostics via expandViewContainerWithDiagnostics). objectui: MetadataProvider.tsx:118-146 merges view metadata into objectDef.listViews — the saved-view switcher (ViewTabBar) reads only listViews (ADR-0047 'views' mode). Same inner shape as `list`; per-key classification lives under list.children. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:1432` had rotted onto the same schema-declaration line its sibling `list.name` carried; two keys shared one wrong pointer. Re-closed by hand against 8cb96ec41." }, "formViews": { - "status": "live", - "verifiedAt": "2026-08-28", - "evidence": "packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeCandidates (`for (const [key, fv] of Object.entries(v.formViews)) forms.push({ form: fv, key });` — every named form view is a public-link candidate); packages/spec/src/ui/view.zod.ts#expandViewContainerWithDiagnostics (flattens them into independent ViewItems)", - "note": "Named form views. Framework: public-form slug resolution scans form + every formViews entry (rest-server.ts:4384-4405); expandViewContainer flattens them. objectui: MetadataProvider routes viewKind:'form' items into objectDef.formViews (never into the list switcher). Same inner shape as `form`; per-key classification lives under form.children. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — `:4384` had rotted onto the same `api`-only comment its sibling `form.sharing` cited; the note's `rest-server.ts:4384-4405` range went with it. Re-closed by hand against 8cb96ec41." + "status": "dead", + "verifiedAt": "2026-12-01", + "note": "REMOVED 2026-12-01 (ADR-0159 D7) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and moved out of sources by the protocol-19 conversion view-forms-to-form-items. The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent); each named form is a `form` item `OBJECT.KEY` under the stack's `forms:` (a create or edit form nothing else opens is deleted, not moved), classified in liveness/form.json. Stored rows are not rewritten: a view read drops the member, and the kept withdrawal reader still reads it through the projection (ADR-0159 D6 rules 10 and 11)." } } } diff --git a/packages/spec/scripts/build-schemas-check-mode.git-topology.test.ts b/packages/spec/scripts/build-schemas-check-mode.git-topology.test.ts index 16521fb533d..cc6794da034 100644 --- a/packages/spec/scripts/build-schemas-check-mode.git-topology.test.ts +++ b/packages/spec/scripts/build-schemas-check-mode.git-topology.test.ts @@ -292,7 +292,8 @@ describe('build-schemas.ts — the drift notice names the direction it measured /** Only in `mainTip`: what origin/main added after the anchor. */ const LANDED_KEY = 'data/Object:description'; /** A key in a DIFFERENT shard, so the unordered fixture's two sides merge without conflict. */ - const UI_KEY = 'ui/View:form'; + // [ADR-0159 D7] `ui/View:form` until protocol 19 tombstoned it ([RETIRED] in the baseline). + const UI_KEY = 'ui/View:listViews'; /** The branch's fork point: upstream, and behind the committed anchor. */ let older: string; diff --git a/packages/spec/scripts/liveness/key-mention.baseline.json b/packages/spec/scripts/liveness/key-mention.baseline.json index 7f4cbd3d47f..dd6b8528ecb 100644 --- a/packages/spec/scripts/liveness/key-mention.baseline.json +++ b/packages/spec/scripts/liveness/key-mention.baseline.json @@ -65,11 +65,6 @@ "path": "ui/packages/plugin-grid/src/ObjectGrid.tsx", "why": "A RENAMED key: ListView forwards `inlineEdit` to the grid node as `editable`, and ObjectGrid reads `schema.editable` (the cell editor, renderCellEditor, and the save/cancel column). The entry's ListView citation names `inlineEdit`. Surfaced when the citation moved from objectui into ui/ (#25712)." }, - { - "entry": "view/form.subforms", - "path": "ui/packages/plugin-form/src/MasterDetailForm.tsx", - "why": "A RENAMED key: ObjectForm hands `subforms` to MasterDetailForm as `details`, and this file reads `details` (`MasterDetailDetailConfig[]`, one panel per entry). The entry's ObjectForm citation names `subforms`. Surfaced when the citation moved from objectui into ui/ (#25712)." - }, { "entry": "translation/flows.screens", "path": "ui/packages/app-shell/src/views/ScreenView.tsx", diff --git a/packages/spec/scripts/liveness/undrilled-containers.baseline.json b/packages/spec/scripts/liveness/undrilled-containers.baseline.json index 28b887127dc..6dff1ceb1ee 100644 --- a/packages/spec/scripts/liveness/undrilled-containers.baseline.json +++ b/packages/spec/scripts/liveness/undrilled-containers.baseline.json @@ -30,11 +30,6 @@ "to": "view/list", "why": "the ViewItem container's list surface — `view.list` is the drilled coordinate for it." }, - { - "container": "view/formViews", - "to": "view/form", - "why": "the ViewItem container's form surface — `view.form` is the drilled coordinate for it." - }, { "container": "manifest/data", "to": "seed", @@ -136,11 +131,6 @@ "translation/objects", "translation/pages", "translation/settingsCommon", - "view/form.buttons", - "view/form.groups", - "view/form.sections", - "view/form.sharing", - "view/form.subforms", "view/list.addRecord", "view/list.appearance", "view/list.aria", diff --git a/packages/spec/scripts/zod-graph.test.ts b/packages/spec/scripts/zod-graph.test.ts index a3ab62f5afa..b199bd4756e 100644 --- a/packages/spec/scripts/zod-graph.test.ts +++ b/packages/spec/scripts/zod-graph.test.ts @@ -231,17 +231,19 @@ describe('pipeAuthorableSide — the registered metadata-type roots (#5317)', () const shape = zodShapeOf(schema!); expect(shape).not.toBeNull(); - // Not a key count (89 today, and every view feature moves it) — one key that - // ONLY a given member declares, so the assertion fails if the merge ever - // silently collapses to a single member. All four members are represented, - // the first of them a nested union: + // Not a key count (every view feature moves it) — one key that ONLY a + // given member declares, so the assertion fails if the merge ever silently + // collapses to a single member. All three members are represented, the + // first of them a nested union: expect(Object.keys(shape ?? {})).toEqual( expect.arrayContaining([ 'isPinned', // member 0 only — and member 0 is itself a union 'list', // the defineView container member 'pagination', // the flattened list-view member - 'sections', // the flattened form-view member ]), ); + // [ADR-0159 D7] There were four members until protocol 19; the flattened + // form-view member left with the form arm, and its keys with it. + expect(Object.keys(shape ?? {})).not.toContain('sections'); }); }); diff --git a/packages/spec/src/api/error-code-ledger.test.ts b/packages/spec/src/api/error-code-ledger.test.ts index 730c6eb2c56..8401cb47f03 100644 --- a/packages/spec/src/api/error-code-ledger.test.ts +++ b/packages/spec/src/api/error-code-ledger.test.ts @@ -295,6 +295,25 @@ describe('ErrorCode (standard ∪ registered)', () => { expect(STANDARD_SYNONYM_WAIVERS.map((w) => w.code)).not.toContain(code); }); + it('accepts the protocol-19 boot refusal\'s code under the runtime, as its own meaning (door: none)', () => { + // ADR-0159 D7, ruling 7303149461: `os serve` refuses a database whose + // protocol-19 switch is not recorded. `@objectstack/runtime`'s + // `FormTypeSwitchBootRefusal` stamps it and its kernel suite asserts this + // exact string by value — pinned here too. Thrown at boot, before any + // socket opens: registered on the "door or no door" rule, like the v18 + // organization-ownership refusal beside it. + const code = 'FORM_TYPE_SWITCH_REQUIRED'; + expect(ErrorCode.parse(code)).toBe(code); + expect(ERROR_CODE_LEDGER['@objectstack/runtime'], `${code} registered under runtime`).toContain(code); + expect(REGISTERED_ERROR_CODES).toContain(code); + // FORM, TYPE and SWITCH are tokens no standard member carries: not a + // synonym of any standard code, and no waiver. + expect(standardSynonymOf(code), `${code} needs no waiver`).toBeUndefined(); + expect(STANDARD_SYNONYM_WAIVERS.map((w) => w.code)).not.toContain(code); + // Not a re-spelling of the v18 refusal: both stay registered, each its own act. + expect(ERROR_CODE_LEDGER['@objectstack/runtime']).toContain('ORGANIZATION_OWNERSHIP_MIGRATION_REQUIRED'); + }); + it('accepts the package disable door\'s dependent-validation-rule refusal code, registered ahead of its runtime producer', () => { // ADR-0141 Open item 4, ruling A on #30379: the disable door answers 409 // while an enabled package's validation rule reads a field the package diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 8aedf2dab8d..fa783eb63a7 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -513,6 +513,21 @@ export const ERROR_CODE_LEDGER = { // WALLED_MEMBERSHIP_POLICY_UNDECLARED precedent); the `code` lets a host // discriminate the refusal structurally. No escape hatch exists (D10). 'ORGANIZATION_OWNERSHIP_MIGRATION_REQUIRED', + // [ADR-0159 D7, ruling 7303149461] The protocol-19 boot refusal + // (`FormTypeSwitchBootGuardPlugin`, `form-type-switch-boot-guard.ts`): + // `os serve` refuses to start against a database whose protocol-19 switch + // is not recorded: the `sys_migration` row `adr-0159-form-type-switch` is + // absent, unverified or unreadable, and the boot did not create the + // database from empty. Thrown from the plugin's `start()`, or by `os serve` + // before the kernel starts when another plugin took the guard's name, so + // no request is ever served (`door: 'none'`, the + // ORGANIZATION_OWNERSHIP_MIGRATION_REQUIRED precedent one row up); the + // `code` lets a host discriminate the refusal structurally. No switch + // skips it. The remedy is the command the message names: + // `os migrate protocol --to 19`. FORM, TYPE and SWITCH are tokens no + // standard member carries, and it is not a synonym of the row above: that + // one is the v18 organization-ownership ceremony, this one the v19 switch. + 'FORM_TYPE_SWITCH_REQUIRED', // [#7557] `DELETE /packages/:id` on the DISPATCHER door — per-item failures // used to ride inside a 200 with a hardcoded `success: true`. Second // EMITTER of the code `@objectstack/rest` already registers for the diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 6538b76a6c0..5e36c90b34d 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -3318,6 +3318,12 @@ export const GetUiViewRequestSchema = lazySchema(() => z.object({ /** * Get UI View Response + * + * For `type: 'list'` the answer is a view (`ViewSchema`). For `type: 'form'` + * it is the form scaffold `{ object, form }`, its `form` a form body + * (`FormViewSchema`): the {@link GetUiViewResponse} type is the union of the + * two. [ADR-0159 D7] A view holds lists only since @objectstack/spec 19, so + * the scaffold is typed on its own; the answer is the same as before. */ export const GetUiViewResponseSchema = lazySchema(() => ViewSchema); @@ -5170,9 +5176,11 @@ export type GetMetaItemCachedResponse = z.input; export type GetUiViewRequest = z.input; -export type GetUiViewResponse = z.input; +/** [ADR-0159 D7] The form scaffold `getUiView` answers for `type: 'form'`. */ +export type GetUiViewFormScaffold = { object: string; form: z.input }; +export type GetUiViewResponse = z.input | GetUiViewFormScaffold; /** Post-parse shape of {@link GetUiViewResponse} — defaults applied, transforms run (ADR-0122). */ -export type GetUiViewResponseParsed = z.infer; +export type GetUiViewResponseParsed = z.infer | { object: string; form: z.infer }; type AnalyticsQueryRequest = z.infer; type AnalyticsResultResponse = z.infer; diff --git a/packages/spec/src/conversions/entries/19/view-forms-to-form-items.ts b/packages/spec/src/conversions/entries/19/view-forms-to-form-items.ts index 071d6a66e15..9d4aed3b109 100644 --- a/packages/spec/src/conversions/entries/19/view-forms-to-form-items.ts +++ b/packages/spec/src/conversions/entries/19/view-forms-to-form-items.ts @@ -37,8 +37,10 @@ import { type Dict, isDict } from '../shared.js'; * after the delete arm below, so an internal record form of a taken name * is deleted rather than left. * 2. **Deleted and reported per form** when it is an internal record form, - * by ADR-0159 D1's three-part test and ⛔ not by - * `form-view-internal-not-loaded`'s `sharing.enabled` test: it sits in a + * by ADR-0159 D1's three-part test and ⛔ not by a `sharing.enabled` + * test (the one the 18 lint rule on internal form views judged by; that + * rule is retired with protocol 19, and its successor on `form` items is + * `form-consumer-less`): it sits in a * record-form slot (the container's default `form`, `formViews.default`, * `formViews.create`, an item with `isDefault: true` or named * `OBJECT.create`), declares no `sharing.publicLink`, no `type: 'form'` diff --git a/packages/spec/src/index.ts b/packages/spec/src/index.ts index 57b18cd7332..7af93cb1c43 100644 --- a/packages/spec/src/index.ts +++ b/packages/spec/src/index.ts @@ -111,7 +111,7 @@ export type { DefineStackOptions, ComposeStacksOptions, ConflictStrategy, Object export * from './stack.zod'; // DX Helper Functions (re-exported for convenience) -export { defineView, defineForm, defineMetadataForm, defineViewItem, isAggregatedViewContainer, expandViewContainer, expandViewContainerWithDiagnostics } from './ui/view.zod'; +export { defineView, defineForm, defineMetadataForm, defineViewItem, isAggregatedViewContainer, expandViewContainer, expandServedViewContainer, isServedViewItem, expandViewContainerWithDiagnostics } from './ui/view.zod'; // [#22934] Which object an aggregated `views` container binds to — the registrars' // slot key, and the identity the stack's same-stack duplicate-entry refusal reads. // `@objectstack/metadata` re-exports this declaration under the same name. @@ -126,7 +126,7 @@ export { partitionAssembledViewArtifacts, } from './ui/assembled-views.zod'; export type { AssembledViewArtifact, AssembledViewArtifactParsed, AssembledViewPartition } from './ui/assembled-views.zod'; -export type { ExpandedViewItem, ViewKeyCollision, ExpandViewResult } from './ui/view.zod'; +export type { ExpandedViewItem, ServedViewItem, ViewKeyCollision, ExpandViewResult } from './ui/view.zod'; export { defineApp } from './ui/app.zod'; export { defineFlow } from './automation/flow.zod'; export { defineJob } from './system/job.zod'; diff --git a/packages/spec/src/inline-grid-column-carriers.test.ts b/packages/spec/src/inline-grid-column-carriers.test.ts index 0b59eeae0a6..c3f0a54c95d 100644 --- a/packages/spec/src/inline-grid-column-carriers.test.ts +++ b/packages/spec/src/inline-grid-column-carriers.test.ts @@ -47,7 +47,7 @@ import { ALL_CONVERSIONS } from './conversions/registry'; import { applyConversionsToStoredItem } from './conversions/stored'; import { InlineGridColumnSchema } from './data/field.zod'; import { applyMetaMigrations } from './migrations/chain'; -import { FormViewSchema, ViewMetadataSchema } from './ui/view.zod'; +import { FormSchema, FormViewSchema, ViewMetadataSchema } from './ui/view.zod'; import { ComponentPropsMap } from './ui/component.zod'; import { defineStack } from './stack.zod'; @@ -97,18 +97,24 @@ const childObject = (inlineColumns?: unknown[]) => ({ type FormSlot = 'form' | 'formViews'; -const stackWithSubformColumns = (columns: unknown[], slot: FormSlot = 'form', child = 'crm_invoice_line') => { - const form = { ...FORM_BASE, subforms: [{ childObject: child, columns }] }; - return { - manifest, - objects: [PARENT, childObject()], - views: [{ - name: 'crm_invoice', - object: 'crm_invoice', - ...(slot === 'form' ? { form } : { formViews: { entry: form } }), - }], - }; -}; +/** + * [ADR-0159 D7] Until protocol 19 the form carrier sat on a view container, + * as its default `form` or a named `formViews` entry. A view holds lists only + * since protocol 19, so each slot is a `form` item now: the default form is + * `crm_invoice.form`, the named entry `crm_invoice.entry`. + */ +const FORM_NAME: Record = { form: 'crm_invoice.form', formViews: 'crm_invoice.entry' }; + +const stackWithSubformColumns = (columns: unknown[], slot: FormSlot = 'form', child = 'crm_invoice_line') => ({ + manifest, + objects: [PARENT, childObject()], + forms: [{ + name: FORM_NAME[slot], + object: 'crm_invoice', + ...FORM_BASE, + subforms: [{ childObject: child, columns }], + }], +}); const stackWithInlineColumns = (inlineColumns: unknown[]) => ({ manifest, @@ -197,17 +203,19 @@ describe('the form-view carrier references the column contract', () => { }); describe('defineStack judges an identity-only column by the type it renders as', () => { - it('refuses the card\'s identity-only column over a currency child field on the form view\'s `form`', () => { + // [ADR-0159 D7] These two read `View[0].form…` and `View[0].formViews.entry…` + // until protocol 19; the carrier is a `form` item now, located by its name. + it('refuses the card\'s identity-only column over a currency child field on a `form` item (the pre-19 default `form`)', () => { expectHydratedCurrencyRefusal( stackWithSubformColumns([{ name: 'quantity' }, IDENTITY_ONLY_WITH_SCALE]), - 'View[0].form.subforms[0].columns[1].scale', + "Form 'crm_invoice.form'.subforms[0].columns[1].scale", ); }); - it('refuses it on a named `formViews` entry too', () => { + it('refuses it on a second `form` item too (the pre-19 named `formViews` entry)', () => { expectHydratedCurrencyRefusal( stackWithSubformColumns([IDENTITY_ONLY_WITH_SCALE], 'formViews'), - 'View[0].formViews.entry.subforms[0].columns[0].scale', + "Form 'crm_invoice.entry'.subforms[0].columns[0].scale", ); }); @@ -359,12 +367,28 @@ describe('the `field` → `name` respelling is a chain step on the form-view car expect(conversion()?.retiredAfter).toBe('17.5.0'); }); - it('a stored row in each `view` spelling is respelled, and only then parses', () => { + /** The form body a stored row carries, in whichever spelling it is stored. */ + const formBodyOf = (row: Record): Record => { + if (row.formViews?.entry) return row.formViews.entry; + if (row.config) return row.config; + const { name: _n, object: _o, viewKind: _k, ...body } = row; + return body; + }; + + // [ADR-0159 D7] Until protocol 19 the respelled row then parsed as a `view`. + // The stored seam still respells it (stored rows are not rewritten into + // `form` items), but a view holds lists only now: the respelled row is + // refused at the `view` door, and its form body parses as a `form` item. + it('a stored row in each `view` spelling is respelled; its form body then parses as a `form` item', () => { for (const [spelling, row] of Object.entries(storedRows(LEGACY))) { expect(ViewMetadataSchema.safeParse(row).success, `${spelling}, as stored`).toBe(false); const converted = applyConversionsToStoredItem('view', structuredClone(row)) as Record; expect(columnsOf(converted), spelling).toEqual(RESPELLED); - expect(ViewMetadataSchema.safeParse(converted).success, `${spelling}, converted`).toBe(true); + expect(ViewMetadataSchema.safeParse(converted).success, `${spelling}, converted, at the view door`).toBe(false); + const asItem = FormSchema.safeParse({ name: 'crm_invoice.entry', object: 'crm_invoice', ...formBodyOf(converted) }); + expect(asItem.success, `${spelling}, converted, as a form item: ${JSON.stringify(asItem.error?.issues)}`).toBe(true); + expect(FormSchema.safeParse({ name: 'crm_invoice.entry', object: 'crm_invoice', ...formBodyOf(row) }).success, + `${spelling}, as stored, as a form item`).toBe(false); } }); @@ -376,7 +400,14 @@ describe('the `field` → `name` respelling is a chain step on the form-view car }); it('`os migrate meta` replays it: the step-18 chain respells a source stack, one edit per column', () => { - const result = applyMetaMigrations(structuredClone(stackWithSubformColumns(LEGACY, 'formViews')), 17, 18); + // A protocol-17 source: the form still sits on the view container, as it + // did then ([ADR-0159 D7] the 18 → 19 step moves it to a `form` item). + const source17 = { + manifest, + objects: [PARENT, childObject()], + views: [{ name: 'crm_invoice', object: 'crm_invoice', formViews: { entry: form(LEGACY) } }], + }; + const result = applyMetaMigrations(structuredClone(source17), 17, 18); const views = result.stack.views as Array>; expect(views[0].formViews.entry.subforms[0].columns).toEqual(RESPELLED); expect(result.applied.filter((a) => a.conversionId === ID).map((a) => a.path)).toEqual([ diff --git a/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__form.ts b/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__form.ts new file mode 100644 index 00000000000..5b12960a09a --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__form.ts @@ -0,0 +1,6 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0159 D7 — `GetUiViewResponseSchema` is `ViewSchema` by reference, so the +// response carries the `ui/View:form` tombstone (see that row): a view read +// serves lists only. +export const entry = 'api/GetUiViewResponse:form'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__formViews.ts b/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__formViews.ts new file mode 100644 index 00000000000..bedd8a40eb6 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.api__GetUiViewResponse__formViews.ts @@ -0,0 +1,5 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0159 D7 — `GetUiViewResponseSchema` is `ViewSchema` by reference, so the +// response carries the `ui/View:formViews` tombstone (see that row). +export const entry = 'api/GetUiViewResponse:formViews'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ui__View__form.ts b/packages/spec/src/migrations/entries/retired-keys/19.ui__View__form.ts new file mode 100644 index 00000000000..5b8e4086424 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ui__View__form.ts @@ -0,0 +1,9 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0159 D7 — a `view` holds lists only, and a form is its own metadata type +// (`form`, under the stack's `forms:`). The container's default `form` is +// tombstoned with `retiredKey()`, its prescription naming the `form` item +// `OBJECT.form`. Stored rows are not rewritten (they are read by the kept +// withdrawal reader and dropped from what a view serves); sources are moved by +// the D2 conversion `view-forms-to-form-items`. +export const entry = 'ui/View:form'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ui__View__formViews.ts b/packages/spec/src/migrations/entries/retired-keys/19.ui__View__formViews.ts new file mode 100644 index 00000000000..ddebe7a3ff9 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ui__View__formViews.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0159 D7 — the container's named forms, the sibling of `ui/View:form` +// (see that row). Each entry moves to a `form` item `OBJECT.KEY` by the D2 +// conversion `view-forms-to-form-items`; a create or edit form that nothing +// else opens is deleted, not moved (#36425). +export const entry = 'ui/View:formViews'; diff --git a/packages/spec/src/shared/retired-key-removal-version.pin.test.ts b/packages/spec/src/shared/retired-key-removal-version.pin.test.ts index 9de26725f91..c014e7479bc 100644 --- a/packages/spec/src/shared/retired-key-removal-version.pin.test.ts +++ b/packages/spec/src/shared/retired-key-removal-version.pin.test.ts @@ -511,7 +511,8 @@ const JOIN: Readonly> = { // refusal is read off a parse. 'view-column-state-removed': [ tombstone(VIEW_METADATA_MEMBERS.listOverlay, 'view (list overlay)', 'columnState'), - tombstone(VIEW_METADATA_MEMBERS.formOverlay, 'view (form overlay)', 'columnState'), + // [ADR-0159 D7] The form overlay member that carried the second tombstone + // was retired in protocol 19; the list overlay and the record remain. refusal( 'a view item record carrying columnState', () => VIEW_METADATA_MEMBERS.viewItem.safeParse({ diff --git a/packages/spec/src/stack-compose-duplicate-entry-census.test.ts b/packages/spec/src/stack-compose-duplicate-entry-census.test.ts index 05a9282098c..582a33e1124 100644 --- a/packages/spec/src/stack-compose-duplicate-entry-census.test.ts +++ b/packages/spec/src/stack-compose-duplicate-entry-census.test.ts @@ -111,10 +111,11 @@ const CENSUS: readonly Row[] = [ byName('aiContexts', 'AI context pack', { name: 'dupe_pack', label: 'Pack', object: 'dupe_thing', fields: ['title'] }), { // The second container binds the same object the other way round: no - // top-level `object`, the binding read off its form. + // top-level `object`, the binding read off its list. [ADR-0159 D7] It read + // the binding off a `form` until protocol 19; a view holds lists only now. key: 'views', first: { object: 'dupe_thing', list: listOf('dupe_thing') }, - second: { form: { type: 'simple', data: { provider: 'object', object: 'dupe_thing' }, sections: [{ fields: ['title'] }] } }, + second: { list: listOf('dupe_thing') }, subject: "View container 'dupe_thing'", }, { diff --git a/packages/spec/src/stack-duplicate-entry.test.ts b/packages/spec/src/stack-duplicate-entry.test.ts index b33f3ea7532..09de5778670 100644 --- a/packages/spec/src/stack-duplicate-entry.test.ts +++ b/packages/spec/src/stack-duplicate-entry.test.ts @@ -150,10 +150,10 @@ const BATCH: readonly Row[] = [ entry: { object: 'dupe_thing', list: listOf('dupe_thing') }, identity: 'dupe_thing', // A second container for the same object, written the other way round: - // no top-level `object`, the binding read off its form instead. - sameIdentity: () => ({ - form: { type: 'simple', data: { provider: 'object', object: 'dupe_thing' }, sections: [{ fields: ['title'] }] }, - }), + // no top-level `object`, the binding read off its list instead. + // [ADR-0159 D7] It read the binding off a `form` until protocol 19; a + // view holds lists only now. + sameIdentity: () => ({ list: listOf('dupe_thing') }), otherIdentity: () => ({ object: 'dupe_second', list: listOf('dupe_second') }), subject: "View container 'dupe_thing'", context: { objects: [thing, { ...thing, name: 'dupe_second', label: 'Second' }] }, diff --git a/packages/spec/src/stack-extension-hook-view-foreign-object.test.ts b/packages/spec/src/stack-extension-hook-view-foreign-object.test.ts index 22444a52b0f..a899d23163a 100644 --- a/packages/spec/src/stack-extension-hook-view-foreign-object.test.ts +++ b/packages/spec/src/stack-extension-hook-view-foreign-object.test.ts @@ -9,9 +9,11 @@ * build, even when the stack extends that object through `objectExtensions`. * ADR-0130 §1.5 records that refusal as deliberate: "the split must follow * hook ownership". A hook on an object the stack defines is accepted; - * - a top-level view whose `list` or `form` data source is an object the stack - * does not define is refused the same way, extended or not. A view on an - * object the stack defines is accepted. + * - a top-level view whose `list` data source is an object the stack does not + * define is refused the same way, extended or not. A view on an object the + * stack defines is accepted. ([ADR-0159 D7] A view's `form` was judged here + * too until protocol 19; a view holds lists only now, and a view carrying a + * `form` is refused at the schema parse, before any cross-reference.) * * Both refusals come from `validateCrossReferences` in `stack.zod.ts`, which * keeps exactly what it accepts and refuses; only the guidance text names it. @@ -65,10 +67,15 @@ describe('defineStack and a top-level view whose data source is an object outsid expect(err.message).toContain(`View[0].list references object '${FOREIGN}'`); }); - it('refuses a view whose `form` reads an object the stack only extends', () => { - const err = refusalOf({ manifest, objects: [OWN], objectExtensions: extendsForeign, views: [formView(FOREIGN)] }); - expect(err).toMatchObject({ code: 'STACK_CROSS_REFERENCE_INVALID', status: 422 }); - expect(err.message).toContain(`View[0].form references object '${FOREIGN}'`); + // [ADR-0159 D7] Refused as a cross-reference until protocol 19. The view's + // `form` is tombstoned now, so the refusal moves earlier, to the schema + // parse, and carries the D7 prescription whatever object the form reads. + it('refuses a view whose `form` reads an object the stack only extends — at the schema parse since protocol 19', () => { + for (const object of [FOREIGN, OWN.name]) { + const err = refusalOf({ manifest, objects: [OWN], objectExtensions: extendsForeign, views: [formView(object)] }); + expect(err).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); + expect(err.message).toContain('`view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)'); + } }); it('accepts a view on an object the stack defines (the control)', () => { diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 2ec4ff50a96..8c5c4aece4d 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -3479,11 +3479,10 @@ const SAME_STACK_ENTRY_IDENTITY = Object.freeze({ subject: (object) => `View container '${object}'`, consequence: () => 'The runtime files a `views` container under the object it binds to (`object`, else ' + - '`list.data.object`, else `form.data.object`, else its `name`), so these entries occupy one ' + + '`list.data.object`, else its `name`), so these entries occupy one ' + 'registry slot and only the last of them is kept in it.', remedy: () => - 'Keep one container per object: merge their `list`, `form`, `listViews` and `formViews` into a ' + - 'single entry.', + 'Keep one container per object: merge their `list` and `listViews` into a single entry.', }, apis: { identity: readEntryName, @@ -5074,9 +5073,9 @@ function collectExtensionPlacementErrors(config: ObjectStackDefinition): string[ * * - a relationship field's `inlineColumns` — the field sits on the CHILD * object, so a column names a field of the object that owns the field; - * - a form view's `subforms[].columns` (the container's `form` and each - * `formViews` entry) — a column names a field of the subform's - * `childObject`; + * - a `form` item's `subforms[].columns` — a column names a field of the + * subform's `childObject` (ADR-0159: a form is a `form` item; the view + * container's `form` and `formViews` were retired in protocol 19); * - [#20928] an `object-master-detail-form` page block's `details[].columns`, * wherever the block sits on a page ({@link forEachPageComponent}) — a column * names a field of the detail entry's `childObject`; @@ -5133,20 +5132,14 @@ function collectHydratedInlineColumnErrors(config: ObjectStackDefinition): strin } } - for (const [i, view] of (config.views ?? []).entries()) { - const forms: Array<[where: string, form: unknown]> = []; - if (view.form) forms.push([`View[${i}].form`, view.form]); - for (const [key, form] of Object.entries(view.formViews ?? {})) { - forms.push([`View[${i}].formViews.${key}`, form]); - } - for (const [where, form] of forms) { - const subforms = isRecord(form) ? form.subforms : undefined; - if (!Array.isArray(subforms)) continue; - subforms.forEach((subform: unknown, j: number) => { - if (!isRecord(subform) || typeof subform.childObject !== 'string') return; - judge(subform.columns, subform.childObject, `${where}.subforms[${j}].columns`); - }); - } + for (const [i, form] of (config.forms ?? []).entries()) { + const where = isRecord(form) && typeof form.name === 'string' ? `Form '${form.name}'` : `Form[${i}]`; + const subforms = isRecord(form) ? form.subforms : undefined; + if (!Array.isArray(subforms)) continue; + subforms.forEach((subform: unknown, j: number) => { + if (!isRecord(subform) || typeof subform.childObject !== 'string') return; + judge(subform.columns, subform.childObject, `${where}.subforms[${j}].columns`); + }); } // [#20928] The page carriers: `properties` is an open record the stack's @@ -6491,9 +6484,6 @@ function validateCrossReferences( if (view.list?.data) { checkViewData(view.list.data, `View[${i}].list`); } - if (view.form?.data) { - checkViewData(view.form.data, `View[${i}].form`); - } } } diff --git a/packages/spec/src/system/i18n-resolver.form-item.test.ts b/packages/spec/src/system/i18n-resolver.form-item.test.ts index 4372c56175c..10eee6fd229 100644 --- a/packages/spec/src/system/i18n-resolver.form-item.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-item.test.ts @@ -2,10 +2,11 @@ /** * [ADR-0159 card ② item 8] The `forms` translation family: a `form` item's - * `label`, `description`, `title` and `submitBehavior` read `forms.NAME` - * first; `title` and `submitBehavior` fall back to the `_views.KEY` tails a - * pack keyed under the old view address carries; `_views.KEY.label` is never - * read (a view's label names the view, not the form). + * `label`, `description`, `title` and `submitBehavior` read `forms.NAME`. + * Until protocol 19 `title` and `submitBehavior` fell back to the `_views.KEY` + * tails a pack keyed under the old view address carried; [ADR-0159 D8] those + * tails are tombstoned in protocol 19 and read by nothing, and `_views.KEY.label` + * was never read (a view's label names the view, not the form). */ import { describe, expect, it } from 'vitest'; @@ -42,7 +43,7 @@ const ZH_VIEWS_ONLY = { }, }; -describe('translateForm — the `forms` family, `_views` tails as fallback', () => { +describe('translateForm — the `forms` family, and no `_views` tail since protocol 19', () => { it('composes a legal pack: the `forms` group is part of the translation data', () => { const parsed = TranslationDataSchema.safeParse(ZH_FORMS); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); @@ -59,12 +60,17 @@ describe('translateForm — the `forms` family, `_views` tails as fallback', () }); }); - it('falls back to the `_views.KEY` tails for title and submitBehavior, never for the label', () => { + // [ADR-0159 D8] This case pinned the fallback until protocol 19; the + // fallback is gone, so a pack keyed only under the old address translates + // nothing of the form. + it('reads no `_views.KEY` tail for title, submitBehavior or the label (protocol 19)', () => { const bundle: TranslationBundle = { 'zh-CN': ZH_VIEWS_ONLY as any }; - const out = translateForm(clone(FORM), bundle, { locale: 'zh-CN' }) as any; - expect(out.title).toBe('旧地址标题'); - expect(out.submitBehavior.message).toBe('旧地址消息'); + const doc = clone(FORM); + const out = translateForm(doc, bundle, { locale: 'zh-CN' }) as any; + expect(out.title).toBe('Contact us'); + expect(out.submitBehavior.message).toBe('We will be in touch.'); expect(out.label).toBe('Web to lead'); + expect(out).toBe(doc); }); it('`forms.NAME` wins over the `_views` tail when both are present', () => { diff --git a/packages/spec/src/system/i18n-resolver.form-sections.test.ts b/packages/spec/src/system/i18n-resolver.form-sections.test.ts index a00fb05a0b8..8690de737ed 100644 --- a/packages/spec/src/system/i18n-resolver.form-sections.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-sections.test.ts @@ -1,11 +1,11 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Pin: `translateView` localizes a served FORM view's `sections` — each - * section's `label` and `description` — through + * Pin: a form's `sections` — each section's `label` and `description`, and + * each entry's `label`, `placeholder` and `helpText` — are localized through * `objects.._sections.`, on the shared locale chain and under - * the same catalog-vs-explicit-override rule as every other string the view - * translator overlays (ADR-0029 D9.2a). + * the same catalog-vs-explicit-override rule as every other overlaid string + * (ADR-0029 D9.2a). * * Before this, `TranslationDataSchema` declared the key, the i18n extractor * scaffolded it and objectui's form renderers resolved it client-side, but no @@ -14,24 +14,31 @@ * bundle — served every section heading as authored, beside translated field * labels. * - * The served documents below are what `expandViewContainer` emits from an - * authored container (the composer the registrars run), and both the - * container and the bundle's object node are PARSED by the authoring schemas, - * so a section address or a catalog key neither schema carries cannot pass. + * [ADR-0159 D7] Until protocol 19 these were FORM views, served by + * `expandViewContainer` with the sections under `config` and translated by + * `translateView`. A view holds lists only since protocol 19: the same bodies + * are `form` items, sections at the top level, translated by + * {@link translateForm} (whose own `forms.NAME.sections` node is pinned in + * `i18n-resolver.form-item.test.ts`; `_sections` is the object-level default + * read here). Every fixture is PARSED by `FormSchema` and the pack by the + * bundle schema, so a section address or a catalog key neither schema carries + * cannot pass. */ import { describe, it, expect } from 'vitest'; -import { translateView, translateMetadataDocument } from './i18n-resolver'; +import { translateForm, translateMetadataDocument } from './i18n-resolver'; import { ObjectTranslationDataSchema, type TranslationBundle } from './translation.zod'; -import { ViewSchema, expandViewContainer } from '../ui/view.zod'; +import { FormSchema } from '../ui/view.zod'; const clone = (v: T): T => JSON.parse(JSON.stringify(v)); -/** The container as the package ships it. */ -const CONTAINER = { - form: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, +/** The forms as the package ships them. */ +const FORMS: Record = { + // The pre-19 default form, keyed by its runtime identity `form`. + 'crm_lead.form': { + name: 'crm_lead.form', + object: 'crm_lead', + type: 'simple', sections: [ { name: 'basics', label: 'Basics', description: 'Who is asking', fields: ['name'] }, // No bundle entry — the negative control for a missing key. @@ -43,19 +50,19 @@ const CONTAINER = { { name: 'extra', fields: ['phone'] }, ], }, - formViews: { - // Retargeted at another object: its sections key under the form's OWN - // binding, the object the extractor and the linter bind them to. - referral: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_contact' }, - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, + // Bound to another object: its sections key under the form's OWN binding, + // the object the extractor and the linter bind them to. (Until protocol 19 + // this was a `crm_lead` view retargeted through `data.object`.) + 'crm_contact.referral': { + name: 'crm_contact.referral', + object: 'crm_contact', + type: 'simple', + sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], }, }; const served = (name: string): any => { - const item = expandViewContainer('crm_lead', CONTAINER).find((v) => v.name === name); + const item = FORMS[name]; if (!item) throw new Error(`fixture missing ${name}`); return item; }; @@ -80,111 +87,112 @@ const BUNDLE: TranslationBundle = { 'zh-CN': { objects: { crm_lead: LEAD_ZH, crm_contact: CONTACT_ZH } } as any, }; -const section = (view: any, name: string): any => view.config.sections.find((s: any) => s.name === name); +const section = (form: any, name: string): any => form.sections.find((s: any) => s.name === name); -describe('translateView — a form view\'s sections, keyed under `_sections`', () => { - it('composes the identity this test is pinned to — legal fixtures, sections live under `config`', () => { - expect(ViewSchema.safeParse(CONTAINER).success).toBe(true); +describe('translateForm — a form\'s sections, keyed under `_sections`', () => { + it('composes the identity this test is pinned to — legal fixtures, sections are the form item\'s own key', () => { + for (const f of Object.values(FORMS)) { + const parsed = FormSchema.safeParse(f); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + } for (const node of [LEAD_ZH, LEAD_EN, CONTACT_ZH]) { expect(ObjectTranslationDataSchema.safeParse(node).success).toBe(true); } - expect(PACKAGED.viewKind).toBe('form'); expect(PACKAGED.object).toBe('crm_lead'); - expect(PACKAGED.sections).toBeUndefined(); - expect(PACKAGED.config.sections.map((s: any) => s.name)).toEqual(['basics', 'notes', undefined, 'extra']); + expect(PACKAGED.sections.map((s: any) => s.name)).toEqual(['basics', 'notes', undefined, 'extra']); }); it('a zh-CN pack with a `_sections` key yields the translated label and description', () => { - const out = translateMetadataDocument('view', clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }); + const out = translateMetadataDocument('form', clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }); expect(section(out, 'basics')).toMatchObject({ label: '基本信息', description: '咨询人是谁', fields: ['name'] }); }); it('a missing key yields the authored text', () => { - const out = translateMetadataDocument('view', clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }); - expect(section(out, 'notes')).toEqual(PACKAGED.config.sections[1]); + const out = translateMetadataDocument('form', clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }); + expect(section(out, 'notes')).toEqual(PACKAGED.sections[1]); // A key that carries a label but no description leaves the description as authored. - const label = translateMetadataDocument('view', clone(served('crm_lead.referral')), BUNDLE, { locale: 'zh-CN' }); + const label = translateMetadataDocument('form', clone(served('crm_contact.referral')), BUNDLE, { locale: 'zh-CN' }); expect(section(label, 'basics').label).toBe('联系人基本信息'); expect(section(label, 'basics').description).toBeUndefined(); }); it('a section with no `name` is left as authored — it has no key, and its label is never slugged into one', () => { const doc = clone(PACKAGED); - const out = translateView(doc, BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.sections[2]).toBe(doc.config.sections[2]); - expect(out.config.sections[2]).toMatchObject({ label: 'Contact Details', description: 'How to reach them' }); + const out = translateForm(doc, BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.sections[2]).toBe(doc.sections[2]); + expect(out.sections[2]).toMatchObject({ label: 'Contact Details', description: 'How to reach them' }); }); it('the catalog translates authored copy only — it never adds a heading or a description', () => { - const out = translateView(clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }) as any; + const out = translateForm(clone(PACKAGED), BUNDLE, { locale: 'zh-CN' }) as any; expect(section(out, 'extra').label).toBeUndefined(); expect(section(out, 'extra').description).toBeUndefined(); }); it('an inline locale map heading is authored text and takes the catalog, as a view label does', () => { const doc = clone(PACKAGED); - doc.config.sections[0].label = { en: 'Basics', 'zh-CN': '基础' }; - const out = translateView(doc, BUNDLE, { locale: 'zh-CN' }) as any; + doc.sections[0].label = { en: 'Basics', 'zh-CN': '基础' }; + const out = translateForm(doc, BUNDLE, { locale: 'zh-CN' }) as any; expect(section(out, 'basics').label).toBe('基本信息'); }); - it('keys a retargeted form\'s sections under the form\'s own `data.object`', () => { - const referral = served('crm_lead.referral'); - expect(referral.object).toBe('crm_lead'); - const out = translateView(clone(referral), BUNDLE, { locale: 'zh-CN' }) as any; + it('keys a form\'s sections under the form\'s own `object`', () => { + const referral = served('crm_contact.referral'); + expect(referral.object).toBe('crm_contact'); + const out = translateForm(clone(referral), BUNDLE, { locale: 'zh-CN' }) as any; // `crm_lead._sections.basics` would read 基本信息; the form binds crm_contact. expect(section(out, 'basics').label).toBe('联系人基本信息'); }); it('walks the shared locale chain — BCP-47 ladder, declared fallback chain, default locale', () => { - expect(section(translateView(clone(PACKAGED), BUNDLE, { locale: 'zh' }), 'basics').label).toBe('基本信息'); - const viaChain = translateView(clone(PACKAGED), BUNDLE, { locale: 'fr-FR', fallbackChain: ['zh-CN'] }); + expect(section(translateForm(clone(PACKAGED), BUNDLE, { locale: 'zh' }), 'basics').label).toBe('基本信息'); + const viaChain = translateForm(clone(PACKAGED), BUNDLE, { locale: 'fr-FR', fallbackChain: ['zh-CN'] }); expect(section(viaChain, 'basics').label).toBe('基本信息'); // A request for the default locale never walks the chain: the authored text answers. - const asDefault = translateView(clone(PACKAGED), BUNDLE, { + const asDefault = translateForm(clone(PACKAGED), BUNDLE, { locale: 'fr-FR', defaultLocale: 'fr-FR', fallbackChain: ['zh-CN'], }); expect(section(asDefault, 'basics').label).toBe('Basics'); }); - it('returns the SAME `config` reference when no section gained a translation, and never mutates its input', () => { + it('returns the SAME document when no section gained a translation, and never mutates its input', () => { const doc = clone(PACKAGED); - expect((translateView(doc, { 'ja-JP': {} }, { locale: 'ja-JP' }) as any).config).toBe(doc.config); + expect(translateForm(doc, { 'ja-JP': {} }, { locale: 'ja-JP' })).toBe(doc); const before = clone(doc); - translateView(doc, BUNDLE, { locale: 'zh-CN' }); + translateForm(doc, BUNDLE, { locale: 'zh-CN' }); expect(doc).toEqual(before); }); }); -describe('translateView — a form section\'s copy loses to an explicit override (ADR-0029 D9.2a)', () => { - it('an unedited form view gets the catalog for every section string', () => { - const out = translateView(clone(PACKAGED), BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); +describe('translateForm — a form section\'s copy loses to an explicit override (ADR-0029 D9.2a)', () => { + it('an unedited form gets the catalog for every section string', () => { + const out = translateForm(clone(PACKAGED), BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); expect(section(out, 'basics')).toMatchObject({ label: '基本信息', description: '咨询人是谁' }); }); it('an edited heading is served as edited — in zh-CN and in the source locale — and judged apart from its description', () => { const doc = clone(PACKAGED); - doc.config.sections[0].label = 'Basics (edited)'; + doc.sections[0].label = 'Basics (edited)'; for (const locale of ['zh-CN', 'en']) { - const out = translateView(doc, BUNDLE, { locale, packagedBase: PACKAGED }); + const out = translateForm(doc, BUNDLE, { locale, packagedBase: PACKAGED }); expect(section(out, 'basics').label, locale).toBe('Basics (edited)'); } - expect(section(translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }), 'basics').description) + expect(section(translateForm(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }), 'basics').description) .toBe('咨询人是谁'); }); it('a section the package does not ship was authored after the fact and keeps its strings', () => { const doc = clone(PACKAGED); - doc.config.sections[0].name = 'contact_details'; - doc.config.sections[0].label = 'Added by the org'; - const out = translateView(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); + doc.sections[0].name = 'contact_details'; + doc.sections[0].label = 'Added by the org'; + const out = translateForm(doc, BUNDLE, { locale: 'zh-CN', packagedBase: PACKAGED }); expect(section(out, 'contact_details').label).toBe('Added by the org'); }); it('NO packaged base supplied → the catalog applies (the control)', () => { const doc = clone(PACKAGED); - doc.config.sections[0].label = 'Basics (edited)'; - expect(section(translateView(doc, BUNDLE, { locale: 'zh-CN' }), 'basics').label).toBe('基本信息'); + doc.sections[0].label = 'Basics (edited)'; + expect(section(translateForm(doc, BUNDLE, { locale: 'zh-CN' }), 'basics').label).toBe('基本信息'); }); }); @@ -193,32 +201,29 @@ describe('translateView — a form section\'s copy loses to an explicit override * `helpText` for that form alone, and those three are addressed under the * section's own node: `objects.._sections.
.fields.`. */ -const ENTRY_CONTAINER = { - form: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_case' }, - sections: [ - { - name: 'submitter', - label: 'About you', - fields: [ - { field: 'contact_name', label: 'Your name', placeholder: 'Jane Doe', helpText: 'As on your ID' }, - // Authors only a label: the catalog never adds a placeholder or help text. - { field: 'contact_email', label: 'Your email' }, - // A bare name authors no copy at all. - 'subject', - // No bundle entry — the negative control for a missing key. - { field: 'phone', label: 'Your phone', placeholder: '+1 555', helpText: 'Optional' }, - ], - }, - // No `name`: its entries have no address, whatever the bundle carries. - { label: 'Details', fields: [{ field: 'description', label: 'What happened' }] }, - ], - }, +const ENTRY_PACKAGED: any = { + name: 'crm_case.form', + object: 'crm_case', + type: 'simple', + sections: [ + { + name: 'submitter', + label: 'About you', + fields: [ + { field: 'contact_name', label: 'Your name', placeholder: 'Jane Doe', helpText: 'As on your ID' }, + // Authors only a label: the catalog never adds a placeholder or help text. + { field: 'contact_email', label: 'Your email' }, + // A bare name authors no copy at all. + 'subject', + // No bundle entry — the negative control for a missing key. + { field: 'phone', label: 'Your phone', placeholder: '+1 555', helpText: 'Optional' }, + ], + }, + // No `name`: its entries have no address, whatever the bundle carries. + { label: 'Details', fields: [{ field: 'description', label: 'What happened' }] }, + ], }; -const ENTRY_PACKAGED: any = expandViewContainer('crm_case', ENTRY_CONTAINER).find((v) => v.name === 'crm_case.form'); - const CASE_ZH = { _sections: { submitter: { @@ -235,72 +240,72 @@ const CASE_ZH = { const ENTRY_BUNDLE: TranslationBundle = { 'zh-CN': { objects: { crm_case: CASE_ZH } } as any }; -const entry = (view: any, sectionIndex: number, field: string): any => - view.config.sections[sectionIndex].fields.find((f: any) => (typeof f === 'string' ? f : f.field) === field); +const entry = (form: any, sectionIndex: number, field: string): any => + form.sections[sectionIndex].fields.find((f: any) => (typeof f === 'string' ? f : f.field) === field); -describe('translateView — a form section entry\'s copy, keyed under `_sections.
.fields.`', () => { - it('composes legal fixtures — the container and the pack node both parse', () => { - expect(ViewSchema.safeParse(ENTRY_CONTAINER).success).toBe(true); +describe('translateForm — a form section entry\'s copy, keyed under `_sections.
.fields.`', () => { + it('composes legal fixtures — the form and the pack node both parse', () => { + expect(FormSchema.safeParse(ENTRY_PACKAGED).success).toBe(true); expect(ObjectTranslationDataSchema.safeParse(CASE_ZH).success).toBe(true); - expect(ENTRY_PACKAGED.config.sections[0].fields).toHaveLength(4); + expect(ENTRY_PACKAGED.sections[0].fields).toHaveLength(4); }); it('a zh-CN pack yields the translated entry `label`', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(entry(out, 0, 'contact_name').label).toBe('您的姓名'); }); it('a zh-CN pack yields the translated entry `placeholder`', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(entry(out, 0, 'contact_name').placeholder).toBe('张三'); }); it('a zh-CN pack yields the translated entry `helpText`', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(entry(out, 0, 'contact_name').helpText).toBe('与证件一致'); // The section heading beside it is translated by the same reading. - expect(out.config.sections[0].label).toBe('关于您'); + expect(out.sections[0].label).toBe('关于您'); }); it('a missing key yields the authored entry copy', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); - expect(entry(out, 0, 'phone')).toEqual(ENTRY_PACKAGED.config.sections[0].fields[3]); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + expect(entry(out, 0, 'phone')).toEqual(ENTRY_PACKAGED.sections[0].fields[3]); }); it('only authored copy is translated — the catalog never adds a placeholder or help text, nor copy to a bare name', () => { - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(entry(out, 0, 'contact_email')).toEqual({ field: 'contact_email', label: '您的邮箱' }); expect(entry(out, 0, 'subject')).toBe('subject'); }); it('an entry of a section with no `name` is left as authored', () => { const doc = clone(ENTRY_PACKAGED); - const out = translateView(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.sections[1]).toBe(doc.config.sections[1]); + const out = translateForm(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.sections[1]).toBe(doc.sections[1]); }); it('an edited entry string keeps its value against the packaged base, judged apart from its siblings', () => { const doc = clone(ENTRY_PACKAGED); - doc.config.sections[0].fields[0].label = 'Full name (edited)'; - const out = translateView(doc, ENTRY_BUNDLE, { locale: 'zh-CN', packagedBase: ENTRY_PACKAGED }); + doc.sections[0].fields[0].label = 'Full name (edited)'; + const out = translateForm(doc, ENTRY_BUNDLE, { locale: 'zh-CN', packagedBase: ENTRY_PACKAGED }); expect(entry(out, 0, 'contact_name')).toMatchObject({ label: 'Full name (edited)', placeholder: '张三', helpText: '与证件一致', }); // NO packaged base supplied → the catalog applies (the control). - expect(entry(translateView(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }), 0, 'contact_name').label).toBe('您的姓名'); + expect(entry(translateForm(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }), 0, 'contact_name').label).toBe('您的姓名'); }); it('an entry the packaged section does not carry was authored after the fact and keeps its strings', () => { const base = clone(ENTRY_PACKAGED); - base.config.sections[0].fields = base.config.sections[0].fields.slice(1); - const out = translateView(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN', packagedBase: base }); + base.sections[0].fields = base.sections[0].fields.slice(1); + const out = translateForm(clone(ENTRY_PACKAGED), ENTRY_BUNDLE, { locale: 'zh-CN', packagedBase: base }); expect(entry(out, 0, 'contact_name').label).toBe('Your name'); }); it('never mutates its input', () => { const doc = clone(ENTRY_PACKAGED); const before = clone(doc); - translateView(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }); + translateForm(doc, ENTRY_BUNDLE, { locale: 'zh-CN' }); expect(doc).toEqual(before); }); }); diff --git a/packages/spec/src/system/i18n-resolver.form-thank-you.test.ts b/packages/spec/src/system/i18n-resolver.form-thank-you.test.ts index 9b23c4874af..2ae04bbe5da 100644 --- a/packages/spec/src/system/i18n-resolver.form-thank-you.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-thank-you.test.ts @@ -1,184 +1,157 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Pin: `translateView` localizes a served FORM view's thank-you panel — the - * `title` and `message` of a `kind: 'thank-you'` `FormViewSchema - * .submitBehavior`, served at `config.submitBehavior` — through - * `objects.._views..submitBehavior.{title,message}`, on the - * shared locale chain and under the same catalog-vs-explicit-override rule as - * every other string the view translator overlays (ADR-0029 D9.2a). + * Pin: a form's thank-you panel (the `title` and `message` of a + * `kind: 'thank-you'` `submitBehavior`) is localized on the shared locale chain + * and under the same catalog-vs-explicit-override rule as every other overlaid + * string (ADR-0029 D9.2a). * - * Before this, the panel had no translation key at all: the strict `_views` - * entry declared no `submitBehavior`, and `translateView` never read - * `config.submitBehavior`. A public form read in another language showed a - * translated heading and field labels, then confirmed the submit in the - * authoring language. - * - * The served documents below are what `expandViewContainer` emits from an - * authored container, and both the container and the bundle's object node are - * PARSED by the authoring schemas, so an address neither schema carries cannot - * pass. + * Before protocol 19 the panel belonged to a FORM view, served at + * `config.submitBehavior`, and was translated through + * `objects.._views..submitBehavior.{title,message}`. + * [ADR-0159 D7/D8] A view holds lists only since protocol 19 and a form is a + * `form` item: the panel is translated through `forms..submitBehavior` + * by {@link translateForm}, and `translateView` reads no `_views` form tail. + * Each case below is the pre-19 case, rewritten to that answer; the last blocks + * pin the panel face at its new address and the old address as refused. */ import { describe, it, expect } from 'vitest'; -import { translateView, translateMetadataDocument } from './i18n-resolver'; -import { ObjectTranslationDataSchema, type TranslationBundle } from './translation.zod'; -import { ViewSchema, expandViewContainer } from '../ui/view.zod'; +import { translateForm, translateView, translateMetadataDocument } from './i18n-resolver'; +import { ObjectTranslationDataSchema, TranslationDataSchema, type TranslationBundle } from './translation.zod'; +import { FormSchema, expandViewContainer } from '../ui/view.zod'; const clone = (v: T): T => JSON.parse(JSON.stringify(v)); -const data = { provider: 'object' as const, object: 'crm_lead' }; const sections = [{ name: 'basics', label: 'Basics', fields: ['name'] }]; +const form = (name: string, extra: Record): any => ({ + name: `crm_lead.${name}`, + object: 'crm_lead', + type: 'simple', + sections, + ...extra, +}); -const CONTAINER = { - form: { - type: 'simple' as const, - data, - sections, - submitBehavior: { kind: 'thank-you' as const, title: 'Saved', message: 'The lead is in.' }, - }, - formViews: { - web_to_lead: { - type: 'simple' as const, - data, - title: 'Contact us', - sections, - submitBehavior: { kind: 'thank-you' as const, title: 'Thanks!', message: 'We will reach out shortly.' }, - }, - // Authors a title and no message: the bundle's message must not invent one. - title_only: { - type: 'simple' as const, - data, - sections, - submitBehavior: { kind: 'thank-you' as const, title: 'Got it' }, - }, - // Not a thank-you panel: its keys translate nothing. - redirect: { - type: 'simple' as const, - data, - sections, - submitBehavior: { kind: 'redirect' as const, url: '/thanks' }, - }, - // Authors a panel the bundle carries no key for. - referral: { - type: 'simple' as const, - data, - sections, - submitBehavior: { kind: 'thank-you' as const, title: 'Referral sent', message: 'Thank you for the referral.' }, - }, - }, -}; - -const served = (name: string): any => { - const item = expandViewContainer('crm_lead', CONTAINER).find((v) => v.name === name); - if (!item) throw new Error(`fixture missing ${name}`); - return item; +const FORMS: Record = { + // The pre-19 default form, keyed by its runtime identity `form`. + form: form('form', { submitBehavior: { kind: 'thank-you', title: 'Saved', message: 'The lead is in.' } }), + web_to_lead: form('web_to_lead', { + title: 'Contact us', + submitBehavior: { kind: 'thank-you', title: 'Thanks!', message: 'We will reach out shortly.' }, + }), + // Authors a title and no message: the bundle's message must not invent one. + title_only: form('title_only', { submitBehavior: { kind: 'thank-you', title: 'Got it' } }), + // Not a thank-you panel: its keys translate nothing. + redirect: form('redirect', { submitBehavior: { kind: 'redirect', url: '/thanks' } }), + // Authors a panel the bundle carries no key for. + referral: form('referral', { + submitBehavior: { kind: 'thank-you', title: 'Referral sent', message: 'Thank you for the referral.' }, + }), }; -const LEAD_ZH = { - _views: { - web_to_lead: { +const ZH = { + forms: { + 'crm_lead.web_to_lead': { title: '联系我们', submitBehavior: { title: '感谢您!', message: '我们会尽快与您联系。' }, }, - form: { submitBehavior: { title: '已保存', message: '线索已录入。' } }, - title_only: { submitBehavior: { title: '收到', message: 'MUST-NOT-APPLY' } }, - redirect: { submitBehavior: { title: 'MUST-NOT-APPLY', message: 'MUST-NOT-APPLY' } }, + 'crm_lead.form': { submitBehavior: { title: '已保存', message: '线索已录入。' } }, + 'crm_lead.title_only': { submitBehavior: { title: '收到', message: 'MUST-NOT-APPLY' } }, + 'crm_lead.redirect': { submitBehavior: { title: 'MUST-NOT-APPLY', message: 'MUST-NOT-APPLY' } }, }, }; -const LEAD_EN = { _views: { web_to_lead: { submitBehavior: { title: 'Thanks!' } } } }; +const EN = { forms: { 'crm_lead.web_to_lead': { submitBehavior: { title: 'Thanks!' } } } }; const BUNDLE: TranslationBundle = { - en: { objects: { crm_lead: LEAD_EN } } as any, - 'zh-CN': { objects: { crm_lead: LEAD_ZH } } as any, + en: EN as any, + 'zh-CN': ZH as any, }; -describe("translateView — a form view's thank-you panel, keyed `_views..submitBehavior`", () => { - it('composes the identity this test is pinned to — legal fixtures, the panel lives under `config`', () => { - expect(ViewSchema.safeParse(CONTAINER).success).toBe(true); - for (const node of [LEAD_ZH, LEAD_EN]) { - const parsed = ObjectTranslationDataSchema.safeParse(node); +describe("translateForm — a form's thank-you panel, keyed `forms..submitBehavior` (protocol 19)", () => { + it('composes the identity this test is pinned to — legal fixtures, the panel is the form item\'s own key', () => { + for (const f of Object.values(FORMS)) { + const parsed = FormSchema.safeParse(f); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + } + for (const pack of [ZH, EN]) { + const parsed = TranslationDataSchema.safeParse(pack); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); } - const item = served('crm_lead.web_to_lead'); - expect(item.viewKind).toBe('form'); - expect(item.config.submitBehavior).toEqual(CONTAINER.formViews.web_to_lead.submitBehavior); }); it('a zh-CN pack yields the translated panel title and message', () => { - const out = translateMetadataDocument('view', clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'zh-CN' }); - expect(out.config.submitBehavior).toEqual({ kind: 'thank-you', title: '感谢您!', message: '我们会尽快与您联系。' }); + const out = translateMetadataDocument('form', clone(FORMS.web_to_lead), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.submitBehavior).toEqual({ kind: 'thank-you', title: '感谢您!', message: '我们会尽快与您联系。' }); // The form heading is translated beside it, from its own key. - expect(out.config.title).toBe('联系我们'); - // The default form is keyed by its runtime identity, `form`. - const def = translateMetadataDocument('view', clone(served('crm_lead.form')), BUNDLE, { locale: 'zh-CN' }); - expect(def.config.submitBehavior).toEqual({ kind: 'thank-you', title: '已保存', message: '线索已录入。' }); + expect(out.title).toBe('联系我们'); + const def = translateMetadataDocument('form', clone(FORMS.form), BUNDLE, { locale: 'zh-CN' }) as any; + expect(def.submitBehavior).toEqual({ kind: 'thank-you', title: '已保存', message: '线索已录入。' }); }); it('a locale the bundle lacks reads the declared fallback chain — ja-JP over `[zh-CN]`', () => { - const out = translateView(clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'ja-JP', fallbackChain: ['zh-CN'] }) as any; - expect(out.config.submitBehavior.title).toBe('感谢您!'); - expect(out.config.submitBehavior.message).toBe('我们会尽快与您联系。'); + const out = translateForm(clone(FORMS.web_to_lead), BUNDLE, { locale: 'ja-JP', fallbackChain: ['zh-CN'] }) as any; + expect(out.submitBehavior.title).toBe('感谢您!'); + expect(out.submitBehavior.message).toBe('我们会尽快与您联系。'); }); it('a missing key yields the authored panel', () => { - const out = translateView(clone(served('crm_lead.referral')), BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.submitBehavior).toEqual(CONTAINER.formViews.referral.submitBehavior); + const out = translateForm(clone(FORMS.referral), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.submitBehavior).toEqual(FORMS.referral.submitBehavior); }); it('CONTROL: a panel that authors no message gains none — the bundle key does not invent one', () => { - const out = translateView(clone(served('crm_lead.title_only')), BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.submitBehavior).toEqual({ kind: 'thank-you', title: '收到' }); - expect('message' in out.config.submitBehavior).toBe(false); + const out = translateForm(clone(FORMS.title_only), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.submitBehavior).toEqual({ kind: 'thank-you', title: '收到' }); + expect('message' in out.submitBehavior).toBe(false); }); - it('CONTROL: a `redirect` behavior is not a panel — its keys translate nothing and its `config` reference is kept', () => { - const doc = clone(served('crm_lead.redirect')); - const out = translateView(doc, BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config).toBe(doc.config); - expect(out.config.submitBehavior).toEqual({ kind: 'redirect', url: '/thanks' }); + it('CONTROL: a `redirect` behavior is not a panel — its keys translate nothing and its reference is kept', () => { + const doc = clone(FORMS.redirect); + const out = translateForm(doc, BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.submitBehavior).toBe(doc.submitBehavior); + expect(out.submitBehavior).toEqual({ kind: 'redirect', url: '/thanks' }); }); it('CONTROL: the panel title key does not reach the form heading, and the heading key does not reach the panel', () => { const headingOnly: TranslationBundle = { - 'zh-CN': { objects: { crm_lead: { _views: { web_to_lead: { title: '联系我们' } } } } } as any, + 'zh-CN': { forms: { 'crm_lead.web_to_lead': { title: '联系我们' } } } as any, }; - const viaHeading = translateView(clone(served('crm_lead.web_to_lead')), headingOnly, { locale: 'zh-CN' }) as any; - expect(viaHeading.config.title).toBe('联系我们'); - expect(viaHeading.config.submitBehavior.title).toBe('Thanks!'); + const viaHeading = translateForm(clone(FORMS.web_to_lead), headingOnly, { locale: 'zh-CN' }) as any; + expect(viaHeading.title).toBe('联系我们'); + expect(viaHeading.submitBehavior.title).toBe('Thanks!'); const panelOnly: TranslationBundle = { - 'zh-CN': { objects: { crm_lead: { _views: { web_to_lead: { submitBehavior: { title: '感谢您!' } } } } } } as any, + 'zh-CN': { forms: { 'crm_lead.web_to_lead': { submitBehavior: { title: '感谢您!' } } } } as any, }; - const viaPanel = translateView(clone(served('crm_lead.web_to_lead')), panelOnly, { locale: 'zh-CN' }) as any; - expect(viaPanel.config.title).toBe('Contact us'); - expect(viaPanel.config.submitBehavior.title).toBe('感谢您!'); + const viaPanel = translateForm(clone(FORMS.web_to_lead), panelOnly, { locale: 'zh-CN' }) as any; + expect(viaPanel.title).toBe('Contact us'); + expect(viaPanel.submitBehavior.title).toBe('感谢您!'); }); - it('an override beats the catalog — an edited panel string keeps the edit against the packaged view, per string', () => { - const packaged = served('crm_lead.web_to_lead'); + it('an override beats the catalog — an edited panel string keeps the edit against the packaged form, per string', () => { + const packaged = FORMS.web_to_lead; const edited = clone(packaged); - edited.config.submitBehavior.message = 'Sales will call you (edited)'; - const out = translateView(edited, BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; - expect(out.config.submitBehavior.message).toBe('Sales will call you (edited)'); + edited.submitBehavior.message = 'Sales will call you (edited)'; + const out = translateForm(edited, BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; + expect(out.submitBehavior.message).toBe('Sales will call you (edited)'); // The unedited sibling string, judged against the same base, translates. - expect(out.config.submitBehavior.title).toBe('感谢您!'); - // A packaged view with no panel makes every served string an authored one. + expect(out.submitBehavior.title).toBe('感谢您!'); + // A packaged form with no panel makes every served string an authored one. const bare = clone(packaged); - delete bare.config.submitBehavior; - const authored = translateView(clone(packaged), BUNDLE, { locale: 'zh-CN', packagedBase: bare }) as any; - expect(authored.config.submitBehavior.title).toBe('Thanks!'); + delete bare.submitBehavior; + const authored = translateForm(clone(packaged), BUNDLE, { locale: 'zh-CN', packagedBase: bare }) as any; + expect(authored.submitBehavior.title).toBe('Thanks!'); }); it('the served document is not mutated', () => { - const doc = clone(served('crm_lead.web_to_lead')); - translateView(doc, BUNDLE, { locale: 'zh-CN' }); - expect(doc.config.submitBehavior).toEqual(CONTAINER.formViews.web_to_lead.submitBehavior); + const doc = clone(FORMS.web_to_lead); + translateForm(doc, BUNDLE, { locale: 'zh-CN' }); + expect(doc.submitBehavior).toEqual(FORMS.web_to_lead.submitBehavior); }); }); -describe('the `_views..submitBehavior` translation face', () => { +describe('the `forms..submitBehavior` translation face', () => { const issuesOf = (node: unknown) => { - const parsed = ObjectTranslationDataSchema.safeParse({ _views: { web_to_lead: node } }); + const parsed = TranslationDataSchema.safeParse({ forms: { 'crm_lead.web_to_lead': node } }); return parsed.success ? [] : parsed.error.issues; }; @@ -186,7 +159,7 @@ describe('the `_views..submitBehavior` translation face', () => { expect(issuesOf({ submitBehavior: { title: '感谢您!', message: '我们会尽快与您联系。' } })).toEqual([]); const [issue] = issuesOf({ submitBehavior: { title: '感谢您!', url: '/zh/thanks' } }); expect(issue?.code).toBe('unrecognized_keys'); - expect(issue?.path).toEqual(['_views', 'web_to_lead', 'submitBehavior']); + expect(issue?.path).toEqual(['forms', 'crm_lead.web_to_lead', 'submitBehavior']); }); it('refuses a copied `kind` with a prescription naming the two translatable strings', () => { @@ -195,3 +168,27 @@ describe('the `_views..submitBehavior` translation face', () => { expect(issue?.message).toContain('`title` and `message`'); }); }); + +describe('the pre-19 address `objects.._views..submitBehavior` (ADR-0159 D8)', () => { + const OLD_PACK = { _views: { web_to_lead: { submitBehavior: { title: '感谢您!', message: '我们会尽快与您联系。' } } } }; + + it('is refused at the bundle, with the prescription naming `forms[\'OBJECT.KEY\'].submitBehavior`', () => { + const r = ObjectTranslationDataSchema.safeParse(OLD_PACK); + expect(r.success).toBe(false); + const issue = r.error?.issues.find((i) => i.path.join('.') === '_views.web_to_lead.submitBehavior'); + expect(issue?.message, JSON.stringify(r.error?.issues)).toMatch( + /^`translation\.objects\.OBJECT\._views\.KEY\.submitBehavior` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D8\)/, + ); + expect(issue?.message).toContain("forms['OBJECT.KEY'].submitBehavior"); + }); + + it('is read by nothing: neither `translateForm` nor `translateView` takes a panel string from it', () => { + const bundle: TranslationBundle = { 'zh-CN': { objects: { crm_lead: OLD_PACK } } as any }; + expect((translateForm(clone(FORMS.web_to_lead), bundle, { locale: 'zh-CN' }) as any).submitBehavior) + .toEqual(FORMS.web_to_lead.submitBehavior); + // A served view is a list since protocol 19; the tail reaches no key of it. + const list = clone(expandViewContainer('crm_lead', { list: { type: 'grid', columns: ['name'] } })[0]!) as any; + const out = translateView(list, bundle, { locale: 'zh-CN' }) as any; + expect(out.config.submitBehavior).toBeUndefined(); + }); +}); diff --git a/packages/spec/src/system/i18n-resolver.form-title.test.ts b/packages/spec/src/system/i18n-resolver.form-title.test.ts index 262b84d13f4..a0529801700 100644 --- a/packages/spec/src/system/i18n-resolver.form-title.test.ts +++ b/packages/spec/src/system/i18n-resolver.form-title.test.ts @@ -1,154 +1,152 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Pin: `translateView` localizes a served FORM view's `title` - * (`FormViewSchema.title`, served at `config.title`) through - * `objects.._views..title`, on the shared locale chain and under - * the same catalog-vs-explicit-override rule as every other string the view - * translator overlays (ADR-0029 D9.2a). + * Pin: a form's `title` (the heading a public form shows above its sections) + * is localized on the shared locale chain and under the same + * catalog-vs-explicit-override rule as every other overlaid string + * (ADR-0029 D9.2a). * - * Before this, the title had no translation key at all: the `_views` entry - * named `title` as a rename onto `label`, and `translateView` never read - * `config.title`. A public form that declared a title served it in the - * authoring language to every visitor, so an app could not give a public form - * a localized title. + * Before protocol 19 the heading belonged to a FORM view, served at + * `config.title`, and was translated through `objects.._views..title`. + * [ADR-0159 D7/D8] A view holds lists only since protocol 19 and a form is a + * `form` item: the heading is translated through `forms..title` by + * {@link translateForm}, and `translateView` reads no `_views` form tail. Each + * case below is the pre-19 case, rewritten to that answer; the last block pins + * the old address as refused at the bundle and read by nothing. * - * `title` is its own key, not the view's `label` key, because they are two - * authored strings: a view item's `label` names the view (and a form-family - * container entry carries none), while the form's `title` is the heading the - * form shows. One translation cannot stand for two source strings. - * - * The served documents below are what `expandViewContainer` emits from an - * authored container, and both the container and the bundle's object node are - * PARSED by the authoring schemas, so an address neither schema carries cannot - * pass. + * `title` is its own key, not the form's `label` key, because they are two + * authored strings: the `label` names the form, the `title` is its heading. One + * translation cannot stand for two source strings. */ import { describe, it, expect } from 'vitest'; -import { translateView, translateMetadataDocument } from './i18n-resolver'; -import { ObjectTranslationDataSchema, type TranslationBundle } from './translation.zod'; -import { ViewSchema, expandViewContainer } from '../ui/view.zod'; +import { translateForm, translateView, translateMetadataDocument } from './i18n-resolver'; +import { ObjectTranslationDataSchema, TranslationDataSchema, type TranslationBundle } from './translation.zod'; +import { FormSchema, ViewSchema, expandViewContainer } from '../ui/view.zod'; const clone = (v: T): T => JSON.parse(JSON.stringify(v)); -const CONTAINER = { - form: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, - title: 'New lead', - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, - formViews: { - web_to_lead: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, - title: 'Contact us', - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, - // Authors no title: the bundle's key must not invent one. - quick: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, - // Authors a title the bundle carries no key for. - referral: { - type: 'simple' as const, - data: { provider: 'object' as const, object: 'crm_lead' }, - title: 'Refer a friend', - sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], - }, - }, -}; +const form = (name: string, extra: Record = {}): any => ({ + name: `crm_lead.${name}`, + object: 'crm_lead', + type: 'simple', + sections: [{ name: 'basics', label: 'Basics', fields: ['name'] }], + ...extra, +}); -const served = (name: string): any => { - const item = expandViewContainer('crm_lead', CONTAINER).find((v) => v.name === name); - if (!item) throw new Error(`fixture missing ${name}`); - return item; +const FORMS: Record = { + // The pre-19 default form, keyed by its runtime identity `form`. + form: form('form', { title: 'New lead' }), + web_to_lead: form('web_to_lead', { label: 'Web to lead', title: 'Contact us' }), + // Authors no title: the bundle's key must not invent one. + quick: form('quick'), + // Authors a title the bundle carries no key for. + referral: form('referral', { title: 'Refer a friend' }), }; -const LEAD_ZH = { - label: '线索', - _views: { - web_to_lead: { title: '联系我们' }, - form: { title: '新建线索' }, - quick: { title: 'MUST-NOT-APPLY' }, +const ZH = { + forms: { + 'crm_lead.web_to_lead': { title: '联系我们' }, + 'crm_lead.form': { title: '新建线索' }, + 'crm_lead.quick': { title: 'MUST-NOT-APPLY' }, }, }; -const LEAD_EN = { _views: { web_to_lead: { title: 'Contact us' } } }; +const EN = { forms: { 'crm_lead.web_to_lead': { title: 'Contact us' } } }; const BUNDLE: TranslationBundle = { - en: { objects: { crm_lead: LEAD_EN } } as any, - 'zh-CN': { objects: { crm_lead: LEAD_ZH } } as any, + en: EN as any, + 'zh-CN': ZH as any, }; -describe('translateView — a form view\'s title, keyed `_views..title`', () => { - it('composes the identity this test is pinned to — legal fixtures, the title lives under `config`', () => { - expect(ViewSchema.safeParse(CONTAINER).success).toBe(true); - for (const node of [LEAD_ZH, LEAD_EN]) { - const parsed = ObjectTranslationDataSchema.safeParse(node); +describe('translateForm — a form\'s title, keyed `forms..title` (protocol 19)', () => { + it('composes the identity this test is pinned to — legal fixtures, the title is the form item\'s own key', () => { + for (const f of Object.values(FORMS)) { + const parsed = FormSchema.safeParse(f); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + } + for (const pack of [ZH, EN]) { + const parsed = TranslationDataSchema.safeParse(pack); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); } - const item = served('crm_lead.web_to_lead'); - expect(item.viewKind).toBe('form'); - expect(item.label).toBeUndefined(); - expect(item.config.title).toBe('Contact us'); + expect(FORMS.web_to_lead.title).toBe('Contact us'); }); - it('a zh-CN pack with a `_views..title` key yields the translated title', () => { - const out = translateMetadataDocument('view', clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'zh-CN' }); - expect(out.config.title).toBe('联系我们'); - // The default form is keyed by its runtime identity, `form`. - const def = translateMetadataDocument('view', clone(served('crm_lead.form')), BUNDLE, { locale: 'zh-CN' }); - expect(def.config.title).toBe('新建线索'); + it('a zh-CN pack with a `forms..title` key yields the translated title', () => { + const out = translateMetadataDocument('form', clone(FORMS.web_to_lead), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.title).toBe('联系我们'); + const def = translateMetadataDocument('form', clone(FORMS.form), BUNDLE, { locale: 'zh-CN' }) as any; + expect(def.title).toBe('新建线索'); }); it('a locale the bundle lacks reads the declared fallback chain — ja-JP over `[zh-CN]`', () => { - const out = translateView(clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'ja-JP', fallbackChain: ['zh-CN'] }) as any; - expect(out.config.title).toBe('联系我们'); + const out = translateForm(clone(FORMS.web_to_lead), BUNDLE, { locale: 'ja-JP', fallbackChain: ['zh-CN'] }) as any; + expect(out.title).toBe('联系我们'); }); it('a missing key yields the authored title', () => { - const out = translateView(clone(served('crm_lead.referral')), BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.title).toBe('Refer a friend'); + const out = translateForm(clone(FORMS.referral), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.title).toBe('Refer a friend'); }); it('CONTROL: a form that authors no title gains none — the bundle key does not invent one', () => { - const doc = clone(served('crm_lead.quick')); - const out = translateView(doc, BUNDLE, { locale: 'zh-CN' }) as any; - expect(out.config.title).toBeUndefined(); - expect('title' in out.config).toBe(false); + const out = translateForm(clone(FORMS.quick), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.title).toBeUndefined(); + expect('title' in out).toBe(false); }); - it('CONTROL: the title key does not leak into the view `label`, and the `label` key does not reach the title', () => { - const out = translateView(clone(served('crm_lead.web_to_lead')), BUNDLE, { locale: 'zh-CN' }) as any; - // No `_views.web_to_lead.label` key: the label falls back to the item's - // name, exactly as before this change. - expect(out.label).toBe('crm_lead.web_to_lead'); + it('CONTROL: the title key does not leak into the form `label`, and the `label` key does not reach the title', () => { + const out = translateForm(clone(FORMS.web_to_lead), BUNDLE, { locale: 'zh-CN' }) as any; + expect(out.label).toBe('Web to lead'); const labelOnly: TranslationBundle = { - 'zh-CN': { objects: { crm_lead: { _views: { web_to_lead: { label: '网页线索' } } } } } as any, + 'zh-CN': { forms: { 'crm_lead.web_to_lead': { label: '网页线索' } } } as any, }; - const viaLabel = translateView(clone(served('crm_lead.web_to_lead')), labelOnly, { locale: 'zh-CN' }) as any; + const viaLabel = translateForm(clone(FORMS.web_to_lead), labelOnly, { locale: 'zh-CN' }) as any; expect(viaLabel.label).toBe('网页线索'); - expect(viaLabel.config.title).toBe('Contact us'); + expect(viaLabel.title).toBe('Contact us'); }); - it('an override beats the catalog — an edited title keeps the edit against the packaged view', () => { - const packaged = served('crm_lead.web_to_lead'); + it('an override beats the catalog — an edited title keeps the edit against the packaged form', () => { + const packaged = FORMS.web_to_lead; const edited = clone(packaged); - edited.config.title = 'Talk to sales (edited)'; - const out = translateView(edited, BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; - expect(out.config.title).toBe('Talk to sales (edited)'); + edited.title = 'Talk to sales (edited)'; + const out = translateForm(edited, BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; + expect(out.title).toBe('Talk to sales (edited)'); // CONTROL: the unedited title, judged against the same base, translates. - const same = translateView(clone(packaged), BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; - expect(same.config.title).toBe('联系我们'); + const same = translateForm(clone(packaged), BUNDLE, { locale: 'zh-CN', packagedBase: packaged }) as any; + expect(same.title).toBe('联系我们'); }); - it('the served document is not mutated, and a form with nothing to translate keeps its `config` reference', () => { - const doc = clone(served('crm_lead.web_to_lead')); - translateView(doc, BUNDLE, { locale: 'zh-CN' }); - expect(doc.config.title).toBe('Contact us'); - const quick = clone(served('crm_lead.quick')); - expect((translateView(quick, BUNDLE, { locale: 'zh-CN' }) as any).config).toBe(quick.config); + it('the served document is not mutated, and a form with nothing to translate is returned as is', () => { + const doc = clone(FORMS.web_to_lead); + translateForm(doc, BUNDLE, { locale: 'zh-CN' }); + expect(doc.title).toBe('Contact us'); + const referral = clone(FORMS.referral); + expect(translateForm(referral, BUNDLE, { locale: 'zh-CN' })).toBe(referral); + }); +}); + +describe('the pre-19 address `objects.._views..title` (ADR-0159 D8)', () => { + const OLD_PACK = { _views: { web_to_lead: { title: '联系我们' } } }; + + it('is refused at the bundle, with the prescription naming `forms[\'OBJECT.KEY\'].title`', () => { + const r = ObjectTranslationDataSchema.safeParse(OLD_PACK); + expect(r.success).toBe(false); + const issue = r.error?.issues.find((i) => i.path.join('.') === '_views.web_to_lead.title'); + expect(issue?.message, JSON.stringify(r.error?.issues)).toMatch( + /^`translation\.objects\.OBJECT\._views\.KEY\.title` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D8\)/, + ); + expect(issue?.message).toContain("forms['OBJECT.KEY'].title"); + }); + + it('is read by nothing: neither `translateForm` nor `translateView` takes a heading from it', () => { + const bundle: TranslationBundle = { 'zh-CN': { objects: { crm_lead: OLD_PACK } } as any }; + expect((translateForm(clone(FORMS.web_to_lead), bundle, { locale: 'zh-CN' }) as any).title).toBe('Contact us'); + // A served view is a list since protocol 19; the tail reaches no key of it. + const container = { list: { type: 'grid' as const, columns: ['name'] } }; + expect(ViewSchema.safeParse(container).success).toBe(true); + const list = clone(expandViewContainer('crm_lead', container)[0]!) as any; + const out = translateView(list, bundle, { locale: 'zh-CN' }) as any; + expect(out.config.title).toBeUndefined(); + expect(out.title).toBeUndefined(); }); }); diff --git a/packages/spec/src/system/i18n-resolver.test.ts b/packages/spec/src/system/i18n-resolver.test.ts index 53a15d16b60..139667ab71f 100644 --- a/packages/spec/src/system/i18n-resolver.test.ts +++ b/packages/spec/src/system/i18n-resolver.test.ts @@ -245,11 +245,12 @@ describe('resolveViewLabel — served view-document shape', () => { columns: [{ field: 'name' }], }, }, - // A default form carries no `data` at all, so top-level `object` is the - // ONLY field that can identify its object. - form: { - type: 'simple' as const, - sections: [{ label: 'Details', fields: [{ field: 'name' }] }], + // A default list that carries no `data` at all, so top-level `object` is + // the ONLY field that can identify its object. [ADR-0159 D7] This was a + // default FORM until protocol 19; a view holds lists only now. + list: { + type: 'grid' as const, + columns: [{ field: 'name' }], }, }; @@ -296,13 +297,13 @@ describe('resolveViewLabel — served view-document shape', () => { .toBe('Recent Accounts'); }); - it('resolves an object whose config carries no `data` (default form)', () => { - const form = served.find((v) => v.viewKind === 'form')!; - expect((form.config as any).data).toBeUndefined(); + it('resolves an object whose config carries no `data` (default list)', () => { + const list = served.find((v) => !v.name.endsWith('_accounts'))!; + expect((list.config as any).data).toBeUndefined(); // No `_views` entry for it — but it must reach the lookup on top-level // `object` instead of bailing at the `!objectName` guard, i.e. fall back to // the literal name rather than to `undefined`. - expect(resolveViewLabel(bundle, form as any, { locale: 'zh-CN' })).toBe(form.name); + expect(resolveViewLabel(bundle, list as any, { locale: 'zh-CN' })).toBe(list.name); }); it('translates through the REST boundary entry point', () => { diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index dcf489fb230..96c17d7d372 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -1673,49 +1673,13 @@ function translateFormSectionEntries( return changed ? next : entries; } -/** - * A served form view's translated `title` (`FormViewSchema.title`, at - * `config.title`), read from `objects.._views..title` — - * the SAME `_views` node, object and view key the view's own `label` is read - * from ({@link lookupViewText}), so the two strings of one view share one - * address and never a second key convention. - * - * Returns `title` itself (the same value) when nothing applies, so the caller - * can tell "unchanged" by identity: - * - * - only an AUTHORED title is translated — a non-empty string, which is all - * `FormViewSchema.title` admits. A form without one gains none, so its - * heading keeps falling back to the object label (the anonymous form - * page's `label ?? form.title ?? objectSchema.label`); - * - an explicit override beats the catalog (ADR-0029 D9.2a): when the - * packaged view's `config` is known and its `title` differs from the - * served one, the served title was authored on top of the package, and the - * catalog — the translation of the PACKAGED title — does not overwrite it; - * - a missing key keeps the authored title. - */ -function translateFormTitle( - title: unknown, - catalogs: LabelCatalogs, - objectName: string, - viewKey: string, - opts: ResolveOptions | undefined, - packagedConfig: Record | undefined, -): unknown { - if (typeof title !== 'string' || title.length === 0) return title; - const catalog = catalogFor(catalogs, valueOverridesPackagedBase(packagedConfig, 'title', title)); - return lookupViewText(catalog, objectName, viewKey, 'title', opts) ?? title; -} - /** * A form's translated thank-you panel (`FormViewSchema.submitBehavior`) — the * ONE comparison both of its carriers run, each supplying its own address as * `lookup`: * - * - a served form view, at `config.submitBehavior`, read from - * `objects.._views..submitBehavior.{title,message}` — the - * same `_views` node {@link translateFormTitle} reads the form's heading - * from, one level down, the way the authored copy sits one level down - * ({@link translateView}); + * - a `form` item, at `submitBehavior`, read from + * `forms..submitBehavior.{title,message}` ({@link translateForm}); * - a page `object-form` component, at `properties.submitBehavior` (the form * view's member by reference), read from * `pages..components..submitBehavior.{title,message}` @@ -1762,25 +1726,6 @@ function translateFormSubmitBehavior( /** The two strings a thank-you panel authors, and so the two its translation carries. */ type SubmitBehaviorCopyKey = 'title' | 'message'; -/** - * One string off a view's `_views..submitBehavior` node, across the - * locale chain — `undefined` when no locale carries it. - */ -function lookupSubmitBehaviorText( - bundle: TranslationBundle | undefined, - objectName: string, - viewKey: string, - attr: SubmitBehaviorCopyKey, - opts: ResolveOptions | undefined, -): string | undefined { - if (!bundle) return undefined; - for (const code of localeChain(opts)) { - const candidate = pickData(bundle, code)?.objects?.[objectName]?._views?.[viewKey]?.submitBehavior?.[attr]; - if (typeof candidate === 'string' && candidate.length > 0) return candidate; - } - return undefined; -} - /** * Apply the active locale to a view metadata document by overwriting `label` * and `description` with translated values when available, and overlaying the @@ -1836,51 +1781,13 @@ function lookupSubmitBehaviorText( * diverged. No base supplied is the pre-#20731 behaviour, unchanged: the * catalog applies. * - * ## [#23632] A form view's `sections` are translated HERE too - * - * A served form view carries its sections at `config.sections` — the form arm - * of `ViewItemSchema` nests the whole `FormViewSchema` under `config`, as the - * list arm nests its `bulkActionDefs` — and each section's heading and - * description are addressed at `objects.._sections.`, the - * convention `TranslationDataSchema` declares, the i18n extractor scaffolds and - * objectui's form renderers resolve client-side. A caller that cannot load the - * bundle itself — the anonymous public form — had no exported reading of that - * key, so its section titles stayed in the source language beside translated - * field labels. {@link translateFormSections} is that reading, on the same - * locale chain and the same override rule as every other string here; a - * container's form slot receives it through the same `config` projection its - * bulk-action defs do. - * - * A section's entries override an object field's `label`, `placeholder` and - * `helpText` for that form alone, and those three are addressed under the - * same node, at `objects.._sections..fields.` — so an - * entry's copy is served in the reader's language beside its section heading, - * by the same reading and the same rules. - * - * ## A form view's `title` is translated HERE too - * - * A served form view carries its heading at `config.title` - * (`FormViewSchema.title`), and it is addressed at - * `objects.._views..title` — the view's own `_views` node, - * beside its `label`, not the `label` key itself: a view item's `label` names - * the view and a container's form entries carry none, while `title` is what - * the form draws, so they are two strings with two keys. Before this the - * title had no key, and the anonymous public form — whose visitor cannot load - * the bundle — served it in the authoring language beside translated section - * headings and field labels. {@link translateFormTitle} applies it, on the - * same locale chain and the same override rule as every other string here. - * - * ## …and its thank-you panel - * - * The confirmation a form shows after a submit is its `submitBehavior`'s - * `title` and `message` when the `kind` is `'thank-you'`, served at - * `config.submitBehavior` and addressed at - * `objects.._views..submitBehavior` — nested the way the - * authored copy is nested, so the panel's heading never shares a key with the - * form's own `title`. Before this the panel had no key, and a public form - * read in another language confirmed the submit in the authoring language - * under a translated heading. {@link translateFormSubmitBehavior} applies it, - * by the same rules. + * ## [ADR-0159 D7] A view is a list + * + * A view serves lists only since @objectstack/spec 19: a form is a `form` + * item, translated by {@link translateForm} from `forms.`. The form + * strings a view used to carry under `config` (`sections`, `title`, + * `submitBehavior`) and their `_views..title` / `.submitBehavior` + * tails are no longer read here. */ export function translateView( view: T, @@ -1907,7 +1814,7 @@ export function translateView( const objectName = viewObjectName(view); if (config && typeof config === 'object' && catalogs.unchanged && objectName) { // The base's own `config` — `{}` when the base is known but carries none, - // so every def and section on the served view then counts as authored. + // so every def on the served view then counts as authored. const packagedConfig = base === undefined ? undefined : asRecord(base.config) ?? {}; const defs = translateBulkActionDefs( config.bulkActionDefs, @@ -1917,42 +1824,7 @@ export function translateView( opts, packagedConfig, ); - const sections = translateFormSections( - config.sections, - catalogs, - formSectionObjectName(config, objectName), - opts, - packagedConfig, - ); - const title = translateFormTitle( - config.title, - catalogs, - objectName, - viewTranslationKey(view, objectName), - opts, - packagedConfig, - ); - const viewKey = viewTranslationKey(view, objectName); - const submitBehavior = translateFormSubmitBehavior( - config.submitBehavior, - catalogs, - (catalog, attr) => lookupSubmitBehaviorText(catalog, objectName, viewKey, attr, opts), - packagedConfig, - ); - if ( - defs !== config.bulkActionDefs - || sections !== config.sections - || title !== config.title - || submitBehavior !== config.submitBehavior - ) { - config = { - ...config, - ...(defs !== config.bulkActionDefs ? { bulkActionDefs: defs } : {}), - ...(sections !== config.sections ? { sections } : {}), - ...(title !== config.title ? { title } : {}), - ...(submitBehavior !== config.submitBehavior ? { submitBehavior } : {}), - }; - } + if (defs !== config.bulkActionDefs) config = { ...config, bulkActionDefs: defs }; } return { @@ -1994,12 +1866,10 @@ function lookupFormText( /** * [ADR-0159 D8] Apply the active locale to a `form` item. * - * Every string reads `forms.` FIRST. The form tails a form defined in a - * view had under `objects.._views.` (`title`, and the thank-you - * panel's `submitBehavior`) are the declared fallback, read when the family - * has no value, so a bundle written for the old shape keeps translating the - * same form. `label` and `description` read `forms.` only: under - * `_views.` they are the view's own strings, never a form's. Section + * Every string reads `forms.`. The form tails a form defined in a view + * had under `objects.._views.` (`title`, and the thank-you + * panel's `submitBehavior`) were tombstoned in @objectstack/spec 19 and are + * no longer read: the 19 conversion moves them to `forms.`. Section * copy reads `forms..sections.
` first and keeps * `objects.._sections.
` as its object-level default, key by * key ({@link translateFormSections}). The override rule is the view's: @@ -2016,7 +1886,6 @@ export function translateForm( const catalogs = labelCatalogs(bundle, opts); const name = form.name; const objectName = form.object; - const key = name.startsWith(`${objectName}.`) ? name.slice(objectName.length + 1) : name; const own = (attr: 'label' | 'description'): string | undefined => { const value = form[attr]; if (typeof value !== 'string' || value.length === 0) return undefined; @@ -2027,15 +1896,12 @@ export function translateForm( let title: unknown = form.title; if (typeof form.title === 'string' && form.title.length > 0) { const catalog = catalogFor(catalogs, valueOverridesPackagedBase(base, 'title', form.title)); - title = lookupFormText(catalog, name, ['title'], opts) - ?? lookupViewText(catalog, objectName, key, 'title', opts) - ?? form.title; + title = lookupFormText(catalog, name, ['title'], opts) ?? form.title; } const submitBehavior = translateFormSubmitBehavior( form.submitBehavior, catalogs, - (catalog, attr) => lookupFormText(catalog, name, ['submitBehavior', attr], opts) - ?? lookupSubmitBehaviorText(catalog, objectName, key, attr, opts), + (catalog, attr) => lookupFormText(catalog, name, ['submitBehavior', attr], opts), base, ); const sections = catalogs.unchanged @@ -2207,8 +2073,9 @@ const METADATA_DOCUMENT_TRANSLATORS: Readonly` first, its old-shape `_views` - // tails as the declared fallback. + // [ADR-0159 D8] A `form` item, translated from `forms.`. The fallback + // read of its old-shape `_views` tails left with their tombstones in + // protocol 19. form: translateForm, } satisfies Record<(typeof TRANSLATED_METADATA_TYPE_NAMES)[number], MetadataDocumentTranslator>; diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index daf67e7e108..cc0958b12d4 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -538,13 +538,8 @@ const LEDGER: ReadonlyArray = [ key: 'titleFormat', why: "`[DEPRECATED → nameField (ADR-0079)]` render-only title template the server cannot return or query, deliberately not offered to new authors; its own describe prescribes the migration — a single-field title to `nameField`, a composite title that import, sort or search must match to a stored computed field (a non-formula field with an `expression`) designated as `nameField`, a text formula staying legal for display only — and every target is authorable", }, - { - kind: 'omit', - type: 'view', - path: ROOT_PATH, - key: 'groups', - why: '`[LEGACY ALIAS → sections]` accepted for back-compat and folded onto `sections` at parse (`sections` wins when both are present), deliberately not offered to new authors', - }, + // [ADR-0159 D7] The `view` form's `groups` omit left in protocol 19: it was + // a key of the form overlay member, and a view holds lists only now. // Renderer-owned vocabulary — a key is admitted here only when all three // hold: its `describe()` says the spec declares no vocabulary for its value; diff --git a/packages/spec/src/system/migration.zod.ts b/packages/spec/src/system/migration.zod.ts index a938e72e16f..072cf7e93de 100644 --- a/packages/spec/src/system/migration.zod.ts +++ b/packages/spec/src/system/migration.zod.ts @@ -290,22 +290,43 @@ export const NOTIFICATION_EVENT_MIGRATION_ID = 'adr-0030-notification-event'; * `viewKind: 'form'` item) has moved to a `form` row or been removed as an * internal record form. * - * Written by `os migrate protocol --to 19 --apply` ONLY, and only after the - * stored-form ceremony committed (`applyStoredFormsOf`, - * `@objectstack/metadata-protocol`) AND a re-run of its census - * (`listStoredFormsOf`) found the deployment can switch with nothing left to - * move or remove: `verified_at` is then set. ⛔ A run the precheck holds writes - * nothing, this row included: the ceremony is all or nothing with the switch - * (ruling record 7142585849, item 2), and a row recording a failed attempt is a - * write before the switch verdict. + * It has two writers and no third: * - * It is the switch's record, not a gate: no boot reads it in this release (the - * boot guard is a separate decision). `details` carries the census counts of - * the verifying run and the rows the ceremony wrote. + * 1. `os migrate protocol --to 19 --apply`, only after the stored-form + * ceremony committed (`applyStoredFormsOf`, + * `@objectstack/metadata-protocol`) AND a re-run of its census + * (`listStoredFormsOf`) found the deployment can switch with nothing left + * to move or remove: `verified_at` is then set, and `applied_at` with it. + * On a datastore with no `sys_metadata` table there is no stored row to + * move and no ceremony to run: the command records the row on the census + * alone, verified, and leaves `applied_at` unset. ⛔ A run the precheck + * holds writes nothing, this row included: the ceremony is all or nothing + * with the switch (ruling record 7142585849, item 2), and a row recording + * a failed attempt is a write before the switch verdict. + * 2. A boot, on a datastore it observed being CREATED FROM EMPTY (ruling + * record 7308112533): the store's BIRTH MARKER, verified, `applied_at` + * unset, with `details.birth` = `{ protocol, platformVersion, createdAt }` + * naming the protocol major the store was born on, the platform version + * that created it and when. It claims no ceremony ran: it records that + * none was owed, because a store with no prior data holds no stored form. + * Written by the form-type-switch boot guard of `os serve` and by the + * birth half every CLI data and schema boot composes + * (`@objectstack/runtime`). ⛔ Never for a store that was found rather + * than created: a database an earlier release created runs the command + * once, even when it holds no stored form. * - * ⛔ Not a member of {@link CREATION_ATTESTED_MIGRATION_IDS}: a datastore born - * empty holds no old-shape row, but a row claiming the ceremony ran where none - * did would read as the switch it records. + * The served boot reads it (ruling record 7303149461): `os serve` refuses to + * start on a datastore whose row is absent or not verified, names + * `os migrate protocol --to 19`, and no variable, flag or config key skips the + * check. Only `verified_at` and `blocking` are decided on + * ({@link isDataMigrationFlagVerified}); `details` is provenance: the + * command's row carries the census counts of the verifying run and the rows + * the ceremony wrote, the birth marker carries `details.birth`. + * + * ⛔ Not a member of {@link CREATION_ATTESTED_MIGRATION_IDS}: those rows are + * written by `attestFreshDatastore` in one uniform shape once the seed has + * settled, and this row is judged before any plugin writes and must say which + * of its two writers wrote it. */ export const FORM_TYPE_SWITCH_MIGRATION_ID = 'adr-0159-form-type-switch'; diff --git a/packages/spec/src/system/translation.test.ts b/packages/spec/src/system/translation.test.ts index 3eaf82bc2dc..463fd1a0c85 100644 --- a/packages/spec/src/system/translation.test.ts +++ b/packages/spec/src/system/translation.test.ts @@ -2337,24 +2337,36 @@ describe('retired translation.validationMessages', () => { }); // ────────────────────────────────────────────────────────────────────────── -// `_views..title` — a form view's heading (`FormViewSchema.title`) +// `_views..title` — a form view's heading (`FormViewSchema.title`), +// RETIRED in protocol 19 (ADR-0159 D8): a form's heading is `forms.NAME.title` // ────────────────────────────────────────────────────────────────────────── -describe('`objects.._views..title`, the key a form view\'s title is translated through', () => { +describe('`objects.._views..title`, the key a form view\'s title was translated through', () => { const parse = (view: unknown) => ObjectTranslationDataSchema.safeParse({ label: 'Lead', _views: { web_to_lead: view } }); - it('accepts `title` as its own key, beside the view\'s `label`', () => { + // [ADR-0159 D8] Accepted as its own key until protocol 19; tombstoned now, + // with the prescription naming the `forms` address. The `label` beside it stays. + it('refuses `title` at its own path with the D8 prescription; the view\'s `label` stays', () => { const result = parse({ label: '网页线索', title: '联系我们' }); - expect(result.success, JSON.stringify(result.error?.issues)).toBe(true); - expect(result.success && result.data._views?.web_to_lead).toEqual({ label: '网页线索', title: '联系我们' }); + expect(result.success).toBe(false); + const issue = result.error?.issues.find((i) => i.path.join('.') === '_views.web_to_lead.title'); + expect(issue?.message, JSON.stringify(result.error?.issues)).toMatch( + /^`translation\.objects\.OBJECT\._views\.KEY\.title` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D8\)/, + ); + expect(issue?.message).toContain("forms['OBJECT.KEY'].title"); + expect(parse({ label: '网页线索' }).success).toBe(true); }); - it('a heading-shaped neighbour is named as a rename onto `title`, not onto `label`', () => { + // [ADR-0159 D8] Named as a rename onto `title` until protocol 19; the + // neighbour now carries the same retirement prescription, never a rename + // onto a key that is itself refused, and never onto `label`. + it('a heading-shaped neighbour carries the retirement prescription, not a rename', () => { const result = parse({ heading: '联系我们' }); expect(result.success).toBe(false); - const issue = result.error?.issues.find((i) => i.code === 'unrecognized_keys'); - expect(issue?.message).toContain('this view translation'); - expect(issue?.message).toContain('`heading` → `title`'); + const text = JSON.stringify(result.error?.issues); + expect(text).toContain("forms['OBJECT.KEY'].title"); + expect(text).not.toContain('`heading` → `title`'); + expect(text).not.toContain('`heading` → `label`'); }); it('CONTROL: the entry stays closed — a key it does not declare is still refused', () => { diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index ab9e8b44ad1..4760dffcfd1 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -525,9 +525,29 @@ const actionTranslationSchema = (surface: string) => strictObject({ * } * ``` */ +/** + * [ADR-0159 D8, #37112] The two form tails under a view's translations, + * RETIRED in protocol 19: a form is a `form` item, and its copy lives in the + * bundle's `forms` family (`forms.NAME.title`, `forms.NAME.submitBehavior`). + * The conversion `translation-view-form-tails-to-forms` moves each tail of a + * form that is a `form` item; `label` and `description` under `_views` stay, + * because a list carries them too. + */ +const VIEW_TRANSLATION_FORM_TITLE_RETIRED = + '`translation.objects.OBJECT._views.KEY.title` was removed in @objectstack/spec 19.0.0 (ADR-0159 D8) — a ' + + 'form is a `form` item, and no view carries a heading. Move the string to `forms[\'OBJECT.KEY\'].title`, ' + + 'the address the translator reads a form\'s heading from. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +const VIEW_TRANSLATION_FORM_SUBMIT_RETIRED = + '`translation.objects.OBJECT._views.KEY.submitBehavior` was removed in @objectstack/spec 19.0.0 (ADR-0159 D8) ' + + '— a form is a `form` item, and no view has a thank-you panel. Move the `title` and `message` to ' + + '`forms[\'OBJECT.KEY\'].submitBehavior`, the address the translator reads a form\'s panel from. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + /** * A form's thank-you panel translation — one shape, used at two addresses: a - * form view's `_views..submitBehavior` and a page `object-form` + * form item's `forms..submitBehavior` and a page `object-form` * component's `pages..components..submitBehavior` (the block * `ObjectFormPropsSchema.submitBehavior` takes from the form view by * reference). Built by a factory for {@link actionTranslationSchema}'s @@ -623,9 +643,6 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ * Convention (auto-resolved by `resolveViewLabel`): * objects.._views..label * objects.._views..description - * objects.._views..title (a form view's heading) - * objects.._views..submitBehavior.title / .message - * (a form's thank-you panel) * objects.._views..emptyState.title * objects.._views..emptyState.message * objects.._views..bulkActions..* @@ -634,19 +651,20 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ surface: 'this view translation', history: TRANSLATION_HISTORY, aliases: { - // `title` is a declared key below (a form view's heading), so it is no - // longer named as a rename onto `label`; the heading-shaped neighbours - // are named as renames onto it. - name: 'label', heading: 'title', formTitle: 'title', empty: 'emptyState', emptyMessage: 'emptyState', + // [ADR-0159 D8] `title` and `submitBehavior` (a form's heading and + // thank-you panel) were retired in protocol 19; the heading-shaped + // neighbours that were renames onto them are named in `guidance` below. + name: 'label', empty: 'emptyState', emptyMessage: 'emptyState', // The authoring key is `bulkActionDefs`; the translation group drops the // `Defs` suffix the way `_actions` drops nothing and `_tabs` drops // `tabs[]`'s bracket — one address per surface, and the authoring // spelling is the one an author reaches for first. bulkActionDefs: 'bulkActions', bulkActionDef: 'bulkActions', bulk: 'bulkActions', - // The panel's everyday name; the address mirrors the authoring key. - thankYou: 'submitBehavior', }, guidance: { + heading: VIEW_TRANSLATION_FORM_TITLE_RETIRED, + formTitle: VIEW_TRANSLATION_FORM_TITLE_RETIRED, + thankYou: VIEW_TRANSLATION_FORM_SUBMIT_RETIRED, rowActions: '`rowActions` names actions the OBJECT declares — a row-action label is translated where the ' + "action lives: 'objects.._actions..label' (or 'globalActions..label' " @@ -656,42 +674,10 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ }, { label: z.string().optional().describe('Translated view label'), description: z.string().optional().describe('Translated view description'), - /** - * A FORM view's heading — overlays `FormViewSchema.title`, which a served - * form item carries at `config.title` (the title an anonymous public form - * shows above its sections). - * - * **Its own key, not the view's `label` key.** They are two authored - * strings on two layers: a view item's `label` names the view, and a - * form-family container entry (`formViews.`, the default `form`) - * carries no `label` at all, while `title` is the heading the form itself - * draws. One translation cannot stand for two source strings, so the key - * mirrors the authored one, the way `emptyState.title` does. - * - * Applied by `translateView` only where the form AUTHORS a title: a form - * without one gains none, and its heading keeps falling back to the - * object label. A list view carries no title, so the key over one - * resolves nothing (`objectstack validate` refuses it). - */ - title: z.string().optional().describe("Translated form view title — overlays a form view's own `title` (`FormViewSchema.title`); only a form that authors one is translated"), - /** - * A FORM view's thank-you panel — overlays the `title` and `message` of - * `FormViewSchema.submitBehavior` when its `kind` is `'thank-you'`, which - * a served form item carries at `config.submitBehavior` (the confirmation - * an anonymous public form shows after a submit). - * - * **Nested under `submitBehavior`, not flattened onto the view node.** - * The address mirrors the authored path, the way `emptyState.title` - * does: the panel's `title` is a second heading beside the form's own - * `title` above, and one key cannot stand for two source strings. The - * three other kinds (`redirect`, `continue`, `next-record`) author no - * copy, so this face carries the thank-you member's two strings only. - * - * Applied by `translateView` only where the form authors a thank-you - * `title` / `message`: a form with another kind, or none, gains no - * panel copy, and the console's own default wording stays in charge. - */ - submitBehavior: submitBehaviorTranslationSchema('this form submit behavior translation').optional().describe("Translated thank-you panel copy — overlays a form view's `submitBehavior` `title` / `message` when its `kind` is `'thank-you'`; only copy the form authors is translated"), + // [ADR-0159 D8] RETIRED in protocol 19 — a form's heading and thank-you + // panel are translated under `forms.NAME` (see the constants above). + title: retiredKey(VIEW_TRANSLATION_FORM_TITLE_RETIRED), + submitBehavior: retiredKey(VIEW_TRANSLATION_FORM_SUBMIT_RETIRED), emptyState: strictObject({ surface: 'this view empty-state translation', history: TRANSLATION_HISTORY, @@ -1843,12 +1829,12 @@ const appTranslationDataShape = () => ({ * in different words, and a key under `objects.` (the * `_sections` precedent) would make them share one translation. The * component's own `id` already addresses its `title` / `description` - * here, so its panel sits beside them; a form view's panel keeps its - * own address under `_views`, because there the copy is the view's. + * here, so its panel sits beside them; a `form` item's panel keeps its + * own address under `forms.NAME`, because there the copy is the form's. * * Nested the way the authored copy is nested, so the panel's heading * never shares the component's own `title` key. The same rules as the - * form view's panel apply, through the one function both share: only a + * `form` item's panel apply, through the one function both share: only a * `kind: 'thank-you'` panel is touched, only authored copy is * translated, and a missing key keeps the authored string. An * `object-form` without an `id` has no key; give it one. @@ -1873,12 +1859,13 @@ const appTranslationDataShape = () => ({ * forms..sections..fields..placeholder * forms..sections..fields..helpText * - * The translator reads `forms.NAME` first; the form tails a form defined in - * a view had under `objects.OBJECT._views.KEY` (`title`, `submitBehavior`) - * are the declared fallback, so a bundle written for the old shape keeps - * translating the same form. `label` and `description` under `_views.KEY` - * are a view's, not form tails: they are neither moved nor read as a - * fallback. A section with no key under `forms.NAME.sections` reads + * The translator reads a form's copy from `forms.NAME` alone. The form + * tails a form defined in a view had under `objects.OBJECT._views.KEY` + * (`title`, `submitBehavior`) are retired in protocol 19 and are not read as + * a fallback: `os migrate meta --from 18` moves them here (the conversion + * `translation-view-form-tails-to-forms`). `label` and `description` under + * `_views.KEY` are a view's, not form tails: they are neither moved nor read + * as a fallback. A section with no key under `forms.NAME.sections` reads * `objects.OBJECT._sections.SECTION`, its object-level default: field * groups and forms of one object share section names on purpose, so that * is not a legacy fallback, and an entry key the form's section lacks falls diff --git a/packages/spec/src/ui/anonymous-form-intake.ts b/packages/spec/src/ui/anonymous-form-intake.ts index d4bf389b212..838ac93745d 100644 --- a/packages/spec/src/ui/anonymous-form-intake.ts +++ b/packages/spec/src/ui/anonymous-form-intake.ts @@ -88,13 +88,17 @@ export function anonymousFormIntakeSlug(sharing: unknown): string | null { /** * The object an open form candidate submits into: the form's own `data.object`, - * else the view's `list.data.object`, `form.data.object` and `object`. The one - * rung order both anonymous doors and the authoring lint resolve by. + * else the body's `form.data.object` and `object`. The one rung order the + * projection of a stored old-shape body resolves by. + * + * [ADR-0159 D7] A form no longer reads its binding off a list: the rung that + * read the container's `list.data.object` left with the old shapes in + * @objectstack/spec 19. A `form` item names its object itself (`object`). */ export function anonymousFormObjectName(view: unknown, form: unknown): string | undefined { const v = (view && typeof view === 'object' ? view : {}) as Record; const f = (form && typeof form === 'object' ? form : {}) as Record; - return f.data?.object ?? v.list?.data?.object ?? v.form?.data?.object ?? v.object; + return f.data?.object ?? v.form?.data?.object ?? v.object; } /** Every form candidate of a `view` body that is open to anonymous intake, in scan order. */ diff --git a/packages/spec/src/ui/assembled-view-artifact-type.test.ts b/packages/spec/src/ui/assembled-view-artifact-type.test.ts index a94154c802b..b2e904ef342 100644 --- a/packages/spec/src/ui/assembled-view-artifact-type.test.ts +++ b/packages/spec/src/ui/assembled-view-artifact-type.test.ts @@ -39,14 +39,12 @@ const viewItem: AssembledViewArtifact = { config: { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'] }, }; const listOverlay: AssembledViewArtifact = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'list' }; -const formOverlay: AssembledViewArtifact = { - type: 'simple', - sections: [{ label: 'Main', fields: ['name'] }], - object: 'crm_lead', - viewKind: 'form', -}; +// [ADR-0159 D7] The form overlay member was retired in protocol 19 (a view is a list): its body no +// longer type-checks as an artifact, and the schema refuses it (pinned below). +// @ts-expect-error -- a flattened form overlay is no view artifact since protocol 19. +const formOverlay: AssembledViewArtifact = { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }], object: 'crm_lead', viewKind: 'form' }; -const BODY_OF_EACH_MEMBER: Record = { viewItem, listOverlay, formOverlay }; +const BODY_OF_EACH_MEMBER: Record = { viewItem, listOverlay }; // ── What the two types refuse at compile time ──────────────────────────────────────────────── @@ -63,6 +61,10 @@ const parsedFromUnknown: AssembledViewArtifactParsed = someValue; void [fromUnknown, container, undeclaredKey, parsedFromUnknown]; describe('AssembledViewArtifact is a non-container view artifact, not unknown', () => { + it('[ADR-0159 D7] the retired form overlay body is refused by the artifact schema', () => { + expect(AssembledViewArtifactSchema.safeParse(formOverlay).success).toBe(false); + }); + it('has a typed body for every non-container member', () => { expect(Object.keys(BODY_OF_EACH_MEMBER).sort()).toEqual( VIEW_METADATA_BRANCHES.filter((branch) => branch !== 'container').sort(), diff --git a/packages/spec/src/ui/assembled-views.test.ts b/packages/spec/src/ui/assembled-views.test.ts index 01390d92775..74f59e38a5e 100644 --- a/packages/spec/src/ui/assembled-views.test.ts +++ b/packages/spec/src/ui/assembled-views.test.ts @@ -27,6 +27,7 @@ import { AssembledViewArtifactSchema, partitionAssembledViewArtifacts, expandViewContainer, + expandServedViewContainer, } from './index'; import { ObjectStackDefinitionSchema } from '../stack.zod'; @@ -34,10 +35,16 @@ const DATA = { provider: 'object', object: 'account' } as const; /** The minimal schema-valid container of the fork's probe: a default list and * a default form → expands to `account.default` + `account.form`. */ +/** [ADR-0159 D7] A container holds lists only since protocol 19 (it carried a `form` before). */ const CONTAINER = { name: 'account', object: 'account', list: { type: 'grid', columns: ['name'], data: DATA }, +} as const; + +/** The pre-19 container: the same list plus a view-held `form`, as a stored row may still hold it. */ +const OLD_SHAPE_CONTAINER = { + ...CONTAINER, form: { type: 'simple', sections: [{ label: 'Details', fields: [{ field: 'name' }] }] }, } as const; @@ -73,7 +80,7 @@ describe('AssembledViewArtifactSchema — the declared home for non-container vi expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); }); - it('accepts a flattened form overlay (vocabulary branch 4)', () => { + it('[ADR-0159 D7] refuses a flattened form overlay (vocabulary branch 4 until protocol 19)', () => { const r = AssembledViewArtifactSchema.safeParse({ name: 'account.form', object: 'account', @@ -81,7 +88,7 @@ describe('AssembledViewArtifactSchema — the declared home for non-container vi type: 'simple', sections: [{ label: 'Details', fields: [{ field: 'name' }] }], }); - expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); + expect(r.success).toBe(false); }); it('refuses a container — containers travel in `views:`, not `viewItems:`', () => { @@ -99,7 +106,7 @@ describe('partitionAssembledViewArtifacts — re-aggregation where a container e // the bare object key AND its expanded items (dual-read) — the exact 3-entry // set the fork's probe read back from `getMetaItems('view', pkg)`. const expanded = expandViewContainer('account', CONTAINER); - expect(expanded.map((v) => v.name).sort()).toEqual(['account.default', 'account.form']); + expect(expanded.map((v) => v.name).sort()).toEqual(['account.default']); const { views, viewItems, folded } = partitionAssembledViewArtifacts([ CONTAINER, @@ -107,7 +114,14 @@ describe('partitionAssembledViewArtifacts — re-aggregation where a container e ]); expect(views).toEqual([CONTAINER]); expect(viewItems).toEqual([]); - expect(folded.sort()).toEqual(['account.default', 'account.form']); + expect(folded.sort()).toEqual(['account.default']); + }); + + it('[ADR-0159 D7] an old-shape container is SERVED as its lists only — its `form` is not served', () => { + expect(expandServedViewContainer('account', OLD_SHAPE_CONTAINER).map((v) => v.name)).toEqual(['account.default']); + // …while the raw expansion still sees the stored form: the replacement + // check and the stored-form ceremony read a stored container through it. + expect(expandViewContainer('account', OLD_SHAPE_CONTAINER).map((v) => v.name)).toEqual(['account.default', 'account.form']); }); it('keeps a standalone ViewItem — no container to re-aggregate from', () => { @@ -185,5 +199,10 @@ describe('authored `viewItems:` is refused loudly (machine-assembled only)', () views: [CONTAINER], }); expect(r.success, JSON.stringify((r as { error?: unknown }).error)).toBe(true); + // [ADR-0159 D7] …and an old-shape container is refused at its `form`. + expect(ObjectStackDefinitionSchema.safeParse({ + manifest: { id: 'com.test.app', name: 'test', version: '1.0.0', type: 'app' }, + views: [OLD_SHAPE_CONTAINER], + }).success).toBe(false); }); }); diff --git a/packages/spec/src/ui/form-field-public-picker-retirement.test.ts b/packages/spec/src/ui/form-field-public-picker-retirement.test.ts index 0d0b44cd570..98e57d08076 100644 --- a/packages/spec/src/ui/form-field-public-picker-retirement.test.ts +++ b/packages/spec/src/ui/form-field-public-picker-retirement.test.ts @@ -47,7 +47,7 @@ import { ALL_CONVERSIONS } from '../conversions/registry'; import { applyConversionsToStoredItem } from '../conversions/stored'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; -import { FormFieldSchema, FormViewSchema, ViewMetadataSchema, type FormFieldInput } from './view.zod'; +import { FormFieldSchema, FormSchema, FormViewSchema, ViewMetadataSchema, type FormFieldInput } from './view.zod'; /** The block as an author wrote it before the retirement — every key it declared. */ const PICKER = { displayFields: ['name'], maxResults: 10, object: 'crm_contact' }; @@ -71,6 +71,16 @@ const viewItem = (fields: unknown[]) => ({ }, }); +/** [ADR-0159 D7] The same form as a `form` item (`forms:`, the `form` save door): body at the top level, bound with `object`. */ +const formItem = (fields: unknown[]) => ({ + name: 'crm_inquiry.contact', + object: 'crm_inquiry', + label: 'Contact us', + type: 'simple', + sections: [{ label: 'About you', fields }], + sharing: { allowAnonymous: true, publicLink: '/forms/contact' }, +}); + describe('form field publicPicker retirement — the tombstone, at every door that carries a form field', () => { it('the form field schema refuses `publicPicker` at its path, with the prescription', () => { const r = FormFieldSchema.safeParse({ field: 'contact', publicPicker: PICKER }); @@ -107,13 +117,22 @@ describe('form field publicPicker retirement — the tombstone, at every door th expect(flat).toContain('"publicPicker"'); }); - it('the stored-view write door (ViewMetadataSchema, ViewItem branch) refuses it with the prescription', () => { - const r = ViewMetadataSchema.safeParse(viewItem(['subject', { field: 'contact', publicPicker: PICKER }])); + it('the `form` item door (FormSchema) refuses it with the prescription', () => { + const r = FormSchema.safeParse(formItem(['subject', { field: 'contact', publicPicker: PICKER }])); expect(r.success).toBe(false); if (r.success) return; expect(JSON.stringify(r.error.issues)).toMatch(PRESCRIPTION); // CONTROL: the same item without the key is accepted by the same door. - expect(ViewMetadataSchema.safeParse(viewItem(['subject', { field: 'contact' }])).success).toBe(true); + expect(FormSchema.safeParse(formItem(['subject', { field: 'contact' }])).success).toBe(true); + }); + + it('[ADR-0159 D7] the stored-view write door refuses a form view item whatever it carries, with the D7 prescription', () => { + for (const fields of [['subject', { field: 'contact', publicPicker: PICKER }], ['subject', { field: 'contact' }]]) { + const r = ViewMetadataSchema.safeParse(viewItem(fields)); + expect(r.success).toBe(false); + if (r.success) continue; + expect(JSON.stringify(r.error.issues)).toContain("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0"); + } }); it('the authoring door, defineStack, refuses it with the STACK_SCHEMA_INVALID envelope — never rewrites it', () => { @@ -127,15 +146,13 @@ describe('form field publicPicker retirement — the tombstone, at every door th contact: { type: 'lookup', label: 'Contact', reference: 'crm_contact' }, }, }], - views: [{ - formViews: { - contact: { - type: 'simple', - data: { provider: 'object', object: 'crm_inquiry' }, - sections: [{ label: 'About you', fields: ['subject', field] }], - sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/contact' }, - }, - }, + // [ADR-0159 D7] The form is a `form` item since protocol 19 (it was a `formViews` entry). + forms: [{ + name: 'crm_inquiry.contact', + object: 'crm_inquiry', + type: 'simple', + sections: [{ label: 'About you', fields: ['subject', field] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/contact' }, }], }); let thrown: unknown; @@ -240,14 +257,17 @@ describe('form field publicPicker retirement — the D2 conversion', () => { expect(twice.stack).toBe(once.stack); }); - it('a STORED view row carrying the key replays clean through the rehydration seam, and the write door accepts the result', () => { + it('a STORED view row carrying the key replays clean through the rehydration seam; the form view door accepts the replayed body', () => { const stored = viewItem(['subject', { field: 'contact', publicPicker: PICKER }]); // Before: the retired key is refused at parse — the row a pre-retirement // author left behind would be badged invalid without the replay. expect(ViewMetadataSchema.safeParse(stored).success).toBe(false); const converted = applyConversionsToStoredItem('view', stored) as ReturnType; expect(converted.config.sections[0]!.fields).toEqual(['subject', { field: 'contact' }]); - expect(ViewMetadataSchema.safeParse(converted).success).toBe(true); + // [ADR-0159 D7] The replayed row is still a form view item, which the 19 write door refuses + // whatever it carries; its replayed body is what the form view door accepts. + expect(ViewMetadataSchema.safeParse(converted).success).toBe(false); + expect(FormViewSchema.safeParse(converted.config).success).toBe(true); }); it('is retired from the load path — a live author is refused at parse, never silently rewritten', () => { diff --git a/packages/spec/src/ui/form-intake-layer.ts b/packages/spec/src/ui/form-intake-layer.ts index b9e1c00bb57..03d52abc3d8 100644 --- a/packages/spec/src/ui/form-intake-layer.ts +++ b/packages/spec/src/ui/form-intake-layer.ts @@ -7,13 +7,14 @@ import { oldShapeFormWithdrawals } from './old-shape-form-withdrawals'; /** * [ADR-0159 D6] The anonymous doors' withdrawal judgement over BOTH types. * - * The doors offer the open forms of the effective `form` read (authored - * items and the projection of the old shapes, resolved over both types). - * Each candidate is judged against a layer never narrower than the one the - * doors judged before card ②: the effective lists and the per-package layers - * of both `form` and `view`, the old shapes passed through the projection - * first. Narrowing only, in both directions: a withdrawal held in either type - * closes the form served from either type. + * The doors offer the open forms of the effective `form` read: `form` items, + * resolved over both types (rule 11). Since @objectstack/spec 19 the + * projection of the old shapes serves no content (D7), so no candidate is a + * projected item. Each candidate is judged against the layer the doors judged + * before: the effective lists and the per-package layers of both `form` and + * `view`, the old shapes passed through the projection first (rule 10). + * Narrowing only, in both directions: a withdrawal held in either type closes + * the form. * * - **Identity is the served name** (rule 6): inside one name, the whole * item. A body of the form's name that explicitly withdraws a form (its @@ -52,9 +53,9 @@ const nameOf = (item: unknown): string | undefined => { /** * Build the two-type layer from what the doors read: `forms` (the effective - * and per-package `form` lists, authored and projected items alike), `views` - * (the effective and per-package `view` lists, raw), and `unreadable` (the - * stored bodies the protocol could not project, rule 7). + * and per-package `form` lists), `views` (the effective and per-package + * `view` lists, raw), and `unreadable` (the stored bodies the protocol could + * not project, rule 7). */ export function formIntakeLayer(input: { forms: ReadonlyArray; diff --git a/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts b/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts index f454d317b40..e66260cbeb8 100644 --- a/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts +++ b/packages/spec/src/ui/form-layout-inline-grid-retired.test.ts @@ -33,7 +33,8 @@ import { CONVERSIONS_BY_MAJOR } from '../conversions/registry.js'; import { applyConversionsToStoredItem } from '../conversions/stored.js'; import { MIGRATIONS_BY_MAJOR } from '../migrations/registry.js'; import { ComponentPropsMap, ObjectFormPropsSchema } from './component.zod.js'; -import { FormViewSchema, VIEW_METADATA_MEMBERS, ViewSchema } from './view.zod.js'; +import { FormSchema, FormViewSchema, ViewSchema } from './view.zod.js'; +import { RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit.js'; const CONVERSION_ID = 'form-layout-inline-grid-to-vertical'; const SEMANTIC_ID = 'ui-form-layout-inline-grid-retired'; @@ -67,21 +68,13 @@ const DOORS: readonly Door[] = [ parse: (layout) => FormViewSchema.safeParse({ type: 'simple', layout }), layoutPath: ['layout'], }, + // [ADR-0159 D7] The two view-held doors this table listed (a container's + // `formViews.*` and the flattened form overlay) refuse the whole form since + // protocol 19, pinned below from `RETIRED_VIEW_FORM_DOORS`; a form body is + // judged as a `form` item, whose body keys are the form view's by reference. { - name: 'ViewSchema.formViews.* (a container)', - parse: (layout) => ViewSchema.safeParse({ formViews: { quick: { type: 'simple', layout } } }), - layoutPath: ['formViews', 'quick', 'layout'], - }, - { - // The flattened form overlay spreads `FormViewSchema`'s shape, so the - // narrowing reaches it without an edit of its own. - name: 'VIEW_METADATA_MEMBERS.formOverlay (the flattened form overlay)', - parse: (layout) => VIEW_METADATA_MEMBERS.formOverlay.safeParse({ - object: 'crm_lead', - viewKind: 'form', - type: 'simple', - layout, - }), + name: '`form` item', + parse: (layout) => FormSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', type: 'simple', layout }), layoutPath: ['layout'], }, ]; @@ -128,6 +121,10 @@ describe('form `layout` — the retired arms are refused with the prescription', }); } + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] %s refuses a form of any layout — at its own key, with the D7 prescription', (_, door) => { + for (const layout of ['grid', 'inline', 'vertical', 'horizontal']) expectRetiredViewFormDoorRefuses(door, { type: 'simple', layout }); + }); + it('the two schemas speak the same two-arm vocabulary, each under its own surface name', () => { const objectForm = ObjectFormPropsSchema.safeParse({ layout: 'grid' }); const formView = FormViewSchema.safeParse({ layout: 'grid' }); @@ -183,20 +180,24 @@ describe(`D2 conversion \`${CONVERSION_ID}\``, () => { expect(out.pages[0]!.regions[0]!.components[0]!.properties.layout).toBe('grid'); }); - it("a stored form view row replays clean: 'grid' → 'vertical', `columns` kept, and the row parses", () => { + // [ADR-0159 D7] A stored row is not rewritten past the conversion (constraint 1), + // and its view-held form is refused by the 19 door whatever it carries; the + // replayed form body is what the form door accepts. + it("a stored form view row replays clean: 'grid' → 'vertical', `columns` kept, and the form body parses", () => { const row = { object: 'crm_lead', form: { type: 'simple', layout: 'grid', columns: 3 } }; expect(ViewSchema.safeParse(row).success).toBe(false); const replayed = applyConversionsToStoredItem('view', structuredClone(row))!; expect(replayed.form).toEqual({ type: 'simple', layout: 'vertical', columns: 3 }); - expect(ViewSchema.safeParse(replayed).success).toBe(true); + expect(FormViewSchema.safeParse(replayed.form).success).toBe(true); + expect(ViewSchema.safeParse(replayed).success).toBe(false); }); - it("a stored flattened form overlay replays clean: 'inline' → 'vertical', and the overlay parses", () => { + it("a stored flattened form overlay replays clean: 'inline' → 'vertical', and the form body parses", () => { const row = { object: 'crm_lead', viewKind: 'form', type: 'simple', layout: 'inline' }; - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse(row).success).toBe(false); + expect(FormViewSchema.safeParse({ type: row.type, layout: row.layout }).success).toBe(false); const replayed = applyConversionsToStoredItem('view', structuredClone(row))!; expect(replayed.layout).toBe('vertical'); - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse(replayed).success).toBe(true); + expect(FormViewSchema.safeParse({ type: replayed.type, layout: replayed.layout }).success).toBe(true); }); it("leaves the surviving arm, and the same key on a non-`object-form` component, untouched", () => { diff --git a/packages/spec/src/ui/form-view-buttons-reset-retirement.test.ts b/packages/spec/src/ui/form-view-buttons-reset-retirement.test.ts index 486dcd23045..9837ee7756c 100644 --- a/packages/spec/src/ui/form-view-buttons-reset-retirement.test.ts +++ b/packages/spec/src/ui/form-view-buttons-reset-retirement.test.ts @@ -38,7 +38,8 @@ import { applyConversionsToStoredItem } from '../conversions/stored'; import type { ConversionNotice } from '../conversions/types'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; -import { FormViewSchema, VIEW_METADATA_MEMBERS, ViewItemSchema, ViewSchema } from './view.zod'; +import { FormViewSchema, ViewItemSchema, ViewSchema } from './view.zod'; +import { FORM_ITEM_DOOR, RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit'; const CONVERSION_ID = 'form-view-buttons-reset-removed'; const D3_ID = 'ui-form-view-buttons-reset-retired'; @@ -54,21 +55,18 @@ type Door = { name: string; parse: (form: Record) => Parse; at: const SECTIONS = [{ label: 'Main', fields: ['name'] }]; -/** Every door a form view payload is parsed through, with the path the payload sits at. */ +/** + * Every door a form view payload is parsed through, with the path the payload sits at. + * + * [ADR-0159 D7] Since protocol 19 a form body is judged by `FormViewSchema` and the `form` item + * only. The four view-held doors this table also listed (`view.form`, `view.formViews.*`, a + * `viewKind: 'form'` record, the flattened form overlay) refuse the whole form at their own key + * with the D7 prescription, whatever it carries — pinned below from + * {@link RETIRED_VIEW_FORM_DOORS}. + */ const DOORS: readonly Door[] = [ { name: 'FormViewSchema', parse: (f) => FormViewSchema.safeParse(f), at: [] }, - { name: 'view.form', parse: (f) => ViewSchema.safeParse({ form: f }), at: ['form'] }, - { name: 'view.formViews.*', parse: (f) => ViewSchema.safeParse({ formViews: { quick: f } }), at: ['formViews', 'quick'] }, - { - name: 'ViewItem form record', - parse: (f) => ViewItemSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', viewKind: 'form', config: f }), - at: ['config'], - }, - { - name: 'flattened form overlay', - parse: (f) => VIEW_METADATA_MEMBERS.formOverlay.safeParse({ ...f, object: 'crm_lead', viewKind: 'form' }), - at: [], - }, + FORM_ITEM_DOOR, ]; /** The issues a door reports under the payload — a wrapper may report others of its own. */ @@ -88,6 +86,11 @@ describe('FormView.buttons.reset — a tombstone inside the live `buttons` block } }); + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] %s refuses a form carrying `buttons.reset`, or not — at its own key, with the D7 prescription', (_, door) => { + expectRetiredViewFormDoorRefuses(door, { sections: SECTIONS, buttons: { submit: { label: 'Save' }, reset: { show: true } } }); + expectRetiredViewFormDoorRefuses(door, { sections: SECTIONS, buttons: { submit: { show: true, label: 'Save' }, cancel: { show: false } } }); + }); + it.each(DOORS.map((d) => [d.name, d] as const))('%s still accepts `submit` and `cancel`', (_, door) => { const r = door.parse({ sections: SECTIONS, buttons: { submit: { show: true, label: 'Save' }, cancel: { show: false } } }); expect(r.success, JSON.stringify(r.error?.issues)).toBe(true); @@ -103,16 +106,17 @@ describe('FormView.buttons.reset — a tombstone inside the live `buttons` block it('defineStack refuses it with the ADR-0112 envelope and the prescription', () => { let refusal: unknown; try { - defineStack({ views: [{ object: 'crm_lead', formViews: { quick: { sections: SECTIONS, buttons: { reset: { show: true } } } } }] } as never); + // [ADR-0159 D7] The form is a `form` item since protocol 19 (it was a `formViews` entry). + defineStack({ forms: [{ name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, buttons: { reset: { show: true } } }] } as never); } catch (error) { refusal = error; } expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = (refusal as { issues: { path: PropertyKey[]; message: string }[] }).issues; - expect(issues.map((i) => i.path.join('.'))).toEqual(['views.0.formViews.quick.buttons.reset']); + expect(issues.map((i) => i.path.join('.'))).toEqual(['forms.0.buttons.reset']); expect(issues[0]!.message.startsWith(FIRST_SENTENCE)).toBe(true); expect(() => defineStack({ - views: [{ object: 'crm_lead', formViews: { quick: { sections: SECTIONS, buttons: { cancel: { label: 'Back' } } } } }], + forms: [{ name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, buttons: { cancel: { label: 'Back' } } }], } as never)).not.toThrow(); }); @@ -151,8 +155,9 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { expect(notices.filter(ours).map(brief)).toEqual([ { conversionId: CONVERSION_ID, path: 'views[0].formViews.quick.buttons.reset', from: 'reset', to: '(removed)' }, ]); - const parsed = ViewSchema.parse(out); - expect(parsed.formViews?.quick?.buttons).toEqual({ cancel: { show: false } }); + // [ADR-0159 D7] The replayed row still holds a view-held form, which the 19 door refuses. + expect(out.formViews.quick.buttons).toEqual({ cancel: { show: false } }); + expect(ViewSchema.safeParse(out).success).toBe(false); // A form without `reset` is the author's and is never touched. expect(out.form).toBe(row.form); // Copy-on-write: the stored row is not mutated. @@ -165,7 +170,8 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { const out = applyConversionsToStoredItem('view', row, { onNotice: (n) => notices.push(n) }) as typeof row; expect(notices.filter(ours).map((n) => n.path)).toEqual(['views[0].config.buttons.reset']); expect(out.config).toEqual({ sections: SECTIONS, buttons: {} }); - expect(ViewItemSchema.safeParse(out).success).toBe(true); + // [ADR-0159 D7] A form view item is refused by the 19 door whatever its config carries. + expect(ViewItemSchema.safeParse(out).success).toBe(false); }); it('is idempotent by construction: a second replay converts nothing', () => { diff --git a/packages/spec/src/ui/form-view-drawer-keys-retirement.test.ts b/packages/spec/src/ui/form-view-drawer-keys-retirement.test.ts index 1712ec96c17..825bd6d6d35 100644 --- a/packages/spec/src/ui/form-view-drawer-keys-retirement.test.ts +++ b/packages/spec/src/ui/form-view-drawer-keys-retirement.test.ts @@ -61,7 +61,8 @@ import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/regist import { defineStack } from '../stack.zod'; import { ObjectFormPropsSchema } from './component.zod'; import { REACT_BLOCKS, REACT_OVERLAY_SHADOWS } from './react-blocks'; -import { FormSchema, FormViewSchema, VIEW_METADATA_MEMBERS, ViewItemSchema, ViewSchema } from './view.zod'; +import { FormSchema, FormViewSchema, ViewItemSchema, ViewSchema } from './view.zod'; +import { FORM_ITEM_DOOR, RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit'; const CONVERSION_ID = 'form-view-drawer-keys-removed'; const D3_ID = 'ui-form-view-drawer-keys-retired'; @@ -85,21 +86,18 @@ type Door = { name: string; parse: (form: Record) => Parse; at: const SECTIONS = [{ label: 'Main', fields: ['name'] }]; -/** Every door a form view payload is parsed through, with the path the payload sits at. */ +/** + * Every door a form view payload is parsed through, with the path the payload sits at. + * + * [ADR-0159 D7] Since protocol 19 a form body is judged by `FormViewSchema` and the `form` item + * only. The four view-held doors this table also listed (`view.form`, `view.formViews.*`, a + * `viewKind: 'form'` record, the flattened form overlay) refuse the whole form at their own key + * with the D7 prescription, whatever it carries — pinned per key below from + * {@link RETIRED_VIEW_FORM_DOORS}. + */ const DOORS: readonly Door[] = [ { name: 'FormViewSchema', parse: (f) => FormViewSchema.safeParse(f), at: [] }, - { name: 'view.form', parse: (f) => ViewSchema.safeParse({ form: f }), at: ['form'] }, - { name: 'view.formViews.*', parse: (f) => ViewSchema.safeParse({ formViews: { quick: f } }), at: ['formViews', 'quick'] }, - { - name: 'ViewItem form record', - parse: (f) => ViewItemSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', viewKind: 'form', config: f }), - at: ['config'], - }, - { - name: 'flattened form overlay', - parse: (f) => VIEW_METADATA_MEMBERS.formOverlay.safeParse({ ...f, object: 'crm_lead', viewKind: 'form' }), - at: [], - }, + FORM_ITEM_DOOR, ]; /** The issues a door reports under the payload — a wrapper may report others of its own. */ @@ -121,6 +119,16 @@ describe('FormView.drawerSide / drawerWidth — tombstones at every form-view do }); } + for (const key of KEYS) { + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))(`[ADR-0159 D7] %s refuses a form carrying \`${key}\` — at its own key, with the D7 prescription`, (_, door) => { + for (const value of VALUES[key]) expectRetiredViewFormDoorRefuses(door, { type: 'simple', sections: SECTIONS, [key]: value }); + }); + } + + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] CONTROL: %s refuses the same form without the keys too — a view is a list', (_, door) => { + expectRetiredViewFormDoorRefuses(door, { type: 'simple', sections: SECTIONS, columns: 2 }); + }); + it.each(DOORS.map((d) => [d.name, d] as const))('CONTROL: %s still accepts the same form without the keys, a live key beside them included', (_, door) => { // [#36544] The live key was `modalSize` until it became a tombstone too. const r = door.parse({ type: 'simple', sections: SECTIONS, columns: 2 }); @@ -130,8 +138,9 @@ describe('FormView.drawerSide / drawerWidth — tombstones at every form-view do it('defineStack refuses them with the ADR-0112 envelope and the prescription', () => { let refusal: unknown; try { + // [ADR-0159 D7] The form is a `form` item since protocol 19 (it was a `formViews` entry). defineStack({ - views: [{ object: 'crm_lead', formViews: { quick: { sections: SECTIONS, drawerSide: 'left', drawerWidth: '480px' } } }], + forms: [{ name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, drawerSide: 'left', drawerWidth: '480px' }], } as never); } catch (error) { refusal = error; @@ -139,15 +148,15 @@ describe('FormView.drawerSide / drawerWidth — tombstones at every form-view do expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = (refusal as { issues: { path: PropertyKey[]; message: string }[] }).issues; expect(issues.map((i) => i.path.join('.')).sort()).toEqual([ - 'views.0.formViews.quick.drawerSide', - 'views.0.formViews.quick.drawerWidth', + 'forms.0.drawerSide', + 'forms.0.drawerWidth', ]); for (const issue of issues) { const key = issue.path[issue.path.length - 1] as (typeof KEYS)[number]; expect(issue.message.startsWith(FIRST_SENTENCE[key]), issue.message).toBe(true); } expect(() => defineStack({ - views: [{ object: 'crm_lead', formViews: { quick: { sections: SECTIONS, columns: 2 } } }], + forms: [{ name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, columns: 2 }], } as never)).not.toThrow(); }); @@ -213,10 +222,12 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { { conversionId: CONVERSION_ID, path: 'views[0].formViews.quick.drawerSide', from: 'drawerSide', to: '(removed)' }, { conversionId: CONVERSION_ID, path: 'views[0].formViews.quick.drawerWidth', from: 'drawerWidth', to: '(removed)' }, ]); - const parsed = ViewSchema.parse(out); - expect(parsed.formViews?.quick).not.toHaveProperty('drawerSide'); - expect(parsed.formViews?.quick).not.toHaveProperty('drawerWidth'); - expect(parsed.formViews?.quick?.columns).toBe(2); + // [ADR-0159 D7] The replayed row still holds a view-held form, which the 19 door refuses + // whatever it carries (a read serves the row's lists only; the stored row is not rewritten). + expect(out.formViews.quick).not.toHaveProperty('drawerSide'); + expect(out.formViews.quick).not.toHaveProperty('drawerWidth'); + expect(out.formViews.quick.columns).toBe(2); + expect(ViewSchema.safeParse(out).success).toBe(false); // A form without the keys is the author's and is never touched. expect(out.form).toBe(row.form); // Copy-on-write: the stored row is not mutated. @@ -229,7 +240,8 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { const out = applyConversionsToStoredItem('view', row, { onNotice: (n) => notices.push(n) }) as typeof row; expect(notices.filter(ours).map((n) => n.path)).toEqual(['views[0].config.drawerWidth']); expect(out.config).toEqual({ sections: SECTIONS }); - expect(ViewItemSchema.safeParse(out).success).toBe(true); + // [ADR-0159 D7] A form view item is refused by the 19 door whatever its config carries. + expect(ViewItemSchema.safeParse(out).success).toBe(false); }); it('never touches the `object-form` page block, whose drawer reads the keys', () => { @@ -290,15 +302,8 @@ const MODAL_MIGRATE_SENTENCE = 'Run `os migrate meta --from 18` to list the mech /** Every value the key accepted while it was declared. */ const MODAL_VALUES = ['sm', 'default', 'lg', 'xl', 'full'] as const; -/** The form-view doors, and the `form` item (ADR-0159), whose body keys are the form view's by reference. */ -const MODAL_DOORS: readonly Door[] = [ - ...DOORS, - { - name: '`form` item', - parse: (f) => FormSchema.safeParse({ name: 'crm_lead.intake', object: 'crm_lead', ...f }), - at: [], - }, -]; +/** The form-view doors: `FormViewSchema` and the `form` item (ADR-0159), whose body keys are the form view's by reference. */ +const MODAL_DOORS: readonly Door[] = DOORS; describe('FormView.modalSize — a tombstone at every form-view door', () => { it.each(MODAL_DOORS.map((d) => [d.name, d] as const))('%s refuses `modalSize`, whatever it carries, with its prescription', (_, door) => { @@ -313,6 +318,10 @@ describe('FormView.modalSize — a tombstone at every form-view door', () => { } }); + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] %s refuses a form carrying `modalSize` — at its own key, with the D7 prescription', (_, door) => { + for (const value of MODAL_VALUES) expectRetiredViewFormDoorRefuses(door, { type: 'simple', sections: SECTIONS, modalSize: value }); + }); + it.each(MODAL_DOORS.map((d) => [d.name, d] as const))('CONTROL: %s still accepts the same form without the key', (_, door) => { const r = door.parse({ type: 'simple', sections: SECTIONS, columns: 2 }); expect(r.success, JSON.stringify(r.error?.issues)).toBe(true); @@ -321,8 +330,12 @@ describe('FormView.modalSize — a tombstone at every form-view door', () => { it('defineStack refuses it with the ADR-0112 envelope and the prescription', () => { let refusal: unknown; try { + // [ADR-0159 D7] The two forms are `form` items since protocol 19 (a container's `form` and a `formViews` entry before). defineStack({ - views: [{ object: 'crm_lead', form: { sections: SECTIONS, modalSize: 'full' }, formViews: { quick: { sections: SECTIONS, modalSize: 'lg' } } }], + forms: [ + { name: 'crm_lead.form', object: 'crm_lead', sections: SECTIONS, modalSize: 'full' }, + { name: 'crm_lead.quick', object: 'crm_lead', sections: SECTIONS, modalSize: 'lg' }, + ], } as never); } catch (error) { refusal = error; @@ -330,8 +343,8 @@ describe('FormView.modalSize — a tombstone at every form-view door', () => { expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = (refusal as { issues: { path: PropertyKey[]; message: string }[] }).issues; expect(issues.map((i) => i.path.join('.')).sort()).toEqual([ - 'views.0.form.modalSize', - 'views.0.formViews.quick.modalSize', + 'forms.0.modalSize', + 'forms.1.modalSize', ]); for (const issue of issues) { expect(issue.message.startsWith(MODAL_FIRST_SENTENCE), issue.message).toBe(true); @@ -399,9 +412,10 @@ describe(`the D2 conversion ${MODAL_CONVERSION_ID}`, () => { expect(notices.filter(oursModal).map(brief)).toEqual([ { conversionId: MODAL_CONVERSION_ID, path: 'views[0].formViews.quick.modalSize', from: 'modalSize', to: '(removed)' }, ]); - const parsed = ViewSchema.parse(out); - expect(parsed.formViews?.quick).not.toHaveProperty('modalSize'); - expect(parsed.formViews?.quick?.columns).toBe(2); + // [ADR-0159 D7] The replayed row still holds a view-held form, which the 19 door refuses. + expect(out.formViews.quick).not.toHaveProperty('modalSize'); + expect(out.formViews.quick.columns).toBe(2); + expect(ViewSchema.safeParse(out).success).toBe(false); // A form without the key is the author's and is never touched. expect(out.form).toBe(row.form); // Copy-on-write: the stored row is not mutated. @@ -414,7 +428,8 @@ describe(`the D2 conversion ${MODAL_CONVERSION_ID}`, () => { const out = applyConversionsToStoredItem('view', row, { onNotice: (n) => notices.push(n) }) as typeof row; expect(notices.filter(oursModal).map((n) => n.path)).toEqual(['views[0].config.modalSize']); expect(out.config).toEqual({ sections: SECTIONS }); - expect(ViewItemSchema.safeParse(out).success).toBe(true); + // [ADR-0159 D7] A form view item is refused by the 19 door whatever its config carries. + expect(ViewItemSchema.safeParse(out).success).toBe(false); }); it('a STORED `form` item converts its top-level body', () => { diff --git a/packages/spec/src/ui/form-view-type-layout-retirement.test.ts b/packages/spec/src/ui/form-view-type-layout-retirement.test.ts index 94303af5e92..5ca67ef2c85 100644 --- a/packages/spec/src/ui/form-view-type-layout-retirement.test.ts +++ b/packages/spec/src/ui/form-view-type-layout-retirement.test.ts @@ -57,7 +57,8 @@ import type { ConversionNotice } from '../conversions/types'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; import { ObjectFormPropsSchema, ObjectMasterDetailFormPropsSchema } from './component.zod'; -import { FormSectionSchema, FormViewSchema, VIEW_METADATA_MEMBERS, ViewItemSchema, ViewSchema } from './view.zod'; +import { FormSectionSchema, FormViewSchema, ViewItemSchema, ViewSchema } from './view.zod'; +import { FORM_ITEM_DOOR, RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit'; const CONVERSION_ID = 'form-view-presentation-types-removed'; const D3_ID = 'ui-form-view-type-layout-only'; @@ -107,21 +108,18 @@ type Door = { name: string; parse: (form: Record) => Parse; at: const SECTIONS = [{ label: 'Main', fields: ['name'] }]; -/** Every door a form view payload is parsed through, with the path the payload sits at. */ +/** + * Every door a form view payload is parsed through, with the path the payload sits at. + * + * [ADR-0159 D7] Since protocol 19 a form body is judged by `FormViewSchema` and the `form` item + * only. The four view-held doors this table also listed (`view.form`, `view.formViews.*`, a + * `viewKind: 'form'` record, the flattened form overlay) refuse the whole form at their own key + * with the D7 prescription, whatever it carries — pinned below from + * {@link RETIRED_VIEW_FORM_DOORS}. + */ const DOORS: readonly Door[] = [ { name: 'FormViewSchema', parse: (f) => FormViewSchema.safeParse(f), at: [] }, - { name: 'view.form', parse: (f) => ViewSchema.safeParse({ form: f }), at: ['form'] }, - { name: 'view.formViews.*', parse: (f) => ViewSchema.safeParse({ formViews: { quick: f } }), at: ['formViews', 'quick'] }, - { - name: 'ViewItem form record', - parse: (f) => ViewItemSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', viewKind: 'form', config: f }), - at: ['config'], - }, - { - name: 'flattened form overlay', - parse: (f) => VIEW_METADATA_MEMBERS.formOverlay.safeParse({ ...f, object: 'crm_lead', viewKind: 'form' }), - at: [], - }, + FORM_ITEM_DOOR, ]; /** The issues a door reports under the payload — a wrapper may report others of its own. */ @@ -148,6 +146,10 @@ describe('FormView.type — `simple | tabbed | wizard`, default `simple`', () => } }); + it.each(RETIRED_VIEW_FORM_DOORS.map((d) => [d.name, d] as const))('[ADR-0159 D7] %s refuses a form of any layout — at its own key, with the D7 prescription', (_, door) => { + for (const type of [...RETIRED_TYPES, ...LIVE_TYPES]) expectRetiredViewFormDoorRefuses(door, { type, sections: SECTIONS }); + }); + it.each(DOORS.map((d) => [d.name, d] as const))('%s accepts each live layout', (_, door) => { for (const type of LIVE_TYPES) { expect(door.parse({ type, sections: SECTIONS }).success, type).toBe(true); @@ -165,18 +167,19 @@ describe('FormView.type — `simple | tabbed | wizard`, default `simple`', () => for (const type of RETIRED_TYPES) { let refusal: unknown; try { - defineStack({ views: [{ object: 'crm_lead', formViews: { quick: { type, sections: SECTIONS } } }] } as never); + // [ADR-0159 D7] The form is a `form` item since protocol 19 (it was a `formViews` entry). + defineStack({ forms: [{ name: 'crm_lead.quick', object: 'crm_lead', type, sections: SECTIONS }] } as never); } catch (error) { refusal = error; } expect(refusal, type).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = (refusal as { issues: { path: PropertyKey[]; message: string }[] }).issues; - expect(issues.map((i) => i.path.join('.'))).toEqual(['views.0.formViews.quick.type']); + expect(issues.map((i) => i.path.join('.'))).toEqual(['forms.0.type']); expect(issues[0]!.message.startsWith(TYPE_FIRST_SENTENCE[type])).toBe(true); } for (const type of LIVE_TYPES) { const sections = [{ label: 'Step', fields: ['name'] }]; - expect(() => defineStack({ views: [{ object: 'crm_lead', formViews: { quick: { type, sections } } }] } as never)).not.toThrow(); + expect(() => defineStack({ forms: [{ name: 'crm_lead.quick', object: 'crm_lead', type, sections }] } as never)).not.toThrow(); } }); @@ -439,11 +442,15 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { { conversionId: CONVERSION_ID, path: 'views[0].formViews.beside.sections[1].pane', from: 'pane', to: '(removed)' }, { conversionId: CONVERSION_ID, path: 'views[0].formViews.quick.type', from: 'drawer', to: '(removed)' }, ]); - const parsed = ViewSchema.parse(out); - expect(parsed.formViews?.beside?.type).toBe('simple'); - expect(parsed.formViews?.beside).not.toHaveProperty('splitDirection'); - expect(parsed.formViews?.quick?.type).toBe('simple'); - expect(parsed.formViews?.quick?.columns).toBe(2); + // [ADR-0159 D7] The replayed row still holds view-held forms, which the 19 door refuses; each + // replayed form body is what the form door accepts, landing on `simple`. + expect(ViewSchema.safeParse(out).success).toBe(false); + const beside = FormViewSchema.parse(out.formViews.beside); + const quick = FormViewSchema.parse(out.formViews.quick); + expect(beside.type).toBe('simple'); + expect(beside).not.toHaveProperty('splitDirection'); + expect(quick.type).toBe('simple'); + expect(quick.columns).toBe(2); // A live layout is the author's and is never touched. expect(out.form).toBe(row.form); // Copy-on-write: the stored row is not mutated. @@ -456,7 +463,8 @@ describe(`the D2 conversion ${CONVERSION_ID}`, () => { const out = applyConversionsToStoredItem('view', row, { onNotice: (n) => notices.push(n) }) as typeof row; expect(notices.filter(ours).map((n) => n.path)).toEqual(['views[0].config.type']); expect(out.config).toEqual({ columns: 2, sections: SECTIONS }); - expect(ViewItemSchema.safeParse(out).success).toBe(true); + // [ADR-0159 D7] A form view item is refused by the 19 door whatever its config carries. + expect(ViewItemSchema.safeParse(out).success).toBe(false); }); it('is idempotent by construction: a second replay converts nothing', () => { diff --git a/packages/spec/src/ui/retired-view-form-doors.testkit.ts b/packages/spec/src/ui/retired-view-form-doors.testkit.ts new file mode 100644 index 00000000000..c12a65e1b68 --- /dev/null +++ b/packages/spec/src/ui/retired-view-form-doors.testkit.ts @@ -0,0 +1,84 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D7] The four view-held form doors, retired in protocol 19, as ONE + * table for the form-key retirement tests. + * + * Before protocol 19 a form view body was parsed through five doors: the bare + * `FormViewSchema`, a container's `form`, a container's `formViews.*`, a + * `viewKind: 'form'` view item's `config`, and the flattened form overlay. A + * view holds lists only since protocol 19, so the last four refuse the WHOLE + * form, whatever it carries, with the D7 tombstone's prescription at the + * door's own key — never with a prescription of a key inside the body. The + * `form` item (`forms:`) is where a form body is judged key by key now. + * + * The retirement tests keep their old door rows (never deleted) and judge them + * here, against the major's answer. Not exported from `ui/index.ts` and not a + * tsup entry, so it never reaches the package's public surface. + */ + +import { expect } from 'vitest'; +import { FormSchema, VIEW_METADATA_MEMBERS, ViewItemSchema, ViewSchema } from './view.zod'; + +type Issue = { code: string; path: PropertyKey[]; message: string }; +type Parse = { success: boolean; data?: unknown; error?: { issues: Issue[] } }; + +/** One retired view-held form door: where its refusal sits, and the prescription it opens with. */ +export interface RetiredViewFormDoor { + readonly name: string; + readonly parse: (form: Record) => Parse; + /** The path of the refusal: the door's own key, never a key inside the form body. */ + readonly at: readonly PropertyKey[]; + /** The opening of the D7 prescription the door answers. */ + readonly opening: string; +} + +const KIND_RETIRED = "`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"; + +/** The four view-held form doors, named as the retirement tests named them before protocol 19. */ +export const RETIRED_VIEW_FORM_DOORS: readonly RetiredViewFormDoor[] = [ + { + name: 'view.form', + parse: (f) => ViewSchema.safeParse({ form: f }) as Parse, + at: ['form'], + opening: '`view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)', + }, + { + name: 'view.formViews.*', + parse: (f) => ViewSchema.safeParse({ formViews: { quick: f } }) as Parse, + at: ['formViews'], + opening: '`view.formViews` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)', + }, + { + name: 'ViewItem form record', + parse: (f) => ViewItemSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', viewKind: 'form', config: f }) as Parse, + at: ['viewKind'], + opening: KIND_RETIRED, + }, + { + name: 'flattened form overlay', + // The form overlay member is gone; the list member claims a form-bound flat body. + parse: (f) => VIEW_METADATA_MEMBERS.listOverlay.safeParse({ ...f, object: 'crm_lead', viewKind: 'form' }) as Parse, + at: ['viewKind'], + opening: KIND_RETIRED, + }, +]; + +/** The door a form body is judged through since protocol 19: the `form` item, body at the top level. */ +export const FORM_ITEM_DOOR = { + name: '`form` item', + parse: (f: Record) => FormSchema.safeParse({ name: 'crm_lead.quick', object: 'crm_lead', ...f }) as Parse, + at: [] as PropertyKey[], +}; + +/** + * Assert a retired view-held door refuses `form` at its own key with the D7 + * prescription — the answer it gives whatever the form body carries. + */ +export function expectRetiredViewFormDoorRefuses(door: RetiredViewFormDoor, form: Record): void { + const r = door.parse(form); + expect(r.success, `${door.name} must refuse a form body since protocol 19`).toBe(false); + const atDoor = (r.error?.issues ?? []).find((i) => door.at.every((seg, k) => i.path[k] === seg) && i.path.length === door.at.length); + expect(atDoor, `${door.name}: ${JSON.stringify(r.error?.issues)}`).toBeDefined(); + expect(atDoor!.message.startsWith(door.opening), atDoor!.message).toBe(true); +} diff --git a/packages/spec/src/ui/view-authoring-wire-split.test.ts b/packages/spec/src/ui/view-authoring-wire-split.test.ts index 828498fa5f4..d0fa98fbc14 100644 --- a/packages/spec/src/ui/view-authoring-wire-split.test.ts +++ b/packages/spec/src/ui/view-authoring-wire-split.test.ts @@ -137,7 +137,10 @@ describe('`ViewItemSchema` is the authoring gate and is now strict', () => { expect(msg).toContain('config'); }); - it('an undeclared key is rejected on BOTH arms, at the arm where it lives', () => { + // [ADR-0159 D7] The item had a list arm and a form arm until protocol 19. + // The form arm is gone: a form record is refused whole at `viewKind`, with + // the D7 prescription, before any key inside it is judged. + it('an undeclared key is rejected on the list arm; a form record is refused whole at `viewKind`', () => { expect(reject(ViewItemSchema, { ...RECORD, notAViewItemKey: 1 })).toContain('notAViewItemKey'); expect( reject(ViewItemSchema, { @@ -147,7 +150,7 @@ describe('`ViewItemSchema` is the authoring gate and is now strict', () => { config: { type: 'simple', sections: [{ fields: ['name'] }] }, notAViewItemKey: 1, }), - ).toContain('notAViewItemKey'); + ).toContain("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"); }); it('the wire keys are rejected HERE, each with the prescription for its layer', () => { @@ -173,13 +176,15 @@ describe('`ViewItemSchema` is the authoring gate and is now strict', () => { label: 'All Leads', config: { type: 'grid', columns: [], data: { provider: 'object', object: 'crm_lead' } }, }); - accept(ViewItemSchema, { + // [ADR-0159 D7] The form body this emitter also wrote is refused since + // protocol 19: a form is created as a `form` item (`forms:`), not a view. + expect(ViewItemSchema.safeParse({ name: 'crm_lead.intake', object: 'crm_lead', viewKind: 'form', label: 'Intake', config: { type: 'tabbed', data: { provider: 'object', object: 'crm_lead' }, sections: [] }, - }); + }).success).toBe(false); }); it('the two nested console-decorated blocks now reject `id` at their own path', () => { @@ -378,19 +383,20 @@ describe('`stripViewConsoleDecorations`, the write-path mirror of `stripReadDeco // 5. The two landmines the ruling named // =========================================================================== describe('landmine 1: `/api/v1/meta/types/view` must still get an `anyOf`', () => { - it('the REGISTERED schema converts to a four-member `anyOf`, through the preprocess', () => { + // [ADR-0159 D7] Four members until protocol 19; the form overlay left. + it('the REGISTERED schema converts to a three-member `anyOf`, through the preprocess', () => { // Studio's SchemaForm is built from this. `z.preprocess` makes the root a // pipe; a pipe converts to its output side, so the union survives — but // that is a fact about zod, so it is asserted rather than assumed. const json = z.toJSONSchema(getMetadataTypeSchema('view')!, { unrepresentable: 'any' }) as Record; expect(Array.isArray(json.anyOf)).toBe(true); - expect((json.anyOf as unknown[]).length).toBe(4); + expect((json.anyOf as unknown[]).length).toBe(3); }); it('converts in the INPUT direction too — the form is built from what an author sends', () => { const json = z.toJSONSchema(ViewMetadataSchema, { unrepresentable: 'any', io: 'input' }) as Record; expect(Array.isArray(json.anyOf)).toBe(true); - expect((json.anyOf as unknown[]).length).toBe(4); + expect((json.anyOf as unknown[]).length).toBe(3); }); it('the emitted schema does NOT advertise `id` on a filter/sort row', () => { @@ -414,13 +420,15 @@ describe('landmine 1: `/api/v1/meta/types/view` must still get an `anyOf`', () = for (const io of ['output', 'input'] as const) { const json = z.toJSONSchema(getMetadataTypeSchema('view')!, { unrepresentable: 'any', io }) as Record; const members = json.anyOf as Array>; - expect(members).toHaveLength(4); - // Member 1 is the discriminated ViewItem record (a nested union); members - // 2-4 are plain objects. A degraded emission loses exactly this shape. + // [ADR-0159 D7] Four until protocol 19; the form overlay left. + expect(members).toHaveLength(3); + // Member 1 is the discriminated ViewItem record (a nested union, one arm + // since protocol 19); members 2-3 are plain objects. A degraded emission + // loses exactly this shape. expect(Array.isArray(members[0]!.oneOf ?? members[0]!.anyOf)).toBe(true); for (const member of members.slice(1)) expect(member.type).toBe('object'); // The form needs real property sets, not an empty permissive schema. - expect(Object.keys((members[3]!.properties ?? {}) as object).length).toBeGreaterThan(10); + expect(Object.keys((members[2]!.properties ?? {}) as object).length).toBeGreaterThan(10); } }); }); diff --git a/packages/spec/src/ui/view-column-state-retirement.test.ts b/packages/spec/src/ui/view-column-state-retirement.test.ts index e723b512794..22aaf44ac36 100644 --- a/packages/spec/src/ui/view-column-state-retirement.test.ts +++ b/packages/spec/src/ui/view-column-state-retirement.test.ts @@ -61,7 +61,8 @@ type Issue = { code: string; path: PropertyKey[]; message: string; errors?: Issu const MEMBERS = [ ['viewItem', VIEW_METADATA_MEMBERS.viewItem, RECORD], ['listOverlay', VIEW_METADATA_MEMBERS.listOverlay, LIST_OVERLAY], - ['formOverlay', VIEW_METADATA_MEMBERS.formOverlay, FORM_OVERLAY], + // [ADR-0159 D7] The flattened form overlay member was retired in protocol 19; + // a form-bound row is refused by the door below. ] as const; describe('columnState retirement — the tombstone, at every door that parses a stored row', () => { @@ -82,13 +83,16 @@ describe('columnState retirement — the tombstone, at every door that parses a it('the `view` write door refuses every row shape carrying it, the claimed member locating the key', () => { const door = getMetadataTypeSchema('view'); expect(door).toBe(ViewMetadataSchema); - for (const row of [LIST_OVERLAY, FORM_OVERLAY, RECORD]) { + for (const row of [LIST_OVERLAY, RECORD]) { const r = door!.safeParse({ ...row, columnState: VALUE }); expect(r.success, JSON.stringify(row)).toBe(false); if (r.success) continue; const top = r.error.issues[0] as unknown as Issue; expect(top.message).toMatch(PRESCRIPTION); } + // [ADR-0159 D7] A form-bound row is refused whatever it carries: a view is a list. + expect(door!.safeParse({ ...FORM_OVERLAY, columnState: VALUE }).success).toBe(false); + expect(door!.safeParse({ ...FORM_OVERLAY }).success).toBe(false); }); it('the assembled-manifest channel refuses it too — which is why the D2 conversion reaches `viewItems`', () => { @@ -117,7 +121,6 @@ describe('columnState retirement — the tombstone, at every door that parses a for (const [label, schema, body] of [ ['viewItem member', VIEW_METADATA_MEMBERS.viewItem, { ...RECORD, isPinned: true }], ['listOverlay member', VIEW_METADATA_MEMBERS.listOverlay, { ...LIST_OVERLAY, isDefault: true }], - ['formOverlay member', VIEW_METADATA_MEMBERS.formOverlay, { ...FORM_OVERLAY, isDefault: true }], ['door (list)', ViewMetadataSchema, { ...LIST_OVERLAY, hiddenFields: ['name'] }], ] as const) { const r = schema.safeParse(body); diff --git a/packages/spec/src/ui/view-form-slots-retirement.test.ts b/packages/spec/src/ui/view-form-slots-retirement.test.ts new file mode 100644 index 00000000000..c648712b610 --- /dev/null +++ b/packages/spec/src/ui/view-form-slots-retirement.test.ts @@ -0,0 +1,288 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `view` is lists only since protocol 19 (ADR-0159 D7): the container's `form` + * and `formViews` slots and the `viewKind: 'form'` item are tombstones, and a + * form is a `form` item (`defineForm`). The refusals, the prescriptions and the + * conversion have their own pins beside this file (`retired-view-form-doors.testkit.ts` + * and the suites that read it). This one is the tree-scoped absence leg: nothing + * an author copies from still writes a form into a `view`. + * + * What is judged is the AUTHORING SHAPE, three arms: + * + * A. `formViews` in key position (TS / JS / JSON / YAML); + * B. the item kind, `viewKind: 'form'` (and YAML's bare `viewKind: form`); + * C. a `defineView({ … })` container whose own braces hold a `form` member, + * written `form: …` or shorthand. + * + * Inline code spans are prose and are not judged, so a page may still SAY that + * `formViews` was removed; a fenced block, a comment inside one and a file of + * metadata are judged. + * + * The population is every place an author copies from, inside the radius + * `scripts/cross-package-test-inputs.mjs` declares for this package: + * + * - `skills/`, `content/` and `scripts/`, whole; + * - `examples/`: the non-code files and each app's `src/` tree; + * - `packages/`: what a package TEACHES — its Markdown and YAML. + * + * A package's code and JSON are not judged, and that is the bound, stated: + * typed authoring there is refused by `tsc` at the tombstone (the input type of + * each retired slot is `never`), and what names the shapes untyped is the + * reader of rows stored before protocol 19 (ADR-0159 D6 rule 10, D7's + * conversion and ceremony) with the tests and fixtures that feed it. Spelling + * the shapes is that code's job for as long as such a row can exist, so its + * presence is no resurrection and this walk does not ask for its absence. + * + * Also outside what the walk sees: a container literal that is not wrapped in + * `defineView(` (a bare `views: [{ object, form }]`), a member assembled by + * spread or a computed key, and a container in JSON or YAML that holds `form` + * alone (the key is too common to judge without the wrapper; `formViews` and + * the item kind are judged there). + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { describe, expect, it } from 'vitest'; + +import { listRepoWalkFiles } from '../../scripts/lib/repo-walk-testkit'; + +const SPEC_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const REPO_ROOT = path.resolve(SPEC_ROOT, '../..'); + +const WALK_ROOTS = ['packages', 'examples', 'skills', 'content', 'scripts']; +const SCANNED_EXT = new Set(['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs', '.json', '.md', '.mdx', '.yaml', '.yml']); +const EXAMPLES_EXT = new Set(['.json', '.md', '.mdx', '.yaml', '.yml']); +const EXAMPLE_APP_SRC_TS = /^examples\/[^/]+\/src\/.+\.ts$/; +/** What a package teaches. Its code and JSON are the bound the header states. */ +const PACKAGES_EXT = new Set(['.md', '.mdx', '.yaml', '.yml']); +/** Where a bare YAML scalar can be the item kind. */ +const YAML_BEARING_EXT = new Set(['.yaml', '.yml', '.md', '.mdx']); +const SKIPPED_DIRS = new Set(['node_modules', 'dist', '.turbo', '.cache', '.objectstack', 'coverage', '.next', '.source']); + +type Arm = 'formViews' | "viewKind: 'form'" | 'defineView({ form })'; + +/** A. `formViews` as a key. The lookbehind keeps a member READ (`x.formViews ? a : b`) out. */ +const FORM_VIEWS_KEY = /(? 0; i += 1) { + const c = text[i]!; + if (/\s/.test(c)) continue; + if (c === '/' && text[i + 1] === '/') { + const eol = text.indexOf('\n', i); + i = eol === -1 ? text.length : eol; + continue; + } + if (c === '/' && text[i + 1] === '*') { + const end = text.indexOf('*/', i + 2); + i = end === -1 ? text.length : end + 1; + continue; + } + if (c === '"' || c === "'" || c === '`') { + const end = closeQuote(text, i); + const quotedKey = keyPosition && text.slice(i + 1, end) === 'form'; + if (quotedKey && /^\s*:/.test(text.slice(end + 1, end + 40))) return true; + i = end; + keyPosition = false; + continue; + } + if (c === '{' || c === '[' || c === '(') { + depth += 1; + keyPosition = false; + continue; + } + if (c === '}' || c === ']' || c === ')') { + depth -= 1; + keyPosition = false; + continue; + } + if (c === ',') { + keyPosition = depth === 1; + continue; + } + if (keyPosition) { + word.lastIndex = i; + const key = word.exec(text)?.[0]; + if (key !== undefined) { + if (key === 'form' && /^\s*[:,}]/.test(text.slice(i + key.length, i + key.length + 40))) return true; + i += key.length - 1; + } + } + keyPosition = false; + } + } + return false; +} + +/** Inline code spans are prose; newline-bounded, so a fenced example is still judged. */ +const stripInlineCode = (text: string): string => text.replace(/`[^`\n]*`/g, ''); + +/** The arms a file's text authors. `ext` decides whether a bare YAML scalar can be the kind. */ +function judge(text: string, ext: string): Arm[] { + const judged = stripInlineCode(text); + const arms: Arm[] = []; + if (FORM_VIEWS_KEY.test(judged)) arms.push('formViews'); + if (VIEW_KIND_FORM.test(judged) || (YAML_BEARING_EXT.has(ext) && VIEW_KIND_FORM_YAML.test(judged))) { + arms.push("viewKind: 'form'"); + } + if (containerAuthorsForm(judged)) arms.push('defineView({ form })'); + return arms; +} + +/** Whether the walk judges this file at all: the population the header states. */ +function inPopulation(rel: string, ext: string): boolean { + if (rel.startsWith('examples/')) return EXAMPLES_EXT.has(ext) || EXAMPLE_APP_SRC_TS.test(rel); + if (rel.startsWith('packages/')) return PACKAGES_EXT.has(ext); + return SCANNED_EXT.has(ext); +} + +/** + * Structural exclusions, each with its reason. ⛔ NOT an allowlist file + * (`spec-property-retirement` §4): an entry is here because spelling the + * retired shape is its JOB, never because it has not been cleaned up yet. + */ +const EXCLUDED_PREFIXES = [ + // Release-owned prose records the removal; never edited by a code PR. + 'content/docs/releases/', +]; +/** + * Excused from arms A and C only, and still judged on the item kind. Each + * entry READS the pre-19 container as its input, so it has to spell the slots + * it looks for; nothing has the job of teaching a `form` view item. + */ +const READS_THE_OLD_CONTAINER = new Set([ + // ADR-0017's reporter: scans `defineView` containers and looks for their `formViews` block. + 'scripts/codemod/view-to-viewitem.mjs', +]); +const TSUP_BUNDLED_CONFIG = /\.bundled_[^./]+\.mjs$/; + +const readIfPresent = (full: string): string | undefined => { + try { + return fs.readFileSync(full, 'utf-8'); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') throw err; + return undefined; + } +}; + +describe('view is lists only — the retired form slots are authored nowhere an author copies from', () => { + it('the matcher recognises each authoring arm and ignores its neighbours (anti-vacuity)', () => { + // A — `formViews` as a key. + expect(judge("defineView({ object: 'task', listViews: {}, formViews: { edit: {} } })", '.ts')).toEqual(['formViews']); + expect(judge('{ "object": "task", "formViews": { "edit": {} } }', '.json')).toEqual(['formViews']); + expect(judge('object: task\nformViews:\n edit:\n type: simple\n', '.yaml')).toEqual(['formViews']); + // B — the item kind, in each spelling. + expect(judge("defineViewItem({ name: 'task.edit', object: 'task', viewKind: 'form', config: {} })", '.ts')).toEqual(["viewKind: 'form'"]); + expect(judge('{ "name": "task.edit", "viewKind": "form" }', '.json')).toEqual(["viewKind: 'form'"]); + expect(judge('- name: task.edit\n viewKind: form\n config: {}\n', '.yaml')).toEqual(["viewKind: 'form'"]); + expect(judge('Prose.\n\n```yaml\nviewKind: form # the record form\n```\n', '.mdx')).toEqual(["viewKind: 'form'"]); + // C — a container's own `form` member: keyed, quoted, shorthand, and inside a fenced comment. + expect(judge("defineView({\n object: 'task',\n list: { type: 'grid' },\n form: { sections: [] },\n})", '.ts')).toEqual(['defineView({ form })']); + expect(judge('defineView({ "object": "task", "form": {} })', '.ts')).toEqual(['defineView({ form })']); + expect(judge('const v = defineView({ object, list, form });', '.ts')).toEqual(['defineView({ form })']); + expect(judge('```ts\n// A view is authored with defineView({ list, form }); both are nested.\n```\n', '.mdx')).toEqual(['defineView({ form })']); + + // Neighbours that must NOT match. + expect(judge("defineView({ object: 'task', list: { type: 'grid' }, listViews: { mine: { type: 'grid' } } })", '.ts')).toEqual([]); + expect(judge("defineViewItem({ name: 'task.all', object: 'task', viewKind: 'list', config: {} })", '.ts')).toEqual([]); + expect(judge("defineForm({ name: 'task.edit', object: 'task', sections: [] })", '.ts')).toEqual([]); + // Prose: an inline span says what was removed. + expect(judge('`formViews: { … }` and `viewKind: \'form\'` were removed in protocol 19; `defineView({ list, form })` is refused.', '.mdx')).toEqual([]); + // A `form` that is not the container's own member: nested deeper, or a value. + expect(judge("defineView({ object: 'task', list: { rowActions: [{ form: 'task.edit' }] } })", '.ts')).toEqual([]); + expect(judge("defineView({ object: 'task', list: { type: form } })", '.ts')).toEqual([]); + expect(judge("defineView({ object: 'task', list: { type: 'grid', form: 'task.edit' } })", '.ts')).toEqual([]); + expect(judge("defineView({ object: 'task', list: {} }); const form = defineForm({ form: 1 });", '.ts')).toEqual([]); + // A line comment, a block comment and a string inside a container are not members. + expect(judge("defineView({\n object: 'task', // was: list, form, listViews\n list: {},\n})", '.ts')).toEqual([]); + expect(judge("defineView({\n object: 'task', /* gone, form: a form item now */\n list: {},\n})", '.ts')).toEqual([]); + expect(judge("defineView({ object: 'task', description: 'list, form: both once', list: {} })", '.ts')).toEqual([]); + // A member READ is not an authoring; neither is a bare scalar in code. + expect(judge('const forms = view.formViews ? view.formViews : {};', '.ts')).toEqual([]); + expect(judge('const item = { viewKind: form };', '.ts')).toEqual([]); + // The kit's own spellings of the tombstones. + expect(judge("'ui/View:formViews [RETIRED]',", '.json')).toEqual([]); + expect(judge("export const entry = 'ui/View:formViews';", '.ts')).toEqual([]); + }); + + it('the population is the authoring surfaces, and a package contributes what it teaches', () => { + expect(inPopulation('skills/objectstack-ui/rules/list-views.md', '.md')).toBe(true); + expect(inPopulation('content/docs/concepts/architecture.mdx', '.mdx')).toBe(true); + expect(inPopulation('scripts/codemod/view-to-viewitem.mjs', '.mjs')).toBe(true); + expect(inPopulation('examples/app-crm/src/views/lead.view.ts', '.ts')).toBe(true); + expect(inPopulation('examples/app-crm/README.md', '.md')).toBe(true); + expect(inPopulation('packages/cli/README.md', '.md')).toBe(true); + // An example's code outside its `src/` tree is judged by its own `tsc`, as the radius declares. + // Joined, never one quoted path: the radius gate reads a quoted repo path as a file this suite + // reads, and no declared glob covers an example's test (the declaration says why). + expect(inPopulation(['examples', 'app-crm', 'test', 'smoke.test.ts'].join('/'), '.ts')).toBe(false); + // A package's code and JSON: the bound the header states. + expect(inPopulation('packages/metadata/src/plugin.ts', '.ts')).toBe(false); + expect(inPopulation('packages/rest/src/form-old-shape-before.json', '.json')).toBe(false); + }); + + it('no file inside the population still authors a form into a `view`', () => { + const offenders: string[] = []; + let visited = 0; + let mentioning = 0; + const skipDir = (name: string) => SKIPPED_DIRS.has(name) || name.startsWith('.'); + for (const root of WALK_ROOTS) { + for (const full of listRepoWalkFiles(path.join(REPO_ROOT, root), { skipDir })) { + const rel = path.relative(REPO_ROOT, full).split(path.sep).join('/'); + const name = path.basename(full); + const ext = path.extname(name); + if (!inPopulation(rel, ext)) continue; + if (name === 'CHANGELOG.md') continue; // release prose records the removal + if (EXCLUDED_PREFIXES.some((p) => rel.startsWith(p))) continue; + if (TSUP_BUNDLED_CONFIG.test(name)) continue; + visited += 1; + const text = readIfPresent(full); + if (text === undefined) continue; + if (text.includes('formViews') || text.includes('viewKind')) mentioning += 1; + let arms = judge(text, ext); + if (READS_THE_OLD_CONTAINER.has(rel)) arms = arms.filter((arm) => arm === "viewKind: 'form'"); + if (arms.length > 0) offenders.push(`${rel} [${arms.join(' + ')}]`); + } + } + // Anti-vacuity: the walk covered the population, and files that name the + // shapes at all (in prose, mostly) were really judged. + expect(visited).toBeGreaterThan(1000); + expect(mentioning).toBeGreaterThan(5); + expect( + offenders, + 'a form authored into a `view` is refused since protocol 19 (ADR-0159 D7) — write a `form` item (`defineForm`), and say so wherever this teaches', + ).toEqual([]); + }); +}); diff --git a/packages/spec/src/ui/view-inline-object-binding.test.ts b/packages/spec/src/ui/view-inline-object-binding.test.ts index 77ed593bb61..84e1a2cc865 100644 --- a/packages/spec/src/ui/view-inline-object-binding.test.ts +++ b/packages/spec/src/ui/view-inline-object-binding.test.ts @@ -87,13 +87,14 @@ describe('the runtime write door refuses the unbound inline view config', () => }; // The union envelope other consumers key on (ADR-0112 at the issue level). expect(root.code).toBe('invalid_union'); - expect(root.errors).toHaveLength(4); + // [ADR-0159 D7] Three members since the form overlay was retired in protocol 19. + expect(root.errors).toHaveLength(3); // Branch 2 is the listOverlay the body claims (`type: 'grid'`); #7510's - // focusing mutes the other three, so the author reads ONLY the binding + // focusing mutes the other two, so the author reads ONLY the binding // prescription, at the paths of the keys to add. const claimed = root.errors[2]!; expect(claimed.map((i) => i.path)).toEqual([['object'], ['viewKind']]); - for (const index of [0, 1, 3]) { + for (const index of [0, 1]) { expect(root.errors[index]).toHaveLength(1); expect(root.errors[index]![0]!.message).toContain('this body reads as `listOverlay`'); } @@ -200,8 +201,9 @@ describe('the emitted contract declares what it enforces', () => { const json = z.toJSONSchema(door(), { unrepresentable: 'any', io }) as { anyOf?: Array<{ required?: string[] }>; }; - expect(json.anyOf).toHaveLength(4); - for (const member of [json.anyOf![2]!, json.anyOf![3]!]) { + // [ADR-0159 D7] One inline arm since the form overlay was retired in protocol 19. + expect(json.anyOf).toHaveLength(3); + for (const member of [json.anyOf![2]!]) { expect(member.required ?? []).toEqual(expect.arrayContaining(['object', 'viewKind'])); } } diff --git a/packages/spec/src/ui/view-item-config-type.test.ts b/packages/spec/src/ui/view-item-config-type.test.ts index 15001ef2477..4abfbde3a1e 100644 --- a/packages/spec/src/ui/view-item-config-type.test.ts +++ b/packages/spec/src/ui/view-item-config-type.test.ts @@ -40,12 +40,10 @@ const listItem: ViewItem = { viewKind: 'list', config: { type: 'kanban', data: { provider: 'object', object: 'crm_lead' }, columns: ['name', 'stage'] }, }; -const formItem: ViewItem = { - name: 'crm_lead.intake', - object: 'crm_lead', - viewKind: 'form', - config: { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }] }, -}; +// [ADR-0159 D7] The form arm was retired in protocol 19 (a view item is a list): this body no +// longer type-checks, and both doors refuse it at `viewKind` (pinned below). +// @ts-expect-error -- a form view item is no ViewItem since protocol 19. +const formItem: ViewItem = { name: 'crm_lead.intake', object: 'crm_lead', viewKind: 'form', config: { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }] } }; const wireItem: ViewItemWire = { ...listItem, isPinned: true, sortOrder: 2 }; // ── What the arm-typed `config` refuses at compile time ────────────────────────────────────── @@ -53,7 +51,7 @@ const wireItem: ViewItemWire = { ...listItem, isPinned: true, sortOrder: 2 }; const LIST_CONFIG = { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'] } as const; // @ts-expect-error -- a list item's config is a ListView config, not a scalar. const scalarConfig: ViewItem = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'list', config: 42 }; -// @ts-expect-error -- the form arm's config is a FormView config: `grid` is not a form type. +// @ts-expect-error -- no form arm since protocol 19: `viewKind: 'form'` is not a ViewItem's. const listConfigOnFormArm: ViewItem = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'form', config: LIST_CONFIG }; // @ts-expect-error -- the same on the wire member. const wireScalarConfig: ViewItemWire = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'list', config: 42 }; @@ -82,18 +80,26 @@ void [ describe('a ViewItem config is typed by its arm, not unknown', () => { it('each body typed through the published names parses at its door', () => { expect(ViewItemSchema.safeParse(listItem).success).toBe(true); - expect(ViewItemSchema.safeParse(formItem).success).toBe(true); expect(ViewItemWireSchema.safeParse(wireItem).success).toBe(true); }); it('the bodies the type refuses are refused at `config` by both doors', () => { const scalar = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'list', config: 42 }; + for (const door of [ViewItemSchema, ViewItemWireSchema]) { + const result = door.safeParse(scalar); + expect(result.success).toBe(false); + expect(result.error?.issues.every((issue) => issue.path[0] === 'config')).toBe(true); + } + }); + + it('[ADR-0159 D7] a form item — any config — is refused at `viewKind` by both doors, with the prescription', () => { const formWithListConfig = { name: 'crm_lead.x', object: 'crm_lead', viewKind: 'form', config: LIST_CONFIG }; for (const door of [ViewItemSchema, ViewItemWireSchema]) { - for (const body of [scalar, formWithListConfig]) { + for (const body of [formItem, formWithListConfig]) { const result = door.safeParse(body); expect(result.success).toBe(false); - expect(result.error?.issues.every((issue) => issue.path[0] === 'config')).toBe(true); + expect(result.error?.issues.every((issue) => issue.path[0] === 'viewKind')).toBe(true); + expect(result.error?.issues[0]?.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); } } }); diff --git a/packages/spec/src/ui/view-metadata-schema.test.ts b/packages/spec/src/ui/view-metadata-schema.test.ts index 66405ad43df..c3a0b2a07c6 100644 --- a/packages/spec/src/ui/view-metadata-schema.test.ts +++ b/packages/spec/src/ui/view-metadata-schema.test.ts @@ -47,14 +47,18 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha expect(r.success).toBe(false); }); - it('accepts a well-formed form ViewItem', () => { + // [ADR-0159 D7] A view holds lists only since protocol 19: the + // well-formed form ViewItem this case accepted is refused whole, at + // `viewKind`, with the D7 prescription naming `forms:`. + it('REFUSES a well-formed form ViewItem at `viewKind` since protocol 19', () => { const r = ViewMetadataSchema.safeParse({ name: 'crm_lead.edit', object: 'crm_lead', viewKind: 'form', config: { type: 'simple', sections: [{ label: 'Details', fields: ['name'] }] }, }); - expect(r.success).toBe(true); + expect(r.success).toBe(false); + expect(JSON.stringify(r.error?.issues)).toContain("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"); }); it('REJECTS a form ViewItem carrying an invalid form `type` (config validated, not stripped)', () => { @@ -148,7 +152,8 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha expect(text).toContain('Wrap it: `defineView({ list: { type, data, columns, … } })`'); }); - it('accepts a raw form config overlay', () => { + // [ADR-0159 D7] The form overlay member is gone with the form arm. + it('REFUSES a raw form config overlay since protocol 19', () => { const r = ViewMetadataSchema.safeParse({ type: 'simple', sections: [{ label: 'Details', fields: ['name'] }], @@ -156,7 +161,7 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha viewKind: 'form', object: 'crm_lead', }); - expect(r.success).toBe(true); + expect(r.success).toBe(false); }); it('REJECTS a flattened list overlay whose kanban binding is broken (genuine, not stripped)', () => { @@ -252,7 +257,10 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha // Guards against the mirror-image defect: a precondition that rejects the // platform's own writes is strictly worse than the hole it closed. // [#7741] The minimal accepted overlay now carries its binding pair. - expect(ViewMetadataSchema.safeParse({ type: 'simple', object: 'crm_lead', viewKind: 'form' }).success).toBe(true); + // [ADR-0159 D7] It was a form-bound `{ type: 'simple' }`; a view holds + // lists only since protocol 19, so the minimal overlay is list-bound. + expect(ViewMetadataSchema.safeParse({ type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'list' }).success).toBe(true); + expect(ViewMetadataSchema.safeParse({ type: 'simple', object: 'crm_lead', viewKind: 'form' }).success).toBe(false); }); // Every shape the platform itself writes carries a declared key, so the @@ -277,7 +285,8 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha ['a switcher-reorder PUT', { sortOrder: 3, object: 'crm_lead', viewKind: 'list' }], ['a column-only overlay', { columns: ['name'], object: 'crm_lead', viewKind: 'list' }], ['a filter-only overlay', { filter: [{ field: 'name', operator: 'contains', value: 'x' }], object: 'crm_lead', viewKind: 'list' }], - ['an order-only overlay', { order: 2, object: 'crm_lead', viewKind: 'form' }], + // [ADR-0159 D7] form-bound until protocol 19; `order` is a list key too. + ['an order-only overlay', { order: 2, object: 'crm_lead', viewKind: 'list' }], ['a renamed view that still carries its config', { label: 'New name', columns: ['name'], object: 'crm_lead', viewKind: 'list' }], ])('leaves %s alone', (_label, body) => { expect(ViewMetadataSchema.safeParse(body).success).toBe(true); @@ -289,7 +298,8 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha // inert on it, and the refusal belongs to the overlay member, carrying the // retirement prescription at the key. it('REFUSES a hide PUT on a real view at the member, with the retirement prescription', () => { - const bound = { object: 'crm_lead', viewKind: 'form' } as const; + // [ADR-0159 D7] form-bound until protocol 19; a real view is a list now. + const bound = { object: 'crm_lead', viewKind: 'list' } as const; const r = ViewMetadataSchema.safeParse({ ...bound, hidden: true }); expect(r.success).toBe(false); if (r.success) return; @@ -361,11 +371,12 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha it('…but identity PLUS any real view key is fine — leanness is not the bar', () => { // [#7741] "identity" here means the FULL binding pair: `object` alone or // `viewKind` alone is half a binding and the members refuse it now. - expect(ViewMetadataSchema.safeParse({ name: 'v', object: 'o', viewKind: 'form', order: 2 }).success).toBe(true); + // [ADR-0159 D7] The first line was form-bound until protocol 19. + expect(ViewMetadataSchema.safeParse({ name: 'v', object: 'o', viewKind: 'list', order: 2 }).success).toBe(true); expect(ViewMetadataSchema.safeParse({ name: 'v', object: 'o', viewKind: 'list', isPinned: true }).success).toBe(true); // [#20230] …a RETIRED key is not a real view key: `hidden` used to stand // in the first line above, and the same identity plus it is refused now. - const identity = { name: 'v', object: 'o', viewKind: 'form' } as const; + const identity = { name: 'v', object: 'o', viewKind: 'list' } as const; expect(ViewMetadataSchema.safeParse({ ...identity, hidden: true }).success).toBe(false); }); @@ -384,7 +395,13 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha // by hand. ([#7741] full acceptance additionally needs the binding pair; // the vocabulary question this test asks is unchanged. [#29012] It was // `drawerSide` until that key became a tombstone.) - expect(ViewMetadataSchema.safeParse({ showStepIndicator: true, object: 'crm_lead', viewKind: 'form' }).success).toBe(true); + // [ADR-0159 D7] The form member left the union in protocol 19, so its + // keys left the vocabulary with it: `showStepIndicator` is now refused + // by the precondition, and the example is a list key nobody would + // allow-list by hand. + expect(ViewMetadataSchema.safeParse({ showRecordCount: true, object: 'crm_lead', viewKind: 'list' }).success).toBe(true); + const formKey = ViewMetadataSchema.safeParse({ showStepIndicator: true, object: 'crm_lead', viewKind: 'list' }); + expect(formKey.success).toBe(false); // …and a key that exists only NESTED (inside `config`) is not top-level // vocabulary, so it cannot smuggle a garbage body through. expect(ViewMetadataSchema.safeParse({ groupByField: 'stage' }).success).toBe(false); @@ -440,6 +457,7 @@ describe('ViewMetadataSchema — genuine validation across the three runtime sha it('converts to a JSON Schema anyOf (union → anyOf) without throwing', () => { const json = z.toJSONSchema(ViewMetadataSchema, { unrepresentable: 'any' }) as Record; expect(Array.isArray(json.anyOf)).toBe(true); - expect((json.anyOf as unknown[]).length).toBe(4); + // [ADR-0159 D7] Four members until protocol 19; the form overlay left. + expect((json.anyOf as unknown[]).length).toBe(3); }); }); diff --git a/packages/spec/src/ui/view-metadata-type.test.ts b/packages/spec/src/ui/view-metadata-type.test.ts index 8907cdebecd..2fb5283b71a 100644 --- a/packages/spec/src/ui/view-metadata-type.test.ts +++ b/packages/spec/src/ui/view-metadata-type.test.ts @@ -22,6 +22,7 @@ import { describe, it, expect } from 'vitest'; import { + ViewMetadataSchema, VIEW_METADATA_BRANCHES, VIEW_METADATA_MEMBERS, diagnoseViewMetadata, @@ -43,18 +44,14 @@ const container: ViewMetadata = { list: { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'] }, }; const listOverlay: ViewMetadata = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'list' }; -const formOverlay: ViewMetadata = { - type: 'simple', - sections: [{ label: 'Main', fields: ['name'] }], - object: 'crm_lead', - viewKind: 'form', -}; +// [ADR-0159 D7] The form overlay member was retired in protocol 19 (a view is a list). +// @ts-expect-error -- a flattened form overlay is no view body since protocol 19. +const formOverlay: ViewMetadata = { type: 'simple', sections: [{ label: 'Main', fields: ['name'] }], object: 'crm_lead', viewKind: 'form' }; const BODY_OF_EACH_MEMBER: Record = { viewItem, container, listOverlay, - formOverlay, }; // ── What `ViewMetadata` refuses at compile time ────────────────────────────────────────────── @@ -81,6 +78,8 @@ void [parsedFromUnknown, parsedUndeclaredKey, parsedScalar]; describe('ViewMetadata is a view body, not unknown', () => { it('has a typed body for every member of the union', () => { expect(Object.keys(BODY_OF_EACH_MEMBER).sort()).toEqual([...VIEW_METADATA_BRANCHES].sort()); + // [ADR-0159 D7] The retired form overlay body is refused by the door. + expect(ViewMetadataSchema.safeParse(formOverlay).success).toBe(false); }); for (const branch of VIEW_METADATA_BRANCHES) { diff --git a/packages/spec/src/ui/view-overlay-options-bag.test.ts b/packages/spec/src/ui/view-overlay-options-bag.test.ts index b4a03d48d31..99089d8e810 100644 --- a/packages/spec/src/ui/view-overlay-options-bag.test.ts +++ b/packages/spec/src/ui/view-overlay-options-bag.test.ts @@ -192,11 +192,13 @@ describe('what the fold cannot decide stays as stored, with a TODO', () => { }); describe('the form overlay cannot take the bag the list overlay refused', () => { + // [ADR-0159 D7] The flattened form overlay member was retired in protocol 19 + // (a view is a list), so no member is left to take the bag the list member + // refuses, and a form-bound body is refused with the D7 prescription. it('a column-less, type-less body with a bad `options` bag is refused, not accepted as a form', () => { - // Without the form overlay's `options` pin this body is ACCEPTED: the list - // member refuses it (no `columns`, and the bag), the form member — which - // `.strip()`s and requires no list key — takes it, and the bag is stored - // unjudged after all. + // Before protocol 19, without the form overlay's `options` pin this body + // was ACCEPTED: the list member refused it (no `columns`, and the bag), the + // form member — which `.strip()`ped and required no list key — took it. const body = { name: 'crm_lead.all', object: 'crm_lead', @@ -205,11 +207,10 @@ describe('the form overlay cannot take the bag the list overlay refused', () => options: { timeline: { metaFields: ['region'] } }, }; expect(ViewMetadataSchema.safeParse(body).success).toBe(false); - const form = VIEW_METADATA_MEMBERS.formOverlay.safeParse(body); - expect(form.success).toBe(false); + expect(Object.keys(VIEW_METADATA_MEMBERS)).not.toContain('formOverlay'); }); - it('a flat form overlay carrying `options` is refused with the list-view prescription', () => { + it('a flat form overlay carrying `options` is refused, by the list member, with the D7 prescription', () => { const body = { name: 'lead.contact_us', object: 'lead', @@ -220,14 +221,14 @@ describe('the form overlay cannot take the bag the list overlay refused', () => const d = diagnoseViewMetadata(body); expect(d.success).toBe(false); if (d.success) return; - expect(d.branch).toBe('formOverlay'); - const hit = (d.issues as unknown as Issue[]).find((i) => i.path[0] === 'options'); - expect(hit?.message).toContain('A form view carries no `options` bag'); + expect(d.branch).toBe('listOverlay'); + const hit = (d.issues as unknown as Issue[]).find((i) => i.path[0] === 'viewKind'); + expect(hit?.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); }); - it('CONTROL: a flat form overlay without `options` still parses', () => { + it('CONTROL: a flat form overlay without `options` is refused too since 19 (a view is a list)', () => { const body = { name: 'lead.contact_us', object: 'lead', viewKind: 'form', type: 'simple' }; - expect(ViewMetadataSchema.safeParse(body).success).toBe(true); + expect(ViewMetadataSchema.safeParse(body).success).toBe(false); }); }); @@ -269,15 +270,19 @@ describe('a ViewItem record carries no top-level `options` bag', () => { expect(VIEW_METADATA_MEMBERS.viewItem.safeParse(record({ options: {} })).success).toBe(false); }); - it('on the form arm too', () => { - const hit = recordIssueAtOptions({ + it('on the form arm — retired since 19, so the record is refused at `viewKind` with the D7 prescription', () => { + const d = diagnoseViewMetadata({ name: 'lead.contact_us', object: 'lead', viewKind: 'form', config: { type: 'simple', data: { provider: 'object', object: 'lead' } }, options: { timeline: { titleField: 'name' } }, }); - expect(hit.message).toMatch(/^A view item record carries no top-level `options` bag/); + expect(d.success).toBe(false); + if (d.success) return; + expect(d.branch).toBe('viewItem'); + const hit = (d.issues as unknown as Issue[]).find((i) => i.path[0] === 'viewKind'); + expect(hit?.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); }); it('CONTROL: the record without the bag parses, and `config.kanban` is where the block lives', () => { diff --git a/packages/spec/src/ui/view-overlay-owner-hidden-retirement.test.ts b/packages/spec/src/ui/view-overlay-owner-hidden-retirement.test.ts index 0265bbf2b13..ad0de9e0d82 100644 --- a/packages/spec/src/ui/view-overlay-owner-hidden-retirement.test.ts +++ b/packages/spec/src/ui/view-overlay-owner-hidden-retirement.test.ts @@ -76,7 +76,8 @@ const RETIRED = [ const MEMBERS = [ ['listOverlay', VIEW_METADATA_MEMBERS.listOverlay, LIST_OVERLAY], - ['formOverlay', VIEW_METADATA_MEMBERS.formOverlay, FORM_OVERLAY], + // [ADR-0159 D7] The flattened form overlay member was retired in protocol 19; + // a form-bound overlay is refused by the door (pinned below). ] as const; type Issue = { code: string; path: PropertyKey[]; message: string; errors?: Issue[][] }; @@ -114,7 +115,9 @@ describe('overlay owner/hidden retirement — the tombstones, at every door that // `PUT /api/v1/meta/view/:name` body against. const door = getMetadataTypeSchema('view'); expect(door).toBe(ViewMetadataSchema); - for (const overlay of [LIST_OVERLAY, FORM_OVERLAY]) { + // [ADR-0159 D7] A form-bound overlay is refused whatever it carries. + expect(door!.safeParse({ ...FORM_OVERLAY, [key]: value }).success).toBe(false); + for (const overlay of [LIST_OVERLAY]) { const r = door!.safeParse({ ...overlay, [key]: value }); expect(r.success, `${overlay.viewKind} overlay`).toBe(false); if (r.success) continue; @@ -138,13 +141,16 @@ describe('overlay owner/hidden retirement — the tombstones, at every door that }); } + it('[ADR-0159 D7] a form-bound overlay without the keys is refused too: a view is a list since 19', () => { + const live = { isDefault: true, order: 2, scope: 'shared', label: 'Leads' } as const; + expect(ViewMetadataSchema.safeParse({ ...FORM_OVERLAY, ...live }).success).toBe(false); + }); + it('CONTROL: the same overlays without the keys pass every door, live round-trip keys intact', () => { const live = { isDefault: true, order: 2, scope: 'shared', label: 'Leads' } as const; for (const [label, schema, body] of [ ['listOverlay member', VIEW_METADATA_MEMBERS.listOverlay, { ...LIST_OVERLAY, ...live }], - ['formOverlay member', VIEW_METADATA_MEMBERS.formOverlay, { ...FORM_OVERLAY, ...live }], ['door (list)', ViewMetadataSchema, { ...LIST_OVERLAY, ...live }], - ['door (form)', ViewMetadataSchema, { ...FORM_OVERLAY, ...live }], ['assembled (list)', AssembledViewArtifactSchema, { ...LIST_OVERLAY, ...live }], ] as const) { const r = schema.safeParse(body); @@ -200,12 +206,24 @@ describe('overlay owner/hidden retirement — the D2 conversion', () => { // CONTROL: the live round-trip keys on the same row survive. expect(rehydrated.isDefault).toBe(true); expect(rehydrated.label).toBe('Edit lead'); - // …and, because this row carries content (`isDefault`), the rehydrated row - // is what the write door accepts now, so a whole-row re-save of it saves. - // The row that carries NO content is the residue pinned below. - expect(ViewMetadataSchema.safeParse(rehydrated).success).toBe(true); - // CONTROL: the stored row itself, unconverted, is what the door now refuses. + // [ADR-0159 D7] This stored row is a FORM overlay: since protocol 19 the + // write door refuses it whatever it carries (a view is a list), so a + // whole-row re-save of it is refused with the D7 prescription. The stored + // row is not rewritten by the read (constraint 1); the list-bound twin + // below is the row a re-save still saves. + expect(ViewMetadataSchema.safeParse(rehydrated).success).toBe(false); + // CONTROL: the stored row itself, unconverted, is refused too. expect(ViewMetadataSchema.safeParse(stored).success).toBe(false); + + // The list-bound twin: because this row carries content (`isDefault`), the + // rehydrated row is what the write door accepts, so a whole-row re-save of + // it saves. The row that carries NO content is the residue pinned below. + const storedList = { ...LIST_OVERLAY, label: 'All leads', isDefault: true, owner: 'usr_7', hidden: true }; + const rehydratedList = applyConversionsToStoredItem('view', storedList) as Record; + expect(rehydratedList).not.toHaveProperty('owner'); + expect(rehydratedList).not.toHaveProperty('hidden'); + expect(ViewMetadataSchema.safeParse(rehydratedList).success).toBe(true); + expect(ViewMetadataSchema.safeParse(storedList).success).toBe(false); }); it('strips a flat row that has no `viewKind` yet — the write path heals that in, then would refuse the key', () => { diff --git a/packages/spec/src/ui/view-overlay-viewkind-arm.test.ts b/packages/spec/src/ui/view-overlay-viewkind-arm.test.ts index 47c8f111b93..5ab88d992b1 100644 --- a/packages/spec/src/ui/view-overlay-viewkind-arm.test.ts +++ b/packages/spec/src/ui/view-overlay-viewkind-arm.test.ts @@ -45,6 +45,14 @@ * list overlay WITH `columns`. ⛔ Deliberately NOT pinned here as desired * behaviour: it is a named same-family residual (the PR's acceptance notes), * not a contract. + * + * ## [ADR-0159 D7] Since protocol 19: one flattened member + * + * A view holds lists only, so the flattened FORM overlay member was retired + * with the rest of the view-held forms. A `viewKind: 'form'` body is claimed + * by the list member, which refuses it with the retired value's prescription + * (it names the `form` item). The rows below that pinned the form member's + * verdicts are kept and re-measured to that answer. */ import { describe, expect, it } from 'vitest'; import { z } from 'zod'; @@ -165,21 +173,24 @@ describe('a column-less list overlay that NAMES a `type` stays refused — at `c }); }); -describe('the mirror: a `viewKind: form` body is judged by the form member', () => { - it('list `columns` on a form overlay is REFUSED under formOverlay, at `columns`, with the count prescription', () => { +describe('the mirror: a `viewKind: form` body is claimed by the list member, and refused (ADR-0159 D7)', () => { + // Before protocol 19 the form member judged these bodies; it is retired, and + // a form's body-column count is a `form` item's `columns` now. + it('list `columns` on a form-bound body is REFUSED under listOverlay, at `viewKind`, with the D7 prescription', () => { const r = refusal({ ...FORM, columns: ['name'] }); expect(r.topCodes).toEqual(['invalid_union']); - expect(r.branch).toBe('formOverlay'); + expect(r.branch).toBe('listOverlay'); expect(r.issues).toHaveLength(1); - expect(r.issues[0]).toMatchObject({ code: 'invalid_type', path: ['columns'] }); - expect(r.issues[0]!.message).toMatch(/^On a form view `columns` is the NUMBER of body columns/); - expect(r.issues[0]!.message).toContain('set `viewKind: "list"`'); + expect(r.issues[0]).toMatchObject({ path: ['viewKind'] }); + expect(r.issues[0]!.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); }); - it('…while a form body-column COUNT is still accepted (the form schema\'s own constraints, unchanged)', () => { - expect(acceptance({ ...FORM, columns: 2 }).branch).toBe('formOverlay'); - const r = refusal({ ...FORM, columns: 0 }); - expect(r.issues[0]).toMatchObject({ code: 'too_small', path: ['columns'] }); + it('…and so is a form body-column COUNT, which only a `form` item carries now', () => { + for (const columns of [2, 0]) { + const r = refusal({ ...FORM, columns }); + expect(r.branch).toBe('listOverlay'); + expect(r.issues.some((i) => i.path[0] === 'viewKind' && /removed in @objectstack\/spec 19\.0\.0/.test(i.message))).toBe(true); + } }); }); @@ -197,16 +208,12 @@ describe('W2 — a list-legal value under a key both arms declare differently is }); describe('controls — byte-identical parse output (measured on origin/main ce70876e)', () => { - it('a real form overlay', () => { - const { data, branch } = acceptance({ + it('a real form overlay — accepted until protocol 19, refused since (ADR-0159 D7)', () => { + const r = refusal({ name: 'acct.f', object: 'account', viewKind: 'form', type: 'simple', sections: [{ label: 'Main', fields: ['name'] }], }); - expect(branch).toBe('formOverlay'); - expect(JSON.stringify(data)).toBe( - // No `columns`: a section's undeclared density is the renderer's, and the parse adds no default. - '{"type":"simple","sections":[{"label":"Main","collapsible":false,"collapsed":false,"fields":["name"]}],' - + '"name":"acct.f","object":"account","viewKind":"form"}', - ); + expect(r.branch).toBe('listOverlay'); + expect(r.issues.some((i) => i.path[0] === 'viewKind' && /removed in @objectstack\/spec 19\.0\.0/.test(i.message))).toBe(true); }); it('a list overlay WITH `columns` (and no `type` — the default still lands in its own key position)', () => { @@ -221,23 +228,21 @@ describe('controls — byte-identical parse output (measured on origin/main ce70 }); describe('each member judges ONE viewKind — read off the members themselves', () => { - it('a direct parse of the form member names where a list body is judged', () => { - const r = VIEW_METADATA_MEMBERS.formOverlay.safeParse({ ...LIST, sort: [{ field: 'name', order: 'asc' }] }); - expect(r.success).toBe(false); - const issue = r.error!.issues.find((i) => i.path[0] === 'viewKind'); - expect(issue?.message).toMatch(/^This is the flattened FORM overlay member, which judges `viewKind: "form"` only\./); - expect(issue?.message).toContain('`VIEW_METADATA_MEMBERS.listOverlay`'); + it('[ADR-0159 D7] there is no form member any more; the list member is the one flattened member', () => { + expect(Object.keys(VIEW_METADATA_MEMBERS)).not.toContain('formOverlay'); + expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ ...LIST, sort: [{ field: 'name', order: 'asc' }] }).success).toBe(true); }); - it('…and the list member refuses a form body the same way', () => { + it('…and the list member refuses a form body with the retired value\'s prescription', () => { const r = VIEW_METADATA_MEMBERS.listOverlay.safeParse({ ...FORM, columns: ['name'] }); expect(r.success).toBe(false); const issue = r.error!.issues.find((i) => i.path[0] === 'viewKind'); - expect(issue?.message).toMatch(/^This is the flattened LIST overlay member, which judges `viewKind: "list"` only\./); + expect(issue?.message).toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D7\)/); + expect(issue?.message).toContain('`form` item'); }); - it('an ABSENT viewKind keeps the binding prescription, on both members', () => { - for (const member of [VIEW_METADATA_MEMBERS.listOverlay, VIEW_METADATA_MEMBERS.formOverlay]) { + it('an ABSENT viewKind keeps the binding prescription', () => { + for (const member of [VIEW_METADATA_MEMBERS.listOverlay]) { const r = member.safeParse({ object: 'crm_lead', hidden: true }); const issue = r.error!.issues.find((i) => i.path[0] === 'viewKind'); expect(issue?.message).toContain('This inline view config names no `viewKind`'); @@ -246,22 +251,20 @@ describe('each member judges ONE viewKind — read off the members themselves', }); describe('the premise: no pipe, and the served JSON Schema moves only by the contract', () => { - it('both overlay members are still plain object schemas', () => { + it('the overlay member is still a plain object schema', () => { // A pipe serves its INPUT side to `/api/v1/meta/types/view`, and for a // transform that is `{}` (the `assertViewIdentity` docblock). The input-side // refusal and the default are both CHECKS on the object instead. expect((VIEW_METADATA_MEMBERS.listOverlay as unknown as { _zod: { def: { type: string } } })._zod.def.type).toBe('object'); - expect((VIEW_METADATA_MEMBERS.formOverlay as unknown as { _zod: { def: { type: string } } })._zod.def.type).toBe('object'); }); - it.each(['input', 'output'] as const)('the %s JSON Schema: four members, one viewKind per overlay arm, list `type` default kept', (io) => { + it.each(['input', 'output'] as const)('the %s JSON Schema: three members (the form overlay retired), viewKind `list` on the overlay, list `type` default kept', (io) => { const json = z.toJSONSchema(ViewMetadataSchema, { unrepresentable: 'any', io }) as { anyOf: Array<{ properties: Record; required?: string[] }>; }; - expect(json.anyOf).toHaveLength(4); - const [, , list, form] = json.anyOf; + expect(json.anyOf).toHaveLength(3); + const [, , list] = json.anyOf; expect(list!.properties.viewKind!.enum).toEqual(['list']); - expect(form!.properties.viewKind!.enum).toEqual(['form']); expect(list!.properties.type!.default).toBe('grid'); expect(list!.required).not.toContain('columns'); expect(list!.required).toEqual(expect.arrayContaining(['object', 'viewKind'])); diff --git a/packages/spec/src/ui/view-overlay-viewkind-type.test.ts b/packages/spec/src/ui/view-overlay-viewkind-type.test.ts index 08d6107f2e8..42190d7d2e9 100644 --- a/packages/spec/src/ui/view-overlay-viewkind-type.test.ts +++ b/packages/spec/src/ui/view-overlay-viewkind-type.test.ts @@ -2,7 +2,9 @@ /** * [#19920] Each flattened overlay member's static `viewKind` is its own arm's literal: `'list'` on - * the list overlay, `'form'` on the form overlay. The list overlay's `type` and `columns` carry the + * the list overlay. [ADR-0159 D7] The form overlay was retired in protocol 19 (a view is a list), + * so the list overlay is the one flattened member, and a `viewKind: 'form'` body answers the + * retired value's prescription. The list overlay's `type` and `columns` carry the * list shape's own types, not `unknown`. And the list overlay's `type` default, which the parse * applies and the output type does not carry, is what the `ViewMetadataParsed` / * `AssembledViewArtifactParsed` TSDoc says it is. @@ -34,6 +36,7 @@ import type { z } from 'zod'; import { VIEW_METADATA_MEMBERS, ViewMetadataSchema, + diagnoseViewMetadata, type ViewMetadata, type ViewMetadataParsed, } from './view.zod'; @@ -45,23 +48,15 @@ import { type ListOverlayIn = z.input; type ListOverlayOut = z.output; -type FormOverlayIn = z.input; -type FormOverlayOut = z.output; // ── Each member's `viewKind` is its own arm's literal ──────────────────────────────────────── const listKindIn: ListOverlayIn['viewKind'] = 'list'; const listKindOut: ListOverlayOut['viewKind'] = 'list'; -const formKindIn: FormOverlayIn['viewKind'] = 'form'; -const formKindOut: FormOverlayOut['viewKind'] = 'form'; // @ts-expect-error -- the list overlay member judges `viewKind: 'list'` only. const listKindInForm: ListOverlayIn['viewKind'] = 'form'; // @ts-expect-error -- on its output too. const listKindOutForm: ListOverlayOut['viewKind'] = 'form'; -// @ts-expect-error -- the form overlay member judges `viewKind: 'form'` only. -const formKindInList: FormOverlayIn['viewKind'] = 'list'; -// @ts-expect-error -- on its output too. -const formKindOutList: FormOverlayOut['viewKind'] = 'list'; // ── The body both doors refuse no longer type-checks as any union type ─────────────────────── @@ -73,7 +68,7 @@ const parsedArtifact: AssembledViewArtifactParsed = { type: 'grid', columns: ['n const metadata: ViewMetadata = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'form' }; // @ts-expect-error -- nor a parsed one. const parsedMetadata: ViewMetadataParsed = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'form' }; -void [listKindIn, listKindOut, formKindIn, formKindOut, listKindInForm, listKindOutForm, formKindInList, formKindOutList]; +void [listKindIn, listKindOut, listKindInForm, listKindOutForm]; void [artifact, parsedArtifact, metadata, parsedMetadata]; // ── The list overlay's `type` and `columns` carry the list shape's types ───────────────────── @@ -113,11 +108,21 @@ describe('the flattened overlay members keep their own viewKind literal', () => it('the list-shaped `viewKind: "form"` body is refused by every door that judges it', () => { const body = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'form' }; expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse(body).success).toBe(false); - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse(body).success).toBe(false); expect(ViewMetadataSchema.safeParse(body).success).toBe(false); expect(AssembledViewArtifactSchema.safeParse(body).success).toBe(false); }); + it("[ADR-0159 D7] the refusal is the retired `viewKind: 'form'` prescription, naming the `form` item", () => { + const body = { type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'form' }; + expect(ViewMetadataSchema.safeParse(body).success).toBe(false); + const d = diagnoseViewMetadata(body); + expect(d.success).toBe(false); + if (d.success) return; + expect(d.branch).toBe('listOverlay'); + const messages = d.issues.map((i) => i.message).join('\n'); + expect(messages).toMatch(/`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0.*`form` item/s); + }); + it('a list overlay whose `columns` is a number is refused by every door that judges it', () => { const body = { object: 'crm_lead', viewKind: 'list', columns: 42 }; expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse(body).success).toBe(false); diff --git a/packages/spec/src/ui/view-union-branch-focus.test.ts b/packages/spec/src/ui/view-union-branch-focus.test.ts index 95373042a46..849834baf8a 100644 --- a/packages/spec/src/ui/view-union-branch-focus.test.ts +++ b/packages/spec/src/ui/view-union-branch-focus.test.ts @@ -55,6 +55,12 @@ * every misdirected body is asserted to have picked `container` under it. * Delete the `.check()` in `view.zod.ts` and the tests in §1 go red; that * assertion is what says so without needing the revert. + * + * [ADR-0159 D7] Since protocol 19 a view item is a list: the form arm, and the + * flattened form overlay, were retired. The form-item bodies below are kept; + * each is now refused at `viewKind` with the retired value's prescription, and + * that prescription is what the claimed branch surfaces in place of the + * container text — the focusing this file pins, on the major's answer. */ import { describe, expect, it } from 'vitest'; @@ -129,21 +135,24 @@ function rendered(body: unknown): string { * The general case the card asked to confirm before sizing: four unrelated * ViewItem-branch failures, each expected to name its OWN key. */ +/** [ADR-0159 D7] What a form-item body surfaces since protocol 19: the retired value's prescription. */ +const FORM_KIND_RETIRED = "`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"; + const MISDIRECTED: Array<[string, unknown, string]> = [ [ - 'the card\'s repro, on `keyField` — an unknown subkey inside a nested form-field block', + 'the card\'s repro, on `keyField` — a form item, refused since 19 at `viewKind`', formItem({ field: 'owner', keyField: { field: 'name', sort: [{ field: 'email', order: 'desc' }] } }), - 'sort', + FORM_KIND_RETIRED, ], [ - 'the retired `publicPicker` key itself — its prescription, not the container text', + 'the retired `publicPicker` key on a form item — the D7 prescription, not the container text', formItem({ field: 'owner', publicPicker: { displayFields: ['name'] } }), - 'publicPicker', + FORM_KIND_RETIRED, ], [ - 'an unknown key on the form FIELD itself', + 'an unknown key on a form item\'s FIELD — the D7 prescription, not the container text', formItem({ field: 'owner', widthh: 6 }), - 'widthh', + FORM_KIND_RETIRED, ], [ 'a typo\'d column summary inside a LIST item', @@ -181,11 +190,14 @@ describe('a ViewItem-branch failure surfaces the ViewItem branch', () => { } }); - it('the byte-identical body minus the bad subkey still saves', () => { - // The card's own control: this is what makes the rejection a diagnostic - // problem rather than an acceptance one. - const r = ViewMetadataSchema.safeParse(formItem({ field: 'owner', keyField: { field: 'name' } })); - expect(r.success, JSON.stringify((r as any).error?.issues)).toBe(true); + it('the byte-identical body minus the bad subkey is refused too since 19, with the same prescription', () => { + // The card's own control, re-measured on the major (ADR-0159 D7): a form + // item no longer saves through the view door at all. The list-item row + // above keeps the diagnostic-versus-acceptance contrast for a live arm. + const body = formItem({ field: 'owner', keyField: { field: 'name' } }); + expect(ViewMetadataSchema.safeParse(body).success).toBe(false); + expect(rendered(body)).toContain(FORM_KIND_RETIRED); + expect(rendered(body)).not.toContain(CONTAINER_MISDIRECT); }); }); @@ -221,17 +233,17 @@ describe('the container diagnostic still belongs to containers', () => { describe('the union\'s error payload is focused, never reshaped', () => { const CLAIMED = formItem({ field: 'owner', keyField: { field: 'name', sort: [] } }); - it('keeps four branches, in position — a positional consumer still finds its member', () => { + it('keeps every branch, in position — a positional consumer still finds its member (three since the form overlay was retired)', () => { const issue = ViewMetadataSchema.safeParse(CLAIMED).error!.issues[0] as unknown as { code: string; errors: unknown[][]; }; expect(issue.code).toBe('invalid_union'); - expect(issue.errors).toHaveLength(4); + expect(issue.errors).toHaveLength(3); // Branch 0 is the claimed one and keeps its own issues; the rest are muted // in place rather than filtered out (objectui#3624's canary read errors[2]). - expect(issue.errors[0]).toMatchObject([{ path: ['config', 'sections', 0, 'fields', 0] }]); - for (const index of [1, 2, 3]) { + expect(issue.errors[0]).toMatchObject([{ path: ['viewKind'], message: expect.stringContaining(FORM_KIND_RETIRED) }]); + for (const index of [1, 2]) { expect(issue.errors[index]).toHaveLength(1); expect(issue.errors[index]![0]).toMatchObject({ code: 'invalid_type', path: [] }); } @@ -248,7 +260,7 @@ describe('the union\'s error payload is focused, never reshaped', () => { errors: { code?: string }[][]; }; expect(issue.code).toBe('invalid_union'); - expect(issue.errors).toHaveLength(4); + expect(issue.errors).toHaveLength(3); expect(issue.errors.some((branch) => branch.some((i) => i.code === 'unrecognized_keys'))).toBe(true); }); @@ -276,17 +288,23 @@ describe('⛔ the branch focusing did not move the acceptance face', () => { // this list is now REFUSED (pinned below, with the MISDIRECTED case that // shows its prescription reaching the author). Its slot here is taken by the // same form item with a `keyField` block, the nested control. + // + // [ADR-0159 D7] A third deliberate move, by the major: a view holds lists + // only, so the three form-shaped ACCEPTED entries (a form item, a + // container's `formViews`, a bound form overlay) are REFUSED since protocol + // 19 and pinned at the head of REFUSED below. const ACCEPTED: unknown[] = [ - formItem({ field: 'owner', keyField: { field: 'name' } }), { name: 'crm_lead.all', object: 'crm_lead', viewKind: 'list', config: { type: 'grid', columns: ['name'] } }, { object: 'crm_lead', list: { type: 'grid', columns: ['name'] } }, - { object: 'crm_lead', formViews: { my: { type: 'simple' } } }, { type: 'grid', columns: ['name'], isDefault: true, order: 2, object: 'crm_lead', viewKind: 'list' }, - { type: 'simple', object: 'crm_lead', viewKind: 'form' }, { isPinned: true, object: 'crm_lead', viewKind: 'list' }, ]; const REFUSED: Array<[unknown, string[]]> = [ + // [ADR-0159 D7] the three form-shaped bodies ACCEPTED before protocol 19. + [formItem({ field: 'owner', keyField: { field: 'name' } }), ['invalid_union']], + [{ object: 'crm_lead', formViews: { my: { type: 'simple' } } }, ['invalid_union']], + [{ type: 'simple', object: 'crm_lead', viewKind: 'form' }, ['invalid_union']], // [#7741] the unbound originals of the last three ACCEPTED entries. [{ type: 'grid', columns: ['name'], isDefault: true, order: 2 }, ['invalid_union']], [{ type: 'simple' }, ['invalid_union']], diff --git a/packages/spec/src/ui/view-union-diagnostics.test.ts b/packages/spec/src/ui/view-union-diagnostics.test.ts index fce177b362e..01e1059d76d 100644 --- a/packages/spec/src/ui/view-union-diagnostics.test.ts +++ b/packages/spec/src/ui/view-union-diagnostics.test.ts @@ -60,12 +60,13 @@ function unionOptions(): readonly unknown[] { } describe('the union members are contractual, not positional', () => { - it('exposes exactly four branches, in the union\'s own order', () => { + // [ADR-0159 D7] Three since protocol 19: the flattened FORM overlay was + // retired with the rest of the view-held forms (a view is a list). + it('exposes exactly three branches, in the union\'s own order', () => { expect([...VIEW_METADATA_BRANCHES]).toEqual([ 'viewItem', 'container', 'listOverlay', - 'formOverlay', ]); expect(Object.keys(VIEW_METADATA_MEMBERS)).toEqual([...VIEW_METADATA_BRANCHES]); }); @@ -94,8 +95,11 @@ describe('the union members are contractual, not positional', () => { // [#7741] The overlay arms require the `object` + `viewKind` binding. expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ type: 'grid', columns: ['name'], object: 'crm_lead', viewKind: 'list' }).success).toBe(true); expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ type: 'grid', columns: ['name'] }).success).toBe(false); - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse({ type: 'wizard', object: 'crm_lead', viewKind: 'form' }).success).toBe(true); - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse({ type: 'wizard' }).success).toBe(false); + // [ADR-0159 D7] The form overlay is gone; a form-bound flat body is the + // list overlay's to refuse, with the retired value's prescription. + expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ type: 'wizard', object: 'crm_lead', viewKind: 'form' }).success).toBe(false); + expect(VIEW_METADATA_MEMBERS.listOverlay.safeParse({ object: 'crm_lead', viewKind: 'form' }).error!.issues[0]!.message) + .toMatch(/^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/); }); }); @@ -105,9 +109,12 @@ describe('selectViewMetadataBranch reads the members\' own discriminants', () => ['…even when the config is the broken part', { viewKind: 'list', config: { type: 'grid', columns: 1 } }, 'viewItem'], ['a container slot is a container', { object: 'a', list: LIST_CFG }, 'container'], ['listViews too', { object: 'a', listViews: {} }, 'container'], - ['an inherited viewKind settles a flat overlay', { viewKind: 'form', title: 'T' }, 'formOverlay'], + // [ADR-0159 D7] `viewKind: 'form'` claims the list overlay, whose parse + // names the retired value's prescription; a form-family `type` alone + // settles nothing, as an unknown type does. + ['an inherited viewKind settles a flat overlay', { viewKind: 'form', title: 'T' }, 'listOverlay'], ['so does a list-family type', { type: 'kanban' }, 'listOverlay'], - ['and a form-family type', { type: 'wizard' }, 'formOverlay'], + ['a form-family type settles nothing since 19', { type: 'wizard' }, null], ['nothing settles a bare aux PUT', { isPinned: true }, null], ['nor an unknown type', { type: 'sideways' }, null], ['non-objects claim nothing', 'nope', null], @@ -119,11 +126,11 @@ describe('selectViewMetadataBranch reads the members\' own discriminants', () => // The `type` enums are read off the member schemas, never re-listed here, so // a new view type cannot make the dispatch disagree with the members. - it('covers every declared list/form type', () => { + it('covers every declared list type; a form type claims nothing since 19', () => { const listTypes = ['grid', 'kanban', 'gallery', 'calendar', 'timeline', 'gantt', 'map', 'chart', 'tree']; const formTypes = ['simple', 'tabbed', 'wizard']; for (const type of listTypes) expect(selectViewMetadataBranch({ type })).toBe('listOverlay'); - for (const type of formTypes) expect(selectViewMetadataBranch({ type })).toBe('formOverlay'); + for (const type of formTypes) expect(selectViewMetadataBranch({ type })).toBe(null); }); // [#27155] The retired form `type` members left the enum, so on their own @@ -132,7 +139,7 @@ describe('selectViewMetadataBranch reads the members\' own discriminants', () => it('a retired form type settles nothing on its own; viewKind still does', () => { for (const type of ['split', 'drawer', 'modal']) { expect(selectViewMetadataBranch({ type })).toBe(null); - expect(selectViewMetadataBranch({ type, viewKind: 'form' })).toBe('formOverlay'); + expect(selectViewMetadataBranch({ type, viewKind: 'form' })).toBe('listOverlay'); } }); }); @@ -164,7 +171,7 @@ describe('diagnoseViewMetadata names the failing branch', () => { errors: unknown[][]; }; expect(root.code).toBe('invalid_union'); - expect(root.errors).toHaveLength(4); + expect(root.errors).toHaveLength(3); expect(root.errors[2]).toMatchObject([{ path: ['columns'] }]); }); @@ -254,9 +261,6 @@ describe('diagnoseViewMetadata names the failing branch', () => { // parse output re-measured, and the unbound original moves to REFUSED so the // flip itself is pinned rather than silently absorbed. describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostics work; every move since is deliberate and pinned', () => { - // A section's `columns` has no default: an undeclared density is the renderer's, - // so the parse adds no `columns` key (it added `columns: 1` before the default was dropped). - const SECTION = { label: 'Main', collapsible: false, collapsed: false, fields: ['name'] }; /** [#7741] The binding pair the write path inherits onto a shadowing overlay. */ const BOUND_LIST = { object: 'crm_lead', viewKind: 'list' } as const; const BOUND_FORM = { object: 'crm_lead', viewKind: 'form' } as const; @@ -282,15 +286,10 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic const ACCEPTED: Array<[string, unknown, unknown]> = [ ['viewItem.list', { name: 'crm_lead.all', object: 'crm_lead', viewKind: 'list', config: LIST_CFG }, { viewKind: 'list', config: LIST_CFG, name: 'crm_lead.all', object: 'crm_lead' }], - ['viewItem.form', { name: 'crm_lead.edit', object: 'crm_lead', viewKind: 'form', config: FORM_CFG }, - { viewKind: 'form', config: { type: 'simple', sections: [SECTION] }, name: 'crm_lead.edit', object: 'crm_lead' }], ['viewItem.wire.aux', { name: 'a.b', object: 'a', viewKind: 'list', config: LIST_CFG, isPinned: true, sortOrder: 3 }, { viewKind: 'list', config: LIST_CFG, name: 'a.b', object: 'a', isPinned: true, sortOrder: 3 }], ['container.list', { object: 'crm_lead', list: LIST_CFG }, { object: 'crm_lead', list: LIST_CFG }], - ['container.form', { object: 'crm_lead', form: FORM_CFG }, { object: 'crm_lead', form: { type: 'simple', sections: [SECTION] } }], ['container.listViews', { object: 'crm_lead', listViews: { my: LIST_CFG } }, { object: 'crm_lead', listViews: { my: LIST_CFG } }], - ['container.formViews', { object: 'crm_lead', formViews: { my: FORM_CFG } }, - { object: 'crm_lead', formViews: { my: { type: 'simple', sections: [SECTION] } } }], ['overlay.list.columns', { columns: ['name', 'stage'], ...BOUND_LIST }, { type: 'grid', columns: ['name', 'stage'], ...BOUND_LIST }], // [#20230] `hidden` left this row: the overlay's `owner` / `hidden` are @@ -298,11 +297,6 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic // same row WITH `hidden` is now in REFUSED as `overlay.list.aux.retiredHidden`. ['overlay.list.aux', { type: 'grid', columns: ['name'], isDefault: true, order: 2, ...BOUND_LIST }, { type: 'grid', columns: ['name'], isDefault: true, order: 2, ...BOUND_LIST }], - ['overlay.form.min', { type: 'simple', ...BOUND_FORM }, { type: 'simple', ...BOUND_FORM }], - ['overlay.form.sections', { sections: [{ label: 'Main', fields: ['name'] }], ...BOUND_FORM }, - { type: 'simple', sections: [SECTION], ...BOUND_FORM }], - ['overlay.form.identity', { name: 'x', object: 'crm_lead', viewKind: 'form', type: 'wizard' }, - { type: 'wizard', name: 'x', object: 'crm_lead', viewKind: 'form' }], ['overlay.list.consoleSortId', { sort: [{ id: 'row-1', field: 'name', order: 'asc' }], ...BOUND_LIST }, { type: 'grid', sort: [{ field: 'name', order: 'asc' }], ...BOUND_LIST }], ['overlay.list.consoleFilterId', { filter: [{ id: 'row-1', field: 'name', operator: 'equals', value: 'x' }], ...BOUND_LIST }, @@ -320,6 +314,18 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic ]; const REFUSED: Array<[string, unknown, string[]]> = [ + // [ADR-0159 D7] Formerly ACCEPTED: a view holds lists only since protocol + // 19. Each form shape is refused, and the claimed member's message is the + // retired key's (or value's) prescription naming the `form` item — pinned + // below. `overlay.form.sections` names no view key the identity check + // knows any more (`sections` was the form overlay's), so it is refused + // before the union runs, as any non-view body is. + ['viewItem.form', { name: 'crm_lead.edit', object: 'crm_lead', viewKind: 'form', config: FORM_CFG }, ['invalid_union']], + ['container.form', { object: 'crm_lead', form: FORM_CFG }, ['invalid_union']], + ['container.formViews', { object: 'crm_lead', formViews: { my: FORM_CFG } }, ['invalid_union']], + ['overlay.form.min', { type: 'simple', ...BOUND_FORM }, ['invalid_union']], + ['overlay.form.sections', { sections: [{ label: 'Main', fields: ['name'] }], ...BOUND_FORM }, ['custom']], + ['overlay.form.identity', { name: 'x', object: 'crm_lead', viewKind: 'form', type: 'wizard' }, ['invalid_union']], ['viewItem.badKind', { name: 'a.b', object: 'a', viewKind: 'chart', config: LIST_CFG }, ['invalid_union']], ['viewItem.badConfig', { name: 'a.b', object: 'a', viewKind: 'list', config: { type: 'grid', columns: 'nope' } }, ['invalid_union']], ['viewItem.typoConfg', { name: 'a.b', object: 'a', viewKind: 'list', confg: LIST_CFG }, ['custom']], @@ -336,7 +342,10 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic // `put.hidden`): the overlay's `hidden` / `owner` are retired, and a bound // overlay carrying either is refused at the key with the prescription. ['overlay.list.aux.retiredHidden', { type: 'grid', columns: ['name'], isDefault: true, order: 2, hidden: false, ...BOUND_LIST }, ['invalid_union']], - ['put.hidden', { hidden: true, ...BOUND_FORM }, ['invalid_union']], + // [ADR-0159 D7] Bound as a list now: a form binding is itself retired, and + // its prescription would come first (`put.hidden.formBound` keeps that row). + ['put.hidden', { hidden: true, ...BOUND_LIST }, ['invalid_union']], + ['put.hidden.formBound', { hidden: true, ...BOUND_FORM }, ['invalid_union']], ['put.owner', { owner: 'usr_7', ...BOUND_LIST }, ['invalid_union']], // [#26711] Formerly ACCEPTED with `filter` / `sort` stripped by the form // overlay, which declares neither: the save stored a bare form overlay. @@ -351,7 +360,9 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic ['unbound.overlay.list.columns', { columns: ['name', 'stage'] }, ['invalid_union']], ['unbound.overlay.list.aux', { type: 'grid', columns: ['name'], isDefault: true, order: 2, hidden: false }, ['invalid_union']], ['unbound.overlay.form.min', { type: 'simple' }, ['invalid_union']], - ['unbound.overlay.form.sections', { sections: [{ label: 'Main', fields: ['name'] }] }, ['invalid_union']], + // [ADR-0159 D7] `sections` is no view key the identity check knows since + // the form overlay was retired, so the body is refused before the union. + ['unbound.overlay.form.sections', { sections: [{ label: 'Main', fields: ['name'] }] }, ['custom']], ['unbound.overlay.badOperator', { filter: [{ field: 'name', operator: 'sorta_equals', value: 'x' }] }, ['invalid_union']], ['unbound.overlay.consoleSortId', { sort: [{ id: 'row-1', field: 'name', order: 'asc' }] }, ['invalid_union']], ['unbound.overlay.consoleFilterId', { filter: [{ id: 'row-1', field: 'name', operator: '=', value: 'x' }] }, ['invalid_union']], @@ -414,13 +425,33 @@ describe('the acceptance face of ViewMetadataSchema — frozen by the diagnostic } }); + // [ADR-0159 D7] The form rows are refused BY the retirement: the claimed + // member's first message is the prescription that names the `form` item. + it('the view-held form rows are refused by the D7 tombstones, with their prescription', () => { + const expected: Record = { + 'viewItem.form': /^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/, + 'container.form': /^`view\.form` was removed in @objectstack\/spec 19\.0\.0/, + 'container.formViews': /^`view\.formViews` was removed in @objectstack\/spec 19\.0\.0/, + 'put.hidden.formBound': /^`view\.viewKind: 'form'` was removed in @objectstack\/spec 19\.0\.0/, + }; + for (const [label, pattern] of Object.entries(expected)) { + const row = REFUSED.find(([l]) => l === label); + expect(row, label).toBeDefined(); + const d = diagnoseViewMetadata(row![1]); + expect(d.success, label).toBe(false); + if (d.success) continue; + expect(d.issues[0]!.message, label).toMatch(pattern); + expect(d.issues[0]!.message, label).toMatch(/`form` item/); + } + }); + // The JSON-Schema face the `/api/v1/meta/types/view` endpoint serves is // pinned in `view-metadata-schema.test.ts`; re-asserted here in the one // dimension this change could have moved — the member COUNT. - it('still emits an anyOf of exactly four members', () => { + it('still emits an anyOf of exactly three members (four before the form overlay was retired)', () => { const json = z.toJSONSchema(ViewMetadataSchema, { unrepresentable: 'any', io: 'input' }) as { anyOf?: unknown[]; }; - expect(json.anyOf).toHaveLength(4); + expect(json.anyOf).toHaveLength(3); }); }); diff --git a/packages/spec/src/ui/view-union-retirement-prescription.test.ts b/packages/spec/src/ui/view-union-retirement-prescription.test.ts index f117e15982c..47f50be0d9e 100644 --- a/packages/spec/src/ui/view-union-retirement-prescription.test.ts +++ b/packages/spec/src/ui/view-union-retirement-prescription.test.ts @@ -126,15 +126,18 @@ const BRANCH_PINS: ReadonlyArray> = { - // The ViewItem record's top-level `options` bag, on both arms: the record's - // per-kind blocks live under `config` (stage (iv) of #20051, Q3). + // The ViewItem record's top-level `options` bag: the record's per-kind + // blocks live under `config` (stage (iv) of #20051, Q3). [ADR-0159 D7] One + // arm since protocol 19 (the form arm, `|1`, was retired). 'viewItem.|0.options': /^A view item record carries no top-level `options` bag: .*Move each `options\.KIND` block to `config\.KIND`/, - 'viewItem.|1.options': /^A view item record carries no top-level `options` bag: .*Move each `options\.KIND` block to `config\.KIND`/, }; describe('§2 population — every non-catchall `never` leaf on this surface is a prescription', () => { diff --git a/packages/spec/src/ui/view-wire-unknown-key-refusal.test.ts b/packages/spec/src/ui/view-wire-unknown-key-refusal.test.ts index 23db5247e77..54aade174a3 100644 --- a/packages/spec/src/ui/view-wire-unknown-key-refusal.test.ts +++ b/packages/spec/src/ui/view-wire-unknown-key-refusal.test.ts @@ -13,6 +13,10 @@ * key, the member named), a retired key's prescription in both channels the * protocol has for it, the alias spellings the #20456 census found, and a * clean body of each shape still saving with what the console writes. + * + * [ADR-0159 D7] Since protocol 19 the flattened form overlay member is + * retired (a view is a list). Its clean body is kept, and pinned refused with + * the D7 prescription whatever else it carries. */ import { describe, expect, it } from 'vitest'; import { z } from 'zod'; @@ -23,7 +27,7 @@ import { ViewMetadataSchema, diagnoseViewMetadata, type ViewMetadataBranch } fro const DATA = { provider: 'object', object: 'crm_lead' } as const; /** One clean body per member the change closed, as the write path delivers it. */ -const CLEAN: Record<'viewItem' | 'listOverlay' | 'formOverlay', { body: Record; surface: string }> = { +const CLEAN: Record<'viewItem' | 'listOverlay', { body: Record; surface: string }> = { viewItem: { body: { name: 'crm_lead.mine', @@ -39,12 +43,12 @@ const CLEAN: Record<'viewItem' | 'listOverlay' | 'formOverlay', { body: Record; /** The claimed member's issues, read the way Studio and an MCP author get them. */ @@ -132,3 +136,16 @@ describe('the alias spellings the census found point at the declared key', () => expect(issues[0]!.message).toContain('Did you mean `id` → `name`?'); }); }); + +describe('[ADR-0159 D7] the retired form overlay body is refused, whatever it carries', () => { + it.each([ + ['clean', {}], + ['an unknown key', { zzz_junk_key: true }], + ['`objectName`', { objectName: 'crm_lead' }], + ['a top-level `id`', { id: 'crm_lead.mine' }], + ])('%s', (_label, extra) => { + const { branch, issues } = refusal({ ...FORM_OVERLAY_BODY, ...extra }); + expect(branch).toBe('listOverlay'); + expect(issues.some((i) => i.path[0] === 'viewKind' && FORM_KIND_RETIRED.test(i.message))).toBe(true); + }); +}); diff --git a/packages/spec/src/ui/view.test.ts b/packages/spec/src/ui/view.test.ts index 035299981a6..f3f6ae8c51e 100644 --- a/packages/spec/src/ui/view.test.ts +++ b/packages/spec/src/ui/view.test.ts @@ -42,11 +42,12 @@ import { type HttpRequest, defineView, defineMetadataForm, - ViewItemSchema, ViewMetadataSchema, VIEW_METADATA_MEMBERS, TreeConfigSchema, + FormSchema, } from './view.zod'; +import { RETIRED_VIEW_FORM_DOORS, expectRetiredViewFormDoorRefuses } from './retired-view-form-doors.testkit'; import { exportNamesOf, @@ -952,11 +953,14 @@ describe('FormViewSchema', () => { expect(issueAt(r, 'groups.0.visibleWhen')?.message).toMatch(/no predicate slot/); }); - it('covers the runtime-overlay door for step KEYS (the pane precedent\'s reach)', () => { - const r = VIEW_METADATA_MEMBERS.formOverlay.safeParse({ - type: 'wizard', + // [ADR-0159 D7] This case read the flattened form overlay member until + // protocol 19. That member left with the form arm; the door a form body is + // judged through now is the `form` item, and the step-key refusal reaches it. + it('covers the `form` item door for step KEYS (the pane precedent\'s reach)', () => { + const r = FormSchema.safeParse({ + name: 'crm_lead.wiz', object: 'crm_lead', - viewKind: 'form', + type: 'wizard', sections: [{ label: 'Step', collapsible: true, fields: ['name'] }], }); expect(r.success).toBe(false); @@ -1006,16 +1010,15 @@ describe('FormViewSchema', () => { expect(issueAt(r, 'sections')?.message).toMatch(/empty/); }); - it('the flattened runtime overlay stays EXEMPT — a partial patch is its contract, and the union corpus pins it accepted', () => { - // `{ type: 'wizard' }` beside the required binding, `sections` supplied - // by the shadowed base view — the `overlay.form.identity` shape the - // #7025 corpus pins as ACCEPTED. Moving that membership needs its own - // ruling (#7741's precedent); this pin keeps the D7 refusal off it. - expect(VIEW_METADATA_MEMBERS.formOverlay.safeParse({ - type: 'wizard', - object: 'crm_lead', - viewKind: 'form', - }).success).toBe(true); + // [ADR-0159 D7] Until protocol 19 the flattened form overlay was EXEMPT + // here: a partial patch was its contract. The overlay is refused whole + // since protocol 19, at `viewKind`, with the retirement prescription, + // never with the wizard's step refusal. + it('the flattened runtime overlay is refused whole at `viewKind`, never with the step refusal', () => { + const door = RETIRED_VIEW_FORM_DOORS.find((d) => d.name === 'flattened form overlay')!; + expectRetiredViewFormDoorRefuses(door, { type: 'wizard' }); + const r = door.parse({ type: 'wizard' }); + expect(JSON.stringify(r.error?.issues)).not.toMatch(/must declare its steps/); }); it('…but the ViewItem record door carries a COMPLETE view, so D7 fires there', () => { @@ -1101,22 +1104,27 @@ describe('FormViewSchema — the `groups` legacy alias folds onto `sections`', ( }); describe('every parse door inherits the fold (one declaration, not per-door)', () => { - it('ViewSchema.form', () => { - const parsed = ViewSchema.parse({ form: { type: 'simple', groups: [S('Account')] } }); - expect(has(parsed.form, 'groups')).toBe(false); - expect(parsed.form?.sections?.map((s) => s.label)).toEqual(['Account']); - }); + // [ADR-0159 D7] Until protocol 19 the fold was pinned at four view-held + // doors (`ViewSchema.form`, `.formViews.*`, the `form` record arm and the + // flattened form overlay) and at `defineView` and the container member. + // A view holds lists only since protocol 19: each of those doors refuses + // the WHOLE form at its own key, and the fold is pinned where a form body + // is judged now, the `form` item. + for (const door of RETIRED_VIEW_FORM_DOORS) { + it(`${door.name} refuses the form whole (protocol 19)`, () => { + expectRetiredViewFormDoorRefuses(door, { type: 'simple', groups: [S('Account')] }); + }); + } - it('ViewSchema.formViews.*', () => { - const parsed = ViewSchema.parse({ formViews: { edit: { type: 'simple', groups: [S('Account')] } } }); - expect(has(parsed.formViews?.edit, 'groups')).toBe(false); - expect(parsed.formViews?.edit?.sections?.map((s) => s.label)).toEqual(['Account']); + it('defineView (the authored container door) refuses `form` (protocol 19)', () => { + expect(() => defineView({ form: { type: 'simple', groups: [S('Account')] } } as never)) + .toThrow(/`view\.form` was removed in @objectstack\/spec 19\.0\.0/); }); - it('defineView (the authored container door)', () => { - const view = defineView({ form: { type: 'simple', groups: [S('Account')] } }); - expect(has(view.form, 'groups')).toBe(false); - expect(view.form?.sections?.map((s) => s.label)).toEqual(['Account']); + it('ViewMetadataSchema — the container member refuses `form` (protocol 19)', () => { + const r = ViewMetadataSchema.safeParse({ form: { type: 'simple', groups: [S('Account')] } }); + expect(r.success).toBe(false); + expect(JSON.stringify(r.error?.issues)).toContain('`view.form` was removed in @objectstack/spec 19.0.0'); }); it('defineMetadataForm (the metadata-admin form door)', () => { @@ -1125,30 +1133,9 @@ describe('FormViewSchema — the `groups` legacy alias folds onto `sections`', ( expect(form.sections?.map((s) => s.label)).toEqual(['Account']); }); - it('ViewItemSchema — the standalone `form` record arm', () => { - const parsed = ViewItemSchema.parse({ - name: 'crm_account.edit', - object: 'account', - viewKind: 'form', - config: { type: 'simple', groups: [S('Account')] }, - }); - const config = (parsed as { config: Record }).config; - expect(has(config, 'groups')).toBe(false); - expect((config.sections as Array<{ label?: string }>).map((s) => s.label)).toEqual(['Account']); - }); - - it('ViewMetadataSchema — the container member', () => { - const parsed = ViewMetadataSchema.parse({ form: { type: 'simple', groups: [S('Account')] } }) as { - form?: Record; - }; - expect(has(parsed.form, 'groups')).toBe(false); - expect((parsed.form?.sections as Array<{ label?: string }>).map((s) => s.label)).toEqual(['Account']); - }); - - it('ViewMetadataSchema — the FLATTENED form-overlay member (`.extend()` inherits the fold)', () => { - // [#7741] the overlay arm requires the `object` + `viewKind` binding. - const parsed = ViewMetadataSchema.parse({ - viewKind: 'form', + it('FormSchema — the `form` item, where a form body is judged since protocol 19', () => { + const parsed = FormSchema.parse({ + name: 'account.edit', object: 'account', type: 'simple', groups: [S('Account')], @@ -1159,6 +1146,31 @@ describe('FormViewSchema — the `groups` legacy alias folds onto `sections`', ( }); }); +/** + * [ADR-0159 D7] A container that still carries a view-held form, typed as the + * pre-19 container was, so the rewritten cases keep their authored fixtures. + */ +type OldShapeView = Omit & { form?: FormView; formViews?: Record }; + +/** + * [ADR-0159 D7] The major's answer to a pre-19 container: its lists parse on + * their own, and the whole container is refused at each view-held form key, + * with that key's D7 prescription. + */ +function expectListsParseAndFormsRefused(view: OldShapeView): void { + const { form, formViews, ...lists } = view; + expect(() => ViewSchema.parse(lists)).not.toThrow(); + const r = ViewSchema.safeParse(view); + expect(r.success).toBe(false); + for (const [key, present] of [['form', form], ['formViews', formViews]] as const) { + if (present === undefined) continue; + const issue = r.error?.issues.find((i) => i.path.length === 1 && i.path[0] === key); + expect(issue?.message, JSON.stringify(r.error?.issues)).toMatch( + new RegExp(`^\`view\\.${key}\` was removed in @objectstack/spec 19\\.0\\.0 \\(ADR-0159 D7\\)`), + ); + } +} + describe('ViewSchema', () => { it('should accept minimal view schema', () => { const view: View = {}; @@ -1166,8 +1178,9 @@ describe('ViewSchema', () => { expect(() => ViewSchema.parse(view)).not.toThrow(); }); - it('should accept view with default list and form', () => { - const view: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of view with default list and form and refuses its view-held form (protocol 19)', () => { + const view: OldShapeView = { list: { columns: ['name', 'status'], }, @@ -1178,7 +1191,7 @@ describe('ViewSchema', () => { }, }; - expect(() => ViewSchema.parse(view)).not.toThrow(); + expectListsParseAndFormsRefused(view); }); it('should accept view with named list views', () => { @@ -1207,8 +1220,9 @@ describe('ViewSchema', () => { expect(() => ViewSchema.parse(view)).not.toThrow(); }); - it('should accept view with named form views', () => { - const view: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of view with named form views and refuses its view-held form (protocol 19)', () => { + const view: OldShapeView = { form: { type: 'simple', sections: [{ fields: ['name'] }], @@ -1228,12 +1242,13 @@ describe('ViewSchema', () => { }, }; - expect(() => ViewSchema.parse(view)).not.toThrow(); + expectListsParseAndFormsRefused(view); }); describe('Real-World View Examples', () => { - it('should accept CRM opportunity views', () => { - const opportunityViews: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of CRM opportunity views and refuses its view-held form (protocol 19)', () => { + const opportunityViews: OldShapeView = { list: { type: 'grid', columns: ['name', 'account_name', 'amount', 'stage', 'close_date'], @@ -1288,11 +1303,12 @@ describe('ViewSchema', () => { }, }; - expect(() => ViewSchema.parse(opportunityViews)).not.toThrow(); + expectListsParseAndFormsRefused(opportunityViews); }); - it('should accept project task views with calendar and gantt', () => { - const taskViews: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of project task views with calendar and gantt and refuses its view-held form (protocol 19)', () => { + const taskViews: OldShapeView = { list: { columns: ['subject', 'status', 'priority', 'assigned_to', 'due_date'], }, @@ -1338,7 +1354,7 @@ describe('ViewSchema', () => { }, }; - expect(() => ViewSchema.parse(taskViews)).not.toThrow(); + expectListsParseAndFormsRefused(taskViews); }); }); }); @@ -2042,8 +2058,9 @@ describe('Enhanced FormViewSchema with Complex Fields', () => { }); describe('Real-World Enhanced View Examples', () => { - it('should accept CRM account view with enhanced columns', () => { - const accountViews: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of CRM account view with enhanced columns and refuses its view-held form (protocol 19)', () => { + const accountViews: OldShapeView = { list: { type: 'grid', columns: [ @@ -2094,11 +2111,12 @@ describe('Real-World Enhanced View Examples', () => { }, }; - expect(() => ViewSchema.parse(accountViews)).not.toThrow(); + expectListsParseAndFormsRefused(accountViews); }); - it('should accept project management view with all enhancements', () => { - const projectViews: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of project management view with all enhancements and refuses its view-held form (protocol 19)', () => { + const projectViews: OldShapeView = { list: { type: 'grid', columns: [ @@ -2157,7 +2175,7 @@ describe('Real-World Enhanced View Examples', () => { }, }; - expect(() => ViewSchema.parse(projectViews)).not.toThrow(); + expectListsParseAndFormsRefused(projectViews); }); }); @@ -3107,8 +3125,9 @@ describe('Airtable-style ListView enhancements', () => { expect(() => ListViewSchema.parse(airtableView)).not.toThrow(); }); - it('should accept complete Airtable-style View container with multiple view types', () => { - const views: View = { + // [ADR-0159 D7] Accepted whole until protocol 19; a view holds lists only now. + it('accepts the lists of complete Airtable-style View container with multiple view types and refuses its view-held form (protocol 19)', () => { + const views: OldShapeView = { list: { type: 'grid', columns: [ @@ -3168,7 +3187,7 @@ describe('Airtable-style ListView enhancements', () => { }, }; - expect(() => ViewSchema.parse(views)).not.toThrow(); + expectListsParseAndFormsRefused(views); }); }); @@ -3282,24 +3301,24 @@ describe('defineView', () => { expect(result.list?.columns).toEqual(['name', 'status']); }); - it('should return a parsed view with form config', () => { - const result = defineView({ + // [ADR-0159 D7] defineView returned a parsed `form` until protocol 19; it + // refuses the key now, with the D7 prescription naming `forms:`. + it('refuses a view with form config (protocol 19)', () => { + expect(() => defineView({ form: { type: 'simple', sections: [{ fields: ['name', 'email'] }], }, - }); - expect(result.form).toBeDefined(); - expect(result.form?.type).toBe('simple'); + } as never)).toThrow(/`view\.form` was removed in @objectstack\/spec 19\.0\.0 \(ADR-0159 D7\)/); }); - it('should return a parsed view with list and form', () => { - const result = defineView({ + it('refuses a view with list and form, and returns the list alone (protocol 19)', () => { + expect(() => defineView({ list: { type: 'kanban', columns: ['name'] }, form: { type: 'tabbed', sections: [{ fields: ['name'] }] }, - }); + } as never)).toThrow(/`view\.form` was removed/); + const result = defineView({ list: { type: 'kanban', columns: ['name'] } }); expect(result.list?.type).toBe('kanban'); - expect(result.form?.type).toBe('tabbed'); }); it('should accept named list views', () => { @@ -4583,7 +4602,11 @@ describe("ListViewSchema — the RETIRED `page` view type", () => { // match the list arm and have its `sections` stripped. The page mount was the // one view type that made `columns: []` look like a wart worth relaxing; it // is gone, and the property it would have broken is pinned here regardless. - it('still tells a flattened FORM overlay apart from a list overlay', () => { + // + // [ADR-0159 D7] Since protocol 19 the form overlay member is gone, so the + // property is: a flattened FORM body never matches the list arm with its + // `sections` stripped. It is refused whole, at `viewKind`. + it('still never lets a flattened FORM overlay pass as a list overlay', () => { const form = ViewMetadataSchema.safeParse({ name: 'crm_lead.edit', object: 'crm_lead', @@ -4591,8 +4614,8 @@ describe("ListViewSchema — the RETIRED `page` view type", () => { type: 'simple', sections: [{ label: 'Basics', fields: [{ field: 'name' }] }], }); - expect(form.success).toBe(true); - expect((form as { data: { sections?: unknown[] } }).data.sections).toHaveLength(1); + expect(form.success).toBe(false); + expect(JSON.stringify(form.error?.issues)).toContain("`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7)"); }); // `page` was never a visualization users could switch to, and it must not diff --git a/packages/spec/src/ui/view.zod.ts b/packages/spec/src/ui/view.zod.ts index 35866620614..c2e59e72c3b 100644 --- a/packages/spec/src/ui/view.zod.ts +++ b/packages/spec/src/ui/view.zod.ts @@ -19,7 +19,7 @@ * |:---|:---|:---|:---| * | standalone **ViewItem record** | a nested `config` | {@link ViewItemNameSchema} — `QUALIFIED_ITEM_NAME_PATTERN`, dot REQUIRED | **rejected**, located at `["name"]` | * | flattened runtime **overlay** | an inline view config; no `config`, no container slot | `z.string().optional()` — no grammar at all | accepted | - * | `defineView` **container** | a container slot (`list` / `form` / `listViews` / `formViews`) | `z.string().optional()` on {@link ViewSchema} — no grammar at all | accepted, and normally IS flat | + * | `defineView` **container** | a container slot (`list` / `listViews`; a body that names the retired `form` / `formViews` is read as a container too, and refused with their prescription) | `z.string().optional()` on {@link ViewSchema} — no grammar at all | accepted, and normally IS flat | * * The two permissive rows are deliberate, not gaps left to tighten later: * @@ -4927,21 +4927,19 @@ type WithFormSectionAlias = { sections?: unknown; groups?: unknown }; * ## Why `.overwrite()` and not `.transform()` (measured, #6926) * * Both fold identically at parse. `.transform()` returns a `ZodPipe`, and this - * schema is consumed as an OBJECT in two places in this file that a pipe breaks: - * {@link FormViewOverlayWireSchema} builds the flattened form-overlay union - * member with `FormViewSchema.extend(...)` (a pipe has no `.extend`), and - * {@link selectViewMetadataBranch} reads `._zod.def.shape.type` through - * `overlayTypeValues` — which a pipe answers with an EMPTY set, i.e. a silent - * mis-dispatch rather than an error. Splitting into an object schema plus a + * schema is consumed as an OBJECT in this file in ways a pipe breaks: the + * `form` item ({@link FormSchema}) is built from its shape, and the flattened + * form-overlay member (retired in protocol 19, ADR-0159 D7) was built with + * `FormViewSchema.extend(...)` (a pipe has no `.extend`). Splitting into an object schema plus a * piped export would require re-applying the fold on the overlay branch by * hand, which is the re-transcription that lets two doors disagree. * * `.overwrite()` is zod 4's "transform that does not change the type", which is * precisely what a `FormSectionSchema[]` → `FormSectionSchema[]` alias fold is. * It keeps the schema a `ZodObject`, and `.extend()` INHERITS the check, so the - * fold reaches every parse door with one declaration: `FormViewSchema` itself, - * `ViewSchema.form` / `.formViews.*`, both `ViewItemSchema` form arms, and the - * flattened `formOverlay` member of `ViewMetadataSchema`. The cost is that the + * fold reaches every parse door with one declaration: `FormViewSchema` itself + * and the `form` item built from it (the `view` doors that held a form body + * were retired in protocol 19, ADR-0159 D7). The cost is that the * INFERRED output type still declares `groups?` even though a parsed form never * carries it; the runtime contract is the enforced one. (Narrowing the exported * `FormViewParsed` by hand is not the fix — ADR-0122's gate requires it to read @@ -5583,9 +5581,11 @@ function checkFormViewBody(view: any, ctx: z.RefinementCtx): void { // accepted-but-ignored shape. ⛔ No "at least 2 steps" floor: a one-step // wizard is legal and renders. // - // Scoped to the doors where the body claims to be a COMPLETE authored form - // view (`ViewSchema.form` / `formViews`, the ViewItem config arms). The - // flattened runtime-overlay member (`FormViewOverlayWireSchema` = + // Scoped to the doors where the body claims to be a COMPLETE authored form: + // `FormViewSchema` itself and the `form` item built from its shape (until + // protocol 19 also `ViewSchema.form` / `formViews` and the ViewItem config + // arm, which now refuse a form whole, ADR-0159 D7). The + // flattened runtime-overlay member (the retired form overlay, built as // `.extend(flattenedViewOverlayFields()).strip()`) is exempt: an overlay is // a partial patch over a shadowed registry entry — `{ type: 'wizard' }` // beside the required `object`+`viewKind` binding, with `sections` supplied @@ -6047,6 +6047,67 @@ const VIEW_WRAP_REMEDY = 'Wrap it: `defineView({ list: { type, data, columns, … } })`, or name it — ' + '`defineView({ listViews: { my_view: { … } } })`.'; +/** + * [ADR-0159 D7, #37112] The three old form shapes, RETIRED in protocol 19: a + * form is a `form` item (`forms:`), never a member of a `view`. Each shape + * answers with its prescription: the container's `form` and `formViews` + * ({@link ViewSchema}, `retiredKey`) and the `form` member of + * {@link ViewKindSchema} (a `viewKind: 'form'` item or flattened body). + * + * The source conversion `view-forms-to-form-items` moves each form a source + * authors in `views[]` to `forms[]`; stored rows move only through the + * deployment's switch (`os migrate protocol --to 19 --apply`). A stored row the + * switch did not move is still read, never refused at the read: the kept + * withdrawal reader and rule 11's replacement check read its raw body + * (`projectViewForms`, ADR-0159 D6 rules 10 and 11). No `form` read serves its + * form content, and no `view` read serves a form item: a stored `viewKind: + * 'form'` row answers no item. A stored old-shape container is served by name + * as stored, its retired members included, and saving that body back through + * the `view` door is refused (`422 INVALID_METADATA`, located at the retired + * member): nothing stored changes, so the read-modify-write of a console that + * fetched it loses no stored state. Pinned in `@objectstack/rest`'s + * `stored-forms-major19-kept-reader.test.ts` ("a save-back of an old-shape + * container is refused, so no stored state is lost"). + * + * Declared ABOVE {@link ViewSchema} on purpose: under `OS_EAGER_SCHEMAS=1` + * every `lazySchema` factory runs at module init in file order, and a `const` + * below its first eager reader is a TDZ error. + */ +const VIEW_FORM_RETIRED = + '`view.form` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, and ' + + 'a `view` holds lists only. Move the form to the stack\'s `forms:` as a `form` item named `OBJECT.form` ' + + '(`defineForm({ name, object, sections, … })`, the body at the top level and bound with `object`); a ' + + 'record\'s New and Edit dialogs lay out by the object\'s `fieldGroups` and read no form, so a create or ' + + 'edit form that nothing else opens is deleted, not moved. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +const VIEW_FORM_VIEWS_RETIRED = + '`view.formViews` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata type, ' + + 'and a `view` holds lists only. Move each entry to the stack\'s `forms:` as a `form` item named ' + + '`OBJECT.KEY` (`defineForm({ name, object, sections, … })`, the body at the top level and bound with ' + + '`object`); the name stays the one it is served under, so a `type: \'form\'` action and a public link keep ' + + 'reaching it. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +const VIEW_KIND_FORM_RETIRED = + "`view.viewKind: 'form'` was removed in @objectstack/spec 19.0.0 (ADR-0159 D7) — a form is its own metadata " + + 'type, and a view item is a list. Save the form as a `form` item (`forms:`, or `PUT /api/v1/meta/form/NAME`) ' + + 'with its `config` body at the top level and `object` naming the object it submits into; the name stays ' + + '`OBJECT.KEY`. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +/** + * The error a view item's discriminated union answers when no arm matches its + * `viewKind`: the retired `form` value gets its prescription + * ({@link VIEW_KIND_FORM_RETIRED}); any other value keeps zod's own message. + */ +function retiredFormViewKindError(issue: { input?: unknown }): string | undefined { + const input = issue.input; + return input !== null && typeof input === 'object' && (input as { viewKind?: unknown }).viewKind === 'form' + ? VIEW_KIND_FORM_RETIRED + : undefined; +} + /** * Master View Schema * Can define multiple named views. @@ -6058,7 +6119,6 @@ const VIEW_WRAP_REMEDY = * @example * { * list: { type: "grid", columns: ["name"] }, - * form: { type: "simple", fields: ["name"] }, * listViews: { * "all": { label: "All", filter: [] }, * "my": { label: "Mine", filter: [["owner", "=", "{current_user_id}"]] } @@ -6103,7 +6163,7 @@ export const ViewSchema = lazySchema(() => strictObject({ // entry is a claim about the schema, and claims need verifying like code. guidance: Object.fromEntries( ['type', 'columns', 'data', 'viewKind', 'filters', 'sort'] - .map((k) => [k, `\`${k}\` belongs to a single VIEW, not to the container. ${VIEW_WRAP_REMEDY} The container's own keys are \`list\`, \`form\`, \`listViews\`, \`formViews\`.`]), + .map((k) => [k, `\`${k}\` belongs to a single VIEW, not to the container. ${VIEW_WRAP_REMEDY} The container's own keys are \`list\` and \`listViews\`.`]), ), }, { // Item identity. The container is a registered metadata item, so the door @@ -6118,9 +6178,11 @@ export const ViewSchema = lazySchema(() => strictObject({ label: I18nLabelSchema.optional().describe('Human-readable label shown in metadata lists.'), object: z.string().optional().describe('Object this container binds to — how a stack-level `views: [...]` entry says which object its views belong to; read by `getViewsByObject()` / `GET /meta/view?object=`.'), list: ObjectListViewSchema.optional(), // Default list view (views mode — dropdown userFilters allowed, no tabs; ADR-0047) - form: FormViewSchema.optional(), // Default form view + // [ADR-0159 D7] RETIRED in protocol 19 — see {@link VIEW_FORM_RETIRED}. + form: retiredKey(VIEW_FORM_RETIRED), listViews: z.record(z.string(), ObjectListViewSchema).optional().describe('Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047)'), - formViews: z.record(z.string(), FormViewSchema).optional().describe('Additional named form views'), + // [ADR-0159 D7] RETIRED in protocol 19 — see {@link VIEW_FORM_VIEWS_RETIRED}. + formViews: retiredKey(VIEW_FORM_VIEWS_RETIRED), /** * ADR-0010 §3.7 — Package-level protection envelope. Package * authors declare lock policy here, in a code package's source; @@ -6156,10 +6218,6 @@ export const ViewSchema = lazySchema(() => strictObject({ * data: { provider: 'object', object: 'task' }, * columns: ['subject', 'status', 'priority', 'due_date'], * }, - * form: { - * type: 'simple', - * sections: [{ label: 'Details', fields: [{ field: 'subject' }] }], - * }, * }); * ``` */ @@ -6167,13 +6225,11 @@ export function defineView(config: z.input): ViewParsed { const parsed = ViewSchema.parse(config); const viewCount = (parsed.list ? 1 : 0) + - (parsed.form ? 1 : 0) + - Object.keys(parsed.listViews ?? {}).length + - Object.keys(parsed.formViews ?? {}).length; + Object.keys(parsed.listViews ?? {}).length; if (viewCount === 0) { throw new Error( 'defineView: the container defines no views — nothing registers and no view appears in the Console. ' - + 'Declare at least one of `list`, `form`, `listViews`, `formViews`. ' + + 'Declare at least one of `list`, `listViews`. ' + 'If you passed a flat list view ({ name, label, type, columns, ... }), wrap it: ' + 'defineView({ list: { type, data, columns, ... } }).' ); @@ -6261,10 +6317,15 @@ const VIEW_SCOPE_RETIRED = { export const ViewScopeSchema = enumWithRetiredValues(['package', 'shared'], VIEW_SCOPE_RETIRED) .describe('View identity layer: package | shared.'); -/** Discriminator for the kind of view a {@link ViewItemSchema} carries. */ -export const ViewKindSchema = z - .enum(['list', 'form']) - .describe('Whether `config` is a ListView (list family) or a FormView.'); +/** + * Discriminator for the kind of view a {@link ViewItemSchema} carries: a list. + * + * [ADR-0159 D7] `form` was a member until protocol 19 and is RETIRED: it + * answers with {@link VIEW_KIND_FORM_RETIRED}'s prescription. A form is a + * `form` item. + */ +export const ViewKindSchema = enumWithRetiredValues(['list'], { form: VIEW_KIND_FORM_RETIRED }) + .describe('The family of the view: a list (`form` was retired in protocol 19 — a form is a `form` item).'); /** * [#20085] Prescriptions for the view item's two retired identity keys — @@ -6418,9 +6479,13 @@ function viewItemBaseShape() { * read off {@link VIEW_METADATA_MEMBERS}: `config: 42` type-checked while both * doors refuse it. */ -function viewItemArmShape(viewKind: K, config: C) { +function viewItemArmShape(viewKind: K, config: C) { return { - viewKind: z.literal(viewKind), + // [ADR-0159 D7] A list is the one kind; a retired `form` answers with its + // prescription rather than zod's bare literal mismatch. + viewKind: z.literal(viewKind, { + error: (issue) => (issue.input === 'form' ? VIEW_KIND_FORM_RETIRED : undefined), + }), config, ...viewItemBaseShape(), }; @@ -6437,7 +6502,7 @@ function viewItemArmShape(vie * carried a full copy of both config types (+170 KB of `view.zod.d.ts`, * measured); annotated, the file is smaller than when `config` was erased. */ -type ViewItemArmShape = ReturnType>; +type ViewItemArmShape = ReturnType>; /** * [#19920] {@link ViewItemArmShape} plus the wire arm's round-trip keys: the @@ -6445,7 +6510,7 @@ type ViewItemArmShape = Retur * object type rather than an intersection, so the annotation is IDENTICAL to * the type the spread infers, not merely assignable to it. */ -type ViewItemWireArmShape = { +type ViewItemWireArmShape = { [P in keyof (ViewItemArmShape & ReturnType)]: (ViewItemArmShape & ReturnType)[P]; }; @@ -6546,12 +6611,17 @@ const VIEW_ITEM_SURFACE = { */ export const ViewItemSchema: z.ZodDiscriminatedUnion<[ z.ZodObject, z.core.$strict>, - z.ZodObject, z.core.$strict>, ], 'viewKind'> = lazySchema(() => - z.discriminatedUnion('viewKind', [ - strictObject(VIEW_ITEM_SURFACE, viewItemArmShape('list', ListViewSchema.describe('List-family view configuration.'))), - strictObject(VIEW_ITEM_SURFACE, viewItemArmShape('form', FormViewSchema.describe('Form view configuration.'))), - ]), + // [ADR-0159 D7] One arm: a view item is a list. The `form` arm was retired in + // protocol 19 (a form is a `form` item), and `viewKind: 'form'` answers with + // its prescription ({@link VIEW_KIND_FORM_RETIRED}). The arm stays inside the + // discriminated union a view item always was, so every walker that reads it + // as a union of arms, and the published JSON Schema, keep their shape. + z.discriminatedUnion( + 'viewKind', + [strictObject(VIEW_ITEM_SURFACE, viewItemArmShape('list', ListViewSchema.describe('List-family view configuration.')))], + { error: retiredFormViewKindError }, + ), ); /** @@ -6654,7 +6724,7 @@ function viewItemWireFields() { columnState: retiredKey(VIEW_COLUMN_STATE_RETIRED), // [#20051] Pinned ABSENT, refused by name — see // {@link VIEW_ITEM_OPTIONS_REFUSED}. `z.never()` rather than the form - // overlay's `z.undefined()` ({@link FORM_OVERLAY_OPTIONS_REFUSED}): this + // overlay's former `z.undefined()` (retired in protocol 19): this // member is published on its own as `ViewItemWire.json`, and `never` has a // JSON Schema form (`not: {}`) where `undefined` has none. options: z.never({ error: () => VIEW_ITEM_OPTIONS_REFUSED }).optional() @@ -6697,12 +6767,6 @@ const LIST_OVERLAY_WIRE_SURFACE: StrictObjectOptions = { aliases: VIEW_WIRE_ALIASES, }; -/** [#26711] The unknown-key refusal of member 4, the flattened form overlay. */ -const FORM_OVERLAY_WIRE_SURFACE: StrictObjectOptions = { - surface: 'this inline form view', - history: VIEW_WIRE_HISTORY, - aliases: VIEW_WIRE_ALIASES, -}; /** * [#26711] Close a wire member's TOP level, with its own unknown-key refusal. @@ -6746,18 +6810,18 @@ function closeWireMember, z.core.$strict>, - z.ZodObject, z.core.$strict>, ], 'viewKind'> = lazySchema(() => - z.discriminatedUnion('viewKind', [ - strictObject(VIEW_ITEM_WIRE_SURFACE, { - ...viewItemArmShape('list', ListViewSchema.describe('List-family view configuration.')), - ...viewItemWireFields(), - }), - strictObject(VIEW_ITEM_WIRE_SURFACE, { - ...viewItemArmShape('form', FormViewSchema.describe('Form view configuration.')), - ...viewItemWireFields(), - }), - ]), + // [ADR-0159 D7] One arm, as {@link ViewItemSchema}: the `form` arm was retired. + z.discriminatedUnion( + 'viewKind', + [ + strictObject(VIEW_ITEM_WIRE_SURFACE, { + ...viewItemArmShape('list', ListViewSchema.describe('List-family view configuration.')), + ...viewItemWireFields(), + }), + ], + { error: retiredFormViewKindError }, + ), ); /** @@ -6786,9 +6850,9 @@ export function defineViewItem(config: z.input): ViewItem /** * [ADR-0159 D2] The prescription a `data` key on a `form` item answers with. A - * `form` item's object binding has ONE rung, its `object`; the four-rung - * resolution of an old-shape form ({@link anonymousFormObjectName}) lives only - * inside {@link projectViewForms}. A form bound to a JSON Schema + * `form` item's object binding has ONE rung, its `object`; the rung + * resolution of a stored old-shape form ({@link anonymousFormObjectName}) lives + * only inside {@link projectViewForms}. A form bound to a JSON Schema * (`data.provider: 'schema'`) is a Studio metadata form * ({@link defineMetadataForm}), not a `form` item. */ @@ -6925,14 +6989,17 @@ export function defineForm(config: z.input): FormParsed { // and a console personalization overlay (raw view config + inherited identity) // both parse to `{}` — silently "valid" while their `config` is never checked. // -// The three legitimate runtime shapes, each validated GENUINELY here: +// The three legitimate runtime shapes, each validated GENUINELY here. A view is +// a list since protocol 19 (ADR-0159 D7): the form family of each shape (a +// container's `form` / `formViews`, a `viewKind: 'form'` record or flattened +// body) is refused with its prescription, never validated as a view: // // 1. `defineView` aggregate **container** — at least one of -// `list`/`form`/`listViews`/`formViews`. An empty container is rejected +// `list`/`listViews`. An empty container is rejected // (it registers zero views; mirrors the {@link defineView} guard). // 2. Standalone **ViewItem record** — `{ viewKind, config, … }`; the nested -// `config` is validated against ListView/FormView. -// 3. **Flattened runtime overlay** — a raw ListView/FormView config at the +// `config` is validated against ListView. +// 3. **Flattened runtime overlay** — a raw ListView config at the // top level plus optional identity fields (`viewKind`/`object`/`label`, // inherited from the shadowed registry entry by `normalizeViewMetadata`; // see #2555). This is what a personalization PUT (column sort, inline @@ -7039,36 +7106,6 @@ const INLINE_VIEW_KIND_REQUIRED = + '(`{ name, object, viewKind, config: { … } }`), or make it a container. ' + VIEW_WRAP_REMEDY; -/** The other flattened overlay family — the `viewKind` the given arm does NOT judge. */ -function otherViewKind(kind: 'list' | 'form'): 'list' | 'form' { - return kind === 'list' ? 'form' : 'list'; -} - -/** - * [#20186] The refusal one flattened overlay member gives a body that names the - * OTHER family's `viewKind`. - * - * Each member judges exactly one `viewKind`, so a body is judged by the arm its - * `viewKind` names and by no other. Before this, both members shared one - * `list | form` enum, and a `viewKind: 'list'` body the list member refused - * (it carried no `columns`) was ACCEPTED by the form member, which `.strip()`s - * every list key unread: its `sort`, `searchableFields` and `timeline` were - * never judged, and the write door stored them as sent. - * - * Seen only by a consumer that parses one member directly - * (`VIEW_METADATA_MEMBERS.formOverlay.safeParse(…)`): through the union, the - * member the body does not claim is muted in favour of the one it does - * ({@link focusClaimedBranch}), so the author reads the claimed arm's own - * diagnosis. So the text says where the diagnosis is, not how to "fix" a - * `viewKind` that is correct. - */ -function overlayViewKindArmMismatch(kind: 'list' | 'form'): string { - const other = otherViewKind(kind); - return `This is the flattened ${kind.toUpperCase()} overlay member, which judges \`viewKind: "${kind}"\` only. ` - + `A \`viewKind: "${other}"\` body is judged by the ${other} overlay member ` - + `(\`VIEW_METADATA_MEMBERS.${other}Overlay\`), and that member's issues are its diagnosis.`; -} - /** * Identity + structural-guard fields layered onto the two "flattened runtime * overlay" members. The `config`/`list`/`form`/`listViews`/`formViews` guards @@ -7097,7 +7134,7 @@ function overlayViewKindArmMismatch(kind: 'list' | 'form'): string { * `viewKind: 'form'` type-checked, through the list member, as every union * type read off {@link VIEW_METADATA_MEMBERS}, while both doors refuse it. */ -function flattenedViewOverlayFields(kind: K) { +function flattenedViewOverlayFields(kind: K) { return { // No grammar, deliberately: the write path stamps this name rather than an // author writing it, so a flat overlay name is legal here while the SAME @@ -7115,7 +7152,8 @@ function flattenedViewOverlayFields(kind: K) { .enum([kind], { error: (issue) => { if (issue.input === undefined) return INLINE_VIEW_KIND_REQUIRED; - return issue.input === otherViewKind(kind) ? overlayViewKindArmMismatch(kind) : undefined; + // [ADR-0159 D7] The retired form family answers with its prescription. + return issue.input === 'form' ? VIEW_KIND_FORM_RETIRED : undefined; }, }) .describe( @@ -7326,8 +7364,8 @@ function assertViewIdentity(body: unknown, ctx: z.RefinementCtx): boolean { path: [], message: 'Not a `view` body: no recognized `view` key. Expected at least one of a container slot ' + - '(`list` / `form` / `listViews` / `formViews`), a ViewItem record (`viewKind` + `config`), ' + - 'or an inline view config (`type`, `columns`, `sections`, `filter`, …). ' + + '(`list` / `listViews`), a ViewItem record (`viewKind` + `config`), ' + + 'or an inline view config (`type`, `columns`, `filter`, `sort`, …). ' + (keys.length === 0 ? 'Received `{}`.' : 'Received ') + (unknown.length > 0 ? `unrecognized ${unknown.length === 1 ? 'key' : 'keys'} ${quote(unknown)}` : '') + (unknown.length > 0 && identity.length > 0 ? ', and ' : '') + @@ -7400,7 +7438,7 @@ function assertViewIdentity(body: unknown, ctx: z.RefinementCtx): boolean { const ViewContainerWireSchema = lazySchema(() => ViewSchema.refine(containerHasAView, { message: - 'A view container must define at least one of `list`, `form`, `listViews`, or `formViews`.', + 'A view container must define at least one of `list` or `listViews`.', }), ); @@ -7427,7 +7465,7 @@ const ViewContainerWireSchema = lazySchema(() => * source files. * * Declared on the list overlay member only. The form overlay pins the bag - * absent with its own text ({@link FORM_OVERLAY_OPTIONS_REFUSED}), and the + * absent with its own text (until it was retired in protocol 19), and the * view item record with {@link VIEW_ITEM_OPTIONS_REFUSED}. */ const LIST_OVERLAY_OPTIONS_REFUSED = @@ -7438,21 +7476,6 @@ const LIST_OVERLAY_OPTIONS_REFUSED = + '`filter`, …) are top-level keys of the view. Stored views are folded on read. ' + 'Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; -/** - * [#20051] The refusal the flattened FORM overlay gives an `options` bag. - * - * `options` is list-view vocabulary, so a body carrying it is a list overlay — - * the same structural-guard reasoning as `config` / `list` / `form` pinned - * absent in {@link flattenedViewOverlayFields}. Without this pin the form - * member, which `.strip()`s and requires no list key, would ACCEPT a list - * overlay the list member refused over its `options` bag (a column-less, - * type-less personalization body reaches it), and the bag would be stored - * unjudged after all. - */ -const FORM_OVERLAY_OPTIONS_REFUSED = - 'A form view carries no `options` bag: `options.kanban`, `options.timeline` and the other per-kind blocks ' - + 'belong to a list view. Remove `options`, or save this body as a list view (`viewKind: "list"` with its `columns`).'; - /** [#20186] The list type a flattened list overlay that names none parses to. */ const LIST_OVERLAY_DEFAULT_TYPE = 'grid'; @@ -7466,15 +7489,6 @@ const LIST_OVERLAY_TYPE_NEEDS_COLUMNS = + 'it shadows (`sort`, `hiddenFields`, `rowHeight`, `inlineEdit`, …) sets no `type` and needs no `columns`: ' + 'remove `type` to save this body as a patch on the view it shadows.'; -/** - * [#20186] The refusal the flattened FORM overlay gives a field LIST under - * `columns`. - */ -const FORM_OVERLAY_COLUMNS_IS_A_COUNT = - 'On a form view `columns` is the NUMBER of body columns (an integer, 1 or more), not a list of fields, ' - + 'and this body says `viewKind: "form"`. A list of fields is a list view\'s `columns`: if this is a ' - + 'list view, set `viewKind: "list"`; if it is a form, list its fields in `sections: [{ fields: [...] }]`.'; - /** * [#20186] The two keys the flattened LIST overlay member declares differently * from the authoring {@link ListViewSchema}: `columns` optional, and `type` @@ -7595,25 +7609,6 @@ function applyListOverlayTypeDefault(view: T): T { return out as T; } -/** - * [#20186] `columns` on the flattened FORM overlay: the form's own count, - * refused with {@link FORM_OVERLAY_COLUMNS_IS_A_COUNT} when a field list - * arrives there. A clone of {@link FormViewSchema}'s own `columns` schema with - * an error map added, so its constraints are that schema's and cannot drift. - */ -function formOverlayColumnsField(): z.ZodOptional { - const optional = (FormViewSchema as unknown as { shape: { columns: z.ZodOptional } }).shape.columns; - const count = optional.unwrap(); - const withPrescription = count.clone({ - ...count._zod.def, - // The def's issue type is `never` for a number's own map; the runtime hands - // it the raw issue, whose `input` is what this reads. - error: (issue: { input?: unknown }) => (Array.isArray(issue.input) ? FORM_OVERLAY_COLUMNS_IS_A_COUNT : undefined), - }); - const description = optional.description; - return description ? withPrescription.optional().describe(description) : withPrescription.optional(); -} - /** * [#6391] Member 3 of {@link ViewMetadataSchema} — a flattened runtime LIST * overlay: an inline `ListView` config at the top level plus the optional @@ -7675,32 +7670,11 @@ const ListViewOverlayWireSchema = lazySchema(() => .overwrite(applyListOverlayTypeDefault), ); -/** - * [#6391] Member 4 of {@link ViewMetadataSchema} — a flattened runtime FORM - * overlay, published as `VIEW_METADATA_MEMBERS.formOverlay`. Same construction - * as {@link ListViewOverlayWireSchema}, and closed at the top level the same way - * (#26711). - * - * [#20051] `options` is pinned ABSENT here — see - * {@link FORM_OVERLAY_OPTIONS_REFUSED} for the fall-through it closes. - * - * [#20186] It judges `viewKind: 'form'` only. Before, it was the union's - * fall-through for every flattened body the list member refused — a - * column-less `viewKind: 'list'` patch among them — and it accepted those with - * their list keys stripped unread. Its `columns` (the form's body-column - * COUNT) now answers a field list with {@link FORM_OVERLAY_COLUMNS_IS_A_COUNT}. - */ -const FormViewOverlayWireSchema = lazySchema(() => - // `.safeExtend()`: this member now re-declares a key the form shape carries - // (`columns`, see {@link formOverlayColumnsField}), and {@link FormViewSchema} - // carries refinements, which `.extend()` refuses to combine with an overwrite. - // The two differ in that throw only — the refinements ride along either way. - closeWireMember(FormViewSchema.safeExtend({ - ...flattenedViewOverlayFields('form'), - options: z.undefined({ error: () => FORM_OVERLAY_OPTIONS_REFUSED }).optional(), - columns: formOverlayColumnsField(), - }), FORM_OVERLAY_WIRE_SURFACE), -); +// [ADR-0159 D7] Member 4, the flattened FORM overlay (`viewKind: 'form'` at the +// top level), was retired in protocol 19 with the `form` member of +// {@link ViewKindSchema}: a form is a `form` item. A flattened body that names +// `viewKind: 'form'` is judged by the list overlay member, which answers with +// {@link VIEW_KIND_FORM_RETIRED}'s prescription. /** * [#6391] The branch names of {@link ViewMetadataSchema}'s union, in @@ -7711,7 +7685,7 @@ const FormViewOverlayWireSchema = lazySchema(() => * branch by name via {@link VIEW_METADATA_MEMBERS}, or let * {@link diagnoseViewMetadata} name the branch for it. */ -export const VIEW_METADATA_BRANCHES = ['viewItem', 'container', 'listOverlay', 'formOverlay'] as const; +export const VIEW_METADATA_BRANCHES = ['viewItem', 'container', 'listOverlay'] as const; /** [#6391] One branch of {@link ViewMetadataSchema}'s union, by name. */ export type ViewMetadataBranch = (typeof VIEW_METADATA_BRANCHES)[number]; @@ -7738,10 +7712,9 @@ export const VIEW_METADATA_MEMBERS = { viewItem: ViewItemWireSchema as typeof ViewItemWireSchema, // 2. Non-empty defineView container. container: ViewContainerWireSchema, - // 3/4. Flattened runtime overlay — inline ListView / FormView config + identity, - // each judging only the `viewKind` it names (#20186). + // 3. Flattened runtime overlay — inline ListView config + identity (#20186). + // [ADR-0159 D7] Its form twin was retired in protocol 19. listOverlay: ListViewOverlayWireSchema, - formOverlay: FormViewOverlayWireSchema, } as const satisfies Record; /** @@ -7857,12 +7830,10 @@ export function selectViewMetadataBranch(body: unknown): ViewMetadataBranch | nu if (b.list !== undefined || b.form !== undefined || b.listViews !== undefined || b.formViews !== undefined) { return 'container'; } - if (b.viewKind === 'form') return 'formOverlay'; - if (b.viewKind === 'list') return 'listOverlay'; - if (typeof b.type === 'string') { - if (overlayTypeValues(FormViewSchema).has(b.type)) return 'formOverlay'; - if (overlayTypeValues(ListViewSchema).has(b.type)) return 'listOverlay'; - } + // [ADR-0159 D7] A flattened `viewKind: 'form'` body is claimed by the list + // overlay, whose `viewKind` answers it with the retirement's prescription. + if (b.viewKind === 'list' || b.viewKind === 'form') return 'listOverlay'; + if (typeof b.type === 'string' && overlayTypeValues(ListViewSchema).has(b.type)) return 'listOverlay'; return null; } @@ -8312,9 +8283,15 @@ function cloneViewConfig(v: any): any { /** * A view-key collision detected while expanding one `defineView` container. * - * List and form views share a single `.` namespace during - * expansion (see {@link expandViewContainer}), and the default `list` - * implicitly claims `.default`. When a later view competes for a name + * The list views of a container share a single `.` namespace + * during expansion (see {@link expandViewContainer}), and the default `list` + * implicitly claims `.default`. A view holds lists only since + * protocol 19 (ADR-0159 D7): a form is a `form` item under `forms:`, keyed by + * its own `name`, and takes no part in this namespace. Only a container stored + * before protocol 19 still carries form members; the form family is expanded + * after the list family, so such a member never takes a list's name, and a + * `view` read serves none of them ({@link expandServedViewContainer}). + * When a later view competes for a name * already taken, it is renamed (`.` → `._2`) to keep * the runtime registry key unique. That rename is a silent footgun: references * to the requested name (form action `target`s, navigation `viewName`s) resolve @@ -8350,13 +8327,15 @@ export interface ExpandViewResult { * The item carrying the declared default list is flagged `isDefault`; with no * `list`, the first named list is. * - * Form family: `formViews` entries, then the default `form`. `ViewSchema` makes + * Form family, present only in a container stored before protocol 19 (a view + * holds lists only since; `ViewSchema` refuses both members): `formViews` + * entries, then the default `form`. Protocol 18's `ViewSchema` made * `form` the container's default form and `formViews` additional named forms, so - * `form` is always served as its own item (`.form`) and is the only form - * item flagged `isDefault` — a named form never stands in for it, even one whose - * body equals it. A container with no `form` declares no default form: none of - * its named forms is flagged, and each is served only where it is asked for by - * name. + * `form` is always expanded as its own item (`.form`) and is the only + * form item flagged `isDefault` — a named form never stands in for it, even one + * whose body equals it. A container with no `form` declares no default form: + * none of its named forms is flagged. No `view` read serves a form item + * ({@link expandServedViewContainer}). * * Collisions are captured at the exact points the shared `used` set forces a * rename, so the diagnostic can never drift from the expansion it describes. @@ -8443,11 +8422,46 @@ export function expandViewContainerWithDiagnostics(object: string, container: an * Thin wrapper over {@link expandViewContainerWithDiagnostics} that discards the * collision diagnostics — the shape every runtime loader consumes. Behaviour is * unchanged: colliding names are still renamed so the registry key stays unique. + * + * [ADR-0159 D7] This is the RAW expansion: a stored old-shape container still + * expands its `form` and `formViews` members here, because the readers that + * must still see a stored old-shape form read through it: the stored-row + * holdings the replacement check and the stored-form ceremony read + * (ADR-0159 D6 rule 11, D7), and the projection the kept withdrawal reader + * reads (rule 10). What a `view` read SERVES is lists only: + * {@link expandServedViewContainer}. */ export function expandViewContainer(object: string, container: any): ExpandedViewItem[] { return expandViewContainerWithDiagnostics(object, container).items; } +/** A served view item: a list (ADR-0159 D7). */ +export type ServedViewItem = ExpandedViewItem & { viewKind: 'list' }; + +/** + * Whether an expanded or stored view body is one a `view` read serves + * (ADR-0159 D7): everything except a `viewKind: 'form'` item. A list passes, + * and so does a stored old-shape container, which carries no `viewKind` and is + * served by name as stored. + */ +export function isServedViewItem(item: unknown): boolean { + return !!item && typeof item === 'object' && (item as { viewKind?: unknown }).viewKind !== 'form'; +} + +/** + * [ADR-0159 D7] The ViewItems a `view` read serves from an aggregated + * container: {@link expandViewContainer}, lists only. A view serves lists only + * since @objectstack/spec 19, so the form members of a stored old-shape + * container (`form`, `formViews`) are not served: they are dropped here, never + * refused, and the stored row is not rewritten. The form family is expanded + * after the list family, so dropping it renames no list. + */ +export function expandServedViewContainer(object: string, container: any): ServedViewItem[] { + return expandViewContainer(object, container).filter( + (item): item is ServedViewItem => item.viewKind === 'list', + ); +} + // ─────────────────────────────────────────────────────────────────────────── // [ADR-0159 D5] The projection of the three old form shapes into `form` items // ─────────────────────────────────────────────────────────────────────────── @@ -8463,7 +8477,7 @@ export const PROJECTED_FORM_SOURCE_KEY = '_formDefinedIn' as const; export interface ProjectedFormItem { /** The name the form is served under today: a stored item's own `name`, or the name `expandViewContainer` gives a container's form. */ name: string; - /** The object the form submits into, by today's four-rung resolution ({@link anonymousFormObjectName}). */ + /** The object the form submits into, by the old shapes' rung resolution ({@link anonymousFormObjectName}). */ object: string; /** The form body, unchanged, at the top level (ruled question 5), plus the item's own `label`, `overrides` and envelope. */ [key: string]: unknown; @@ -8538,7 +8552,7 @@ function projectedItem( * * - A projected item takes the name it is served under today (a stored item's * own `name`; for a container, the name {@link expandViewContainerWithDiagnostics} - * gives it), `object` from today's four-rung resolution + * gives it), `object` from the old shapes' rung resolution * ({@link anonymousFormObjectName}), and its body UNCHANGED, lifted to the top * level (ruled question 5). It is marked {@link PROJECTED_FORM_SOURCE_KEY}. * - ⛔ A projected item is never parsed by {@link FormSchema}: the authored-only @@ -8591,7 +8605,7 @@ export function projectViewForms(body: unknown, options: { object?: string } = { const config = (item.config ?? {}) as Record; const carrier: Record = { ...v, label: item.label }; // The doors read a container's forms as the items it expands to, so the - // four rungs are asked of the expanded item: the form's own + // rungs are asked of the expanded item: the form's own // `data.object`, else the object the container expands under. out.forms.push(projectedItem(item.name, anonymousFormObjectName({ object: item.object }, config) ?? item.object, config, carrier)); } @@ -8616,7 +8630,7 @@ export function projectViewForms(body: unknown, options: { object?: string } = { * [ADR-0159 D5] Every `form` item a set of `view` bodies carries, one per name * in scan order (the first body that projects a name keeps it): the source * half of the `form` read for one package's old shapes. A container comes - * before the items it expands, so the four-rung `object` is the container's. + * before the items it expands, so the resolved `object` is the container's. */ export function projectedFormsOf(bodies: ReadonlyArray): ProjectedFormItem[] { const seen = new Set(); diff --git a/packages/spec/src/ui/visibility-alias-keys-retirement.test.ts b/packages/spec/src/ui/visibility-alias-keys-retirement.test.ts index 6cc170e7513..90f273bcb3f 100644 --- a/packages/spec/src/ui/visibility-alias-keys-retirement.test.ts +++ b/packages/spec/src/ui/visibility-alias-keys-retirement.test.ts @@ -38,7 +38,7 @@ import { applyConversionsToStoredItem } from '../conversions/stored'; import { MIGRATIONS_BY_MAJOR, RETIRED_KEYS_BY_MAJOR } from '../migrations/registry'; import { defineStack } from '../stack.zod'; import { PageComponentSchema, PageSchema, type PageComponent } from './page.zod'; -import { FormFieldSchema, FormSectionSchema, ViewSchema, type FormFieldInput, type FormSection } from './view.zod'; +import { FormFieldSchema, FormSectionSchema, FormViewSchema, ViewSchema, type FormFieldInput, type FormSection } from './view.zod'; const VIEW_CONVERSION = 'view-visibleOn-to-visibleWhen'; const PAGE_CONVERSION = 'page-component-visibility-to-visibleWhen'; @@ -58,6 +58,9 @@ const legacyView = () => ({ }, }); +/** [ADR-0159 D7] The same form as a `form` item: how a form is authored since protocol 19. */ +const legacyForm = () => ({ name: 'crm_lead.form', object: 'crm_lead', ...legacyView().form }); + /** A page written before 18: one component gated through `visibility`. */ const legacyPage = () => ({ name: 'crm_home', @@ -103,7 +106,7 @@ describe('visibility alias keys retirement — the type channel', () => { }); describe('visibility alias keys retirement — the authoring funnel refuses, the stored seam converts', () => { - it('an authored legacy view reaches defineStack as written and is refused at both keys', () => { + it('[ADR-0159 D7] an authored legacy view-held form is refused at the container key since 19', () => { let refusal: unknown; try { defineStack({ views: [legacyView()] } as never); @@ -111,6 +114,19 @@ describe('visibility alias keys retirement — the authoring funnel refuses, the refusal = error; } expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); + const issues = (refusal as { issues: Issue[] }).issues; + expect(issues.map((i) => i.path.join('.'))).toEqual(['views.0.form']); + expect(issues[0]!.message).toMatch(/^`view\.form` was removed in @objectstack\/spec 19\.0\.0/); + }); + + it('an authored legacy form reaches defineStack as written and is refused at both keys', () => { + let refusal: unknown; + try { + defineStack({ forms: [legacyForm()] } as never); + } catch (error) { + refusal = error; + } + expect(refusal).toMatchObject({ code: 'STACK_SCHEMA_INVALID', status: 422 }); const issues = flatten((refusal as { issues: Issue[] }).issues); const retired = issues.filter((i) => /visibleOn` was removed in @objectstack\/spec 18/.test(i.message)); // The section's own key, and the field's (nested inside the `fields` union). @@ -140,7 +156,7 @@ describe('visibility alias keys retirement — the authoring funnel refuses, the expect(stack).toEqual(input); }); - it('a STORED view row written with `visibleOn` loads, renamed, and parses', () => { + it('a STORED view row written with `visibleOn` loads, renamed, and its form body parses', () => { const notices: string[] = []; const row = applyConversionsToStoredItem('view', legacyView(), { onNotice: (n) => notices.push(`${n.conversionId} ${n.path}`) }); expect(notices).toEqual([ @@ -148,7 +164,10 @@ describe('visibility alias keys retirement — the authoring funnel refuses, the `${VIEW_CONVERSION} views[0].form.sections[0].fields[1].visibleWhen`, ]); expect(JSON.stringify(row)).not.toContain('visibleOn'); - expect(ViewSchema.safeParse(row).success).toBe(true); + // [ADR-0159 D7] The replayed row still holds a view-held form, which the 19 door refuses; + // its replayed form body is what the form view door accepts. + expect(ViewSchema.safeParse(row).success).toBe(false); + expect(FormViewSchema.safeParse((row as { form: unknown }).form).success).toBe(true); }); it('a STORED page row written with `visibility` loads, renamed, and parses', () => { diff --git a/packages/spec/variant-docs.json b/packages/spec/variant-docs.json index fdbd42c0278..41a77afb9bb 100644 --- a/packages/spec/variant-docs.json +++ b/packages/spec/variant-docs.json @@ -125,10 +125,10 @@ "reason": "Declared by a settings manifest that Setup/Studio ships and consumes; it is not part of the metadata a tenant authors. (Was labelled generated-reference-only, though its own reason already said so.)" }, { - "key": "viewKind:form|list", + "key": "viewKind:list", "label": "view item kind", "exempt": "not-authorable", - "reason": "Loader-derived. Authors write the `list` / `listViews` / `formViews` containers; the loader expands them and stamps `viewKind`. No author ever types it." + "reason": "Loader-derived. Authors write the `list` / `listViews` containers; the loader expands them and stamps `viewKind`. No author ever types it. `form` left the variant set in protocol 19 (ADR-0159 D7): a form is a `form` item, and a `viewKind: 'form'` body is refused with that prescription." }, { "key": "code:QUOTA_EXCEEDED|RATE_LIMIT_EXCEEDED|UNAUTHENTICATED", diff --git a/packages/spec/vitest.repo-tests.json b/packages/spec/vitest.repo-tests.json index 4f80758a464..5a38a99375a 100644 --- a/packages/spec/vitest.repo-tests.json +++ b/packages/spec/vitest.repo-tests.json @@ -88,6 +88,7 @@ "src/ui/page-header-show-star-retirement.test.ts", "src/ui/page-slots-tabs-retirement.test.ts", "src/ui/view-data-api-provider-retirement.test.ts", + "src/ui/view-form-slots-retirement.test.ts", "src/ui/view-item-owner-hidden-retirement.test.ts", "src/ui/view-list-filterable-fields-retirement.test.ts", "src/ui/view-list-tabs-retirement.test.ts", diff --git a/packages/verify/src/handle.public-form-door.test.ts b/packages/verify/src/handle.public-form-door.test.ts index 0a90730855d..9859ccf2f9b 100644 --- a/packages/verify/src/handle.public-form-door.test.ts +++ b/packages/verify/src/handle.public-form-door.test.ts @@ -32,7 +32,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { defineStack, defineView } from '@objectstack/spec'; +import { defineForm, defineStack, defineView } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import type { Flow } from '@objectstack/spec/automation'; import { PermissionSetSchema } from '@objectstack/spec/security'; @@ -41,6 +41,9 @@ import type { ObjectQL, OperationContext } from '@objectstack/objectql'; import { bootStack, type VerifyStack } from './harness.js'; import type { EngineRow } from './handle.js'; +// Paid at collection: the harness's boot loads this lazily (check:test-source-alias). +import '@objectstack/service-automation'; + // Booting the full in-process stack runs well past vitest's 5s default. const BOOT_TIMEOUT = 120_000; @@ -126,24 +129,25 @@ const Ledger = ObjectSchema.create({ const data = { provider: 'object' as const, object: REQUEST }; const RequestViews = defineView({ list: { label: 'Requests', type: 'grid', data, columns: [{ field: 'subject' }] }, - formViews: { - // Open to anonymous intake: enabled, anonymous, a public link. - intake: { - type: 'simple', - data, - sections: [ - { name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'subject', required: true }, { field: 'email' }] }, - ], - sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${PUBLIC_SLUG}` }, - }, - // Shared, with a link, but NOT anonymous: not a public form. - staff: { - type: 'simple', - data, - sections: [{ name: 'staff', label: 'Staff', columns: 1, fields: [{ field: 'subject', required: true }] }], - sharing: { enabled: true, allowAnonymous: false, publicLink: `/forms/${STAFF_SLUG}` }, - }, - }, +}); +// Each form is a `form` item (ADR-0159): named `OBJECT.KEY`, bound by `object`. +/** Open to anonymous intake: enabled, anonymous, a public link. */ +const IntakeForm = defineForm({ + name: `${REQUEST}.intake`, + object: REQUEST, + type: 'simple', + sections: [ + { name: 'intake', label: 'Intake', columns: 1, fields: [{ field: 'subject', required: true }, { field: 'email' }] }, + ], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${PUBLIC_SLUG}` }, +}); +/** Shared, with a link, but NOT anonymous: not a public form. */ +const StaffForm = defineForm({ + name: `${REQUEST}.staff`, + object: REQUEST, + type: 'simple', + sections: [{ name: 'staff', label: 'Staff', columns: 1, fields: [{ field: 'subject', required: true }] }], + sharing: { enabled: true, allowAnonymous: false, publicLink: `/forms/${STAFF_SLUG}` }, }); /** start (record-after-create) → create_record(pfd_ledger) → end. */ @@ -190,6 +194,7 @@ const fixtureStack = defineStack({ requires: ['automation', 'triggers'], objects: [Request, Ledger], views: [RequestViews], + forms: [IntakeForm, StaffForm], hooks: [{ name: 'pfd_guest_branch', object: REQUEST, events: ['beforeInsert', 'afterInsert'], handler: guestBranch }], flows: [onCreate], permissions: [memberSet], diff --git a/scripts/codemod/view-to-viewitem.mjs b/scripts/codemod/view-to-viewitem.mjs index 6e481482bbb..3b4efc27075 100644 --- a/scripts/codemod/view-to-viewitem.mjs +++ b/scripts/codemod/view-to-viewitem.mjs @@ -12,21 +12,29 @@ * formViews: { default: { … } }, * }) * - * …to independent view entities authored with `defineViewItem`: + * …to independent entities: each list a view item authored with + * `defineViewItem`, and each form a `form` item authored with `defineForm` + * (a `view` holds lists only since protocol 19, ADR-0159 D7): * * export const leadAll = defineViewItem({ name: 'crm_lead.all', object: 'crm_lead', viewKind: 'list', config: { … } }) * export const leadPipeline = defineViewItem({ name: 'crm_lead.pipeline', object: 'crm_lead', viewKind: 'list', config: { … } }) - * export const leadForm = defineViewItem({ name: 'crm_lead.default', object: 'crm_lead', viewKind: 'form', config: { … } }) + * export const leadForm = defineForm({ name: 'crm_lead.default', object: 'crm_lead', sections: [ … ] }) + * + * The `formViews` block above is the protocol-18 input this reporter reads; + * protocol 19 refuses it, and `os migrate meta --from 18` moves each entry to + * the stack's `forms:` (a record form that nothing else opens is deleted, not + * moved). The `[form]` lines of the report name those `form` items. * * WHY THIS IS A REPORTER, NOT AN AUTO-REWRITER * -------------------------------------------- * The backend loader already performs an equivalent expansion at load time * (the "dual-read" path — see ADR-0017 §3.2 and * `packages/metadata/src/plugin.ts` → `expandViewContainer`). Existing - * `defineView` sources therefore keep working unchanged; this migration is - * OPTIONAL. Because it is optional, the tool deliberately does NOT mutate - * source code — a regex/AST rewrite of arbitrary user code (spread configs, - * computed keys, imported fragments, comments) is unsafe for marginal value. + * `defineView` list sources therefore keep working unchanged; for lists this + * migration is OPTIONAL (the forms are not: see above). Because it is + * optional, the tool deliberately does NOT mutate source code — a regex/AST + * rewrite of arbitrary user code (spread configs, computed keys, imported + * fragments, comments) is unsafe for marginal value. * * Instead it SCANS `*.view.ts` files and REPORTS, per `defineView` call site, * the exact `ViewItem` names the loader will generate — so a team can choose diff --git a/scripts/cross-package-test-inputs.mjs b/scripts/cross-package-test-inputs.mjs index fc34a400e03..229f67aec4b 100644 --- a/scripts/cross-package-test-inputs.mjs +++ b/scripts/cross-package-test-inputs.mjs @@ -254,6 +254,12 @@ export const CROSS_PACKAGE_TEST_INPUTS = { // per-extension rule, so it is the second witness on every row, and // src/conversions/conversion-conflict-channel-retirement.test.ts (the // conversion-conflict channel's retirement) the third, for the same reason. + // src/ui/view-form-slots-retirement.test.ts (the view container's form + // slots and the form view item, ADR-0159 D7) walks the same five roots + // and judges a narrower population, so it is a further witness on the + // rows of the extensions it reads and on no other: under `packages/` + // what a package teaches (Markdown and YAML), under `examples/` every + // non-code extension. 'packages/**/*.mts': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', @@ -291,26 +297,31 @@ export const CROSS_PACKAGE_TEST_INPUTS = { 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'packages/**/*.mdx': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'packages/**/*.yaml': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'packages/**/*.yml': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'examples/**/*.json': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', // The template-manifest retirement's absence walk: every // `objectstack.manifest.json` under `packages/` and `examples/`. 'packages/spec/src/marketplace/template-manifest-inert-keys-retirement.test.ts', @@ -319,21 +330,25 @@ export const CROSS_PACKAGE_TEST_INPUTS = { 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'examples/**/*.mdx': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'examples/**/*.yaml': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], 'examples/**/*.yml': [ 'packages/spec/src/system/compliance-families-retirement.test.ts', 'packages/spec/src/ui/view-data-api-provider-retirement.test.ts', 'packages/spec/src/conversions/conversion-conflict-channel-retirement.test.ts', + 'packages/spec/src/ui/view-form-slots-retirement.test.ts', ], }, }, diff --git a/skills/objectstack-i18n/SKILL.md b/skills/objectstack-i18n/SKILL.md index 38e7795c013..22274f0638d 100644 --- a/skills/objectstack-i18n/SKILL.md +++ b/skills/objectstack-i18n/SKILL.md @@ -70,14 +70,14 @@ bundles; delete it and the shipped value returns. ## Key map -`{path}`, `{column_path}` and `{list}` are the declared string as one key, dots included -(`'event.related_to'`); `fields.{path}` and `{column_path}` hold plain strings. +`{path}`, `{column_path}`, `{list}` and `{form}` are the declared string as one key, dots +included (`'event.related_to'`); `fields.{path}` and `{column_path}` hold plain strings. ```text objects.{object}: label, pluralLabel, description fields.{field}: label, help, placeholder, options.{value}, inlineTitle, relatedListTitle - _views.{view}: label, description, title, emptyState.{title,message}, - submitBehavior.{title,message}, bulkActions.{bulkActionDefs_name} + _views.{view}: label, description, emptyState.{title,message}, + bulkActions.{bulkActionDefs_name} _actions.{action}: label, description, confirmText, submitText, cancelText, successMessage, disabledReason, params.{param}(.options.{value}), outcomeMessages.{outcome}, resultDialog.{title,description,acknowledge}, @@ -97,6 +97,8 @@ datasets.{dataset}.{dimensions,measures}.{member} books.{book}: label, description, groups.{group_key}.label mappings.{mapping}.label, packages.{manifest.id}: name, description pages.{page}.components.{tabs_id}.items.{value}.label +forms.{form}: label, description, title, submitBehavior.{title,message}, + sections.{section}: the _sections keys flows.{flow}: approvals.{node_id}.label, screens.{node_id}.title, nodes.{node_id}.label, records.{node_id}.fields.{field} hooks.{hook}: texts.{key}.message, and refusals as under _actions @@ -107,8 +109,7 @@ messages: flat dotted ids ('common.save'); dashboards, metadataForms, settingsCo `relatedListTitle` (its related list on the parent's record page) are keys of the CHILD object, where the field lives: `objects.crm_opportunity_line_item.fields.opportunity.inlineTitle`. Untranslated, the authored text shows, never the child's plural label. -- `_views.{view}.title` is a form's own heading. `_sections` `fields` is that form's - override: `helpText` there, `help` under `fields.{field}`. +- A form's `sections` are read before `_sections`, key by key. - `columns` is a sibling of `fields`: a `format: 'table'` field's `path`, then a column's (`resultDialog: { columns: { rows: { email: '邮箱', 'error.message': '原因' } } }`). `preflight` holds `fields` and `columns` only, no `title`. diff --git a/skills/objectstack-i18n/evals/bundles-locales-coverage.json b/skills/objectstack-i18n/evals/bundles-locales-coverage.json index 7761702bfa1..dee9e27f15d 100644 --- a/skills/objectstack-i18n/evals/bundles-locales-coverage.json +++ b/skills/objectstack-i18n/evals/bundles-locales-coverage.json @@ -63,12 +63,12 @@ }, { "id": 7, - "prompt": "In zh-CN the `contact` quick-create form still shows its English heading and the placeholder its `contact_details` section sets on `email`; the `crm_home` page's `overview` tab and the `manager_review` step of the `crm_expense_claim` flow are English too.", - "expected_output": "Each key spelled as its source: `objects.contact._views.quick_create.title` (a form's own heading), `objects.contact._sections.contact_details.fields.email.placeholder` (that form's override; `helpText` there, `help` at `fields.email`), `pages.crm_home.components.{tabs_id}.items.overview.label` (by the item's `value`), `flows.crm_expense_claim.approvals.manager_review.label` (the node id). Not a view `label`, an object `_tabs` key or a screen `title`.", + "prompt": "In zh-CN the `contact.quick_create` form still shows its English heading and the placeholder its `contact_details` section sets on `email`; the `crm_home` page's `overview` tab and the `manager_review` step of the `crm_expense_claim` flow are English too.", + "expected_output": "Each key spelled as its source: `forms['contact.quick_create'].title` (a form's heading: the `forms` group, keyed by the form's `name` as one key, dot included), `forms['contact.quick_create'].sections.contact_details.fields.email.placeholder` (the form's own section entry, read before the object-level default `objects.contact._sections.contact_details.fields.email.placeholder`, which resolves too; `helpText` in both, `help` at `objects.contact.fields.email`), `pages.crm_home.components.{tabs_id}.items.overview.label` (by the item's `value`), `flows.crm_expense_claim.approvals.manager_review.label` (the node id). Not a `title` under `objects.contact._views` (refused since protocol 19), a form `label`, an object `_tabs` key or a screen `title`.", "files": [], "assertions": { - "must_contain": ["_views", "title", "_sections", "fields", "items", "approvals"], - "must_not_contain": ["stepLabel", "_tabs.overview"] + "must_contain": ["forms", "contact.quick_create", "title", "sections", "fields", "items", "approvals"], + "must_not_contain": ["stepLabel", "_tabs.overview", "_views: {"] } }, { diff --git a/ui/apps/console/src/__tests__/formViewFeaturesRootRefused-6262.test.ts b/ui/apps/console/src/__tests__/formViewFeaturesRootRefused-6262.test.ts index 4fed37e8022..a1dad6ce8b7 100644 --- a/ui/apps/console/src/__tests__/formViewFeaturesRootRefused-6262.test.ts +++ b/ui/apps/console/src/__tests__/formViewFeaturesRootRefused-6262.test.ts @@ -5,7 +5,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * A form view may not name the `features` scope root in a predicate + * A form may not name the `features` scope root in a predicate * (objectui#6262, ruled 2026-08-27, option B). Held here against the * INSTALLED `@objectstack/spec`, because `FormPage`'s predicate-scope comment * rests on it. @@ -16,78 +16,69 @@ * and `visibleWhen` fails OPEN there while the same text resolves inside an app. * The ruling closed that split in the vocabulary instead of wiring * `/auth/config` into the route: the spec refuses the root at parse on every - * form-view predicate. If a spec bump ever loosens that, this file goes red - * beside the comment that relies on it, instead of leaving the comment to - * describe a rule that no longer exists. + * form predicate. If a spec bump ever loosens that, this file goes red beside + * the comment that relies on it, instead of leaving the comment to describe a + * rule that no longer exists. * - * The two schemas are the ones metadata-admin's `view` gates resolve in - * `validateMetadataDraft` (`clientValidation.ts`): `ViewItemSchema` for a - * create draft that carries `viewKind`, and `ViewMetadataSchema` on edit. That - * file's `view` loader note says why the edit gate is the schema the server's - * save runs. The body is the ExpandedViewItem envelope `/forms/:name` loads. + * The schema is `FormSchema`, the `form` item's own: a form is a `form` item + * since `@objectstack/spec` 19 (ADR-0159 D7), it is what `/forms/:name` loads + * (`/meta/form/:name`), and `FormSchema` is the schema the spec registers for + * the `form` type. The body is that item: bound by `object`, its layout at the + * top level. * - * What this file does NOT hold: it parses those schemas directly and never - * calls `validateMetadataDraft`, which `@object-ui/app-shell` does not export. - * The gates' own behaviour is pinned in `clientValidation.viewShapes.test.ts`. - * The refusal was measured through `validateMetadataDraft` in both modes once, - * for objectui#6262, and got the same verdicts. Nothing here re-derives that - * half. + * Until spec 19 this file held the refusal on the two `view` gates + * (`ViewItemSchema` and `ViewMetadataSchema`) over a `viewKind: 'form'` item. + * Both refuse that item outright now, so they can no longer say anything about + * a predicate inside it; the last `describe` pins that, so the old body is not + * read as a place where the rule still lives. + * + * What this file does NOT hold: it parses the schema directly and never calls + * a save. * * The control is load-bearing. The same body with a `current_user.*` predicate * must parse clean, so a refused target is about the root and not about a body * the schema rejects for some other reason. */ import { describe, it, expect } from 'vitest'; -import { ViewItemSchema, ViewMetadataSchema } from '@objectstack/spec/ui'; +import { FormSchema, ViewItemSchema, ViewMetadataSchema } from '@objectstack/spec/ui'; /** The excluded root, in the shape the ruling was about. */ const TARGET = 'features.multiOrgEnabled'; -/** A root form views keep: must parse clean in the identical body. */ +/** A root forms keep: must parse clean in the identical body. */ const CONTROL = "current_user.role == 'admin'"; -/** Field-level predicate, in the envelope `/forms/:name` loads. */ +/** Field-level predicate, in the `form` item `/forms/:name` loads. */ const fieldLevel = (predicate: string) => ({ name: 'account.intake', object: 'account', - viewKind: 'form', label: 'Intake', - config: { - type: 'simple', - sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen: predicate }] }], - }, + type: 'simple', + sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen: predicate }] }], }); -/** Section-level predicate, same envelope. */ +/** Section-level predicate, same item. */ const sectionLevel = (predicate: string) => ({ name: 'account.intake', object: 'account', - viewKind: 'form', label: 'Intake', - config: { - type: 'simple', - sections: [{ label: 'Main', visibleWhen: predicate, fields: ['name'] }], - }, + type: 'simple', + sections: [{ label: 'Main', visibleWhen: predicate, fields: ['name'] }], }); -const GATES = [ - ['ViewItemSchema (create gate)', ViewItemSchema], - ['ViewMetadataSchema (edit gate)', ViewMetadataSchema], -] as const; - const SURFACES = [ - ['field', fieldLevel, ['config', 'sections', 0, 'fields', 0, 'visibleWhen']], - ['section', sectionLevel, ['config', 'sections', 0, 'visibleWhen']], + ['field', fieldLevel, ['sections', 0, 'fields', 0, 'visibleWhen']], + ['section', sectionLevel, ['sections', 0, 'visibleWhen']], ] as const; -describe('form-view predicates may not name the `features` root (objectui#6262)', () => { - describe.each(GATES)('%s', (_gate, schema) => { +describe('form predicates may not name the `features` root (objectui#6262)', () => { + describe('FormSchema (the `form` item)', () => { it.each(SURFACES)('%s-level: a `current_user.*` predicate parses clean (control)', (_surface, build) => { - const parsed = schema.safeParse(build(CONTROL)); + const parsed = FormSchema.safeParse(build(CONTROL)); expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); }); it.each(SURFACES)('%s-level: a `features.*` predicate is refused at that predicate', (_surface, build, path) => { - const parsed = schema.safeParse(build(TARGET)); + const parsed = FormSchema.safeParse(build(TARGET)); expect(parsed.success).toBe(false); const issues = parsed.error?.issues ?? []; // Exactly one issue: the control proves the rest of the body is clean, @@ -95,9 +86,42 @@ describe('form-view predicates may not name the `features` root (objectui#6262)' expect(issues, JSON.stringify(issues)).toHaveLength(1); expect(issues[0].code).toBe('custom'); expect(issues[0].path).toEqual(path); - // `custom` is shared by every refinement on the form view; the named - // subject is what says this is the root refusal and not another one. + // `custom` is shared by every refinement on the form; the named subject + // is what says this is the root refusal and not another one. expect(issues[0].message).toContain('`features.*`'); }); }); }); + +describe('the `view` gates no longer judge a form predicate (ADR-0159 D7)', () => { + /** The body this file parsed until spec 19: a form as a `view` item. */ + const asViewItem = (predicate: string) => ({ + name: 'account.intake', + object: 'account', + viewKind: 'form', + label: 'Intake', + config: { + type: 'simple', + sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen: predicate }] }], + }, + }); + + const GATES = [ + ['ViewItemSchema (create gate)', ViewItemSchema], + ['ViewMetadataSchema (edit gate)', ViewMetadataSchema], + ] as const; + + it.each(GATES)('%s refuses the item whichever predicate it carries, and never at the predicate', (_gate, schema) => { + for (const predicate of [CONTROL, TARGET]) { + const parsed = schema.safeParse(asViewItem(predicate)); + expect(parsed.success, predicate).toBe(false); + const paths = (parsed.error?.issues ?? []).map((i) => i.path.join('.')); + expect(paths, predicate).not.toContain('config.sections.0.fields.0.visibleWhen'); + } + }); + + it('the create gate names the retired family: the one issue is at `viewKind`', () => { + const parsed = ViewItemSchema.safeParse(asViewItem(CONTROL)); + expect((parsed.error?.issues ?? []).map((i) => i.path)).toEqual([['viewKind']]); + }); +}); diff --git a/ui/apps/console/src/components/FormPage.tsx b/ui/apps/console/src/components/FormPage.tsx index d9153e9e07f..238d69eddd8 100644 --- a/ui/apps/console/src/components/FormPage.tsx +++ b/ui/apps/console/src/components/FormPage.tsx @@ -1777,11 +1777,11 @@ async function loadPublicForm(slug: string): Promise { * Unwrap a `/meta/form/:name` response into the {@link FormViewBody} the * renderer consumes (ADR-0159, objectstack#37087). The `form` read serves a * `form` item: its identity (`name`, `object`, `label`) and its form body at - * the top level (ADR-0159 ruled question 5: no `config` wrapper). An old-shape - * form (a container's `form`, a `formViews` entry, a `viewKind: 'form'` item) - * is served in the same shape, through the server's one projection - * (ADR-0159 D5), so this page reads one shape only. The read answers the - * item bare or as `{ item }`. + * the top level (ADR-0159 ruled question 5: no `config` wrapper). It is the + * one shape a form has and the one this page reads: `@objectstack/spec` 19 + * retired the three shapes a `view` once held a form in (ADR-0159 D7), and the + * `form` read serves none of them. The read answers the item bare or as + * `{ item }`. * * A name that is no form (a list view's, an action target that names a list) * answers `404` on the `form` read, so it reaches the not-found state, never an @@ -2565,12 +2565,13 @@ export function FormPage({ mode, recordPath, cancelPath }: FormPageProps) { * change; nothing new is declared to say so. * * `features` is likewise empty here. That is the contract, not a gap: a form - * view may not name the `features` root in a predicate at all (objectui#6262, + * may not name the `features` root in a predicate at all (objectui#6262, * ruled 2026-08-27). The same ruling rejected fetching `/auth/config` on this * route to fill it. `@objectstack/spec` refuses such a predicate at parse, - * on every form-view predicate surface, and metadata-admin's `view` gates run - * that parse. So the in-app versus standalone-route split is closed where the - * form is authored, not in this renderer. + * on every form predicate surface, in the `form` item's own schema + * (`FormSchema`: a form is a `form` item since spec 19, ADR-0159 D7), the + * one the save of a `form` item runs. So the in-app versus standalone-route + * split is closed where the form is authored, not in this renderer. * `formViewFeaturesRootRefused-6262.test.ts` re-derives the refusal against * the installed spec. */ diff --git a/ui/packages/app-shell/src/providers/MetadataProvider.merge.test.ts b/ui/packages/app-shell/src/providers/MetadataProvider.merge.test.ts index a259a9dd960..e5e69c68801 100644 --- a/ui/packages/app-shell/src/providers/MetadataProvider.merge.test.ts +++ b/ui/packages/app-shell/src/providers/MetadataProvider.merge.test.ts @@ -8,8 +8,10 @@ import { resolveRecordFormModalLayout } from '../utils/recordFormNavigation'; * `mergeViewsIntoObjects` folds the `view` metadata type into object * definitions. The backend returns BOTH expanded first-class ViewItems * (`{ name: '.', object, viewKind, config }`, ADR-0017) AND the - * legacy aggregated container — these tests pin the routing so FORM-family - * views stay out of the list-view switcher (`objectDef.listViews`). + * aggregated container. A view is a list since `@objectstack/spec` 19 + * (ADR-0159 D7: a form is a `form` item, and the `view` read serves lists + * only), so these tests pin that the merge routes lists into the list-view + * switcher (`objectDef.listViews`) and merges no form from a `view`. */ describe('mergeViewsIntoObjects', () => { const objects = [{ name: 'crm_activity', fields: {} }]; @@ -30,6 +32,8 @@ describe('mergeViewsIntoObjects', () => { label: 'Activity Calendar', config: { type: 'calendar', data: { object: 'crm_activity' }, calendar: { startDateField: 'due_date' } }, }; + // A row of the retired form family: no `view` read serves one any more. It + // is handed in here to pin what the merge does with it. const formDefault = { name: 'crm_activity.default', object: 'crm_activity', @@ -38,14 +42,15 @@ describe('mergeViewsIntoObjects', () => { config: { type: 'simple', sections: [{ label: 'Details', fields: [{ field: 'subject' }] }] }, }; - it('routes form-family ViewItems into formViews, not listViews', () => { + it('a row of the retired form family reaches no list switcher, and no form is merged from it', () => { const [obj] = mergeViewsIntoObjects(objects, [listAll, listCalendar, formDefault]); - // List-family views populate the switcher… + // List views populate the switcher… expect(Object.keys(obj.listViews).sort()).toEqual(['crm_activity.all', 'crm_activity.calendar']); - // …and the form view is NOT among them (the original bug). + // …and the form row is NOT among them. expect(obj.listViews['crm_activity.default']).toBeUndefined(); - // Form view is available separately for the record-form renderer. - expect(obj.formViews['crm_activity.default']).toBeTruthy(); + // Nor is it merged anywhere else: a form is a `form` item, read by name. + expect(obj).not.toHaveProperty('formViews'); + expect(obj).not.toHaveProperty('form'); }); it('flattens `config` to the renderer shape and preserves type/label/isDefault', () => { @@ -73,16 +78,15 @@ describe('mergeViewsIntoObjects', () => { // `.` identity now (objectui#3770), so the container can no longer // double-list them under short keys — but it still MUST be skipped: its own // `list` is structurally distinct from `listViews.all`, so expanding it would - // add a third `crm_activity.default` list tab (and force the container's - // `formViews.default` into a `_2` rename), and the ViewItem rows are the + // add a third `crm_activity.default` list tab, and the ViewItem rows are the // authoritative ones the runtime heals personalization onto. expect(Object.keys(obj.listViews).sort()).toEqual(['crm_activity.all', 'crm_activity.calendar']); }); /** * Container gate (objectui#3770). A stack-packaged container is served - * UNEXPANDED, so this merge asks `expandViewContainer` for each view's runtime - * identity instead of deriving one. The previous derivation was + * UNEXPANDED, so this merge asks the spec's composer (`expandServedViewContainer`) + * for each view's runtime identity instead of deriving one. The previous derivation was * `list.name || 'list'` — a spelling no producer emits, which is why the * default list's translation key never resolved (the composer, the framework * loader and the i18n extractor all say `.default`). @@ -136,22 +140,24 @@ describe('mergeViewsIntoObjects', () => { expect(obj.listViews['crm_activity.all'].isDefault).toBe(true); }); - it('routes the container form family into formViews only', () => { + // ADR-0159 D7: `form` and `formViews` are tombstones on the container, so + // no authored container carries them. A stored row written before + // protocol 19 still can, and the merge reads the SERVED expansion of it: + // its lists, and nothing of its forms. + it('a stored container that still names `formViews` contributes its lists only', () => { const container = { name: 'crm_activity', list: { type: 'grid', columns: [{ field: 'subject' }] }, formViews: { compact: { type: 'simple' } }, }; const [obj] = mergeViewsIntoObjects(objects, [container]); - expect(obj.formViews['crm_activity.compact']).toBeTruthy(); + expect(obj).not.toHaveProperty('formViews'); expect(obj.listViews['crm_activity.compact']).toBeUndefined(); // …and the list family is untouched by the form entry. expect(Object.keys(obj.listViews)).toEqual(['crm_activity.default']); }); - it('takes a container\'s declared `form` as `.form`, never a named form beside it', () => { - // The default form is expanded AFTER the named ones, so arrival order - // cannot be what picks it. + it('a stored container that still names `form` merges no `.form`, and no named form beside it', () => { const container = { name: 'crm_activity', list: { type: 'grid', columns: [{ field: 'subject' }] }, @@ -159,31 +165,41 @@ describe('mergeViewsIntoObjects', () => { formViews: { quick: { type: 'simple', label: 'Quick log', sections: [{ name: 'quick', label: 'Quick', fields: [{ field: 'subject' }] }] } }, }; const [obj] = mergeViewsIntoObjects(objects, [container]); - expect(obj.form.name).toBe('crm_activity.form'); - expect(obj.form.sections.map((s: any) => s.name)).toEqual(['details']); - expect(obj.formViews['crm_activity.quick'].isDefault).toBe(false); + expect(obj).not.toHaveProperty('form'); + expect(obj).not.toHaveProperty('formViews'); + expect(Object.keys(obj.listViews)).toEqual(['crm_activity.default']); + expect(obj.list.name).toBe('crm_activity.default'); + }); + + it('a stored container that names forms only merges nothing onto its object', () => { + const container = { + name: 'crm_activity', + form: { type: 'simple', sections: [{ name: 'details', fields: [{ field: 'subject' }] }] }, + }; + const [obj] = mergeViewsIntoObjects(objects, [container]); + expect(obj).not.toHaveProperty('form'); + expect(obj).not.toHaveProperty('formViews'); + expect(obj.listViews).toEqual({}); + expect(obj).not.toHaveProperty('list'); }); }); }); /** - * `.form` is the served DEFAULT form only (objectui#11539). + * No form is merged from a `view` (ADR-0159 D7). * - * `@objectstack/spec` `ViewSchema`: `form` is a container's "Default form - * view", `formViews` are "Additional named form views". The served rows carry - * that: the container's own `form` arrives as `OBJECT.form` with `isDefault`, - * and a container with no `form` serves its named forms with no `isDefault` - * key at all (objectstack#21500). The console used to make the FIRST form item - * to arrive its create/edit `.form` whenever none was default, so a named-only - * container rendered its first named form — in the `showcase_inquiry` case the - * public, anonymous contact-us form — as the create and edit form. + * Until `@objectstack/spec` 19 a `view` read served form rows + * (`viewKind: 'form'`), and this merge put them on their object as + * `.formViews`, the default one as `.form` (objectui#11539). A form is now a + * `form` item: the `view` read serves lists only, and the console reads a form + * by its name through `/meta/form`. So a form row handed in here, in any + * arrival order and default or not, is merged nowhere, and the object's lists + * are what they are without it. * - * Fixtures are served `view` rows in the shape the expansion emits - * (`{ name, object, viewKind, label, config, order, scope, isDefault? }`), in - * the order it emits them: named entries first, the container's own default - * after them. + * Fixtures are `view` rows in the shape the expansion emitted before the + * major (`{ name, object, viewKind, label, config, order, scope, isDefault? }`). */ -describe('mergeViewsIntoObjects — `.form` is the served default form only (objectui#11539)', () => { +describe('mergeViewsIntoObjects — no form is merged from a view (ADR-0159 D7)', () => { const row = (object: string, key: string, viewKind: 'list' | 'form', config: Record, extra: Record = {}) => ({ name: `${object}.${key}`, object, @@ -194,9 +210,8 @@ describe('mergeViewsIntoObjects — `.form` is the served default form only (obj ...extra, }); - // examples/app-showcase `showcase_inquiry`: a default list, a named list, and - // ONE named form — the public contact-us form. No `form`, so no form row is - // default. + // `showcase_inquiry`: a default list, a named list, and ONE named form row, + // a public contact-us form. const inquiryData = { provider: 'object', object: 'showcase_inquiry' }; const inquiryRows = [ row('showcase_inquiry', 'triage', 'list', { type: 'grid', label: 'Inquiry Triage', data: inquiryData, columns: [{ field: 'name' }] }, { order: 0 }), @@ -209,8 +224,7 @@ describe('mergeViewsIntoObjects — `.form` is the served default form only (obj }, { order: 2 }), ]; - // examples/app-crm `crm_lead`: the named Web-to-Lead form, then the - // container's own `form`, the one default. + // `crm_lead`: a named form row, then a default form row. const leadData = { provider: 'object', object: 'crm_lead' }; const leadWebToLead = row('crm_lead', 'web_to_lead', 'form', { type: 'simple', @@ -223,8 +237,7 @@ describe('mergeViewsIntoObjects — `.form` is the served default form only (obj sections: [{ name: 'lead_information', label: 'Lead Information', fields: [{ field: 'name' }] }], }, { order: 3, isDefault: true }); - // examples/app-showcase `showcase_contact`: a named `create` form, then the - // container's own `form`, the one default. + // `showcase_contact`: a named `create` form row, then a default form row. const contactCreate = row('showcase_contact', 'create', 'form', { type: 'simple', sections: [{ name: 'quick', label: 'Quick add', fields: [{ field: 'first_name' }] }], @@ -241,43 +254,47 @@ describe('mergeViewsIntoObjects — `.form` is the served default form only (obj ]; const byName = (merged: any[], name: string) => merged.find((o) => o.name === name); - it('a container with only named forms (`showcase_inquiry`) gets no `.form`; its named form stays reachable by name', () => { + it('a named form row beside lists (`showcase_inquiry`) is merged nowhere; the lists keep their own default', () => { const inquiry = byName(mergeViewsIntoObjects(objects, inquiryRows), 'showcase_inquiry'); expect(inquiry).not.toHaveProperty('form'); - expect(Object.keys(inquiry.formViews)).toEqual(['showcase_inquiry.contact']); - expect(inquiry.formViews['showcase_inquiry.contact'].isDefault).toBe(false); - // The list family keeps its own default. + expect(inquiry).not.toHaveProperty('formViews'); + expect(Object.keys(inquiry.listViews).sort()).toEqual(['showcase_inquiry.default', 'showcase_inquiry.triage']); expect(inquiry.list.name).toBe('showcase_inquiry.default'); }); - it('create and edit take no layout from any form view of `showcase_inquiry` (objectstack-ai/objectstack#36425)', () => { + it('create and edit take no layout from any form row of `showcase_inquiry` (objectstack-ai/objectstack#36425)', () => { const inquiry = byName(mergeViewsIntoObjects(objects, inquiryRows), 'showcase_inquiry'); expect(inquiry.form ?? inquiry.formViews?.default).toBeUndefined(); - // The New/Edit dialog (AppContent, `useActionModal`) reads no form view at + // The New/Edit dialog (AppContent, `useActionModal`) reads no form at // all: the same answer as an object that declares none. expect(resolveRecordFormModalLayout(inquiry, 'auto')).toEqual({}); expect(resolveRecordFormModalLayout(inquiry, 'auto')) .toEqual(resolveRecordFormModalLayout({ name: 'showcase_inquiry' } as any, 'auto')); }); - it('`crm_lead` keeps its default when the default arrives AFTER the named Web-to-Lead form', () => { - const lead = byName(mergeViewsIntoObjects(objects, [leadWebToLead, leadForm]), 'crm_lead'); - expect(lead.form.name).toBe('crm_lead.form'); - expect(lead.form.sections?.map((s: any) => s.name)).toEqual(['lead_information']); - expect(lead.formViews['crm_lead.web_to_lead'].isDefault).toBe(false); + it('a default form row is not `.form`, whichever side of a named form row it arrives on (`crm_lead`)', () => { + for (const rows of [[leadWebToLead, leadForm], [leadForm, leadWebToLead]]) { + const lead = byName(mergeViewsIntoObjects(objects, rows), 'crm_lead'); + // No view item is bound to it, so the object is what it was. + expect(lead).toEqual({ name: 'crm_lead', fields: {} }); + } }); - it('`showcase_contact` keeps its default whichever order its two forms arrive in', () => { + it('`showcase_contact` gets no form from its two form rows, in either order', () => { for (const rows of [[contactCreate, contactForm], [contactForm, contactCreate]]) { const contact = byName(mergeViewsIntoObjects(objects, rows), 'showcase_contact'); - expect(contact.form.name).toBe('showcase_contact.form'); - expect(Object.keys(contact.formViews).sort()).toEqual(['showcase_contact.create', 'showcase_contact.form']); + expect(contact).toEqual({ name: 'showcase_contact', fields: {} }); } }); - it('a named form arriving AFTER the default does not displace it', () => { - const lead = byName(mergeViewsIntoObjects(objects, [leadForm, leadWebToLead]), 'crm_lead'); - expect(lead.form.name).toBe('crm_lead.form'); + it('form rows alone do not hide the object\'s container: its lists still merge', () => { + // A form row is no view item, so it does not make the container beside it + // read as already expanded. + const container = { name: 'crm_lead', list: { type: 'grid', columns: [{ field: 'name' }] } }; + const lead = byName(mergeViewsIntoObjects(objects, [leadForm, leadWebToLead, container]), 'crm_lead'); + expect(Object.keys(lead.listViews)).toEqual(['crm_lead.default']); + expect(lead.list.name).toBe('crm_lead.default'); + expect(lead).not.toHaveProperty('form'); }); }); diff --git a/ui/packages/app-shell/src/providers/MetadataProvider.tsx b/ui/packages/app-shell/src/providers/MetadataProvider.tsx index d26a30c6ce1..f13ef9fa55e 100644 --- a/ui/packages/app-shell/src/providers/MetadataProvider.tsx +++ b/ui/packages/app-shell/src/providers/MetadataProvider.tsx @@ -7,7 +7,7 @@ import { useLayoutEffect, type ReactNode, } from 'react'; -import { expandViewContainer } from '@objectstack/spec/ui'; +import { expandServedViewContainer } from '@objectstack/spec/ui'; import { ActiveOrganizationStorage, TokenStorage, useAuth } from '@object-ui/auth'; import { isMetaItemAbsentError, @@ -532,18 +532,18 @@ function isNamedItem(item: unknown): item is { name: string } { * 1. Independent **ViewItem** — the RECORD gate (ADR-0017, "Object has-many * View"): one first-class metadata record per named view, as authored by * `defineViewItem` or written through the runtime `/meta` seam. - * { name: '.', object, viewKind: 'list' | 'form', + * { name: '.', object, viewKind: 'list', * label, isDefault?, config: { type, data, columns, … } } - * `viewKind` is the family discriminant and the view body lives under - * `config`. We route `viewKind: 'list'` items into `listViews` and - * `viewKind: 'form'` items into `formViews` — so FORM-family views never - * surface in the list-view switcher (which only reads `listViews`). + * The view body lives under `config`, and every item is routed into + * `listViews`. A view item is a list: `@objectstack/spec` 19 retired the + * `form` member of `viewKind` (ADR-0159 D7), a form is a `form` metadata + * item, and the `view` read serves lists only. * - * 2. Aggregated **container** `{ list?, form?, listViews?, formViews? }` keyed + * 2. Aggregated **container** `{ list?, listViews? }` keyed * by the bare object name — the STACK gate's packaging shape: what * `defineView` emits and what a stack carries in * `defineStack({ views: [...] })`. The spec treats it as first class - * (`isAggregatedViewContainer` / `expandViewContainer` in + * (`isAggregatedViewContainer` / `expandServedViewContainer` in * `@objectstack/spec/ui`), so it is NOT legacy and this branch is NOT dead * code — delete it and stack-packaged views stop reaching the renderer. * A container is served UNEXPANDED on purpose (the platform's write @@ -553,7 +553,9 @@ function isNamedItem(item: unknown): item is { name: string } { * (objectui#3770). Both gates therefore produce the same canonical * `.` ids — including the default `list`'s implicit * `.default` — and the container inherits the composer's folding and - * collision-renaming rules for free. + * collision-renaming rules for free. The served expansion is the one read + * here (ADR-0159 D7): a stored container that still names the retired + * `form` / `formViews` members contributes its lists and nothing else. * When an object already has expanded ViewItems the container is skipped for * THAT object: it restates the same identities, and the ViewItem rows are * the authoritative ones (the runtime heals personalization overlays onto @@ -563,29 +565,31 @@ function isNamedItem(item: unknown): item is { name: string } { */ interface ViewBucket { primary?: any; - form?: any; listViews: Record; - formViews: Record; } /** - * Is this row BOUND to an object — either persisted ViewItem spelling? + * Is this row a view item BOUND to an object — either persisted ViewItem spelling? * * This answers binding only ("does it belong in an object's bucket?"). WHERE * its body lives is a separate question with a separate answer, {@link * viewItemBody} — and conflating the two is exactly what silently ate a flat * overlay's author-written `columns` (objectui#8411). * - * `viewKind && object` is sound for binding, and that is measured against - * `ViewMetadataSchema` (@objectstack/spec 17.3.0) rather than assumed: both + * `viewKind: 'list'` with an `object` is sound for binding, and that is + * measured against `ViewMetadataSchema` rather than assumed: both * ViewItem-family members carry both keys, so neither can be dropped to widen * this. A body with a nested `config` but no `viewKind` is refused by the - * record member's `viewKind` discriminator ("No matching discriminator"), and a - * flat overlay without `object` is refused as well. The aggregated container - * carries neither key and still falls through to the stack gate below. + * record member's `viewKind` discriminator, and a flat overlay without `object` + * is refused as well. The aggregated container carries neither key and still + * falls through to the stack gate below. + * + * `list` is the one member `ViewKindSchema` holds since `@objectstack/spec` 19 + * (ADR-0159 D7). A row of any other family is no view item: the `view` read + * serves none, and one handed in here binds to no object. */ function isViewItem(view: any): boolean { - return !!view && typeof view === 'object' && !!view.viewKind && !!view.object; + return !!view && typeof view === 'object' && view.viewKind === 'list' && !!view.object; } /** @@ -622,32 +626,21 @@ function viewItemBody(view: any): Record { /** * Route ONE view identity into its object's bucket — shared by both gates: the - * record gate's stored ViewItems and the views `expandViewContainer` materialises - * out of a stack-packaged container. Both shapes are + * record gate's stored ViewItems and the views `expandServedViewContainer` + * materialises out of a stack-packaged container. Both shapes are * `{ name, object, viewKind, label?, isDefault?, config }`, so both are keyed by * the canonical `.` name the composer owns. * * The body is resolved by {@link viewItemBody} — a record's nested `config` is - * flattened to the legacy NamedListView/FormView shape the renderer consumes - * (type/data/columns/sections at top level), and a flat overlay is already in + * flattened to the NamedListView shape the renderer consumes + * (type/data/columns at top level), and a flat overlay is already in * that shape — the item-level label/isDefault ride along and `name` is stamped * with the id so primary-view promotion (which matches on `list.name`) finds * this entry by its listViews key. - * FORM-family views land in `formViews` only, never in the list-view switcher. * - * `bucket.form` is set ONLY from a form item that carries `isDefault` - * (objectui#11539). No record create or edit reads it any more - * (objectstack-ai/objectstack#36425): those lay out by the object's field - * groups. It stays merged so the served object still says what it declares. - * `@objectstack/spec` `ViewSchema` calls a container's `form` its "Default form view" and `formViews` - * "Additional named form views", and the served rows say which one is default: - * `OBJECT.form` alone carries `isDefault`. There is no "first form wins" - * fallback, so arrival order decides nothing: a default arriving after a named - * form still takes `.form`, and a named form arriving after the default does - * not displace it. A container with no `form` serves its named forms with no - * `isDefault`, and `.form` stays unset. A named form — - * which can be a public anonymous intake form or a wizard — is reached only by - * its name, through `formViews`. + * Every identity routed here is a list (ADR-0159 D7): a form is a `form` + * metadata item, read by its own name through `/meta/form`, and no object + * carries one merged from a `view`. */ function applyViewItem(bucket: ViewBucket, view: any): void { const key = view.name || `${view.object}.${view.viewKind}`; @@ -658,13 +651,8 @@ function applyViewItem(bucket: ViewBucket, view: any): void { label: view.label ?? (body as any).label, isDefault: !!view.isDefault, }; - if (view.viewKind === 'form') { - bucket.formViews[key] = entry; - if (view.isDefault) bucket.form = entry; - } else { - bucket.listViews[key] = entry; - if (view.isDefault) bucket.primary = entry; - } + bucket.listViews[key] = entry; + if (view.isDefault) bucket.primary = entry; } export function mergeViewsIntoObjects(objects: any[], views: any[]): any[] { @@ -682,15 +670,15 @@ export function mergeViewsIntoObjects(objects: any[], views: any[]): any[] { if (isViewItem(view)) { // The canonical `.` name doubles as the view id, so // `/view/` URLs resolve directly against the switcher tab ids. - applyViewItem((byObject[view.object] ||= { listViews: {}, formViews: {} }), view); + applyViewItem((byObject[view.object] ||= { listViews: {} }), view); continue; } - // ── Stack gate: aggregated container ({ list, form, listViews, formViews }) ── - const objName = view?.name || view?.list?.data?.object || view?.form?.data?.object; + // ── Stack gate: aggregated container ({ list, listViews }) ── + const objName = view?.name || view?.list?.data?.object; if (!objName) continue; // Expanded ViewItems supersede the bare container for this object. if (hasViewItems.has(objName)) continue; - const bucket = (byObject[objName] ||= { listViews: {}, formViews: {} }); + const bucket = (byObject[objName] ||= { listViews: {} }); // Ask the composer which views this container declares and what each one's // runtime identity is (objectui#3770) — the default `list` implicitly claims // `.default`, and a `listViews` entry that merely restates it folds @@ -698,7 +686,7 @@ export function mergeViewsIntoObjects(objects: any[], views: any[]): any[] { // per @objectstack/spec ViewSchema (below) AND is mirrored into `listViews` // under that identity, so consumers that only iterate `listViews` still see // it and consumers honoring `obj.list` dedup by the same id. - for (const item of expandViewContainer(objName, view)) { + for (const item of expandServedViewContainer(objName, view)) { applyViewItem(bucket, item); } } @@ -706,24 +694,17 @@ export function mergeViewsIntoObjects(objects: any[], views: any[]): any[] { const extra = byObject[obj.name]; if (!extra) return obj; // `listViews` is canonical (#5362; @objectstack/spec declares only camelCase). The - // `list_views` / `form_views` legs are compatibility READS for stored pre-settlement + // `list_views` leg is a compatibility READ for stored pre-settlement // documents (that stock has never been censused: objectstack#7917). Never WRITE snake keys // — the merge below emits camelCase only. const existingListViews = obj.listViews || obj.list_views || {}; - const existingFormViews = obj.formViews || obj.form_views || {}; const merged: any = { ...obj, listViews: { ...extra.listViews, ...existingListViews }, }; - if (Object.keys(extra.formViews).length || Object.keys(existingFormViews).length) { - merged.formViews = { ...extra.formViews, ...existingFormViews }; - } if (extra.primary && !obj.list) { merged.list = extra.primary; } - if (extra.form && !obj.form) { - merged.form = extra.form; - } return merged; }); } @@ -926,7 +907,7 @@ function itemNames(items: readonly unknown[]): string[] { /** The object a view document belongs to, as `mergeViewsIntoObjects` reads it. */ function viewObjectName(view: any): string | undefined { if (isViewItem(view)) return view.object; - const name = view?.name || view?.list?.data?.object || view?.form?.data?.object; + const name = view?.name || view?.list?.data?.object; return typeof name === 'string' && name ? name : undefined; } diff --git a/ui/packages/app-shell/src/utils/recordFormNavigation.ts b/ui/packages/app-shell/src/utils/recordFormNavigation.ts index bdfd87eb5c2..54fc64c7fc2 100644 --- a/ui/packages/app-shell/src/utils/recordFormNavigation.ts +++ b/ui/packages/app-shell/src/utils/recordFormNavigation.ts @@ -139,21 +139,17 @@ export function resolveRecordFormTarget(opts: { } /** - * The form-view body a NAMED form carries (ADR-0017's `viewKind: 'form'` - * item, flattened): what {@link resolveFormViewChrome} reads for a form that - * is opened by its own name — a public form, a form an action of type `form` - * opens, the Setup preview of a form view. + * The form body a NAMED form carries (a `form` item's body, at the top level: + * ADR-0159): what {@link resolveFormViewChrome} reads for a form that is opened + * by its own name — a public form, a form an action of type `form` opens. * - * ⛔ No record create or edit reads one (objectstack-ai/objectstack#36425): an - * object's internal form views are not loaded by the console's create dialog, - * full-page create, action-opened create or edit. Those lay out by the object's - * `fieldGroups` and follow the rules on its fields. + * ⛔ No record create or edit reads one (objectstack-ai/objectstack#36425): the + * console's create dialog, full-page create, action-opened create and edit + * load no form. Those lay out by the object's `fieldGroups` and follow the + * rules on its fields. */ export interface FormViewDefinition { - /** - * The served view item's id (`OBJECT.KEY`), which `MetadataProvider` - * stamps on every form view it merges (objectstack#30057). - */ + /** The served `form` item's name (`OBJECT.KEY`). */ name?: string; /** Layout family declared by the form view (`simple` | `tabbed` | `wizard` | `split`). */ type?: string; @@ -287,8 +283,7 @@ function createSeed( } /** - * Resolve the {@link FormViewChrome} of a named form view (the Setup preview - * of a form view reads it this way, so the canvas and a named form agree). + * Resolve the {@link FormViewChrome} of a named form. * * Every console form host used to hard-set these props — `showSubmit: true`, * its own submit label, `layout: 'vertical'` — over the keys the form view diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx index 3095ad68c42..531ca3aec21 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx @@ -283,10 +283,10 @@ function unionMembers(schema: JsonSchema): JsonSchema[] | undefined { * A value that carries no key at all contradicts no branch — an empty * create-mode value is no evidence, and it still lands on the first branch. * - * This is what tells the four `view` members apart: `viewKind` is a `const` / - * one-value `enum` on each of them, the overlays require `object` + `viewKind` - * (a container carries no `viewKind`), and the ViewItem member declares - * neither the overlay's inline keys nor the container's slots. + * This is what tells the `view` members apart: `viewKind` is a `const` / + * one-value `enum` on the ViewItem and the list overlay, the overlay requires + * `object` + `viewKind` (a container carries no `viewKind`), and the ViewItem + * member declares neither the overlay's inline keys nor the container's slots. */ function valueContradictions(branch: JsonSchema, value: Record): number { const props = branch.properties as Record | undefined; @@ -1302,8 +1302,8 @@ function SchemaFormBody({ const required: string[] = Array.isArray(effectiveSchema.required) ? effectiveSchema.required : []; // Per-property visibility predicate context — the current draft under // `data`, mirroring the sectioned form's field-level filtering. Lets a flat - // (create) schema gate a field on a sibling value (e.g. show the list layout - // picker only when `data.viewKind == 'list'`). No predicate → always shown. + // (create) schema gate a field on a sibling value (e.g. show a layout + // picker only when `data.kind == 'list'`). No predicate → always shown. const predicateData = (value ?? {}) as Record; const keys = flatFormRowKeys(props, hiddenFields, fieldOrder, predicateData, hostScope); @@ -1323,7 +1323,7 @@ function SchemaFormBody({ // Guard: when none of the fields declared by the layout actually exist // in the JSON schema (typically because the schema was reshaped under // a nested wrapper, e.g. `view` now bundles its props under - // `list/form/listViews/formViews`), the layout would render a wall of + // `list/listViews`), the layout would render a wall of // amber "missing from schema" warnings and nothing else. Detect that // total mismatch and fall through to the flat schema-driven // rendering so the user still gets a usable form. diff --git a/ui/packages/app-shell/src/views/metadata-admin/anchors.ts b/ui/packages/app-shell/src/views/metadata-admin/anchors.ts index af64381e933..fb443c2fc58 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/anchors.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/anchors.ts @@ -271,8 +271,10 @@ export function registerBuiltinAnchors(): void { }, }); - // A view is the canonical first-class ViewItem ({ viewKind, config }), - // bound to its object by the top-level `object` foreign key. + // A view is the canonical first-class ViewItem ({ viewKind: 'list', config }), + // bound to its object by the top-level `object` foreign key. A view is a + // list: `@objectstack/spec` 19 retired the form family (ADR-0159 D7), and a + // form is created as a `form` item, under its own type. registerMetadataResource({ type: 'view', anchors: [{ @@ -284,13 +286,13 @@ export function registerBuiltinAnchors(): void { groupLabel: 'Views', order: 30, }], - createFields: ['label', 'name', 'object', 'viewKind', 'kind', 'formType'], + createFields: ['label', 'name', 'object', 'kind'], createDerive: [ { from: 'label', to: 'name', transform: 'slugify', untilUserEdits: true }, ], createSchema: { type: 'object', - required: ['label', 'name', 'object', 'viewKind'], + required: ['label', 'name', 'object'], properties: { label: { type: 'string', title: 'Label', description: 'Human-readable view name.' }, name: { @@ -305,83 +307,35 @@ export function registerBuiltinAnchors(): void { widget: 'ref:object', description: 'The object this view displays.', }, - // The family discriminator (ViewItemSchema is a discriminated union on - // `viewKind`). Picks which config shape — and therefore which layout - // picker below — applies. - viewKind: { - type: 'string', - title: 'View family', - enum: ['list', 'form'], - default: 'list', - description: - 'List views show many records as a collection (grid, kanban, …). Form views show one record as a field layout (simple, tabbed, …).', - }, - // List-family layout. Shown only when `viewKind` is 'list'; its value - // becomes the list `config.type`. + // The list layout; its value becomes the list `config.type`. kind: { type: 'string', title: 'List layout', enum: ['grid', 'kanban', 'gallery', 'calendar', 'timeline', 'gantt', 'chart'], default: 'grid', description: 'Pick a starter layout. Switch later in the designer.', - visibleWhen: "data.viewKind == 'list'", - }, - // Form-family layout (FormViewSchema.type). Shown only when `viewKind` - // is 'form'; its value becomes the form `config.type`. The spec's three - // layouts only: `split`, `drawer` and `modal` left the enum in - // `@objectstack/spec` 18.3.0 (where a form opens is the caller's choice), - // so offering them here would build a body the server refuses. - formType: { - type: 'string', - title: 'Form layout', - enum: ['simple', 'tabbed', 'wizard'], - default: 'simple', - description: 'Pick a starter form layout. Switch later in the designer.', - visibleWhen: "data.viewKind == 'form'", }, }, }, // Emit a canonical ViewItem. `name` is the globally-unique qualified id - // `.`; `viewKind` discriminates the config shape. A list view - // carries the chosen list layout (grid/kanban/…) at `config.type`; a form - // view carries the chosen form layout (simple/tabbed/…) at `config.type` - // with a `sections` body instead of `columns`. + // `.`, and `viewKind` is `list`, the one family a view item + // has (ADR-0159 D7). It carries the chosen list layout (grid/kanban/…) at + // `config.type`. createBuildBody: (draft) => { const object = String(draft.object ?? ''); const key = String(draft.name ?? ''); const qualifiedName = key.includes('.') || !object ? key : `${object}.${key}`; - const isForm = draft.viewKind === 'form'; - const formType = (draft.formType as string) || 'simple'; - const config = isForm - ? { - type: formType, - data: { provider: 'object', object }, - // A `type: 'wizard'` form view must declare its steps: the spec - // refuses absent/EMPTY `sections` on the wizard variant at parse - // (objectstack#13622 D7, ruled 2026-08-31 — before that refusal - // the shape silently rendered as a plain simple form). Seed one - // starter step so a create→save that never opens the designer - // can't 422 once the platform runs a spec carrying the refusal — - // the same seed-the-required-shape move the flow anchor makes for - // its `type` enum (objectui#2326). Other form types keep the bare - // `[]`: only the wizard variant refuses emptiness, and seeding - // where nothing demands it would put fabricated structure into - // every authored view. - sections: - formType === 'wizard' ? [{ label: 'Step 1', fields: [] }] : [], - } - : { - type: (draft.kind as string) || 'grid', - columns: [], - data: { provider: 'object', object }, - }; return { name: qualifiedName, object, - viewKind: isForm ? 'form' : 'list', + viewKind: 'list', label: draft.label, - config, + config: { + type: (draft.kind as string) || 'grid', + columns: [], + data: { provider: 'object', object }, + }, }; }, }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.ts b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.ts index 2f28b04c7b7..f5c12612069 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.ts @@ -94,7 +94,7 @@ type SchemaLoader = (mode: DraftMode) => Promise; * "object has-many view"). This is what this admin AUTHORS: see `anchors.ts` * `createBuildBody` and the `view-create-body.test.ts` guard. * - **Container** (`ViewSchema`) — the aggregated - * `{ name, label, object, list, form, listViews, formViews }`, still served + * `{ name, label, object, list, listViews }`, still served * for records that were never expanded into ViewItems. * * This validator used to name only the container. That looked harmless because @@ -180,18 +180,21 @@ function viewSchemaForDraft(item: ZodLikeSchema, container: ZodLikeSchema): ZodL * issues / deepest path" was measured and picks wrong: for a container carrying * an unknown key, the ViewItem group reports a deeper `viewKind` discriminator * error that is the wrong message entirely. We show ONLY the selected member's - * issues; showing all four would put "this is not a container" in front of - * someone editing a ViewItem. + * issues; showing every member's would put "this is not a container" in front + * of someone editing a ViewItem. * - * Measured member layout of `ViewMetadataSchema`'s union (@objectstack/spec - * 17.0.0-rc.5): + * Member layout of `ViewMetadataSchema`'s union, as `@objectstack/spec`'s + * `VIEW_METADATA_BRANCHES` declares it: * * [0] `ViewItemWireSchema` — the stored ViewItem record (itself a * discriminated union on `viewKind`; a valid discriminator resolves * straight through, so its issues arrive flat and field-addressed). * [1] the aggregated container — same shape as the exported `ViewSchema`. * [2] flattened list-view overlay. - * [3] flattened form-view overlay. + * + * The flattened form-view overlay left the union with the form family in + * `@objectstack/spec` 19 (ADR-0159 D7): a body that names `viewKind: 'form'` + * is refused at `viewKind`, on both gates. * * This indexes members POSITIONALLY, which couples to a spec-internal detail. * That coupling is deliberate and it is guarded, not hoped for: reading the diff --git a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.viewDiagnostics.test.ts b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.viewDiagnostics.test.ts index b62e4932594..f88f43b808f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.viewDiagnostics.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.viewDiagnostics.test.ts @@ -26,6 +26,12 @@ */ import { describe, it, expect } from 'vitest'; +// `clientValidation` reaches `celAuthoring`'s dynamic `@objectstack/formula`, +// `@objectstack/lint` and `@object-ui/core` imports; their first load is paid +// here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; +import '@object-ui/core'; import { validateMetadataDraft } from './clientValidation'; const EDIT = { mode: 'edit' } as const; @@ -701,22 +707,40 @@ describe('view nested union — the sole-candidate rule (objectui#3678)', () => }); it('descends more than one level when each level has a sole candidate', async () => { - // `sections[].fields[]` is `string | FormField`. This is the reach #3678's - // own scope paragraph did not expect: it read this union as rejecting - // wholesale, which it does for a scalar element but not for an object one. - const issues = await bothGates({ - ...AUTHORABLE_ITEM, - viewKind: 'form', - config: { type: 'simple', sections: [{ fields: [{}] }] }, - }); + // `gantt.tooltipFields` is `string[] | { field, … }[]`, a union whose + // object member holds a second one. This is the reach #3678's own scope + // paragraph did not expect: it read such a union as rejecting wholesale, + // which it does for a scalar element but not for an object one. + // + // The vehicle was a form view's `sections[].fields[]` (`string | FormField`) + // until `@objectstack/spec` 19 retired the form family from `view` + // (ADR-0159 D7); the last case of this `describe` pins what that body + // answers now. + const issues = await bothGates( + withConfig({ + type: 'gantt', + gantt: { startDateField: 'start', endDateField: 'end', titleField: 'name', tooltipFields: [{}] }, + }), + ); expect(issues).toEqual([ { - path: 'config.sections.0.fields.0.field', + path: 'config.gantt.tooltipFields.0.field', message: 'Invalid input: expected string, received undefined', }, ]); }); + it('a `viewKind: \'form\'` body is refused at `viewKind` on both gates, before any of its sections is read', async () => { + // The retired vehicle of the case above. The family is a tombstone, so the + // one issue is the family's and nothing under `config.sections` is judged. + const issues = await bothGates({ + ...AUTHORABLE_ITEM, + viewKind: 'form', + config: { type: 'simple', sections: [{ fields: [{}] }] }, + }); + expect(issues.map((i) => i.path)).toEqual(['viewKind']); + }); + // ── MAINTAINED: the cells this rule must stay out of ───────────────────── it('k === 0 — every member rejected the type, so the collapse is kept', async () => { @@ -871,10 +895,13 @@ describe('view verdict parity — sole-candidate bodies (objectui#3678)', () => * the input's type, so an enum member handed an object is counted as a * candidate even though it never looked inside either. * - * Measured over 51 shapes, the whole `view` family produces `invalid_value` at + * Measured over 51 shapes, the whole `view` family produced `invalid_value` at * a member's own root at exactly TWO union sites — `columns[].summary` - * (`enum | {type, field}`) and `sections[].columns` (`enum | 1 | 2 | 3 | 4`) — - * and re-qualifying it is a TRADE on the first of them, not an improvement: + * (`enum | {type, field}`) and `sections[].columns` (`enum | 1 | 2 | 3 | 4`). + * The second left `view` with the form family in `@objectstack/spec` 19 + * (ADR-0159 D7; its case below pins the `viewKind` refusal that replaced it), + * so the first is the one site a view has. Re-qualifying the predicate is a + * TRADE on that first site, not an improvement: * the object-valued shapes gain a named `…summary.type`, the scalar-valued * shapes lose the enum's option list and collapse to `Invalid input`. #3694 * therefore changed no behaviour. This block is the measurement made durable. @@ -987,22 +1014,24 @@ describe('view nested union — the `invalid_value` qualification, measured (obj // ── The OTHER `invalid_value` site, and why it never moves ─────────────── - it('`sections[].columns` — all five members answer `invalid_value`, and no cell claims it either way', async () => { - // `enum('1'|'2'|'3'|'4') | 1 | 2 | 3 | 4`. Every member rejects the value - // as a whole, so today k=5 (the content rule's cell, which declines a - // five-member union) and under a widened predicate k=0 (the empty cell). - // Different cell, same silence — which is why the second `invalid_value` - // site contributes nothing to the trade above. Measured, not assumed. + it('`sections[].columns` left the view with the form family: its body is refused at `viewKind`, whatever the value', async () => { + // `enum('1'|'2'|'3'|'4') | 1 | 2 | 3 | 4` was the second `invalid_value` + // site under a view: every member rejected the value as a whole, so k=5 + // (the content rule's cell, which declines a five-member union) and under + // a widened predicate k=0 (the empty cell). Different cell, same silence. + // + // `@objectstack/spec` 19 retired the form family from `view` (ADR-0159 + // D7), so no view body reaches that union: the family is refused first, + // and the one issue is at `viewKind` for every value. The union lives on + // under the `form` type, which this gate does not judge here. for (const value of ['bogus', 7, {}, null]) { const label = JSON.stringify(value); - expect( - await bothGates({ - ...AUTHORABLE_ITEM, - viewKind: 'form', - config: { type: 'simple', sections: [{ fields: ['a'], columns: value }] }, - }), - label, - ).toEqual([{ path: 'config.sections.0.columns', message: 'Invalid input' }]); + const issues = await bothGates({ + ...AUTHORABLE_ITEM, + viewKind: 'form', + config: { type: 'simple', sections: [{ fields: ['a'], columns: value }] }, + }); + expect(issues.map((i) => i.path), label).toEqual(['viewKind']); } }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.viewShapes.test.ts b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.viewShapes.test.ts index 647fea52f30..b182d800b3f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/clientValidation.viewShapes.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/clientValidation.viewShapes.test.ts @@ -6,8 +6,8 @@ * * `@objectstack/spec/ui` exports both `ViewItemSchema` (the first-class * per-view record this admin authors — `{ name, object, viewKind, config }`, - * ADR-0017) and `ViewSchema` (the aggregated container — `{ list, form, - * listViews, formViews }`), and the backend serves both. + * ADR-0017) and `ViewSchema` (the aggregated container — `{ list, + * listViews }` since spec 19, ADR-0159 D7), and the backend serves both. * * The validator used to name only the container. That looked fine because the * container was non-strict: a ViewItem's `viewKind` / `config` were silently @@ -22,6 +22,12 @@ */ import { describe, it, expect } from 'vitest'; +// `clientValidation` reaches `celAuthoring`'s dynamic `@objectstack/formula`, +// `@objectstack/lint` and `@object-ui/core` imports; their first load is paid +// here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; +import '@object-ui/core'; import { validateMetadataDraft } from './clientValidation'; /** What `anchors.ts`'s `createBuildBody` emits for a default list view. */ diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.containerLabel-11027.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.containerLabel-11027.test.tsx index a81818a04cb..09332103e92 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.containerLabel-11027.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.containerLabel-11027.test.tsx @@ -14,8 +14,9 @@ * source. The readings are the rendered DOM. * * The cases: - * - authored: the label is the preview's heading, on the list and the form - * route alike; + * - authored: the label is the preview's heading. A draft that names the + * retired form family (ADR-0159 D7) has no route of its own: its label is + * the same heading on the one route there is; * - absent: no heading is drawn, and nothing stands in for the label (the * heading set is the authored one minus the label); * - locale map: the label resolves in the designer `locale`, never as @@ -110,7 +111,7 @@ describe('ViewPreview shows the view label as its heading (objectui#11027)', () expect(document.body.textContent).not.toContain('[object Object]'); }); - it('renders the label on the form route too', () => { + it('renders the label of a draft that names the retired form family too: there is one route', () => { render( , editing = false): Promise { +/** Let every effect a mounted form would run settle, so "never drawn" is a reading. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 50)); + +/** Mount the canvas for `draft` and return its container once effects have settled. */ +async function renderCanvas(draft: Record, editing = false): Promise { const { container } = render( , ); - let item: HTMLElement | null = null; - await waitFor(() => { - item = container.querySelector('[data-field="title"]'); - expect(item).not.toBeNull(); - }); - return item!; + await settle(); + return container; } -/** The renderer's horizontal arrangement (`HORIZONTAL_FIELD_ITEM_CLASS`). */ -const isHorizontal = (item: HTMLElement) => - item.classList.contains('sm:grid') && item.classList.contains('sm:grid-cols-[minmax(0,10rem)_minmax(0,1fr)]'); +/** No form is on the canvas: no field item of the form renderer, and no form element. */ +function expectNoForm(container: HTMLElement) { + expect(container.querySelector('[data-field="title"]')).toBeNull(); + expect(container.querySelector('[data-field="status"]')).toBeNull(); + expect(container.querySelector('form')).toBeNull(); +} -describe('objectstack#29676 — the form view canvas honours layout', () => { - it('horizontal: the field item draws the label column beside its control (Run)', async () => { - const item = await renderItem(formView('horizontal')); - expect(isHorizontal(item)).toBe(true); - // The label is still the item's own, the one the vertical item carries. - expect(item.querySelector('label')).toHaveTextContent('Title'); +describe('objectstack#29676 at spec 19 — the view canvas draws no form, whatever layout the draft names', () => { + it('horizontal: no form field item is drawn (Run)', async () => { + expectNoForm(await renderCanvas(formView('horizontal'))); }); it('horizontal: the same in Design, which renders through the same route', async () => { - const item = await renderItem(formView('horizontal'), true); - expect(isHorizontal(item)).toBe(true); + expectNoForm(await renderCanvas(formView('horizontal'), true)); }); - it('horizontal reaches a tabbed view too (its layout reads the same key)', async () => { - const item = await renderItem(formView('horizontal', 'tabbed')); - expect(isHorizontal(item)).toBe(true); + it('horizontal on a tabbed draft: no form field item, and no tab', async () => { + expectNoForm(await renderCanvas(formView('horizontal', 'tabbed'))); + expect(screen.queryByRole('tab', { name: 'Overview' })).toBeNull(); }); - it('CONTROL: vertical draws the stacked item it always drew', async () => { - const item = await renderItem(formView('vertical')); - expect(isHorizontal(item)).toBe(false); - expect(item.className).not.toContain('sm:grid'); + it('vertical: no form field item is drawn', async () => { + expectNoForm(await renderCanvas(formView('vertical'))); }); - it('CONTROL: no layout draws the stacked item it always drew', async () => { - const item = await renderItem(formView()); - expect(isHorizontal(item)).toBe(false); - expect(item.className).not.toContain('sm:grid'); + it('no layout: no form field item is drawn', async () => { + expectNoForm(await renderCanvas(formView())); }); -}); - -describe('objectstack#29676 — the canvas schema carries the form view keys ObjectForm reads', () => { - const build = (config: Record) => buildFormPreviewSchema('task', config, 'en-US'); - it('layout: the console hosts\' mapping (resolveFormViewChrome), horizontal kept', () => { - expect(build({ type: 'simple', layout: 'horizontal' }).layout).toBe('horizontal'); - expect(build({ type: 'simple', layout: 'vertical' }).layout).toBe('vertical'); - // Unset reads the renderer default, as on the record page. - expect(build({ type: 'simple' }).layout).toBe('vertical'); - }); - - it('columns, defaultTab, tabPosition, allowSkip and showStepIndicator reach the schema as authored', () => { - const schema = build({ - type: 'tabbed', - columns: 3, - defaultTab: 'details', - tabPosition: 'left', - allowSkip: true, - showStepIndicator: false, - }); - expect(schema).toMatchObject({ - type: 'object-form', - formType: 'tabbed', - columns: 3, - defaultTab: 'details', - tabPosition: 'left', - allowSkip: true, - showStepIndicator: false, - }); + it('the draft\'s own label is still the canvas heading: the one route draws it', async () => { + await renderCanvas(formView('horizontal')); + expect(screen.getByRole('heading', { name: 'Task intake' })).toBeInTheDocument(); }); +}); - it('CONTROL: unauthored keys stay unset, and the canvas still draws no submit or cancel', () => { - const schema = build({ type: 'simple' }); - for (const key of ['columns', 'defaultTab', 'tabPosition', 'allowSkip', 'showStepIndicator']) { - expect(schema[key]).toBeUndefined(); - } - expect(schema).toMatchObject({ showSubmit: false, showCancel: false, mode: 'create' }); +describe('objectstack#29676 at spec 19 — the module builds no form canvas schema', () => { + it('exports no form schema builder: the canvas is the list one', () => { + expect(Object.keys(ViewPreviewModule)).not.toContain('buildFormPreviewSchema'); + expect(Object.keys(ViewPreviewModule).sort()).toEqual(['ViewPreview', 'resolveObjectName']); }); - it('defaultTab opens the authored tab on the drawn tabbed form', async () => { + it('a tabbed draft with `defaultTab` draws no tab strip of its sections', async () => { const draft = { ...formView(undefined, 'tabbed'), config: { type: 'tabbed', defaultTab: 'details', + columns: 3, + tabPosition: 'left', sections: [ { name: 'overview', label: 'Overview', fields: ['title'] }, { name: 'details', label: 'Details', fields: ['status'] }, ], }, }; - render( - - - , - ); - const details = await screen.findByRole('tab', { name: 'Details' }); - expect(details).toHaveAttribute('aria-selected', 'true'); - expect(screen.getByRole('tab', { name: 'Overview' })).toHaveAttribute('aria-selected', 'false'); + const container = await renderCanvas(draft); + expectNoForm(container); + expect(screen.queryByRole('tab', { name: 'Details' })).toBeNull(); + expect(screen.queryByRole('tab', { name: 'Overview' })).toBeNull(); + }); + + it('CONTROL: the `object-form` renderer is registered here, so a form route would have drawn', () => { + expect(ComponentRegistry.get('object-form')).toBeTruthy(); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.formWarnings-29311.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.formWarnings-29311.test.tsx index 322cf1b581e..e1de998c605 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.formWarnings-29311.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.formWarnings-29311.test.tsx @@ -1,26 +1,26 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#29311 — the Studio form view canvas shows the view's served - * warnings at the section they point into. + * objectstack#29311, at the `@objectstack/spec` 19 answer (ADR-0159 D7) — the + * Studio view canvas has no form warnings block. * - * Since objectstack#29196 the view read adds the lint's `form-field-unknown` - * finding to `_diagnostics.warnings` (`{ path, message }`, the path - * item-relative: `config.sections.0.fields.1`). The editors hand a canvas its - * verdict through the preview contract's `diagnostics`; `ViewPreview`'s form - * route ignored it, so an author designing a form never saw that a section - * names a field its object lacks. + * Until spec 19 a `view` item could be a form, the view read added the lint's + * `form-field-unknown` finding to `_diagnostics.warnings` (objectstack#29196, + * `{ path, message }`, the path item-relative: `config.sections.0.fields.1`), + * and `ViewPreview`'s form route showed each at the section it points into. + * A view is a list now: a form is a `form` item with its own editor, and no + * `view` read serves a form row or a warning into a form section. * - * The cases: - * - a warning into a section is shown with that section's authored label - * and the server's message as served, under the existing warn-block - * heading; - * - a section with no label is named by its `name`; a path into no section - * is shown as the server wrote it; + * The first `describe` keeps #29311's cases as what the canvas answers for a + * draft that still names the retired family: + * - there is no `view-form-warnings` block, whatever is handed in; + * - a served warning is still said, in the one warn block the canvas has, + * with the server's message as served and its path as the server wrote it + * (no section is looked up); * - no warnings (an empty list, or none passed) draws no block; * - errors are not this block's: an error-only list draws none. * - * objectstack#31938 — the list branch (the last `describe`): since + * objectstack#31938 — the list canvas (the last `describe`): since * objectstack#31866 the read adds `list-view-field-unknown` for a column naming * a field its object lacks (`config.columns.1.field`). The list canvas drew * none of it, and its own query was refused for that column. The block now @@ -42,7 +42,7 @@ import type { MetadataPreviewProps } from '../preview-registry'; afterEach(cleanup); -/** A stub adapter: the form route asks for the object, nothing else. */ +/** A stub adapter: the members the canvas calls, not the whole `DataSource` surface. */ function createDataSource(): DataSource { return { find: vi.fn(async () => ({ data: [], total: 0 })), @@ -54,10 +54,11 @@ function createDataSource(): DataSource { } as unknown as DataSource; } -/** The lint's wording, as the server serves it (objectstack#29196). */ +/** The lint's wording, as the server served it on a form row (objectstack#29196). */ const MESSAGE = 'task.form: field "no_such_field" is not a field on object "task" — it is silently skipped and never renders on the form'; +/** A draft naming the retired form family: no `view` read serves one since spec 19. */ const formView = { name: 'task.form', object: 'task', @@ -74,51 +75,60 @@ const formView = { function renderForm(diagnostics: MetadataPreviewProps['diagnostics']) { render( - + new Response(null, { status: 501 }))}> , ); } -const items = () => screen.queryAllByTestId('view-form-warning'); +/** The retired block's rows, and the rows of the one block the canvas has. */ +const formItems = () => screen.queryAllByTestId('view-form-warning'); +const items = () => screen.queryAllByTestId('view-list-warning'); -describe('objectstack#29311 — the form view canvas shows its served warnings', () => { - it('a warning into a section names the section by its label, with the server message as served', () => { +describe('objectstack#29311 at spec 19 — the view canvas has no form warnings block', () => { + it('a warning into a section draws no form block; it is said as served, at the path as written', () => { renderForm([{ path: 'config.sections.0.fields.1', message: MESSAGE, severity: 'warning' }]); - const block = screen.getByTestId('view-form-warnings'); + expect(screen.queryByTestId('view-form-warnings')).toBeNull(); + expect(formItems()).toHaveLength(0); + const block = screen.getByTestId('view-list-warnings'); expect(block).toHaveTextContent('1 warning(s)'); expect(items()).toHaveLength(1); - expect(items()[0].textContent).toBe(`Overview: ${MESSAGE}`); + // No section is looked up: the place is the server's path, not `Overview`. + expect(items()[0].textContent).toBe(`config.sections.0.fields.1: ${MESSAGE}`); expect(items()[0].getAttribute('data-path')).toBe('config.sections.0.fields.1'); }); - it('a label-less section is named by its name; a path into no section is shown as written', () => { + it('no section is named by its label or its name; every path is shown as written', () => { renderForm([ { path: 'config.sections.1.fields.0', message: 'second', severity: 'warning' }, { path: 'config.type', message: 'third', severity: 'warning' }, ]); - expect(items().map((li) => li.textContent)).toEqual(['details: second', 'config.type: third']); + expect(screen.queryByTestId('view-form-warnings')).toBeNull(); + expect(items().map((li) => li.textContent)).toEqual(['config.sections.1.fields.0: second', 'config.type: third']); }); it('no warnings, no block: an empty list and an absent one alike', () => { renderForm([]); expect(screen.queryByTestId('view-form-warnings')).toBeNull(); + expect(screen.queryByTestId('view-list-warnings')).toBeNull(); cleanup(); renderForm(undefined); expect(screen.queryByTestId('view-form-warnings')).toBeNull(); - // The form route itself is up: its heading is drawn. + expect(screen.queryByTestId('view-list-warnings')).toBeNull(); + // The canvas itself is up: its heading is drawn. expect(screen.getByRole('heading', { name: 'Task intake' })).toBeTruthy(); }); it('errors are not this block\'s: an error-only list draws none', () => { renderForm([{ path: 'config.sections.0', message: 'refused', severity: 'error' }]); expect(screen.queryByTestId('view-form-warnings')).toBeNull(); + expect(screen.queryByTestId('view-list-warnings')).toBeNull(); }); }); // --------------------------------------------------------------------------- -// objectstack#31938 — the list branch +// objectstack#31938 — the list canvas // --------------------------------------------------------------------------- /** The card's object: it declares `total_cost`; the shipped view names `cost_total`. */ diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.tsx index c3d350ec9a7..44cc32a5ecb 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/ViewPreview.tsx @@ -6,17 +6,15 @@ * `config` body injected as a named `listView` so the preview reflects the * unsaved edit (not the last saved version). * - * A view is the canonical first-class **ViewItem** ({ viewKind, config }): + * A view is the canonical first-class **ViewItem** ({ viewKind: 'list', config }): * one view, one `config` body — there are no in-document variant tabs. An * object's *other* views are independent ViewItems surfaced by the view * switcher (a query), not nested here. * - * The render path forks on `viewKind`: - * - list-family (grid / kanban / calendar / …) → `object-view`, with the - * draft body injected as a named listView (below); - * - form-family (simple / drawer / …) → `object-form`, with the draft's - * sections mapped onto the form schema (a form view binds a record layout, - * not a list, so the list renderer would just fall back to a bare grid). + * A view is a list (grid / kanban / calendar / …), drawn by `object-view` with + * the draft body injected as a named listView (below). `@objectstack/spec` 19 + * retired the form family (ADR-0159 D7): a form is a `form` item, which has + * its own editor and canvas, and this preview draws none. * * A raw single-schema draft (a bare `{ type, … }` with no `config` wrapper, * e.g. an ad-hoc preview) is rendered straight through SchemaRenderer. @@ -33,13 +31,11 @@ import * as React from 'react'; import { SchemaRenderer, PreviewModeProvider } from '@object-ui/react'; import { resolveI18nLabel } from '@objectstack/spec/ui'; -import { toInlineFormType } from './form-preview.js'; import type { MetadataPreviewProps } from '../preview-registry.js'; import { PreviewShell, PreviewErrorBoundary, PreviewMessage } from './PreviewShell.js'; import { primaryVariantBinding } from '../view-variant-model.js'; import { t as tr, tFormat } from '../i18n.js'; import { withNodes } from './row-nodes.js'; -import { resolveFormViewChrome, type FormViewDefinition } from '../../../utils/recordFormNavigation.js'; /** * The object a stored `view` draft is bound to, read under the spellings the @@ -66,72 +62,6 @@ export function resolveObjectName( return undefined; } -// A ViewItem form section uses the spec's `{ field, readonly, … }` shape, but -// `object-form` selects fields by `name` and reads `readOnly`. Normalize so the -// section's fields resolve (otherwise every section comes up empty). -function toFormFieldEntry(f: unknown): string | Record { - if (typeof f === 'string') return f; - if (f && typeof f === 'object') { - const o = f as Record; - const name = (o.field ?? o.name) as string | undefined; - if (!name) return o; - return { ...o, name, readOnly: o.readOnly ?? o.readonly }; - } - return String(f); -} - -/** - * The `object-form` schema the form view canvas renders from a form view's - * `config` body: Studio Design and Run both draw through it. Exported for its - * pin (objectstack#29676); no other module reads it. - */ -export function buildFormPreviewSchema( - objectName: string, - body: Record, - locale: string | undefined, -): Record { - const rawType = typeof body.type === 'string' ? body.type : 'simple'; - const formType = toInlineFormType(rawType); - const sections = Array.isArray(body.sections) - ? (body.sections as any[]).map((s) => ({ - ...s, - fields: Array.isArray(s?.fields) ? s.fields.map(toFormFieldEntry) : [], - })) - : undefined; - return { - type: 'object-form', - objectName, - // A blank create-mode form: the preview shows the layout without needing a - // sample record to be selected. - mode: 'create', - formType, - sections, - fields: Array.isArray(body.fields) ? body.fields : undefined, - // objectstack#29676 — the form view's keys `ObjectForm` and its layouts - // read, which this canvas dropped, so Studio Design and Run drew a view - // otherwise than the console does. `layout` (the label above or beside its - // control) goes through the console form hosts' own mapping, - // `resolveFormViewChrome`, so the canvas and the runtime read it one way; - // only its layout is taken, as the canvas draws no submit / cancel and - // seeds no create values. The rest are read as the record page reads - // them: `columns` by the field grid, `defaultTab` / `tabPosition` by the - // tabbed layout, `allowSkip` / `showStepIndicator` by the wizard. - layout: resolveFormViewChrome(body as FormViewDefinition, { - flow: 'create', - language: locale ?? 'en', - submitText: '', - cancelText: '', - }).layout, - columns: body.columns, - defaultTab: body.defaultTab, - tabPosition: body.tabPosition, - allowSkip: body.allowSkip, - showStepIndicator: body.showStepIndicator, - showSubmit: false, - showCancel: false, - }; -} - /** * objectstack#31938 — the item-relative path of a served warning ON a list * column, the entry itself or its `field`: what the read's @@ -143,30 +73,20 @@ export function buildFormPreviewSchema( const LIST_COLUMN_WARNING_PATH = /^config\.columns\.(\d+)(?:\.field)?$/; /** - * objectstack#29311 — where a served warning on a view points, said with the + * objectstack#31938 — where a served warning on a view points, said with the * author's own text. The path is the item-relative one the server writes; * `body` is the item's `config`. * - * - Into a form section (`config.sections.0.fields.1`): the section's `label` - * (resolved in the designer `locale`), else its `name`. - * - objectstack#31938 — onto a list column ({@link LIST_COLUMN_WARNING_PATH}): - * the column's `label`, else the field it names; a bare-string column is - * its field name. + * Onto a list column ({@link LIST_COLUMN_WARNING_PATH}): the column's `label`, + * else the field it names; a bare-string column is its field name. * - * A path into neither is shown as the server wrote it, and an absent one + * A path onto no column is shown as the server wrote it, and an absent one * names nothing. */ function warningPlace(path: string | undefined, body: Record, locale: string | undefined): string | undefined { if (!path) return undefined; const column = LIST_COLUMN_WARNING_PATH.exec(path); - if (column) return columnPlace(body, Number(column[1]), locale) ?? path; - const at = /^config\.sections\.(\d+)(?:\.|$)/.exec(path); - const section = at && Array.isArray(body.sections) ? (body.sections as unknown[])[Number(at[1])] : undefined; - if (!section || typeof section !== 'object') return path; - const s = section as { label?: Parameters[0]; name?: unknown }; - const label = resolveI18nLabel(s.label, locale); - if (label && label.trim()) return label; - return typeof s.name === 'string' && s.name ? s.name : path; + return column ? columnPlace(body, Number(column[1]), locale) ?? path : path; } /** The column at `index` in a list view body, named as {@link warningPlace} says. */ @@ -193,22 +113,19 @@ function holdsListCanvas(diagnostics: MetadataPreviewProps['diagnostics']): bool } /** - * objectstack#29311 — a view's served warnings, each at the place it points - * into ({@link warningPlace}), in the canvas's existing warn block: a form - * view's `form-field-unknown` at its sections, and (objectstack#31938) a list + * objectstack#31938 — a view's served warnings, each at the place it points + * into ({@link warningPlace}), in the canvas's existing warn block: a list * view's `list-view-field-unknown` at its columns. The message is the * server's, as served. Errors are not this block's: the editor that holds the * verdict says those. Nothing is drawn when there are none. `held` adds the * line saying the list preview waits for the columns to be fixed. */ function ViewWarnings({ - kind, diagnostics, body, locale, held = false, }: { - kind: 'form' | 'list'; diagnostics: MetadataPreviewProps['diagnostics']; body: Record; locale: string | undefined; @@ -218,7 +135,7 @@ function ViewWarnings({ if (warnings.length === 0) return null; return ( -
+
{tFormat('engine.edit.diagnostics.warnTitle', locale, { count: warnings.length })}
@@ -226,7 +143,7 @@ function ViewWarnings({ {warnings.map((w, i) => { const place = warningPlace(w.path, body, locale); return ( -
  • +
  • {place && {place}: } {w.message}
  • @@ -292,7 +209,7 @@ export function ViewPreview({ name, draft, editing, locale, diagnostics }: Metad // Hoisted above the early returns below so this hook runs on every render // (hook order must stay stable). Only the final `object-view` branch reads it; - // the earlier branches shadow it with their own local `schema`/`formSchema`. + // the raw-schema branch shadows it with its own local `schema`. const schema = React.useMemo( () => ({ type: 'object-view', @@ -339,27 +256,6 @@ export function ViewPreview({ name, draft, editing, locale, diagnostics }: Metad ); } - // ------------------------------------------------------------------------- - // Form-family view (`viewKind: 'form'`): render the record form layout via - // `object-form`. The list renderer (`object-view`) has no form layout, so a - // form view routed through it just falls back to a bare grid. - // ------------------------------------------------------------------------- - if ((draft as any).viewKind === 'form' && body) { - const rawType = String((body as any).type ?? 'simple'); - const formSchema = buildFormPreviewSchema(objectName, body as Record, locale); - return ( - - - } locale={locale} /> - -
    - -
    -
    -
    - ); - } - // ------------------------------------------------------------------------- // Delegate to `object-view` — the same renderer the runtime route uses — // with the draft body injected so the preview reflects unsaved edits. @@ -372,7 +268,7 @@ export function ViewPreview({ name, draft, editing, locale, diagnostics }: Metad {body && ( - } locale={locale} held={held} /> + } locale={locale} held={held} /> )} {!held && ( diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/dataPreviews.i18n-10862-s3.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/dataPreviews.i18n-10862-s3.test.tsx index 94ed5ec7028..d19100b7171 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/dataPreviews.i18n-10862-s3.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/dataPreviews.i18n-10862-s3.test.tsx @@ -398,12 +398,15 @@ describe('ViewPreview reads the designer locale (objectui#10862)', () => { expectEqual('the code span', document.body.querySelector('code')?.textContent, field); }); - pin(`${lang}: the three error-boundary hints (raw schema, form view, list view)`, async () => { + // A view is a list since `@objectstack/spec` 19 (ADR-0159 D7): the preview + // has no form route, so a draft that names the retired family reads the + // list hint. `engine.viewPreview.formFailed` is drawn by no branch. + pin(`${lang}: the two error-boundary hints (raw schema, list view); a draft naming the retired form family reads the list one`, async () => { quietBoundary(); state.schema = 'throw'; const drafts: Array<[Record, string]> = [ [{ name: 'raw', type: 'x_widget' }, 'engine.viewPreview.schemaFailed'], - [{ name: 'intake', viewKind: 'form', config: { type: 'simple', object: 'account' } }, 'engine.viewPreview.formFailed'], + [{ name: 'intake', viewKind: 'form', config: { type: 'simple', object: 'account' } }, 'engine.viewPreview.listFailed'], [{ name: 'all', config: { type: 'grid', object: 'account' } }, 'engine.viewPreview.listFailed'], ]; for (const [draft, key] of drafts) { diff --git a/ui/packages/app-shell/src/views/metadata-admin/registry.ts b/ui/packages/app-shell/src/views/metadata-admin/registry.ts index 2c755bbc1b2..bacd59e030c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/registry.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/registry.ts @@ -285,9 +285,6 @@ export interface MetadataResourceConfig { * AND after every save-refresh, so the editor always sees the canonical * draft shape. Must be a pure function and a no-op for shapes it does * not recognise. Pair with {@link fromDraft} for the save round-trip. - * - * Example: `view` unwraps an expanded ViewItem's `config` into the - * `{ list | form }` family key the View inspector reads. */ toDraft?: (item: Record) => Record; @@ -307,7 +304,7 @@ export interface MetadataResourceConfig { * just describes the simplified create-time input. * * Use this for wrapper types like `view` whose top-level schema has - * no flat identity fields (only `{list,form,listViews,formViews}`): + * no flat identity fields (only `{list,listViews}`): * a `createSchema` lets us ask for `{name,label,object}` up front, * then `createBuildBody` wraps them into the right nested shape. */ diff --git a/ui/packages/app-shell/src/views/metadata-admin/view-create-body.test.ts b/ui/packages/app-shell/src/views/metadata-admin/view-create-body.test.ts index fba9572d9fb..5bbd47a81fe 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/view-create-body.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/view-create-body.test.ts @@ -8,16 +8,23 @@ // View create-body conformance (objectui#2323). // -// `ViewItemSchema` is a discriminated union on `viewKind` with both a `list` -// and a `form` variant. The create form must be able to produce BOTH families, -// and each build output must validate against the REAL spec `ViewItemSchema` -// (not the lenient aggregated container the client validator strips through). +// A view item is a list: `@objectstack/spec` 19 retired the form family +// (ADR-0159 D7), so `ViewItemSchema` has the one `list` member and a form is a +// `form` item with its own create door. The create form builds a list, and +// each build output must validate against the REAL spec `ViewItemSchema` (not +// the lenient aggregated container the client validator strips through). // -// Regression guard: `createBuildBody` used to hardcode `viewKind: 'list'` and -// route the draft `kind` straight into `config.type`, so form-family views were -// unreachable through the create UI. +// History: until spec 19 `ViewItemSchema` was a discriminated union with a +// `form` variant too, and this file pinned that the create form could build +// both families. The pins below are the same cases at the 19 answer: a draft +// that still names the retired family builds a list, and the spec refuses a +// `viewKind: 'form'` item. import { describe, it, expect } from 'vitest'; +// The anchors reach a dynamic `@object-ui/plugin-detail` import; its first +// load is paid here, at collection, never inside a case's clock +// (`check:test-source-alias`). +import '@object-ui/plugin-detail'; import { ViewItemSchema } from '@objectstack/spec/ui'; import { registerBuiltinAnchors } from './anchors'; import { getMetadataResource } from './registry'; @@ -44,8 +51,8 @@ function expectSpecValid(body: unknown) { ).toBe(true); } -describe('view createBuildBody — ViewItem family discrimination (objectui#2323)', () => { - it('defaults to a spec-valid list-family ViewItem when viewKind is unset', () => { +describe('view createBuildBody — a view item is a list (objectui#2323, ADR-0159 D7)', () => { + it('defaults to a spec-valid list ViewItem when the layout is unset', () => { const body = build({ label: 'All Leads', name: 'all_leads', object: 'crm_lead' }); expect(body.viewKind).toBe('list'); expect((body.config as Record).type).toBe('grid'); @@ -68,7 +75,7 @@ describe('view createBuildBody — ViewItem family discrimination (objectui#2323 expectSpecValid(body); }); - it('builds a spec-valid form-family ViewItem carrying the chosen form layout', () => { + it('a draft that still names the retired form family builds a spec-valid list, not a form', () => { const body = build({ label: 'Intake', name: 'intake', @@ -76,91 +83,79 @@ describe('view createBuildBody — ViewItem family discrimination (objectui#2323 viewKind: 'form', formType: 'tabbed', }); - expect(body.viewKind).toBe('form'); + expect(body.viewKind).toBe('list'); const config = body.config as Record; - expect(config.type).toBe('tabbed'); - // Form views carry a `sections` body, never a list `columns` array. - expect(config).toHaveProperty('sections'); - expect(config).not.toHaveProperty('columns'); + // The draft's `formType` is not read: the list layout is `kind`, unset here. + expect(config.type).toBe('grid'); + // A list body: a `columns` array, never a form's `sections`. + expect(config).toHaveProperty('columns'); + expect(config).not.toHaveProperty('sections'); expect(config.data).toEqual({ provider: 'object', object: 'crm_lead' }); expectSpecValid(body); }); - it('defaults the form layout to `simple` when formType is unset', () => { - const body = build({ label: 'Detail', name: 'detail', object: 'crm_lead', viewKind: 'form' }); - expect(body.viewKind).toBe('form'); - expect((body.config as Record).type).toBe('simple'); - expectSpecValid(body); - }); - - it('accepts every form layout the spec enumerates', () => { - for (const formType of ['simple', 'tabbed', 'wizard']) { + it('no form layout reaches the body, whichever the draft names', () => { + for (const formType of ['simple', 'tabbed', 'wizard', 'split', 'drawer', 'modal']) { const body = build({ label: 'F', name: `f_${formType}`, object: 'crm_lead', viewKind: 'form', formType }); - expect((body.config as Record).type).toBe(formType); + expect(body.viewKind, formType).toBe('list'); + expect((body.config as Record).type, formType).toBe('grid'); + expect(body.config, formType).not.toHaveProperty('sections'); expectSpecValid(body); } }); - it('the retired form types are refused by the spec at config.type — why the picker no longer offers them', () => { - // `split`, `drawer` and `modal` left `FormViewSchema.type` in - // `@objectstack/spec` 18.3.0: where a form opens is the caller's choice. - for (const formType of ['split', 'drawer', 'modal']) { - const body = build({ label: 'F', name: `f_${formType}`, object: 'crm_lead', viewKind: 'form', formType }); - const res = ViewItemSchema.safeParse(body); - expect(res.success, formType).toBe(false); - expect(res.error?.issues.map((i) => i.path.join('.'))).toContain('config.type'); - } + it('the spec refuses a `viewKind: \'form\'` item at `viewKind` — why the create form no longer builds one', () => { + // The body this builder produced for a form draft until spec 19. + const formItem = { + name: 'crm_lead.intake', + object: 'crm_lead', + viewKind: 'form', + label: 'Intake', + config: { type: 'simple', sections: [], data: { provider: 'object', object: 'crm_lead' } }, + }; + const res = ViewItemSchema.safeParse(formItem); + expect(res.success).toBe(false); + expect(res.error?.issues.map((i) => i.path.join('.'))).toContain('viewKind'); + // The same item as a list is accepted: the family is what is refused. + expectSpecValid({ ...formItem, viewKind: 'list', config: { type: 'grid', columns: [], data: formItem.config.data } }); }); - it('seeds one starter step for a wizard create — and ONLY for wizard (objectui#6985)', () => { - // A `type: 'wizard'` form view must declare its steps: the spec refuses - // absent/empty `sections` on the wizard variant at parse (objectstack#13622 - // D7, ruled 2026-08-31). An empty-`sections` wizard body would 422 at - // create→save on a platform running a spec that carries the refusal — so - // the build seeds one starter step, exactly as the flow anchor seeds its - // required `type` enum (objectui#2326). + it('seeds no form structure for any draft: a wizard draft builds an empty list (objectui#6985)', () => { + // Until spec 19 a `formType: 'wizard'` create seeded one starter step, + // because the spec refuses a wizard with no steps (objectstack#13622 D7). + // A view create builds no form now, so there is nothing to seed. const wizard = build({ label: 'W', name: 'w', object: 'crm_lead', viewKind: 'form', formType: 'wizard' }); - const sections = (wizard.config as Record).sections as unknown[]; - expect(sections.length).toBeGreaterThanOrEqual(1); + expect(wizard.config).not.toHaveProperty('sections'); + expect((wizard.config as Record).columns).toEqual([]); expectSpecValid(wizard); - - // The boundary: only the wizard variant refuses emptiness, and fabricated - // structure must not leak into every authored view. A tabbed create keeps - // the bare `[]` it always had. - const tabbed = build({ label: 'T', name: 't', object: 'crm_lead', viewKind: 'form', formType: 'tabbed' }); - expect((tabbed.config as Record).sections).toEqual([]); - expectSpecValid(tabbed); }); - it('qualifies the view name to . for both families', () => { + it('qualifies the view name to .', () => { expect(build({ label: 'All', name: 'all', object: 'crm_lead' }).name).toBe('crm_lead.all'); expect( - build({ label: 'Intake', name: 'intake', object: 'crm_lead', viewKind: 'form' }).name, - ).toBe('crm_lead.intake'); + build({ label: 'Board', name: 'board', object: 'crm_lead', kind: 'kanban' }).name, + ).toBe('crm_lead.board'); // An already-qualified key is left untouched. expect(build({ label: 'X', name: 'crm_lead.x', object: 'crm_lead' }).name).toBe('crm_lead.x'); }); }); -describe('view create form contract exposes both families (objectui#2323)', () => { - it('lists viewKind + formType among the create fields', () => { +describe('view create form contract offers the list family only (objectui#2323, ADR-0159 D7)', () => { + it('lists neither viewKind nor formType among the create fields', () => { const cfg = viewConfig(); - expect(cfg.createFields).toContain('viewKind'); - expect(cfg.createFields).toContain('formType'); + expect(cfg.createFields).toEqual(['label', 'name', 'object', 'kind']); + expect(cfg.createFields).not.toContain('viewKind'); + expect(cfg.createFields).not.toContain('formType'); }); - it('offers list vs form families and per-family layouts in the create schema', () => { + it('offers the list layouts, and no family or form-layout picker, in the create schema', () => { const props = (viewConfig().createSchema as Record)?.properties ?? {}; - expect(props.viewKind?.enum).toEqual(['list', 'form']); + expect(props).not.toHaveProperty('viewKind'); + expect(props).not.toHaveProperty('formType'); expect(props.kind?.enum).toEqual(['grid', 'kanban', 'gallery', 'calendar', 'timeline', 'gantt', 'chart']); - expect(props.formType?.enum).toEqual(['simple', 'tabbed', 'wizard']); - // Each layout picker is gated to its family so the form shows only the - // relevant one, through SchemaForm's per-property `visibleWhen`. The - // retired `visibleOn` spelling is not written (objectui#12696): - // `view-create-body.visibility.test.tsx` renders the gate. - expect(props.kind?.visibleWhen).toBe("data.viewKind == 'list'"); - expect(props.formType?.visibleWhen).toBe("data.viewKind == 'form'"); + // With one family there is nothing to gate the list layout picker on. + // `view-create-body.visibility.test.tsx` renders the form. + expect(props.kind).not.toHaveProperty('visibleWhen'); expect(props.kind).not.toHaveProperty('visibleOn'); - expect(props.formType).not.toHaveProperty('visibleOn'); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/view-create-body.visibility.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/view-create-body.visibility.test.tsx index c2d97a57e4b..68e2931966b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/view-create-body.visibility.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/view-create-body.visibility.test.tsx @@ -1,19 +1,26 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * The view anchor's create form gates its two layout pickers on `viewKind` - * through `visibleWhen` (objectui#12696). + * The view anchor's create form shows the list layout picker, and no family or + * form-layout picker (ADR-0159 D7). * - * `anchors.ts` used to write the retired `visibleOn` spelling on the create - * schema's `kind` and `formType` properties, and `SchemaForm` folded it back in - * with `visibleWhen ?? visibleOn`. Both halves now speak `visibleWhen` only, so - * this renders the REAL registered create schema (not a hand-written mirror) - * and flips `viewKind`: if the anchor regresses to `visibleOn`, both pickers - * show for every family and the hidden-picker assertions go red. + * Until `@objectstack/spec` 19 the create schema carried a `viewKind` picker + * and gated two layout pickers on it through `visibleWhen` (objectui#12696). A + * view item is a list now, so the family and the form layout left the schema + * and the list layout picker is ungated. This renders the REAL registered + * create schema (not a hand-written mirror), for a fresh draft and for one + * that still names the retired family: if a form layout picker comes back, or + * the list one is gated on a family again, these go red. */ import { describe, it, expect, afterEach } from 'vitest'; import { render, screen, cleanup } from '@testing-library/react'; +// `SchemaForm` reaches `celAuthoring`'s dynamic `@objectstack/lint` import and +// the anchors a dynamic `@object-ui/plugin-detail` one; their first load is +// paid here, at collection, never inside a case's clock +// (`check:test-source-alias`). +import '@objectstack/lint'; +import '@object-ui/plugin-detail'; import { SchemaForm } from './SchemaForm'; import { registerBuiltinAnchors } from './anchors'; import { getMetadataResource } from './registry'; @@ -27,16 +34,22 @@ function viewCreateSchema(): Record { return schema as Record; } -describe('view create form — layout pickers follow viewKind via visibleWhen (objectui#12696)', () => { - it('a list draft shows the list layout picker and hides the form one', () => { +describe('view create form — the list layout picker only (objectui#12696, ADR-0159 D7)', () => { + it('a fresh draft shows the list layout picker and no form one', () => { + render( {}} />); + expect(screen.getByText('List layout')).toBeInTheDocument(); + expect(screen.queryByText('Form layout')).not.toBeInTheDocument(); + }); + + it('a list draft shows the list layout picker and no form one', () => { render( {}} />); expect(screen.getByText('List layout')).toBeInTheDocument(); expect(screen.queryByText('Form layout')).not.toBeInTheDocument(); }); - it('a form draft shows the form layout picker and hides the list one', () => { + it('a draft that still names the retired form family shows the list layout picker, and no form one', () => { render( {}} />); - expect(screen.getByText('Form layout')).toBeInTheDocument(); - expect(screen.queryByText('List layout')).not.toBeInTheDocument(); + expect(screen.getByText('List layout')).toBeInTheDocument(); + expect(screen.queryByText('Form layout')).not.toBeInTheDocument(); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/view-item-normalize.test.ts b/ui/packages/app-shell/src/views/metadata-admin/view-item-normalize.test.ts index b09f9400d36..24c264b056a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/view-item-normalize.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/view-item-normalize.test.ts @@ -28,6 +28,8 @@ const calendarItem = { }, }; +// A row of the retired form family (ADR-0159 D7): no `view` read serves one +// since `@objectstack/spec` 19. Kept to pin what the helpers answer for it. const formItem = { name: 'crm_lead.intake_form', object: 'crm_lead', @@ -38,7 +40,7 @@ const formItem = { }; describe('isAggregatedViewContainer', () => { - it('accepts a bare container with listViews/formViews', () => { + it('accepts a bare container, a stored one that names the retired `form` / `formViews` included', () => { expect(isAggregatedViewContainer({ name: 'crm_lead', listViews: {}, formViews: {} })).toBe(true); expect(isAggregatedViewContainer({ name: 'crm_lead', list: {} })).toBe(true); expect(isAggregatedViewContainer({ name: 'crm_lead', form: {} })).toBe(true); @@ -57,15 +59,17 @@ describe('viewDisplayType', () => { it('reads config.type for an expanded list item', () => { expect(viewDisplayType(calendarItem)).toBe('calendar'); }); - it('reads config.type for an expanded form item', () => { + it('reads config.type whatever the row`s family: the family is not what names the type', () => { expect(viewDisplayType(formItem)).toBe('simple'); }); it('reads a flat legacy view`s top-level type', () => { expect(viewDisplayType({ name: 'x', type: 'grid' })).toBe('grid'); }); - it('falls back to the family when only viewKind is present', () => { + it('falls back to the family when only viewKind is present, and the family is `list`', () => { expect(viewDisplayType({ name: 'x', viewKind: 'list', config: {} })).toBe('list'); - expect(viewDisplayType({ name: 'x', viewKind: 'form', config: {} })).toBe('form'); + }); + it('answers no type for the retired form family named alone (ADR-0159 D7)', () => { + expect(viewDisplayType({ name: 'x', viewKind: 'form', config: {} })).toBeUndefined(); }); it('returns undefined for an aggregated container', () => { expect(viewDisplayType({ name: 'crm_lead', listViews: {} })).toBeUndefined(); diff --git a/ui/packages/app-shell/src/views/metadata-admin/view-item-normalize.ts b/ui/packages/app-shell/src/views/metadata-admin/view-item-normalize.ts index 9ec41f76684..5a5aa4c4949 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/view-item-normalize.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/view-item-normalize.ts @@ -9,7 +9,7 @@ * { * name: "crm_campaign.campaign_calendar", * object: "crm_campaign", - * viewKind: "list", // list-family | form-family discriminant + * viewKind: "list", // a view item is a list (ADR-0159 D7) * label: "Launch Calendar", * scope: "package", * config: { // ← the single-view spec lives here @@ -31,11 +31,14 @@ function isPlainObject(v: unknown): v is Record { } /** - * True when `item` is a **bare aggregated view container** — the legacy - * per-object `defineView({ list, form, listViews, formViews })` document + * True when `item` is a **bare aggregated view container** — the + * per-object `defineView({ list, listViews })` document * the framework still registers under the bare `` key for runtime * back-compat (dual-read). It carries NO `viewKind` discriminant and holds - * at least one of the aggregate buckets. + * at least one of the aggregate buckets. The spec's predicate still reads a + * stored container that names the retired `form` / `formViews` members as a + * container (ADR-0159 D7), so such a row is hidden from the list like any + * other. * * Studio expands every such container into independent `.` * ViewItems (including the defaults), so the container row is fully @@ -53,16 +56,15 @@ export { isAggregatedViewContainer } from '@objectstack/spec'; /** * Derive the display "type" of a view list row. Expanded ViewItems keep * their display type under `config.type` (`grid` / `calendar` / `kanban` - * / …) and only the list/form *family* at the top level (`viewKind`); a - * legacy flat view carries `type` directly. Returns `undefined` when - * nothing is resolvable (e.g. an aggregated container). + * / …) and only the *family* at the top level (`viewKind`, which is `list`: + * ADR-0159 D7); a legacy flat view carries `type` directly. Returns + * `undefined` when nothing is resolvable (e.g. an aggregated container). */ export function viewDisplayType(item: unknown): string | undefined { if (!isPlainObject(item)) return undefined; const config = item.config; if (isPlainObject(config) && typeof config.type === 'string') return config.type; if (typeof item.type === 'string') return item.type; - if (item.viewKind === 'form') return 'form'; if (item.viewKind === 'list') return 'list'; return undefined; } diff --git a/ui/packages/app-shell/src/views/metadata-admin/view-schema.test.ts b/ui/packages/app-shell/src/views/metadata-admin/view-schema.test.ts index 7053f410f32..e8db12a266c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/view-schema.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/view-schema.test.ts @@ -22,10 +22,18 @@ describe('view-schema (spec-derived View authoring metadata)', () => { expect(JSON.stringify(schema)).toContain('kanban'); }); - it('derives the form-variant JSONSchema (recursive strict FormFieldSchema)', () => { + it('derives the form JSONSchema from the `form` item schema (recursive strict FormFieldSchema)', () => { + // A form is a `form` item since `@objectstack/spec` 19 (ADR-0159 D7), and + // `ViewSchema`'s `form` slot is a tombstone that derives no object schema, + // so the source is `FormSchema`: the item's binding beside its layout body. const schema = getFormVariantSchema(); expect(schema).toBeTruthy(); + expect(schema?.type).toBe('object'); expect(JSON.stringify(schema)).toContain('sections'); + expect(Object.keys(schema?.properties ?? {})).toEqual(expect.arrayContaining(['name', 'object', 'type', 'sections'])); + expect(schema?.properties?.type?.enum).toEqual(['simple', 'tabbed', 'wizard']); + // The item authors no `data` (it is bound by `object`), unlike a view body. + expect(schema?.properties).not.toHaveProperty('data'); }); it('derives the ListColumn JSONSchema', () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/view-schema.ts b/ui/packages/app-shell/src/views/metadata-admin/view-schema.ts index 0482b5c88ad..c8985b3cdaf 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/view-schema.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/view-schema.ts @@ -15,7 +15,12 @@ * type, plus shared basics / filters / navigation. * • `ViewSchema` — the zod schema for the whole (nested) View document. * `properties.list` is the JSONSchema for a single - * list-family view; `properties.form` for a form view. + * list view. A view holds lists only since + * `@objectstack/spec` 19 (ADR-0159 D7): its `form` slot + * is a tombstone, which derives no object schema. + * • `FormSchema` — the zod schema of a `form` metadata item, the type a + * form is since spec 19: its layout body at the top + * level, bound by `object`. * • `ListColumnSchema` — per-column property schema (width / align / * pinned / summary / …). * @@ -28,6 +33,7 @@ import { z } from 'zod'; import { ViewSchema, + FormSchema, ListColumnSchema, viewForm as specViewForm, } from '@objectstack/spec/ui'; @@ -66,9 +72,20 @@ export function getListVariantSchema(): JsonSchema | undefined { return viewDocSchema().properties?.list; } -/** JSONSchema for a single FORM-family view. */ +let _formItemSchema: JsonSchema | undefined; + +/** + * JSONSchema for a form: the `form` metadata item's own schema (`FormSchema`). + * + * Until `@objectstack/spec` 19 this read `ViewSchema`'s `form` slot. ADR-0159 + * D7 made that slot a tombstone (it derives `{ not: {} }`, no object schema) + * and made a form its own `form` item, whose body is the form view's by + * reference, at the top level. So the live source of a form's `type` enum and + * body keys is `FormSchema`, and this derives from it. + */ export function getFormVariantSchema(): JsonSchema | undefined { - return viewDocSchema().properties?.form; + _formItemSchema ??= z.toJSONSchema(FormSchema, TO_JSON_OPTS) as JsonSchema; + return _formItemSchema; } let _listColumnSchema: JsonSchema | undefined; diff --git a/ui/packages/app-shell/src/views/studio-design/packageSurfaces.ts b/ui/packages/app-shell/src/views/studio-design/packageSurfaces.ts index f9abf284825..29a84fb0b6b 100644 --- a/ui/packages/app-shell/src/views/studio-design/packageSurfaces.ts +++ b/ui/packages/app-shell/src/views/studio-design/packageSurfaces.ts @@ -51,26 +51,13 @@ export interface PackageSurface { label: string; /** * objectstack#30046 — a `view` row's bound object and family (`viewKind`, - * `list` | `form`), as the published item declares them (ADR-0017's + * which is `list`: a view item is a list since `@objectstack/spec` 19, + * ADR-0159 D7), as the published item declares them (ADR-0017's * `{ name, object, viewKind }`). Absent on every other type, and on a * draft-only view: its `_drafts` header carries no body. */ object?: string; viewKind?: string; - /** - * objectstack-ai/objectstack#36425 — a `form` view row that is an internal - * create / edit form, which the console no longer loads: the object's - * default form (`isDefault`) or its `OBJECT.create` form, unless its body - * turns on public sharing (`sharing.enabled === true`, a public form, which - * keeps loading at its own link). A form under any other name is a named - * form an action of type `form` opens: not internal. The - * `form-view-internal-not-loaded` lint rule applies this test and, since - * objectstack-ai/objectstack#36545, also leaves out a default or create form - * that a `form`-type action opens by its served name (seat ruling 5 on - * #36425). This row reads no actions, so it does not yet make that - * exemption: which read it should take is open on #36545. - */ - internalForm?: boolean; } /** @@ -171,36 +158,13 @@ function mergeSurfaces( * declares them as strings: the members {@link PackageSurface} carries for a * `view` row. Used for a published row and for a draft-overlaid one alike. */ -export function viewBindingOf(item: Record): Pick { +export function viewBindingOf(item: Record): Pick { return { ...(typeof item.object === 'string' && item.object ? { object: item.object } : {}), ...(typeof item.viewKind === 'string' && item.viewKind ? { viewKind: item.viewKind } : {}), - ...(isInternalFormItem(item) ? { internalForm: true } : {}), }; } -/** - * objectstack-ai/objectstack#36425 — whether a view item is an internal create - * / edit form (see {@link PackageSurface.internalForm}). - */ -function isInternalFormItem(item: Record): boolean { - if (item.viewKind !== 'form' || isPublicFormBody(item)) return false; - const object = typeof item.object === 'string' ? item.object : ''; - return item.isDefault === true || (!!object && item.name === `${object}.create`); -} - -/** - * objectstack-ai/objectstack#36425 — whether a form view item is a public - * form. The one test is the card's: `sharing.enabled === true`, on the item's - * `config` (a stored view item) or on the item itself (a flat overlay). - */ -function isPublicFormBody(item: Record): boolean { - const config = item.config; - const body = config && typeof config === 'object' && !Array.isArray(config) ? (config as Record) : item; - const sharing = body.sharing; - return !!sharing && typeof sharing === 'object' && (sharing as Record).enabled === true; -} - /** The draft-overlaid read {@link withDraftViewBindings} asks: the metadata client's preview door. */ export interface DraftViewBindingClient { withPreviewDrafts(on: boolean): { list(type: string, options?: { packageId?: string }): Promise }; diff --git a/ui/packages/app-shell/src/views/view-config-adapter.test.ts b/ui/packages/app-shell/src/views/view-config-adapter.test.ts index 2391cb57697..9ab6ba56ca0 100644 --- a/ui/packages/app-shell/src/views/view-config-adapter.test.ts +++ b/ui/packages/app-shell/src/views/view-config-adapter.test.ts @@ -30,13 +30,21 @@ describe('view-config-adapter', () => { expect(draft.config.showSearch).toBe(true); }); - it('classifies form/detail types as the form family', () => { - expect( - runtimeViewToInspectorDraft({ id: 'f', type: 'form' }, 'o').viewKind, - ).toBe('form'); - expect( - runtimeViewToInspectorDraft({ id: 'd', type: 'detail' }, 'o').viewKind, - ).toBe('form'); + // ADR-0159 D7: `@objectstack/spec` 19 retired the `form` member of + // `viewKind` and the view door refuses it, so the adapter produces a list + // draft for every type, the two that used to name the form family included. + it('produces no form view kind: a form or detail type yields a list draft', () => { + for (const type of ['form', 'detail', 'grid', 'kanban', undefined]) { + const draft = runtimeViewToInspectorDraft({ id: 'v', type }, 'o'); + expect(draft.viewKind, String(type)).toBe('list'); + expect(JSON.stringify(draft), String(type)).not.toContain('"viewKind":"form"'); + } + // A stored envelope that still says `viewKind: 'form'` resumes as a list draft too. + const resumed = runtimeViewToInspectorDraft( + storedViewToRuntimeView({ name: 'o.edit', object: 'o', viewKind: 'form', config: { type: 'simple' } }), + 'o', + ); + expect(resumed.viewKind).toBe('list'); }); it('defaults a missing type to grid and columns to []', () => { @@ -102,7 +110,9 @@ describe('view-config-adapter', () => { expect(back.kanban).toEqual({ groupByField: 'stage' }); }); - it('preserves a form view through draft and back', () => { + // ADR-0159 D7: the body still round-trips whole, but the draft is a list + // draft (no form view kind is produced); the view door judges the body. + it('preserves a form-typed view body through draft and back, as a list draft', () => { const view = { id: 'lead_form', label: 'Lead Form', @@ -110,7 +120,7 @@ describe('view-config-adapter', () => { sections: [{ label: 'Basics', fields: ['name'] }], }; const draft = runtimeViewToInspectorDraft(view, 'crm_lead'); - expect(draft.viewKind).toBe('form'); + expect(draft.viewKind).toBe('list'); const back = inspectorDraftToRuntimeView(draft); expect(back.id).toBe('lead_form'); expect(back.label).toBe('Lead Form'); diff --git a/ui/packages/app-shell/src/views/view-config-adapter.ts b/ui/packages/app-shell/src/views/view-config-adapter.ts index 3725624b239..77ed1c8c9d3 100644 --- a/ui/packages/app-shell/src/views/view-config-adapter.ts +++ b/ui/packages/app-shell/src/views/view-config-adapter.ts @@ -13,10 +13,15 @@ * The studio {@link ViewVariantInspector} authors a canonical ViewItem draft * (ADR-0017, "Object has-many View"): * - * { name, object, viewKind: 'list' | 'form', label, config: { type, … } } + * { name, object, viewKind: 'list', label, config: { type, … } } * * where the inspector reads/writes the view BODY under `draft.config` and the - * bound object additionally lives at `config.data.object` for list views. + * bound object additionally lives at `config.data.object`. + * + * A view is a list: `@objectstack/spec` 19 retired the `form` member of + * `viewKind` (ADR-0159 D7), and the view door refuses it. A form is a `form` + * metadata item with its own designer, so this adapter produces a list draft + * whatever `type` the runtime view carries. * * This adapter converts both ways so the runtime panel can host the studio * inspector: edits are kept as a ViewItem draft while the panel is open, then @@ -24,9 +29,6 @@ * persist via the metadata draft/publish model). */ -/** View `type`s that belong to the FORM family (no column list). */ -const FORM_FAMILY_TYPES = new Set(['form', 'detail']); - /** Runtime flat view — the shape ObjectView's `activeView` carries. */ export interface RuntimeView { id: string; @@ -42,16 +44,11 @@ export interface RuntimeView { export interface InspectorViewDraft { name: string; object: string; - viewKind: 'list' | 'form'; + viewKind: 'list'; label?: string; config: Record; } -/** True when a view `type` denotes a form-family view. */ -function isFormFamilyType(type: unknown): boolean { - return typeof type === 'string' && FORM_FAMILY_TYPES.has(type); -} - /** * Convert a flat runtime view into a studio inspector draft. * @@ -59,14 +56,15 @@ function isFormFamilyType(type: unknown): boolean { * filter, sort, toolbar flags, … all round-trip), with the bound object * mirrored into `config.data.object` — the list body's render binding the * inspector reads first. `id` maps to the draft's `name`; the top-level - * `object` is the canonical FK both list and form inspectors fall back to. + * `object` is the canonical FK the inspector falls back to. The draft is a + * list (`viewKind: 'list'`) whatever the view's `type`: no form view kind is + * produced (ADR-0159 D7). */ export function runtimeViewToInspectorDraft( activeView: RuntimeView, objectName: string, ): InspectorViewDraft { const type = (activeView.type as string) || 'grid'; - const viewKind: 'list' | 'form' = isFormFamilyType(type) ? 'form' : 'list'; const label = activeView.label; const existingData = activeView.data && typeof activeView.data === 'object' @@ -76,7 +74,7 @@ export function runtimeViewToInspectorDraft( return { name: activeView.id, object: objectName, - viewKind, + viewKind: 'list', label, config: { ...activeView, diff --git a/ui/packages/core/src/utils/__tests__/column-identity.ratchet.test.ts b/ui/packages/core/src/utils/__tests__/column-identity.ratchet.test.ts index 7866f6613df..2c31f4d1a6b 100644 --- a/ui/packages/core/src/utils/__tests__/column-identity.ratchet.test.ts +++ b/ui/packages/core/src/utils/__tests__/column-identity.ratchet.test.ts @@ -113,8 +113,9 @@ interface Entry { * * PR1 recorded 24 family members; two of those were mis-triaged and are * reclassified here after reading what they actually feed: - * - `ViewPreview.tsx` converts a ViewItem FORM section into `object-form`'s + * - `ViewPreview.tsx` converted a ViewItem FORM section into `object-form`'s * runtime shape (`field` -> `name`) — the #3090 two-layer join, not a column. + * (That read left with the form route in objectstack#37112.) * - `SchemaForm.tsx` renders an arbitrary metadata ARRAY into a summary string * and guesses at a display key; the entries are validations/actions/whatever * the JSON schema declares, so there is no column vocabulary to converge. @@ -146,21 +147,20 @@ const INVENTORY: Record = { why: 'BOTH halves of resolveActionParams\' pair, each mirrored on purpose. `defaultFromRowKey` (objectui#10277) names the row key a `defaultFromRow` param seeds from, so the `$select` harvest can ask for it: `field ?? name`, because row data is keyed by object field, the precedence `rowValueKey` reads. `undoableWrittenKeys` (objectui#10404) names the key a param\'s collected value is WRITTEN under, whose prior value the Undo capture then looks up on the row: `name ?? field`, the precedence `paramName` reads. Two concepts, as in the file they mirror. Deliberately NOT `columnIdentity()`: that reader also accepts `fieldName` and treats an empty string as absent, so it would harvest keys the runtime never looks up.', }, - // ── the form cluster — settled the other way (#3090) (2) ───────────────── + // ── the form cluster — settled the other way (#3090) (1) ───────────────── // `plugin-form/src/ObjectForm.tsx` left this list in objectui#10475: its one // read was `SimpleObjectForm`'s own section-entry join (`field ?? name`), // deleted when that arm moved onto `buildSectionFields`, so the scanner no // longer matches the file and it is no longer residue. + // `app-shell/src/views/metadata-admin/previews/ViewPreview.tsx` left it in + // objectstack#37112: its one read was `toFormFieldEntry`, the form route's + // section-entry adapter, deleted with that route when `@objectstack/spec` 19 + // retired the form family from `view` (ADR-0159 D7). 'plugin-form/src/sectionFields.ts': { count: 1, verdict: 'form-cluster', why: 'The #3090 hub itself. #3090 established that spec FormField (`field`) and runtime FormField (`name`) are two LAYERS, and since objectui#10475 this file is the only place every `object-form` arm joins them (`sectionEntryName`, `normalizeSectionField`), the default arm included. Those spell the join as separate `typeof` tests, which the scanner does not match; the one line it does match is `warnOnMixedVocabulary`\'s guard, which compares the two keys to warn when an authored entry carries both.', }, - 'app-shell/src/views/metadata-admin/previews/ViewPreview.tsx': { - count: 1, - verdict: 'form-cluster', - why: 'Re-triaged in PR2: `toFormFieldEntry` adapts a ViewItem FORM section to what `object-form` selects by (`name`), which is the #3090 join — not a list column. Converging it onto `columnIdentity` would be a category error.', - }, // ── not identity reads (3) ─────────────────────────────────────────────── 'app-shell/src/views/metadata-admin/widgets.tsx': { @@ -263,8 +263,10 @@ describe('column identity dual-read ratchet (#3104)', () => { // objectui#12105 retired plugin-grid's hand-mapped `toBulkParam`, whose // param-name read now comes from the shared resolver's `paramName`; 10 // since objectstack#37682 deleted the chat's change card, whose row-name - // fallback was the `unrelated` entry in `ChatbotEnhanced.tsx`. - expect(sum(() => true)).toBe(10); + // fallback was the `unrelated` entry in `ChatbotEnhanced.tsx`; 9 since + // objectstack#37112 deleted `ViewPreview.tsx`'s form route, whose + // section-entry adapter was a `form-cluster` entry. + expect(sum(() => true)).toBe(9); }); it('records a precedence for every read left in the family', () => { diff --git a/ui/packages/core/src/utils/freeze-schema.ts b/ui/packages/core/src/utils/freeze-schema.ts index 305eaf824c9..ffe409096ab 100644 --- a/ui/packages/core/src/utils/freeze-schema.ts +++ b/ui/packages/core/src/utils/freeze-schema.ts @@ -135,8 +135,8 @@ export function deepFreeze(value: T, seen: WeakSet = new WeakSet()): * * Named `defineView` until objectstack#4115, which is a name `@objectstack/spec` * owns for something else entirely: the spec's `defineView(config)` is the - * VIEW-DOCUMENT factory — it parses a `ViewSchema` (`{ list, form, listViews, - * formViews }`) and returns a validated `View`. This one takes an arbitrary + * VIEW-DOCUMENT factory — it parses a `ViewSchema` (`{ list, listViews }`) + * and returns a validated `View`. This one takes an arbitrary * object, stamps the System-View marker and deep-freezes it; it validates * nothing. An app-shell comment already conflated the two, which is precisely * the planted-premise failure the guard exists to stop. diff --git a/ui/packages/types/src/__tests__/imported-defaults-8317.test.ts b/ui/packages/types/src/__tests__/imported-defaults-8317.test.ts index 43f6ec3cb5d..f47cf5e842a 100644 --- a/ui/packages/types/src/__tests__/imported-defaults-8317.test.ts +++ b/ui/packages/types/src/__tests__/imported-defaults-8317.test.ts @@ -502,8 +502,10 @@ describe('the import boundary strips every imported default (objectui#8317)', () it('the walker docblock\'s `lazy` count is re-derived, not quoted', () => { // The `lazy` arm is the one place the identity property cannot hold: it // must rebuild without forcing the getter, so a clean subtree behind a - // `z.lazy` is rebuilt anyway. The module's docblock names FIVE such - // nodes (the fourth, `ViewSchema`'s form-field group, since objectui#7928; + // `z.lazy` is rebuilt anyway. The module's docblock names FOUR such + // nodes (`ViewSchema`'s form-field group, the fourth since objectui#7928, + // left with the container's `form` / `formViews` tombstones in + // `@objectstack/spec` 19, ADR-0159 D7; // the one under `FieldSchema`, added by objectui#11070, is the recursive // filter clause's own object since objectstack#25748's shared chunks; the // form-field group under the `object-form` row's `sections[].fields[]`, @@ -513,7 +515,7 @@ describe('the import boundary strips every imported default (objectui#8317)', () // other owner sits inside a schema that is being rebuilt regardless. // Both halves are measured here, so a spec bump or an import that moves // either one is red rather than quietly making the docblock false. - expect(walk(IMPORTED.map(([, s]) => s)).lazies).toBe(5); + expect(walk(IMPORTED.map(([, s]) => s)).lazies).toBe(4); const lazyOwners = IMPORTED.filter(([, s]) => walk([s]).lazies > 0); expect(lazyOwners.length, 'no schema owns a lazy — the count above found them elsewhere').toBeGreaterThan(0); // The clean owners are exactly the named set: rebuilt (so NOT the spec's diff --git a/ui/packages/types/src/__tests__/object-view-spec-parity.test.ts b/ui/packages/types/src/__tests__/object-view-spec-parity.test.ts index 49cff8bf305..39a4e697dbe 100644 --- a/ui/packages/types/src/__tests__/object-view-spec-parity.test.ts +++ b/ui/packages/types/src/__tests__/object-view-spec-parity.test.ts @@ -287,7 +287,6 @@ const SPEC_COUNTERPART: Record([ // spec's own prescription, the footing `viewTabBar` stands on. Read by // nothing since objectui#13118. 'filterableFields', + // RE-TRIAGED at `@objectstack/spec` 19 (objectstack#37112), out of + // SPEC_COUNTERPART, where its anchor was `ViewSchema.form` ("container + // restructure"): ADR-0159 D7 retired that slot at protocol major 19 with an + // ADR-0087 tombstone. A view holds lists only, and a form is its own `form` + // metadata item, named `OBJECT.KEY`; so the node's `form` key has no live + // spec key to be renamed onto, and its counterpart upstream is another TYPE, + // not a key of the view. It stays declared on both faces as objectui-only + // surface. The sentinel that caught this is the `it.each` below, which is + // kept: it reads SPEC_COUNTERPART, where `table` and `listViews` still + // anchor on the same container. + 'form', ]); // ── the suite ──────────────────────────────────────────────────────────────── diff --git a/ui/packages/types/src/zod/imported-defaults.ts b/ui/packages/types/src/zod/imported-defaults.ts index 32716d702ee..ca8f224a7e4 100644 --- a/ui/packages/types/src/zod/imported-defaults.ts +++ b/ui/packages/types/src/zod/imported-defaults.ts @@ -147,6 +147,10 @@ const walk = (schema: z.ZodType): z.ZodType => { // `FieldSchema.summaryOperations.filter`) is now the SAME object as the // recursive filter clause above rather than a copy of it. The fifth is no // longer a node of its own; nothing in the schemas changed. + // `@objectstack/spec` 19 then made it FOUR: the view container's `form` and + // `formViews` are tombstones (ADR-0159 D7: a form is a `form` item, never a + // member of a `view`), so the fourth, the form-field group under + // `ViewSchema.formViews`, is no longer reachable from the container. // Each sits inside a schema that carries a default anyway, so the exception // costs no extra rebuild. objectui#10872 batch 2 had ONE named exception, // `ElementDataSourceSchema` (the `element:number` arm's `dataSource`), whose