From 280079b3c43b5fa8dc4611eb7a9cb4331ff494a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 16:55:01 +0000 Subject: [PATCH 1/3] feat(lint): form layout, visibility root and page-sort provenance advisories carry a localized user sentence Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyb4HJHsnssCRLUw4F --- packages/lint/src/finding-user-text.ts | 6 + packages/lint/src/validate-form-layout.ts | 28 +++- .../src/validate-form-layout.user-text.ts | 130 +++++++++++++++ .../validate-page-field-bindings.user-text.ts | 86 ++++++++++ packages/lint/src/validate-sortable-fields.ts | 22 ++- .../src/validate-visibility-predicates.ts | 29 +++- ...alidate-visibility-predicates.user-text.ts | 152 ++++++++++++++++++ 7 files changed, 440 insertions(+), 13 deletions(-) create mode 100644 packages/lint/src/validate-form-layout.user-text.ts create mode 100644 packages/lint/src/validate-page-field-bindings.user-text.ts create mode 100644 packages/lint/src/validate-visibility-predicates.user-text.ts diff --git a/packages/lint/src/finding-user-text.ts b/packages/lint/src/finding-user-text.ts index cceabc0cb69..802a310f723 100644 --- a/packages/lint/src/finding-user-text.ts +++ b/packages/lint/src/finding-user-text.ts @@ -56,6 +56,9 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/s import { SECURITY_POSTURE_USER_TEXT } from './validate-security-posture.user-text.js'; import { WIDGET_BINDINGS_USER_TEXT } from './validate-widget-bindings.user-text.js'; import { CHART_BINDINGS_USER_TEXT } from './validate-chart-bindings.user-text.js'; +import { FORM_LAYOUT_USER_TEXT } from './validate-form-layout.user-text.js'; +import { VISIBILITY_PREDICATES_USER_TEXT } from './validate-visibility-predicates.user-text.js'; +import { PAGE_FIELD_BINDINGS_USER_TEXT } from './validate-page-field-bindings.user-text.js'; /** * The names a finding's user sentence interpolates — object, field and @@ -159,6 +162,9 @@ export const FINDING_USER_TEXT_CATALOG: UserTextCatalog = mergeUserTextCatalogs( SECURITY_POSTURE_USER_TEXT, WIDGET_BINDINGS_USER_TEXT, CHART_BINDINGS_USER_TEXT, + FORM_LAYOUT_USER_TEXT, + VISIBILITY_PREDICATES_USER_TEXT, + PAGE_FIELD_BINDINGS_USER_TEXT, ); /** diff --git a/packages/lint/src/validate-form-layout.ts b/packages/lint/src/validate-form-layout.ts index 42be907b4c7..d2fed7465a4 100644 --- a/packages/lint/src/validate-form-layout.ts +++ b/packages/lint/src/validate-form-layout.ts @@ -57,6 +57,7 @@ */ import { collectionEntries } from './collection-entries.js'; +import type { UserTextParams } from './finding-user-text.js'; // [#13855] The field-group reference question, shared with // `validate-page-field-bindings` so both layout escape hatches resolve a // `section.group` against one index and report the same way. @@ -92,6 +93,12 @@ export interface FormLayoutFinding { message: string; /** How to fix it. */ hint: string; + /** + * The names this finding's user-facing sentence interpolates, set at both + * advisory push sites; the sentences are `validate-form-layout.user-text.ts` + * (`AuthoringFinding.userTextParams`). + */ + userTextParams?: UserTextParams; } type AnyRec = Record; @@ -220,14 +227,20 @@ export function validateFormLayout(stack: AnyRec): FormLayoutFinding[] { // ── (c) [#13855] a section's `group` names a declared field group ── // Both buckets, for the reason (a) reads both: a rule that judges only // the canonical spelling is silent on the legacy one. + // + // The user sentence's names are added HERE, not in the shared helper: + // its other host (`validate-page-field-bindings`) emits its group id + // on no write the publish door judges, so it authors no sentence. The + // helper returns a finding only when `objName` resolves, and each + // finding's `path` is its reference's, which names the group. + const groupRefs = sectionGroupRefs(sections, `${site.path}.${bucket}`); + const groupAt = new Map(groupRefs.map((ref) => [ref.path, ref.key])); findings.push( - ...checkSectionGroupRefs( - sectionGroupRefs(sections, `${site.path}.${bucket}`), - objName, - objectFieldGroups, - where, - FORM_SECTION_GROUP_UNKNOWN, - ), + ...checkSectionGroupRefs(groupRefs, objName, objectFieldGroups, where, FORM_SECTION_GROUP_UNKNOWN) + .map((finding) => ({ + ...finding, + userTextParams: { view: viewName, object: objName ?? '', group: groupAt.get(finding.path) ?? '' }, + })), ); for (let s = 0; s < sections.length; s++) { @@ -251,6 +264,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 }, }); } } diff --git a/packages/lint/src/validate-form-layout.user-text.ts b/packages/lint/src/validate-form-layout.user-text.ts new file mode 100644 index 00000000000..118f0d2d82d --- /dev/null +++ b/packages/lint/src/validate-form-layout.user-text.ts @@ -0,0 +1,130 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentences of `validate-form-layout.ts`'s advisory findings, + * in every platform locale (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). + * The finding mechanism and the locale ladder are `finding-user-text.ts`'s; + * 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 + * 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, + * 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: + * + * | 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 | + * + * 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 + * 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 + * its `message` does. + * + * `finding-user-text.pages-forms.test.ts` renders every entry from the rule's + * real findings in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { FORM_FIELD_UNKNOWN, FORM_SECTION_GROUP_UNKNOWN } from './validate-form-layout.js'; + +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 ` + + `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.object}”中添加该字段。`, + 'zh-Hant': (p) => + `檢視「${p.view}」的表單列出了欄位「${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 ` + + `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.object}".`, + fr: (p) => + `Le formulaire de la vue « ${p.view} » 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 ` + + `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.object}».`, + de: (p) => + `Das Formular in der Ansicht „${p.view}“ 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.object}」に` + + `この項目を追加してください。`, + ko: (p) => + `보기 "${p.view}"의 양식에 필드 "${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 ` + + `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.object}”中添加该分组并为其分配字段。`, + 'zh-Hant': (p) => + `檢視「${p.view}」的表單中有一個區段從欄位分組「${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 ` + + `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.object}"، لذلك لا يحتوي القسم على أي حقول ولا يظهر. صحّح اسم المجموعة، أو أضف المجموعة ` + + `إلى "${p.object}" وعيّن لها حقولًا.`, + fr: (p) => + `Une section du formulaire de la vue « ${p.view} » 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}", ` + + `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.object}» не объявляет, поэтому в разделе нет полей и он не отображается. Исправьте имя группы или ` + + `добавьте эту группу в «${p.object}» и назначьте ей поля.`, + de: (p) => + `Ein Abschnitt des Formulars in der Ansicht „${p.view}“ 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.object}」はこのグループを宣言していないため、セクションに項目がなく表示されません。` + + `グループ名を修正するか、「${p.object}」にこのグループを追加して項目を割り当ててください。`, + ko: (p) => + `보기 "${p.view}"의 양식에 있는 섹션이 필드 그룹 "${p.group}"에서 필드를 가져오지만, 개체 ` + + `"${p.object}"은(는) 이 그룹을 선언하지 않으므로 섹션에 필드가 없고 표시되지 않습니다. 그룹 이름을 ` + + `수정하거나 "${p.object}"에 이 그룹을 추가하고 필드를 할당하세요.`, + }, +}); diff --git a/packages/lint/src/validate-page-field-bindings.user-text.ts b/packages/lint/src/validate-page-field-bindings.user-text.ts new file mode 100644 index 00000000000..26589d603c4 --- /dev/null +++ b/packages/lint/src/validate-page-field-bindings.user-text.ts @@ -0,0 +1,86 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `page-field-unprovisioned`, the advisory id + * `validate-page-field-bindings.ts` owns, in every platform locale + * (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding mechanism + * and the locale ladder are `finding-user-text.ts`'s; this file is the id + * owner's half of it, kept beside the rule that declares the id. + * + * Who reads it: the person who saved a page in Studio, in their own language, + * once the save door composes `RuntimeAuthoringIssueSchema.userMessage` from + * it. So it says what the page does wrong (its sort is ignored) and the change + * that fixes it; the developer-facing detail (ADR-0015 injection, `columnMap`) + * stays in the finding's `message`, `hint` and `os explain` entry. + * + * The one push site that sets `userTextParams` is the page-sort site in + * `validate-sortable-fields.ts` (`checkPageSortDeclaration`): that rule judges + * page sorts and runs on a `page` write, so it is the only site of this id the + * publish door returns. This rule's own sites of the id (a page component + * that BINDS an injected column, which then renders blank) run only as a + * reference-integrity member on the frozen `flow` default, and a flow + * write's snapshot carries no pages, so they carry no params and stay on the + * English `message`. The rule's other advisories (`page-field-unknown` at its + * `skipped` grade, `page-section-group-unknown`) are absent for the same + * reason. + * + * | rule id | params | set at | + * |---|---|---| + * | `page-field-unprovisioned` | `page`, `object`, `field` | the page-sort push site in `validate-sortable-fields.ts` | + * + * Names in the sentence are the API names the rule saw, not labels, for the + * reason `validate-security-posture.user-text.ts` gives. `finding-user-text.pages-forms.test.ts` + * renders the entry from real findings at every page-sort position in every + * platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { PAGE_FIELD_UNPROVISIONED } from './validate-page-field-bindings.js'; + +export const PAGE_FIELD_BINDINGS_USER_TEXT: UserTextCatalog = Object.freeze({ + [PAGE_FIELD_UNPROVISIONED]: { + en: (p) => + `Page "${p.page}" sorts by "${p.field}", a column that the external object "${p.object}" does not ` + + `store, so the sort is ignored and the rows appear in no particular order. If the external table has ` + + `this column, add it to the object's fields; otherwise sort by another field.`, + 'zh-Hans': (p) => + `页面“${p.page}”按“${p.field}”排序,但外部对象“${p.object}”并不存储这一列,因此排序会被忽略,` + + `记录以任意顺序显示。如果外部表确实有这一列,请将它添加到该对象的字段中;否则请按其他字段排序。`, + 'zh-Hant': (p) => + `頁面「${p.page}」依「${p.field}」排序,但外部物件「${p.object}」並不儲存這一欄,因此排序會被忽略,` + + `記錄以任意順序顯示。如果外部資料表確實有這一欄,請將它新增到該物件的欄位中;否則請依其他欄位排序。`, + es: (p) => + `La página "${p.page}" ordena por "${p.field}", una columna que el objeto externo "${p.object}" no ` + + `almacena, así que el orden se ignora y las filas aparecen sin un orden concreto. Si la tabla externa ` + + `tiene esa columna, agréguela a los campos del objeto; si no, ordene por otro campo.`, + ar: (p) => + `ترتّب الصفحة "${p.page}" حسب "${p.field}"، وهو عمود لا يخزّنه الكائن الخارجي "${p.object}"، لذلك ` + + `يتم تجاهل الترتيب وتظهر الصفوف بلا ترتيب محدد. إذا كان الجدول الخارجي يحتوي على هذا العمود، فأضفه ` + + `إلى حقول الكائن؛ وإلا فرتّب حسب حقل آخر.`, + fr: (p) => + `La page « ${p.page} » trie par « ${p.field} », une colonne que l'objet externe « ${p.object} » ne ` + + `stocke pas : le tri est donc ignoré et les lignes s'affichent dans un ordre quelconque. Si la table ` + + `externe possède cette colonne, ajoutez-la aux champs de l'objet ; sinon, triez par un autre champ.`, + 'pt-BR': (p) => + `A página "${p.page}" ordena por "${p.field}", uma coluna que o objeto externo "${p.object}" não ` + + `armazena, então a ordenação é ignorada e as linhas aparecem sem ordem definida. Se a tabela externa ` + + `tiver essa coluna, adicione-a aos campos do objeto; caso contrário, ordene por outro campo.`, + ru: (p) => + `Страница «${p.page}» сортирует по «${p.field}» — столбцу, который внешний объект «${p.object}» не ` + + `хранит, поэтому сортировка игнорируется и строки выводятся в произвольном порядке. Если во внешней ` + + `таблице есть этот столбец, добавьте его в поля объекта; иначе сортируйте по другому полю.`, + de: (p) => + `Die Seite „${p.page}“ sortiert nach „${p.field}“, einer Spalte, die das externe Objekt „${p.object}“ ` + + `nicht speichert. Die Sortierung wird daher ignoriert, und die Zeilen erscheinen in beliebiger ` + + `Reihenfolge. Wenn die externe Tabelle diese Spalte hat, fügen Sie sie den Feldern des Objekts hinzu; ` + + `andernfalls sortieren Sie nach einem anderen Feld.`, + ja: (p) => + `ページ「${p.page}」は「${p.field}」で並べ替えていますが、外部オブジェクト「${p.object}」はこの列を` + + `保存していないため、並べ替えは無視され、行は不定の順序で表示されます。外部テーブルにこの列がある場合は` + + `オブジェクトの項目に追加し、ない場合は別の項目で並べ替えてください。`, + ko: (p) => + `페이지 "${p.page}"이(가) "${p.field}" 기준으로 정렬하지만, 외부 개체 "${p.object}"은(는) 이 열을 ` + + `저장하지 않으므로 정렬이 무시되고 행이 임의의 순서로 표시됩니다. 외부 테이블에 이 열이 있으면 개체의 ` + + `필드에 추가하고, 없으면 다른 필드로 정렬하세요.`, + }, +}); diff --git a/packages/lint/src/validate-sortable-fields.ts b/packages/lint/src/validate-sortable-fields.ts index 85b88bd84cc..c310932651a 100644 --- a/packages/lint/src/validate-sortable-fields.ts +++ b/packages/lint/src/validate-sortable-fields.ts @@ -291,6 +291,7 @@ import { suggestName, type ObjectGraph, } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; import { walkPageComponents } from './page-walk.js'; import { LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED, columnSummaryRefusal } from './validate-list-view-field-refs.js'; import { PAGE_FIELD_UNKNOWN, PAGE_FIELD_UNPROVISIONED } from './validate-page-field-bindings.js'; @@ -340,6 +341,13 @@ export interface SortableFieldFinding { message: string; /** How to fix it. */ hint: string; + /** + * The names this finding's user-facing sentence interpolates, set at the + * page-sort `page-field-unprovisioned` push site (the advisory the page + * publish door returns); the sentence is the id owner's, + * `validate-page-field-bindings.user-text.ts` (`AuthoringFinding.userTextParams`). + */ + userTextParams?: UserTextParams; } type AnyRec = Record; @@ -694,6 +702,7 @@ function checkPageSortDeclaration( where: string, path: string, subject: string, + pageName: string, ): SortableFieldFinding[] { if (declared === undefined || declared === null || !objectName) return []; const projection = sortability.get(objectName); @@ -716,6 +725,7 @@ function checkPageSortDeclaration( `${subject}: ${unprovisionedAnchorVerdict(objectName, name)}, so its ORDER BY is ` + 'dropped and every fetch returns rows in an arbitrary order', hint: unprovisionedAnchorFix(objectName, name), + userTextParams: { page: pageName, object: objectName, field: name }, }); } // An author-DECLARED field of a system name is the author's own column, @@ -772,10 +782,12 @@ function validatePageSorts( unprovisionedAnchors: ReadonlyMap>, ): SortableFieldFinding[] { const findings: SortableFieldFinding[] = []; - const check = (declared: unknown, objectName: string | undefined, where: string, path: string, subject: string) => { + const check = ( + declared: unknown, objectName: string | undefined, where: string, path: string, subject: string, pageName: string, + ) => { findings.push( ...checkPageSortDeclaration( - declared, objectName, fieldsByObject, sortability, unprovisionedAnchors, where, path, subject, + declared, objectName, fieldsByObject, sortability, unprovisionedAnchors, where, path, subject, pageName, ), ); }; @@ -792,7 +804,7 @@ function validatePageSorts( const dataSource = isRec(component.dataSource) ? component.dataSource : undefined; if (dataSource) { - check(dataSource.sort, strName(dataSource.object), where, `${path}.dataSource.sort`, `${type} dataSource sort`); + check(dataSource.sort, strName(dataSource.object), where, `${path}.dataSource.sort`, `${type} dataSource sort`, pageName); } if (!props) continue; const objectProp = PAGE_BLOCK_SORT_OBJECT_PROP[type]; @@ -803,6 +815,7 @@ function validatePageSorts( where, `${path}.properties.sort`, `${type} sort`, + pageName, ); } // The PARENT binding is declared on `record:related_list` alone. @@ -815,6 +828,7 @@ function validatePageSorts( where, `${path}.properties.parentDataSource.sort`, `${type} parentDataSource sort`, + pageName, ); } } @@ -827,6 +841,7 @@ function validatePageSorts( `page "${pageName}" · interfaceConfig`, `pages[${pi}].interfaceConfig.sort`, 'list-page sort', + pageName, ); } @@ -838,6 +853,7 @@ function validatePageSorts( `page "${pageName}" · record`, `pages[${pi}].record.sort`, 'page record sort', + pageName, ); } } diff --git a/packages/lint/src/validate-visibility-predicates.ts b/packages/lint/src/validate-visibility-predicates.ts index a0364e12d89..e4fe792e009 100644 --- a/packages/lint/src/validate-visibility-predicates.ts +++ b/packages/lint/src/validate-visibility-predicates.ts @@ -560,6 +560,7 @@ import { import type { CelAstNode, CelBoundsOverrun, UnknownFunctionCall } from '@objectstack/formula'; 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'; @@ -646,6 +647,22 @@ export interface VisibilityFinding { message: string; /** How to fix it. */ hint: string; + /** + * The names this finding's user-facing sentence interpolates, set at the + * `visibility-root-mislayered` push site only (the advisory the publish door + * returns); the sentence is `validate-visibility-predicates.user-text.ts` + * (`AuthoringFinding.userTextParams`). + */ + userTextParams?: UserTextParams; +} + +/** + * The element's owning surface, as the user sentence names it: the view or + * page, by the name the finding's `where` already shows. + */ +interface VisibilitySubject { + surface: 'view' | 'page'; + name: string; } type AnyRec = Record; @@ -1405,6 +1422,7 @@ function declaredPageVariables(page: AnyRec): Set { function checkElement( el: AnyRec, where: string, + subject: VisibilitySubject, path: string, layer: VisibilityLayer, findings: VisibilityFinding[], @@ -1427,6 +1445,9 @@ function checkElement( path, message: rule.message, hint: rule.hint, + // `root` selects the sentence: `data` on a runtime surface, `record` on + // a metadata-editing form. + userTextParams: { surface: subject.surface, name: subject.name, root: rule.forbiddenRoot }, }); } @@ -1670,6 +1691,7 @@ export function validateVisibilityPredicates( 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}"`; @@ -1700,13 +1722,13 @@ export function validateVisibilityPredicates( const sec = sections[s]; if (!sec || typeof sec !== 'object') continue; const secPath = `${site.path}.${bucket}[${s}]`; - checkElement(sec as AnyRec, where, secPath, layer, findings, literalRhs); + checkElement(sec as AnyRec, where, viewSubject, secPath, layer, findings, literalRhs); const secFields = Array.isArray((sec as AnyRec).fields) ? ((sec as AnyRec).fields as unknown[]) : []; for (let f = 0; f < secFields.length; f++) { const entry = secFields[f]; if (isFieldObject(entry)) { - checkElement(entry, where, `${secPath}.fields[${f}]`, layer, findings, literalRhs); + checkElement(entry, where, viewSubject, `${secPath}.fields[${f}]`, layer, findings, literalRhs); } } } @@ -1734,13 +1756,14 @@ export function validateVisibilityPredicates( for (const { rec: page, path: pagePath } of collectionEntries(stack.pages, 'pages')) { const pageName = typeof page.name === 'string' ? page.name : undefined; const where = `page "${pageName ?? pagePath}"`; + const pageSubject: VisibilitySubject = { surface: 'page', name: pageName ?? pagePath }; // #28725 — what `page.NAME` can resolve to on this page. const pageVariables = declaredPageVariables(page); for (const walked of walkPageComponents(page, pagePath)) { // No per-site derivation here: a page component declares no data source of // its own, so nothing in the metadata states a layer for it and // `opts.layer` is the only answer available (#7815). - checkElement(walked.component, where, walked.path, declaredLayer, findings, false, pageVariables); + checkElement(walked.component, where, pageSubject, walked.path, declaredLayer, findings, false, pageVariables); } } diff --git a/packages/lint/src/validate-visibility-predicates.user-text.ts b/packages/lint/src/validate-visibility-predicates.user-text.ts new file mode 100644 index 00000000000..8256f30eab3 --- /dev/null +++ b/packages/lint/src/validate-visibility-predicates.user-text.ts @@ -0,0 +1,152 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `validate-visibility-predicates.ts`'s one + * advisory, `visibility-root-mislayered`, in every platform locale + * (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding mechanism + * and the locale ladder are `finding-user-text.ts`'s; this file is the rule's + * 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 + * 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 + * the record form names it. The developer-facing detail stays in the finding's + * `message`, `hint` and `os explain` entry. + * + * 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. + * + * 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 | + * | `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 + * real findings, for each surface and each root, in every platform locale. + */ + +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); +/** 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}"`; + 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 ` + + `"data." (for example data.type == 'grid').` + : `A visibleWhen rule on ${where} starts with "data.", which only a metadata-editing form provides, so ` + + `the rule never matches and the element is always shown. Start the rule with "record." (for example ` + + `record.status == 'open').`; + }, + 'zh-Hans': (p) => { + const where = `${noun({ view: '视图', page: '页面' }, p)}“${p.name}”`; + return onMetadataForm(p) + ? `${where}上的 visibleWhen 规则以“record.”开头,但这个表单编辑的是元数据,提供的是“data.”,` + + `因此该规则永远不会匹配,元素始终显示。请让规则以“data.”开头(例如 data.type == 'grid')。` + : `${where}上的 visibleWhen 规则以“data.”开头,而只有编辑元数据的表单才提供“data.”,` + + `因此该规则永远不会匹配,元素始终显示。请让规则以“record.”开头(例如 record.status == 'open')。`; + }, + 'zh-Hant': (p) => { + const where = `${noun({ view: '檢視', page: '頁面' }, p)}「${p.name}」`; + return onMetadataForm(p) + ? `${where}上的 visibleWhen 規則以「record.」開頭,但這個表單編輯的是中繼資料,提供的是「data.」,` + + `因此該規則永遠不會符合,元素始終顯示。請讓規則以「data.」開頭(例如 data.type == 'grid')。` + : `${where}上的 visibleWhen 規則以「data.」開頭,而只有編輯中繼資料的表單才提供「data.」,` + + `因此該規則永遠不會符合,元素始終顯示。請讓規則以「record.」開頭(例如 record.status == 'open')。`; + }, + es: (p) => { + const where = `${noun({ view: 'la vista', page: 'la página' }, p)} "${p.name}"`; + return onMetadataForm(p) + ? `Una regla visibleWhen de ${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 ` + + `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}"`; + return onMetadataForm(p) + ? `تبدأ قاعدة visibleWhen في ${where} بـ "record."، لكن هذا النموذج يحرّر البيانات الوصفية ويوفّر "data." ` + + `بدلًا منها، لذلك لا تتطابق القاعدة أبدًا ويظهر العنصر دائمًا. ابدأ القاعدة بـ "data." ` + + `(مثلًا data.type == 'grid').` + : `تبدأ قاعدة visibleWhen في ${where} بـ "data."، ولا يوفّرها إلا نموذج تحرير البيانات الوصفية، لذلك ` + + `لا تتطابق القاعدة أبدًا ويظهر العنصر دائمًا. ابدأ القاعدة بـ "record." ` + + `(مثلًا record.status == 'open').`; + }, + fr: (p) => { + const where = `${noun({ view: 'la vue', page: 'la page' }, p)} « ${p.name} »`; + return onMetadataForm(p) + ? `Une règle visibleWhen de ${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 ` + + `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}"`; + 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 ` + + `"data." (por exemplo, data.type == 'grid').` + : `Uma regra visibleWhen ${where} começa com "data.", que só um formulário de edição de metadados ` + + `oferece, então a regra nunca corresponde e o elemento é sempre exibido. Comece a regra com ` + + `"record." (por exemplo, record.status == 'open').`; + }, + ru: (p) => { + const where = `${noun({ view: 'в представлении', page: 'на странице' }, p)} «${p.name}»`; + return onMetadataForm(p) + ? `Правило visibleWhen ${where} начинается с «record.», но эта форма редактирует метаданные и ` + + `предоставляет «data.», поэтому правило никогда не срабатывает и элемент отображается всегда. ` + + `Начните правило с «data.» (например, data.type == 'grid').` + : `Правило visibleWhen ${where} начинается с «data.», которое предоставляет только форма ` + + `редактирования метаданных, поэтому правило никогда не срабатывает и элемент отображается всегда. ` + + `Начните правило с «record.» (например, record.status == 'open').`; + }, + de: (p) => { + const where = `${noun({ view: 'der Ansicht', page: 'der Seite' }, p)} „${p.name}“`; + return onMetadataForm(p) + ? `Eine visibleWhen-Regel in ${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 ` + + `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}」`; + return onMetadataForm(p) + ? `${where}の visibleWhen ルールは「record.」で始まっていますが、このフォームはメタデータを編集する` + + `フォームで「data.」を提供するため、ルールは一致せず、要素は常に表示されます。ルールを「data.」で` + + `始めてください(例: data.type == 'grid')。` + : `${where}の visibleWhen ルールは「data.」で始まっていますが、「data.」を提供するのはメタデータを` + + `編集するフォームだけのため、ルールは一致せず、要素は常に表示されます。ルールを「record.」で` + + `始めてください(例: record.status == 'open')。`; + }, + ko: (p) => { + const where = `${noun({ view: '보기', page: '페이지' }, p)} "${p.name}"`; + return onMetadataForm(p) + ? `${where}의 visibleWhen 규칙이 "record."로 시작하지만, 이 양식은 메타데이터를 편집하는 양식이라 ` + + `"data."를 제공하므로 규칙이 일치하지 않고 요소가 항상 표시됩니다. 규칙을 "data."로 시작하세요 ` + + `(예: data.type == 'grid').` + : `${where}의 visibleWhen 규칙이 "data."로 시작하지만, "data."는 메타데이터를 편집하는 양식에서만 ` + + `제공되므로 규칙이 일치하지 않고 요소가 항상 표시됩니다. 규칙을 "record."로 시작하세요 ` + + `(예: record.status == 'open').`; + }, + }, +}); From 64567eef1ba5b11ba22a30a85872e6db875f3fe5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 16:56:48 +0000 Subject: [PATCH 2/3] test(lint): pin the form, visibility and page-sort advisory sentences from real findings and the publish door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyb4HJHsnssCRLUw4F --- .../src/finding-user-text.pages-forms.test.ts | 329 ++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 packages/lint/src/finding-user-text.pages-forms.test.ts diff --git a/packages/lint/src/finding-user-text.pages-forms.test.ts b/packages/lint/src/finding-user-text.pages-forms.test.ts new file mode 100644 index 00000000000..3115366272e --- /dev/null +++ b/packages/lint/src/finding-user-text.pages-forms.test.ts @@ -0,0 +1,329 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The form, visibility and page-sort advisories' user-facing sentences in the + * request's language (ruling record 6819749037, the pattern + * `finding-user-text.test.ts` pins for the security-posture rule): the + * form-layout rule's catalog (`validate-form-layout.user-text.ts`), the + * visibility rule's (`validate-visibility-predicates.user-text.ts`) and + * `page-field-unprovisioned`'s (`validate-page-field-bindings.user-text.ts`, + * pushed by `validate-sortable-fields.ts` at a page sort), each rendered from + * the rule's REAL findings in every platform locale, and carried out of the + * publish door. + * + * The page, navigation and translation advisories of the same card's rule + * files have no sentence: they are reference-integrity members on the frozen + * `flow` default, and a flow write's snapshot carries no pages, apps or + * translations, so the door never returns them. The last block pins that. + */ + +import { describe, it, expect } from 'vitest'; +import { RuntimeAuthoringIssueSchema } from '@objectstack/spec/api'; +import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; +import { FINDING_USER_TEXT_CATALOG, findingUserMessage } from './finding-user-text.js'; +import { FORM_LAYOUT_USER_TEXT } from './validate-form-layout.user-text.js'; +import { VISIBILITY_PREDICATES_USER_TEXT } from './validate-visibility-predicates.user-text.js'; +import { PAGE_FIELD_BINDINGS_USER_TEXT } from './validate-page-field-bindings.user-text.js'; +import { FORM_FIELD_UNKNOWN, FORM_SECTION_GROUP_UNKNOWN, validateFormLayout } from './validate-form-layout.js'; +import { VISIBILITY_ROOT_MISLAYERED, validateVisibilityPredicates } from './validate-visibility-predicates.js'; +import { validateSortableFields } from './validate-sortable-fields.js'; +import { + PAGE_FIELD_UNKNOWN, + PAGE_FIELD_UNPROVISIONED, + PAGE_SECTION_GROUP_UNKNOWN, + validatePageFieldBindings, +} from './validate-page-field-bindings.js'; +import { + REACT_CHART_AGGREGATE_INVALID, + REACT_CHART_FIELD_UNPROVISIONED, + REACT_PAGE_SOURCE_UNPARSEABLE, + REACT_PROP_DEPRECATED, +} from './validate-react-page-props.js'; +import { NAV_OBJECT_UNGRANTED, validateNavAccess } from './validate-nav-access.js'; +import { NAV_TARGET_UNRESOLVED, validateNavTargetRefs } from './validate-nav-target-refs.js'; +import { TRANSLATION_OPTION_KEY_UNKNOWN } from './validate-translation-references.js'; +import { TRANSLATION_SECTION_NAME_MISSING } from './validate-translatable-sections.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +type AnyRec = Record; +type Finding = { rule: string; severity: string; path: string; userTextParams?: Record }; + +// ── Fixtures ───────────────────────────────────────────────────────────────── + +const CONTRACT = { + name: 'contract', + fieldGroups: [{ key: 'basics', label: 'Basics' }], + fields: { name: { type: 'text', group: 'basics' }, status: { type: 'text' } }, +}; +/** An ADR-0015 external object: the registry injects `created_at`, the remote table may not store it. */ +const EXTERNAL = { + name: 'showcase_ext_customer', + datasource: 'showcase_external', + external: { remoteName: 'customers' }, + fields: { name: { type: 'text' }, email: { type: 'text' } }, +}; + +const formStack = (view: AnyRec): AnyRec => ({ objects: [CONTRACT], views: [view] }); +const simpleForm = (form: AnyRec): AnyRec => + ({ name: 'contract_form', type: 'simple', data: { provider: 'object', object: 'contract' }, ...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 sortPage = (page: AnyRec): AnyRec => ({ objects: [EXTERNAL], pages: [{ name: 'customer_page', ...page }] }); +const UNSTORED_SORT = [{ field: 'created_at' }]; +const SORT_PARAMS = { page: 'customer_page', object: 'showcase_ext_customer', field: 'created_at' }; + +type Case = { + label: string; + rule: string; + stack: AnyRec; + params: Record; + 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 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 => + ({ label, rule: PAGE_FIELD_UNPROVISIONED, stack: sortPage(page), params: SORT_PARAMS, run: (s) => validateSortableFields(s as never) }); + +/** + * 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. + */ +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' }), + 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' }), + 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' }), + 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: { + 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 } }), + sortCase('block sort', { type: 'app', regions: [{ name: 'main', components: [ + { type: 'object-grid', properties: { objectName: 'showcase_ext_customer', sort: UNSTORED_SORT } }, + ] }] }), + sortCase('block data source sort', { type: 'app', regions: [{ name: 'main', components: [ + { type: 'element:number', dataSource: { object: 'showcase_ext_customer', sort: UNSTORED_SORT }, properties: { field: 'name' } }, + ] }] }), + sortCase('related list parent data source sort', { type: 'app', regions: [{ name: 'main', components: [ + { type: 'record:related_list', properties: { + objectName: 'showcase_ext_customer', relationshipField: 'name', + parentDataSource: { object: 'showcase_ext_customer', sort: UNSTORED_SORT }, + } }, + ] }] }), +]; + +/** The one finding of `rule` the case's stack produces. */ +const findingOf = (c: Case): Finding => { + const found = c.run(c.stack).filter((f) => f.rule === c.rule); + expect(found, `${c.label}: exactly one ${c.rule} finding`).toHaveLength(1); + return found[0]!; +}; + +/** The params that are NAMES the sentence must show (not the variant selectors). */ +const namesOf = (params: Record): string[] => + Object.entries(params).filter(([key]) => key !== 'surface' && key !== 'root').map(([, value]) => value); + +const DOOR_RULES = { + form: [FORM_FIELD_UNKNOWN, FORM_SECTION_GROUP_UNKNOWN], + visibility: [VISIBILITY_ROOT_MISLAYERED], + pageFields: [PAGE_FIELD_UNPROVISIONED], +}; + +describe('form, visibility and page-sort advisories user text · the catalogs', () => { + it.each([ + ['form layout', FORM_LAYOUT_USER_TEXT, DOOR_RULES.form], + ['visibility predicates', VISIBILITY_PREDICATES_USER_TEXT, DOOR_RULES.visibility], + ['page field bindings', PAGE_FIELD_BINDINGS_USER_TEXT, DOOR_RULES.pageFields], + ] as const)('the %s catalog holds a sentence for exactly its door-reaching ids, in every platform locale', (_label, catalog, rules) => { + expect(Object.keys(catalog).sort()).toEqual([...rules].sort()); + for (const [rule, entry] of Object.entries(catalog)) { + expect(Object.keys(entry).sort(), rule).toEqual([...PLATFORM_LOCALE_TAGS].sort()); + } + }); + + it('all three are merged into the one finding catalog the door renders from', () => { + for (const rule of DOOR_RULES.form) expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBe(FORM_LAYOUT_USER_TEXT[rule]); + for (const rule of DOOR_RULES.visibility) { + expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBe(VISIBILITY_PREDICATES_USER_TEXT[rule]); + } + for (const rule of DOOR_RULES.pageFields) { + expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBe(PAGE_FIELD_BINDINGS_USER_TEXT[rule]); + } + }); + + it('keeps every rule id stable: the catalogs are keyed by the ids the findings already carry', () => { + expect([...DOOR_RULES.form, ...DOOR_RULES.visibility, ...DOOR_RULES.pageFields]).toEqual([ + 'form-field-unknown', + 'form-section-group-unknown', + 'visibility-root-mislayered', + 'page-field-unprovisioned', + ]); + }); + + it('the advisory ids the door never returns have no sentence, and stay on the English message', () => { + for (const rule of [ + REACT_PAGE_SOURCE_UNPARSEABLE, REACT_PROP_DEPRECATED, 'react-prop-typo', REACT_CHART_AGGREGATE_INVALID, + REACT_CHART_FIELD_UNPROVISIONED, NAV_OBJECT_UNGRANTED, NAV_TARGET_UNRESOLVED, PAGE_FIELD_UNKNOWN, + PAGE_SECTION_GROUP_UNKNOWN, TRANSLATION_OPTION_KEY_UNKNOWN, TRANSLATION_SECTION_NAME_MISSING, + ]) { + expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBeUndefined(); + } + }); +}); + +describe('form, visibility and page-sort advisories user text · rendered from the rules\' real findings', () => { + it.each(CASES.map((c) => [c.label, c] as const))('%s: carries its params and renders in every platform locale', (_label, c) => { + const finding = findingOf(c); + expect(finding.severity).toBe('warning'); + expect(finding.userTextParams).toEqual(c.params); + + const english = findingUserMessage(finding, ['en'])!; + for (const tag of PLATFORM_LOCALE_TAGS) { + const text = findingUserMessage(finding, [tag]); + expect(text, `${c.rule} · ${tag}`).toBeTruthy(); + expect(text, `${c.rule} · ${tag}`).not.toMatch(/undefined|\$\{/); + for (const name of namesOf(c.params)) expect(text, `${c.rule} · ${tag} names ${name}`).toContain(name); + // A real translation, not the English floor standing in for it. + if (tag !== 'en') expect(text, `${c.rule} · ${tag}`).not.toBe(english); + } + }); + + 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'] + .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. + const texts = [runtime!, metadata!].map((f) => + findingUserMessage({ ...f, userTextParams: { ...f.userTextParams!, name: 'n' } }, [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'] + .map((label) => findingOf(CASES.find((c) => c.label === label)!)); + for (const tag of PLATFORM_LOCALE_TAGS) { + const texts = [view!, page!].map((f) => + findingUserMessage({ ...f, userTextParams: { ...f.userTextParams!, name: 'n' } }, [tag])); + expect(new Set(texts).size, tag).toBe(2); + } + }); + + it('renders the form sentence in zh-Hans and en with the view, 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"'); + }); + + it('gives no sentence where the id is not advice the door returns', () => { + // The page-field-bindings rule's own sites of the provenance id, and its + // section-group id: judged only on a flow write, whose snapshot has no pages. + const bound = validatePageFieldBindings({ + objects: [EXTERNAL, CONTRACT], + pages: [{ name: 'p', type: 'record', object: 'contract', regions: [{ name: 'main', components: [ + { type: 'record:details', properties: { objectName: 'contract', sections: [{ label: 'S', group: 'money', fields: ['name'] }] } }, + ] }] }], + } as never); + expect(bound.map((f) => f.rule)).toContain(PAGE_SECTION_GROUP_UNKNOWN); + for (const f of bound) expect((f as Finding).userTextParams, f.rule).toBeUndefined(); + // The navigation advisories. + const nav = [ + ...validateNavAccess({ objects: [CONTRACT], permissions: [{ name: 'ps', objects: {} }], + apps: [{ name: 'a', navigation: [{ id: 'n', type: 'object', objectName: 'contract' }] }] } as never), + ...validateNavTargetRefs({ apps: [{ name: 'a', navigation: [{ id: 'n', type: 'page', pageName: 'ghost' }] }] } as never), + ]; + expect(nav.map((f) => f.rule).sort()).toEqual([NAV_OBJECT_UNGRANTED, NAV_TARGET_UNRESOLVED].sort()); + 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); + expect(syntax.map((f) => f.severity)).toEqual(['error']); + expect(syntax[0]!.userTextParams).toBeUndefined(); + }); +}); + +describe('form, visibility and page-sort advisories user text · from the runtime gate to the wire field', () => { + /** The element the save door's `advisories[]` carries, with the sentence it renders. */ + const issueOf = (advisory: Finding & { where: string; message: string; hint: string }, locales: string[]) => + RuntimeAuthoringIssueSchema.parse({ + rule: advisory.rule, + path: advisory.path, + where: advisory.where, + message: advisory.message, + hint: advisory.hint, + severity: advisory.severity, + 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] } }); + 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' }); + + const issue = issueOf(advisory!, ['de-DE', 'en']); + expect(issue.rule).toBe('form-section-group-unknown'); + expect(issue.userMessage).toContain('aus der Feldgruppe „money“'); + 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] } }); + 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」のフォーム'); + }); + + it('a page write\'s mislayered root and unstored sort carry their params out of the gate', () => { + const page = { + name: 'customer_page', type: 'list', object: 'showcase_ext_customer', + interfaceConfig: { sort: UNSTORED_SORT }, + regions: [{ name: 'main', components: [{ type: 'record:details', visibleWhen: RUNTIME_RULE, properties: {} }] }], + }; + const result = runRuntimeAuthoringRules({ type: 'page', item: page, context: { objects: [EXTERNAL] } }); + const sort = result.advisories.find((f) => f.rule === PAGE_FIELD_UNPROVISIONED); + const root = result.advisories.find((f) => f.rule === VISIBILITY_ROOT_MISLAYERED); + expect(sort, 'the gate returns the unstored-sort advisory for this write').toBeDefined(); + expect(root, 'the gate returns the mislayered-root advisory for this write').toBeDefined(); + expect(sort!.userTextParams).toEqual(SORT_PARAMS); + expect(root!.userTextParams).toEqual({ surface: 'page', name: 'customer_page', root: 'data' }); + + expect(issueOf(sort!, ['zh-CN']).userMessage).toContain('页面“customer_page”按“created_at”排序'); + expect(issueOf(root!, ['fr-FR']).userMessage).toContain('la page « customer_page »'); + }); +}); From d2634c67f6ad0ffff9fb4501b4683b538c3f5bfc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 16:57:23 +0000 Subject: [PATCH 3/3] chore: changeset for the form, visibility and page-sort advisory sentences Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyb4HJHsnssCRLUw4F --- .changeset/32840-advisory-user-text.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/32840-advisory-user-text.md diff --git a/.changeset/32840-advisory-user-text.md b/.changeset/32840-advisory-user-text.md new file mode 100644 index 00000000000..1d51fb54514 --- /dev/null +++ b/.changeset/32840-advisory-user-text.md @@ -0,0 +1,10 @@ +--- +'@objectstack/lint': patch +--- + +Clause-②: no +Metadata-protocol: none + +The form layout, visibility and page-sort advisories now carry a user-facing sentence in all 11 platform locales, for the save door's `userMessage` (the pattern the security-posture and dashboard advisories already follow). Four advisory rule ids gain one: the form-layout rule's `form-field-unknown` and `form-section-group-unknown` on a view write, `visibility-root-mislayered` on a view or page write, and `page-field-unprovisioned` where a page's sort names an injected column an external object does not store. Their findings carry the names the sentence interpolates as `userTextParams`, and `findingUserMessage` renders the sentence in the request's locale, else the workspace default, else English. + +Rule ids, `message` and `hint` are unchanged, so `os validate`, `os lint` and every save response read exactly as before. The page, navigation and translation advisories of the same rules (`react-page-source-unparseable`, `react-prop-deprecated`, `react-prop-typo`, `react-chart-aggregate-invalid`, `react-chart-field-unprovisioned`, `nav-object-ungranted`, `nav-target-unresolved`, `page-field-unknown` and `page-section-group-unknown` at their advisory grade, `page-field-unprovisioned` on a page component's field binding, `translation-option-key-unknown`, `translation-section-name-missing`) have no sentence: the publish door never returns them, because those rules run there only on a flow write, whose snapshot carries no pages, apps or translations. They stay on the English `message`.