A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps: form topology + richer layouts, download round-trip fixes, and verification oracles (#567, #572, #574, #575) (#579)
Akshay Maloob869e5f5cb76
diff --git a/evals/model-apps/app-builder/evals.json b/evals/model-apps/app-builder/evals.jsonindex ff0f3bbd4..5701a1a53 100644--- a/evals/model-apps/app-builder/evals.json+++ b/evals/model-apps/app-builder/evals.json@@ -33,7 +33,11 @@"process: every BPF step binds a field on the flow entity","process: every BPF stage is scoped to the flow entity (v1 is single-entity)","ui: enriched default views keep parent lookups and drop createdon",- "ui: each sub-grid is a full-width section titled by the child display name"+ "ui: each sub-grid is a full-width section titled by the child display name",+ "ui: every compiled form places each field exactly once",+ "ui: every compiled form places exactly the fields it intends to carry",+ "round-trip: a lookup's shadow columns are never recovered as spec columns (#574)",+ "round-trip: a download recovers no column the spec never authored"],"evals": [{@@ -161,6 +165,32 @@"a rule with two conditions compiles both, ANDed, and neither is dropped","every business rule and the process flow each get exactly one teardown step"]+ },+ {+ "id": 6,+ "tier": "full",+ "spec": "app-spec.json",+ "prompt": "Delivery: projects and work items on hand-authored forms — a two-form-column tab with 65/35 widths, two-column sections, a full-width title, a collapsed tab, and a polymorphic Customer lookup.",+ "expect": {+ "tables": [+ "new_project",+ "new_workitem"+ ],+ "relationships": [+ "new_project_new_workitem"+ ],+ "views": [+ "Active Projects",+ "Open Work Items"+ ],+ "charts": [+ "Work Items by Status"+ ]+ },+ "expectations": [+ "ui: an explicit layout compiles to the authored tab, form-column and section topology (it is not flattened)",+ "ui: an authored colspan and rowspan survive into the compiled cell"+ ]}]}diff --git a/evals/model-apps/app-builder/fixtures/6-form-layout/app-spec.json b/evals/model-apps/app-builder/fixtures/6-form-layout/app-spec.jsonnew file mode 100644index 000000000..9d76a13c2--- /dev/null+++ b/evals/model-apps/app-builder/fixtures/6-form-layout/app-spec.json@@ -0,0 +1,92 @@+{+ "schemaVersion": 2,+ "solution": { "uniqueName": "ContosoDelivery", "displayName": "Contoso Delivery", "publisherPrefix": "new" },+ "app": { "name": "Delivery", "description": "Plan projects and work items on hand-authored two-column forms" },+ "globalChoices": [+ { "name": "new_workstatus", "displayName": "Work Status", "options": ["Not Started", "In Progress", "Blocked", "Done"] }+ ],+ "entities": [+ { "schemaName": "new_project", "displayName": "Project", "pluralName": "Projects",+ "primaryAttribute": { "schemaName": "new_name", "displayName": "Project Name" },+ "columns": [+ { "schemaName": "new_stage", "displayName": "Stage", "type": "Choice", "globalChoice": "new_workstatus" },+ { "schemaName": "new_startdate", "displayName": "Start Date", "type": "DateTime" },+ { "schemaName": "new_budget", "displayName": "Budget", "type": "Money" }+ ] },+ { "schemaName": "new_workitem", "displayName": "Work Item", "pluralName": "Work Items",+ "primaryAttribute": { "schemaName": "new_title", "displayName": "Title" },+ "columns": [+ { "schemaName": "new_status", "displayName": "Status", "type": "Choice", "globalChoice": "new_workstatus" },+ { "schemaName": "new_priority", "displayName": "Priority", "type": "Choice",+ "options": ["Low", "Normal", "High"] },+ { "schemaName": "new_estimate", "displayName": "Estimate (days)", "type": "Decimal" },+ { "schemaName": "new_completed", "displayName": "Completed", "type": "Boolean" },+ { "schemaName": "new_duedate", "displayName": "Due Date", "type": "DateTime" },+ { "schemaName": "new_reviewer", "displayName": "Reviewer", "type": "Text" },+ { "schemaName": "new_requestedby", "displayName": "Requested By", "type": "Customer" },+ { "schemaName": "new_notes", "displayName": "Notes", "type": "Memo" }+ ] }+ ],+ "relationships": [+ { "type": "OneToMany", "referenced": "new_project", "referencing": "new_workitem",+ "lookup": { "schemaName": "new_ProjectId", "displayName": "Project" } }+ ],+ "forms": [+ { "entity": "new_workitem", "type": "main", "name": "Work Item",+ "tabs": [+ { "name": "tab_details", "label": "Details", "expanded": true,+ "columns": [+ { "width": "65%",+ "sections": [+ { "name": "section_execution", "label": "Execution", "columns": 2, "showLabel": true,+ "fields": [+ { "name": "new_title", "colspan": 2 },+ "new_status",+ "new_priority",+ "new_estimate",+ "new_completed"+ ] },+ { "name": "section_notes", "label": "Notes", "columns": 1, "showLabel": true,+ "fields": [ { "name": "new_notes", "rowspan": 2 } ] }+ ] },+ { "width": "35%",+ "sections": [+ { "name": "section_context", "label": "Planning Context", "columns": 1, "showLabel": true,+ "fields": ["new_projectid", "new_requestedby", "new_duedate"] }+ ] }+ ] },+ { "name": "tab_admin", "label": "Administration", "expanded": false,+ "sections": [+ { "name": "section_audit", "label": "Audit", "columns": 2, "showLabel": true,+ "fields": [ { "name": "new_reviewer", "readOnly": true } ] }+ ] }+ ] },+ { "entity": "new_project", "type": "main", "name": "Project",+ "tabs": [+ { "label": "General",+ "sections": [+ { "label": "Project", "columns": 2, "showLabel": true,+ "fields": ["new_name", "new_stage", "new_startdate", "new_budget"] }+ ] }+ ] }+ ],+ "views": [+ { "entity": "new_project", "type": "main", "name": "Active Projects",+ "columns": ["new_name", "new_stage", "new_startdate", "new_budget"], "activeOnly": true },+ { "entity": "new_workitem", "type": "main", "name": "Open Work Items",+ "columns": ["new_title", "new_status", "new_priority", "new_projectid", "new_duedate"], "activeOnly": true }+ ],+ "charts": [+ { "entity": "new_workitem", "name": "Work Items by Status", "groupBy": "new_status", "measure": "count", "chartType": "Column" }+ ],+ "appShell": {+ "areas": [+ { "label": "Delivery", "groups": [+ { "label": "Plan", "subAreas": [+ { "entity": "new_project", "title": "Projects" },+ { "entity": "new_workitem", "title": "Work Items" }+ ] }+ ] }+ ]+ }+}diff --git a/evals/model-apps/app-builder/lib/assertions.js b/evals/model-apps/app-builder/lib/assertions.jsindex f9ffff32c..0ae3b46f0 100644--- a/evals/model-apps/app-builder/lib/assertions.js+++ b/evals/model-apps/app-builder/lib/assertions.js@@ -488,4 +488,141 @@ ASSERTIONS.set('quick create is enabled on the new_ticket table (#8)', ({ factsreturn planned ? PASS : fail('the build plan has no "enable quick create on new_ticket" step');});+// --- form layout: the shape an author wrote must be the shape that ships (#575) ----------------+// An explicit `tabs` layout was FLATTENED on build: every field landed in the deployed form's first+// section and no tab / form-column / section was created or resized, so a hand-authored two-column+// form shipped as one long single-column list. It survived because the corpus graded a form's flat+// FIELD LIST and never its SHAPE — a flattened form has exactly the right fields.++ASSERTIONS.set('ui: an explicit layout compiles to the authored tab, form-column and section topology (it is not flattened)', ({ facts }) => {+ const explicit = (facts.ui.forms || []).filter((f) => f.authoredShape);+ if (!explicit.length) return skip('no form in this fixture declares an explicit layout');+ for (const f of explicit) {+ const a = f.authoredShape, c = f.compiledShape;+ if (a.length !== c.length) return fail(`form ${f.name}: ${a.length} tab(s) authored, ${c.length} compiled`);+ for (let i = 0; i < a.length; i++) {+ const at = a[i], ct = c[i], where = `form ${f.name} tab ${JSON.stringify(at.label)}`;+ if (at.label !== ct.label) return fail(`${where}: label became ${JSON.stringify(ct.label)}`);+ if (at.expanded !== ct.expanded) return fail(`${where}: expanded ${at.expanded} became ${ct.expanded}`);+ if (at.columnCount !== ct.columnCount) return fail(`${where}: ${at.columnCount} form-column(s) authored, ${ct.columnCount} compiled — a multi-column tab was collapsed`);+ // Only the widths the author actually WROTE. An omitted width is split evenly by the compiler,+ // and grading that split here would compare the compiler against a copy of itself.+ for (let wi = 0; wi < at.declaredWidths.length; wi++) {+ const w = at.declaredWidths[wi];+ if (w !== null && w !== ct.declaredWidths[wi]) return fail(`${where} form-column ${wi}: authored width ${w}, compiled ${ct.declaredWidths[wi]}`);+ }+ if (at.sectionsByColumn.length !== ct.sectionsByColumn.length) return fail(`${where}: ${at.sectionsByColumn.length} form-column(s) of sections authored, ${ct.sectionsByColumn.length} compiled`);+ // Compared PER FORM-COLUMN. A flat list would let a section that moved from column 0 to+ // column 1 pass whenever its order and fields were unchanged — the exact topology this+ // assertion exists to prove.+ for (let ci = 0; ci < at.sectionsByColumn.length; ci++) {+ const acol = at.sectionsByColumn[ci], ccol = ct.sectionsByColumn[ci];+ if (acol.length !== ccol.length) return fail(`${where} form-column ${ci}: ${acol.length} section(s) authored, ${ccol.length} compiled`);+ for (let si = 0; si < acol.length; si++) {+ const as = acol[si], cs = ccol[si];+ if (as.label !== cs.label) return fail(`${where} form-column ${ci} section ${si}: label ${JSON.stringify(as.label)} became ${JSON.stringify(cs.label)}`);+ if (as.columns !== cs.columns) return fail(`${where} form-column ${ci} section ${JSON.stringify(as.label)}: ${as.columns} grid column(s) authored, ${cs.columns} compiled`);+ if (!eq(as.fields, cs.fields)) return fail(`${where} form-column ${ci} section ${JSON.stringify(as.label)}: authored [${as.fields}] compiled [${cs.fields}]`);+ }+ }+ }+ }+ return PASS;+});++// colspan/rowspan are the reason a two-column section is worth authoring at all — a full-width title+// over a two-up grid. Both are dropped silently by a serializer that does not carry them, so a form+// can look correct in the field list and still render as a plain stack.+ASSERTIONS.set('ui: an authored colspan and rowspan survive into the compiled cell', ({ facts, spec }) => {+ const wanted = [];+ for (const f of spec.forms || []) {+ for (const t of f.tabs || []) {+ const sections = Array.isArray(t.columns) ? t.columns.flatMap((c) => (c && c.sections) || []) : (t.sections || []);+ for (const s of sections) {+ for (const entry of s.fields || []) {+ if (entry && typeof entry === 'object' && (entry.colspan > 1 || entry.rowspan > 1)) {+ wanted.push({ form: f.name, field: String(entry.name).toLowerCase(), colspan: entry.colspan || 1, rowspan: entry.rowspan || 1 });+ }+ }+ }+ }+ }+ if (!wanted.length) return skip('no field in this fixture authors a colspan or rowspan');+ for (const w of wanted) {+ const form = (facts.ui.forms || []).find((x) => x.name === w.form);+ if (!form) return fail(`no compiled form named ${w.form}`);+ const cell = (form.placements || []).find((p) => p.field === w.field);+ if (!cell) return fail(`form ${w.form}: field ${w.field} was not placed at all`);+ if (cell.colspan !== w.colspan) return fail(`form ${w.form} field ${w.field}: authored colspan ${w.colspan}, compiled ${cell.colspan}`);+ if (cell.rowspan !== w.rowspan) return fail(`form ${w.form} field ${w.field}: authored rowspan ${w.rowspan}, compiled ${cell.rowspan}`);+ }+ return PASS;+});++// Universal — these hold on EVERY layout, auto included. The build-time reconcile MOVES a control+// that sits in the wrong section rather than placing a second copy, so a field appearing twice is+// the signature of a placement pass that created instead of moved. Dataverse accepts a duplicated+// control and renders both, so nothing downstream would report it.+ASSERTIONS.set('ui: every compiled form places each field exactly once', ({ facts }) => {+ for (const f of facts.ui.forms || []) {+ const seen = new Map();+ for (const p of f.placements || []) seen.set(p.field, (seen.get(p.field) || 0) + 1);+ const dupes = [...seen.entries()].filter(([, n]) => n > 1).map(([k, n]) => `${k}×${n}`);+ if (dupes.length) return fail(`form ${f.name} places ${dupes.join(', ')}`);+ }+ return PASS;+});++// The converse of the duplication guard: a topology pass that creates containers and a field pass+// that fills them can also drop a field on the floor — the form still builds, just without it.+//+// For an EXPLICIT layout the comparison is against what the AUTHOR wrote, not against+// formFieldLogicals(intent). That list is derived from the same compiled object as the placements,+// so a compiler that drops a field drops it from both sides and the two agree on the wrong answer —+// a tautology that mutation testing caught. The authored shape is an independent statement of intent.+ASSERTIONS.set('ui: every compiled form places exactly the fields it intends to carry', ({ facts }) => {+ for (const f of facts.ui.forms || []) {+ const placed = sorted([...new Set((f.placements || []).map((p) => p.field))]);+ const intended = f.authoredShape+ ? sorted([...new Set(f.authoredShape.flatMap((t) => t.sectionsByColumn.flat().flatMap((s) => s.fields)))])+ : sorted([...new Set((f.fields || []).map((x) => String(x).toLowerCase()))]);+ if (!eq(placed, intended)) {+ const missing = intended.filter((x) => !placed.includes(x));+ const extra = placed.filter((x) => !intended.includes(x));+ return fail(`form ${f.name}: missing [${missing}] unplaced-extra [${extra}]`);+ }+ }+ return PASS;+});++// --- download column projection: nothing invented, no shadows (#574) ---------------------------+// Creating a lookup also materialises `<lookup>name` / `<lookup>yominame` (and `<lookup>idtype` for a+// polymorphic one). A download that emits them declares Text columns the author never wrote, and the+// next rebuild CREATES them for real — replacing a lookup with text fields. The facts feed both+// shadow shapes (logical for a single-target lookup, physically stored for a polymorphic one) through+// the real projection, so a regression in either filter shows up here.+ASSERTIONS.set("round-trip: a lookup's shadow columns are never recovered as spec columns (#574)", ({ facts }) => {+ const rows = (facts.download || []).filter((r) => r.shadowNames.length);+ if (!rows.length) return skip('no table in this fixture carries a lookup');+ for (const r of rows) {+ const leaked = r.shadowNames.filter((s) => r.recoveredColumns.includes(s));+ if (leaked.length) return fail(`${r.entity}: download recovered shadow column(s) ${leaked.join(', ')}`);+ }+ return PASS;+});++// The general form of the same rule, and the one that catches a NEW invention rather than a known+// shadow spelling: a downloaded table must not declare a column the spec never authored. Stock+// attributes are the other half — `createdon` and friends feed defaultViewColumns, so recovering one+// would rewrite a customer's default views on the next build.+ASSERTIONS.set('round-trip: a download recovers no column the spec never authored', ({ facts }) => {+ for (const r of facts.download || []) {+ const invented = r.recoveredColumns.filter((c) => !r.authoredColumns.includes(c));+ if (invented.length) return fail(`${r.entity}: download invented column(s) ${invented.join(', ')}`);+ const system = r.systemAttributes.filter((c) => r.recoveredColumns.includes(c));+ if (system.length) return fail(`${r.entity}: download recovered stock attribute(s) ${system.join(', ')}`);+ }+ return PASS;+});+module.exports = { ASSERTIONS };\ No newline at end of filediff --git a/evals/model-apps/app-builder/lib/facts.js b/evals/model-apps/app-builder/lib/facts.jsindex 3fc88be1c..1d10a003d 100644--- a/evals/model-apps/app-builder/lib/facts.js+++ b/evals/model-apps/app-builder/lib/facts.js@@ -5,6 +5,9 @@ const path = require('node:path');// same depth genpage/lib uses to reach references/verified-icons.txt). These are offline-only modules// with no I/O, no SDK handle, and no network access, so they are safe to call from the eval harness.function pluginLib(name) { return require(path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'scripts', 'lib', name)); }+// Same, for a top-level script rather than a lib module. download-model-app.js exports its pure+// helpers and performs no I/O at require time, so it is safe to load from the offline harness.+function pluginLib2(name) { return require(path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'scripts', name)); }const { migrateAppSpec, validateAppSpec, lookupColumnsFor, SDK_ROLE_MARKER } = pluginLib('app-spec.js');const { lintAppSpec } = pluginLib('spec-lint.js');@@ -17,6 +20,10 @@ const { verifySpec } = pluginLib('verify-spec.js');// and the reverse-of-build teardown plan fully offline (no live env). See EVAL_GUIDE.md.const { planTeardown } = pluginLib('sdk-teardown.js');const { hydrateSpec } = pluginLib('hydrate-spec.js');+// entityFromMetadata is the PURE metadata->spec projection the downloader uses for a table's+// `columns[]`. Grading it here (rather than only in the plugin's unit tests) puts the download+// side of the round-trip under the same fixture corpus as the build side.+const { entityFromMetadata } = pluginLib2('download-model-app.js');// Plan 3's pure PAGEREF_ resolver may not be landed yet — load it optionally so the page oracle// degrades to a SKIP instead of crashing the harness. It IS present on this branch, but the@@ -86,7 +93,18 @@ function wireFacts(spec) {return {views: (spec.views || []).map((v) => { const d = viewDef(spec, v); return { entity: d.entityLogicalName, name: d.name, columns: d.columns.map((c) => c.name) }; }),charts: (spec.charts || []).map((c) => { const d = chartDef(spec, c); return { entity: d.entityLogicalName, name: d.name, measure: d.series[0].aggregate, groupBy: d.categories[0].attribute }; }),- forms: (spec.forms || []).map((f) => { const intent = compileFormIntent(spec, f, {}); return { entity: intent.entityLogicalName, name: intent.name, fields: formFieldLogicals(intent) }; }),+ forms: (spec.forms || []).map((f) => {+ const intent = compileFormIntent(spec, f, {});+ return {+ entity: intent.entityLogicalName,+ name: intent.name,+ fields: formFieldLogicals(intent),+ explicit: !!intent.__explicitLayout,+ authoredShape: authoredFormShape(f),+ compiledShape: compiledFormShape(intent),+ placements: formPlacements(intent),+ };+ }),defaultViews: defaultViewFacts(spec),subgrids: subgridFacts(spec),};@@ -128,6 +146,180 @@ function subgridFacts(spec) {return out;}+// --- form layout (#575) ------------------------------------------------------------------------+// An explicit `tabs` layout used to be FLATTENED at build time: every field was pushed into the+// deployed form's first section and no tab / form-column / section was ever created or resized, so a+// two-column form an author wrote was deployed as one long single-column list. Nothing in this corpus+// caught it, because no fixture used an explicit layout and no fact projected a form's SHAPE — only+// its flat field list.+//+// So the shape is projected TWICE, from two independent code paths, which is what makes comparing+// them an oracle rather than a restatement:+// · `authored` reads the raw spec, normalising the `sections` shorthand and the multi-column+// `columns[]` form itself rather than borrowing the plugin's helper — a reader that opens+// `tab.sections` directly silently skips every multi-column tab.+// · `compiled` reads compileFormIntent's output, which is what the engine actually deploys.+// Flattening collapses `compiled` while `authored` is unchanged, so the two diverge.+//+// Both keep sections GROUPED BY FORM-COLUMN. An earlier version flattened both sides, which made the+// oracle blind to a section moved between columns with its order and fields intact — the one thing a+// multi-column topology assertion most needs to see.+const cellsOfSection = (s) => ((s && s.rows) || []).flatMap((r) => (r && r.cells) || []);+// A sub-grid cell carries a RelationshipName parameter instead of a plain field control. The engine+// appends sub-grid sections on EVERY layout (auto included), so a shape comparison must ignore them+// or an authored-vs-compiled diff would report a section the author never wrote.+const isSubgridCell = (c) => !!(c && c.control && c.control.parameters && c.control.parameters.RelationshipName);+const labelOf = (x) => (x && x.label !== undefined ? x.label : null);++function authoredFormShape(f) {+ if (!f || !Array.isArray(f.tabs)) return null; // `auto` — the author declared no shape to honour+ // The `sections` shorthand IS one full-width form-column, so both shapes normalise to columns[].+ // Normalised HERE rather than through the plugin's own helper, so the oracle states the structure+ // independently of the code it grades.+ const columnsOf = (t) => (Array.isArray(t.columns) ? t.columns : [{ width: null, sections: t.sections || [] }]);+ return f.tabs.map((t) => ({+ label: labelOf(t),+ expanded: t.expanded !== false,+ columnCount: Array.isArray(t.columns) ? t.columns.length : 1,+ // Only widths the author actually WROTE. Omitted widths are split evenly by the compiler, and+ // asserting the eval's own copy of that split would grade the compiler against itself.+ declaredWidths: Array.isArray(t.columns) ? t.columns.map((c) => (c && c.width) || null) : [null],+ // Grouped BY FORM-COLUMN, not flattened. A flat list cannot see a section that moved from column+ // 0 to column 1 with its order and fields intact — which is precisely the topology this fixture+ // exists to prove, so flattening let the oracle pass a form it should have failed.+ sectionsByColumn: columnsOf(t).map((c) => ((c && c.sections) || []).map((s) => ({+ label: labelOf(s),+ columns: s.columns === undefined ? 1 : s.columns,+ fields: (s.fields || []).map((x) => lc(typeof x === 'string' ? x : x && x.name)),+ }))),+ }));+}++function compiledFormShape(intent) {+ return (intent.tabs || []).map((t) => ({+ label: labelOf(t),+ expanded: t.expanded !== false,+ columnCount: (t.columns || []).length,+ declaredWidths: (t.columns || []).map((c) => (c && c.width) || null),+ sectionsByColumn: (t.columns || []).map((c) => ((c && c.sections) || [])+ .filter((s) => !cellsOfSection(s).some(isSubgridCell))+ .map((s) => ({+ label: labelOf(s),+ columns: s.columns === undefined ? 1 : s.columns,+ fields: cellsOfSection(s).map((cell) => lc(cell.control && cell.control.fieldName)),+ }))),+ }));+}++// Every placed control, flattened. Feeds the two invariants that hold on EVERY layout: a field is+// placed exactly ONCE (the reconcile MOVES a misplaced control between sections — it must never+// duplicate one), and the placed set is exactly the set the form intends to carry.+function formPlacements(intent) {+ const out = [];+ for (const t of intent.tabs || []) {+ for (const c of t.columns || []) {+ for (const s of (c && c.sections) || []) {+ for (const cell of cellsOfSection(s)) {+ if (isSubgridCell(cell)) continue;+ out.push({+ tab: t.name,+ section: s.name,+ field: lc(cell.control && cell.control.fieldName),+ colspan: cell.colspan === undefined ? 1 : cell.colspan,+ rowspan: cell.rowspan === undefined ? 1 : cell.rowspan,+ });+ }+ }+ }+ }+ return out;+}++// --- download column projection (#574) ----------------------------------------------------------+// Dataverse materialises SHADOW attributes beside every lookup: `<lookup>name`, `<lookup>yominame`,+// and for a polymorphic (Customer / multi-target) lookup also `<lookup>idtype`. None was ever+// authored, and a download that emits them invents Text columns which a fresh-environment rebuild+// then really creates — replacing a lookup with two text fields.+//+// The two shadow shapes differ in the one field that used to be the whole filter. A single-target+// lookup's shadow is logical (`IsLogical: true`); a POLYMORPHIC lookup's shadow is physically stored,+// so `IsLogical` is false and that rule could not see it (#574). `AttributeOf` names the attribute a+// shadow projects and is the fact that covers both. Feeding both shapes through the real projection+// means a regression in EITHER rule surfaces here as an invented column.+//+// Dataverse's own AttributeType spelling per spec type — deliberately written out here rather than+// imported, because this models what the PLATFORM returns, not what the plugin believes.+const DATAVERSE_ATTRIBUTE_TYPE = {+ Text: 'String', Memo: 'Memo', Choice: 'Picklist', MultiChoice: 'Virtual', Boolean: 'Boolean',+ Money: 'Money', DateTime: 'DateTime', Integer: 'Integer', BigInt: 'BigInt', Decimal: 'Decimal',+ Double: 'Double', File: 'File', Image: 'Image', AutoNumber: 'String', Customer: 'Customer',+ Lookup: 'Lookup',+};++function downloadFacts(spec) {+ const out = [];+ for (const e of spec.entities || []) {+ if (!e || e.existing || !e.primaryAttribute) continue;+ const logical = lc(e.schemaName);+ const primary = lc(e.primaryAttribute.schemaName);+ const attrs = [];+ const shadows = [];+ const attr = (o) => attrs.push(Object.assign({ IsCustomAttribute: true, IsLogical: false, AttributeOf: null }, o));+ attr({ SchemaName: e.primaryAttribute.schemaName, LogicalName: primary, AttributeType: 'String' });++ // `polymorphic` picks the IsLogical value Dataverse reports, and gates the third shadow: only a+ // multi-target lookup needs an `idtype` discriminator.+ const addShadows = (lookupLogical, polymorphic) => {+ const isLogical = !polymorphic;+ for (const suffix of ['name', 'yominame']) {+ const n = `${lookupLogical}${suffix}`;+ attr({ SchemaName: n, LogicalName: n, AttributeType: 'String', AttributeOf: lookupLogical, IsLogical: isLogical });+ shadows.push(n);+ }+ if (polymorphic) {+ const n = `${lookupLogical}idtype`;+ attr({ SchemaName: n, LogicalName: n, AttributeType: 'EntityName', AttributeOf: lookupLogical, IsLogical: false });+ shadows.push(n);+ }+ };++ for (const col of e.columns || []) {+ if (!col || !col.schemaName) continue;+ const type = String(col.type || 'Text');+ attr({ SchemaName: col.schemaName, LogicalName: lc(col.schemaName), AttributeType: DATAVERSE_ATTRIBUTE_TYPE[type] || 'String' });+ if (type === 'Customer' || type === 'Lookup') addShadows(lc(col.schemaName), type === 'Customer');+ // A Money column gets a base-currency twin, and it is the awkward case: no `AttributeOf`, not+ // logical, and `IsCustomAttribute: true`, so every shadow rule is blind to it. `IsBaseCurrency`+ // is the only unambiguous signal — deliberately NOT the write-capability flag, which this spec+ // supports on authored read-only columns and which would turn a round-trip into a deletion.+ if (type === 'Money') {+ const twin = `${lc(col.schemaName)}_base`;+ attr({ SchemaName: twin, LogicalName: twin, AttributeType: 'Money', IsBaseCurrency: true });+ shadows.push(twin);+ }+ }+ // A relationship's lookup lands on the REFERENCING table and is single-target, so its shadow is+ // the logical variant. lookupColumnsFor is the same resolver the build side uses.+ for (const l of lookupColumnsFor(spec, logical) || []) {+ if (!l || !l.logical) continue;+ attr({ SchemaName: l.logical, LogicalName: l.logical, AttributeType: 'Lookup' });+ addShadows(l.logical, false);+ }+ // One stock attribute, so the custom-only rule stays under test alongside the shadow rules.+ attr({ SchemaName: 'CreatedOn', LogicalName: 'createdon', AttributeType: 'DateTime', IsCustomAttribute: false });++ const recovered = entityFromMetadata({ primaryNameAttribute: primary, attributes: attrs }, logical);+ out.push({+ entity: logical,+ authoredColumns: (e.columns || []).map((c) => lc(c && c.schemaName)).sort(),+ recoveredColumns: (((recovered && recovered.columns) || []).map((c) => lc(c && c.schemaName))).sort(),+ shadowNames: shadows.sort(),+ systemAttributes: ['createdon'],+ });+ }+ return out;+}+// app: sitemap subarea target facts + navigation-graph validity. appDef resolves page/dashboard// subareas from a result map; synthesize deterministic ids offline (no build) so the shape is stable.//@@ -483,6 +675,7 @@ async function stageFacts(rawSpec) {page: pageFacts(spec),process: processFacts(spec),teardown: teardownFacts(spec),+ download: downloadFacts(spec),roundTrip: await roundTripFacts(spec),PHASES,};diff --git a/evals/model-apps/app-builder/tests/facts.test.js b/evals/model-apps/app-builder/tests/facts.test.jsindex 9cf6b7401..bd83a3582 100644--- a/evals/model-apps/app-builder/tests/facts.test.js+++ b/evals/model-apps/app-builder/tests/facts.test.js@@ -242,3 +242,32 @@ test('security #2 least-privilege assertion: passes faithful mapping, catches ovgranted: { new_order: { read: 'user' }, appmodule: { read: 'organization' } },})).reason, /leak/);});++// The form-shape oracle used to FLATTEN sections across form-columns on both sides, so a section+// that moved from column 0 to column 1 — keeping its order and fields — produced identical flat+// lists and passed. That is precisely the topology this assertion exists to prove, so the oracle was+// blind to the defect class it was written for. Both projections now group by form-column.+test('the form-topology assertion sees a section moved between form-columns', () => {+ const check = ASSERTIONS.get('ui: an explicit layout compiles to the authored tab, form-column and section topology (it is not flattened)');+ const sec = (label, fields) => ({ label, columns: 1, fields });+ const tab = (byColumn) => ({+ label: 'General', expanded: true, columnCount: byColumn.length,+ declaredWidths: byColumn.map(() => null), sectionsByColumn: byColumn,+ });+ const authored = [tab([[sec('L', ['a'])], [sec('R', ['b'])]])];+ const run = (compiled) => check({ facts: { ui: { forms: [{ name: 'F', authoredShape: authored, compiledShape: compiled, placements: [] }] } } });++ assert.strictEqual(run([tab([[sec('L', ['a'])], [sec('R', ['b'])]])]).status, 'pass',+ 'the authored topology compiled faithfully must still pass');++ // Both sections collapsed into column 0. Flattened, this is still [L, R] — indistinguishable from+ // the correct shape, which is exactly how it used to slip through.+ const collapsed = run([tab([[sec('L', ['a']), sec('R', ['b'])], []])]);+ assert.strictEqual(collapsed.status, 'fail', 'a section moved out of its form-column must fail');+ assert.match(collapsed.reason, /form-column 0/, `the failure must name the form-column: ${collapsed.reason}`);++ // Same section count per column, but swapped between them — the subtlest version, where every+ // per-column count matches and only the contents moved.+ const swapped = run([tab([[sec('R', ['b'])], [sec('L', ['a'])]])]);+ assert.strictEqual(swapped.status, 'fail', 'sections swapped between form-columns must fail');+});\ No newline at end of filediff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 6d812aee6..c2ce722dc 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -12,6 +12,12 @@ downloads that round-trip Choice columns.### Added+- **Richer form layouts: multi-column tabs, cell spans, and per-container visibility.** A tab can+ now hold several form-columns (`tabs[].columns[]` with a `width`), a field entry can set+ `colspan`/`rowspan`, and `expanded`/`visible`/`showLabel` are author-controlled. Layout keys are+ allow-listed, so a typo — or a key the SDK's serializer would discard — fails instead of silently+ vanishing. The form wireframe renders the new structure, since that preview is the approval gate.+- **The dry run resolves create-vs-reuse against the live environment** ([#559]). Without `--apply`the plan was a static echo of the spec, identical whether every artifact already existed or nonedid — the one question a dry run exists to answer. Each item is now `+ create` or `= reuse`, with@@ -27,6 +33,80 @@ downloads that round-trip Choice columns.### Fixed+- **Editing a form with an explicit layout reshapes it, instead of flattening it** ([#575]). Every+ field was appended to the first section of the first tab, nothing was ever created or resized, and+ declaring explicit `tabs` simultaneously switched **pruning** on — so an author moving a deployed+ form to a two-column layout got the old layout, minus any field they had not re-declared, and a+ green build. Tabs, form-columns and sections are now created when missing, patched in place when+ they differ, and a field in the wrong section is **moved** rather than duplicated. Containers match+ by `name`, then `label`, then position, so a form built by an earlier `auto` layout converges+ instead of gaining a duplicate tab on every rebuild; sections the engine owns (a sub-grid host, the+ notes/timeline section) are matched by name only.+- **`--verify` no longer demands a default form the build never promotes.** The build refuses to+ re-point the default form of a reused or stock table, but the verifier asserted it anyway — so any+ spec with a Main form on `account`, `contact`, or an `existing: true` table failed verify+ permanently. Verify now applies the build's own guard.+- **A tab's `columns` must be a list of form-columns.** `columns` is an integer grid width on a+ *section* and an array of form-columns on a *tab* — the schema's most confusable key. `"columns": 2`+ on a tab validated clean and was then discarded by the compiler, silently shipping a one-column+ form. It is now an error that names the fix.+- **Duplicate sample-data names fail at author time, not halfway through the build.** The loader+ refuses to use a duplicated value as its `matchOn` key — a refusal that landed after tables, forms+ and views were already deployed. Two tickets both called "Printer issue" is ordinary sample data;+ it is now caught by `validateAppSpec`, with the same escape hatches the loader honours, and the+ rule now also covers a single-column alternate key when that is what `matchOn` selects.+- **Cell spans converge on an existing form, and are clamped where they are written.** `colspan`/+ `rowspan` were create-only, so widening a field on a deployed form produced a green build and an+ unchanged cell. A declared span is now written to the deployed cell, while an undeclared one is+ still never sent, so a cell a maker widened by hand survives. A `colspan` wider than its section is+ now clamped in the emitted cell, not only in the row arithmetic. A `rowspan` is rejected unless it+ is the last field in its section — a compiler limitation, tracked in [#581].+- **A build no longer reports a default form it failed to set.** `result.created.defaultForms`+ recorded the entity even when the `isdefault` write threw.+- **`--verify` proves sort PRECEDENCE, not just membership.** Each authored order was checked for+ existence anywhere in the deployed query, so a deployed `[name asc, createdon desc]` satisfied an+ authored `[createdon desc, name asc]` — two views that return rows in different orders. Authored+ orders must now appear in their declared relative order; extra platform orders are still tolerated.+- **Dashboard id-passthrough tiles are validated per tile type.** One shared test covered both+ shapes, so a list tile carrying a stray `visualizationId` skipped the `viewId` requirement and a+ chart tile with only a `viewId` passed with no visualization to render. The download was made+ consistent in the same change.+- **A downloaded relationship that is renamed is no longer reported as lost.** A relationship carried+ into the spec under a generated name was also recorded as skipped, so the summary claimed it was+ absent. It is now reported as a rename, and a parent table whose metadata could not be read is+ reported as undetermined rather than diagnosed wrongly.+- **Two silent no-ops now report themselves.** A failed default-form promotion was swallowed+ entirely; it now warns with the reason, and `--verify` proves the deployed `systemform.isdefault`+ independently. An **existing** view's authored filters/sort are still not reapplied — only columns+ and description converge — and that is now said out loud instead of reported as success.+- **`_seedKey` in `sampleData` is rejected instead of being sent to Dataverse.** It was never a+ loader sentinel, so it reached the API as an attribute no table has. The error names the real+ mechanism: a single-column alternate key. Ambiguous parent binds are rejected for the same reason+ rather than binding to an arbitrary row.+- **`--verify` gained three oracles**: the deployed default Main form, a view's authored+ filters/sort parsed from `fetchxml`, and app-role associations. Each fails closed when its proof+ cannot be read.+- **A download no longer invents text columns from a polymorphic lookup** ([#574]). A polymorphic+ lookup's shadow attributes are stored physically, so unlike a single-target lookup's they slipped+ past the filter that catches the rest: `<lookup>name` and `<lookup>yominame` were emitted as real+ `Text` columns, and a rebuild into a fresh environment gained two invented text fields where a+ lookup used to be. The filter now keys on `AttributeOf`, which names the attribute a shadow belongs+ to; an unreadable value keeps the column rather than deleting it.+- **A download no longer invents a Money column's base-currency twin either.** Found by live+ round-trip after the fix above. Dataverse generates a `<money>_base` column beside every `Money`+ column, and it carries no `AttributeOf`, so the rule above is blind to it — the downloaded spec+ declared it as an authored column, and a rebuild would try to create a column the platform owns.+ Recognised by `IsBaseCurrency`, which is the only unambiguous signal; an unreadable value keeps the+ column.+- **A download reconstructs `relationships[]`** ([#567]). The block was absent entirely and nothing+ said so, so a downloaded spec looked complete while a rebuild produced tables with no lookups and+ no hierarchy, reporting success. 1:N and N:N relationships are now read from live metadata, and any+ the App Spec cannot express — a polymorphic lookup, a parent outside the app — are named with a+ reason instead of vanishing.+- **A downloaded spec no longer fails its own lint** ([#572]). A downloaded dashboard carries+ id-passthrough tiles, which `validateAppSpec` and the build accept but the lint did not — so+ `lint-app-spec.js` rejected a freshly downloaded spec with six errors reporting a chart literally+ named `'undefined'`. The lint now understands them and reports a missing reference as missing.- **A download round-trips Choice and MultiChoice columns** ([#564]). They were emitted with no`type`, so rebuilding into a **fresh** environment created single-line Text while Memo, Money andDateTime survived — an asymmetry harder to notice than an outright failure. Option sets are now@@ -84,12 +164,26 @@ downloads that round-trip Choice columns.mean" suggestion cannot drift between commands.- **Deeper tests on the paths connectors GA just made live**, including a connector *edit* eval anda contract test pinning the dispatch fields the skills hand to the page-builder.+- **A form layout may no longer place the same field twice, or reuse a tab/section `name`.** Both+ are now rejected at author time: a duplicated field deployed two cells on a fresh build and one on+ the next, so the spec did not survive its own rebuild. Remove the duplicate placement. Identity is+ per form — a second form on the same table may still place the same column.+- **A download now reports every dashboard tile it drops** instead of discarding it in silence,+ naming the parameter the tile lacks.+- **An explicit form layout with no tabs, or a tab with no sections, is rejected at author time.** It+ previously passed the build gate — only the standalone lint caught it — and silently dropped every+ field the form declared.[#541]: https://github.com/microsoft/power-platform-skills/issues/541[#544]: https://github.com/microsoft/power-platform-skills/issues/544[#559]: https://github.com/microsoft/power-platform-skills/issues/559[#564]: https://github.com/microsoft/power-platform-skills/issues/564[#565]: https://github.com/microsoft/power-platform-skills/issues/565+[#567]: https://github.com/microsoft/power-platform-skills/issues/567+[#572]: https://github.com/microsoft/power-platform-skills/issues/572+[#574]: https://github.com/microsoft/power-platform-skills/issues/574+[#575]: https://github.com/microsoft/power-platform-skills/issues/575+[#581]: https://github.com/microsoft/power-platform-skills/issues/581## [2.7.1]diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex 1388b772e..b6b27bb62 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -234,6 +234,13 @@ works through.- Built after views/charts (it references their ids). The dashboard is **global** (not entity-scoped)and added to the solution. To surface it in the app nav, add a `dashboard` sitemap subarea (below) —that also auto-pins it as an app component.+- **ID-passthrough tiles (what a download emits).** A tile may instead carry the *deployed* ids —+ `viewId` (+ `visualizationId` for a chart) and the target `entity` — with no `chart`/`view` name.+ That form binds to artifacts that **already exist**, which is what a downloaded app needs: its+ views and charts are not reconstructed into `views[]`/`charts[]`, so a name could not resolve.+ An id-based chart tile needs `viewId` **and** `entity` (a visualization with no view has nothing+ to plot); an id-based list tile needs `viewId` and `entity`. Author specs by name; let downloads+ use ids.## roleGrants[] (optional — extend a role you did NOT author)diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex c508ba746..3f14b2485 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -234,6 +234,18 @@ agent later inspects an app it did not build — to extend it, debug it, or answGood: `"Severity 1-5; drives the escalation rule and the SLA clock."`Weak: `"The priority column."` (restates the name and adds nothing)+**`app.description` additionally has to ROUTE.** It is the one field an orchestrator reads to decide+whether *this* app is the right place to send a request, and there is no separate "AI description"+field — the SDK's app surface has nowhere to put one, so anything extra would be silently dropped.+Write the routing signal into `app.description` itself: who the app is for, the tasks it covers,+what it deliberately **excludes**, and — when two apps expose the same tables — how to tell them+apart. Sibling apps over the same data are precisely where a purpose-only description fails.++Good: `"Project-manager and portfolio work: planning projects, assigning and reprioritizing work,+and managing sprints, budgets, risks and releases. Prefer the My Work app when the request is about+the signed-in contributor's own assigned items."`+Weak: `"An app for managing projects."` (no persona, no scope boundary, nothing to disambiguate)+**Rules:** must be a non-empty string, max 2000 characters (the Dataverse ceiling — the platformtruncates silently past it, so it is rejected at author time instead). Omit the field entirely ratherthan setting `""`; every write site omits an absent description, so **a rebuild never blanks one a@@ -480,6 +492,24 @@ run the lint, so an unlinted spec hits the failure at build time instead).the junction. Sample rows then bind **both** parents via `$parents` (see sampleData). This is therecommended pattern for "Technician ↔ Work Order with a Role".+**What a download reconstructs.** `download-model-app.js` rebuilds `relationships[]` from live+metadata, keeping the lookup's deployed casing (`new_CustomerId`, not `new_customerid`) and its+label. It emits an explicit `schemaName` only when the deployed name differs from the generated+default, so a rebuild into the **same** environment matches the existing relationship instead of+creating a second one beside it. Three cases it **cannot** express are reported by name and reason+rather than silently dropped:+- a **polymorphic** lookup — one column targeting several tables (Dataverse surfaces it as several+ relationships sharing one lookup attribute), where `relationships[]` declares exactly one+ `referenced` table per lookup;+- a parent that is a **custom table the app does not include**, which a rebuild target would not+ have (a bridge to a *standard* table like `systemuser`/`account` is kept — every org has one);+- an **N:N whose partner table is outside the app**.++A polymorphic lookup's **shadow attributes** (`<lookup>name`, `<lookup>yominame`) are excluded from+`columns[]` along with it, so a rebuild does not gain invented Text columns where the lookup used to+be. Every lookup has shadows; a polymorphic one's are physically stored rather than logical, which is+why they need naming here at all.+## views[]```jsonc{ "entity": "new_ticket", "name": "Active Tickets", "columns": ["new_subject","new_priority"],@@ -537,6 +567,19 @@ run the lint, so an unlinted spec hits the failure at build time instead)."tabs": [ { "label": "General", "sections": [{ "label": "Details", "columns": 2, "fields": ["new_name","new_budget","new_status"] } ] } ] }+// explicit layout, richer: multi-column tabs, per-cell spans, visibility+{ "entity": "new_project", "type": "main", "name": "Project",+ "tabs": [+ { "name": "tab_delivery", "label": "Delivery", "expanded": true, "columns": [+ { "width": "65%", "sections": [+ { "name": "sec_scope", "label": "Scope", "columns": 2, "fields": [+ { "name": "new_summary", "colspan": 2 }, // span the whole 2-column section+ "new_startdate", "new_targetdate" ] } ] },+ { "width": "35%", "sections": [+ { "name": "sec_status", "label": "Status", "columns": 1, "fields": ["new_status","new_owner"] } ] } ] },+ { "name": "tab_audit", "label": "Audit", "expanded": false,+ "sections": [ { "name": "sec_audit", "label": "Audit", "columns": 2, "fields": ["createdon","modifiedon"] } ] } ] }+// per-field control options: read-only, hidden, and targeted positioning{ "entity": "new_workitem", "name": "Work Item", "layout": "auto","fieldOptions": {@@ -589,6 +632,12 @@ run the lint, so an unlinted spec hits the failure at build time instead).default and only ever applies to a table THIS build owns (a custom, publisher-prefixed, non-`existing`table); it never touches a reused/system table. Teardown reactivates the stock form before deletingours, so a torn-down table is left clean.+- **`isDefault`** *(optional, boolean, Main forms only)* — which Main form the table **opens with**.+ Exactly one Main form per table may set it; the fallback is the first Main form in spec order, so+ selection is order-independent either way (it is applied once, after every form exists, rather than+ each form racing to promote itself). A promotion the environment refuses is reported as a warning+ and fails `--verify`, which proves the deployed `systemform.isdefault` independently — so a build+ can no longer record a default it did not actually set.- **Form resolution is by `(entity, name, formType)`** — a Dataverse form name is unique only per`(entity, type)`, so a table's auto-created **Main**, **Quick View**, and **Card** forms can all benamed "Information" without colliding. A `formType:"Main"` edit reconciles **only** the Main form;@@ -606,6 +655,77 @@ run the lint, so an unlinted spec hits the failure at build time instead).is truthy in JS and would silently enable a handler you meant to disable.The build fetches the pushed form, injects the handlers, then publishes it.+### Explicit layout — tabs, form-columns, sections++| Level | Key | Meaning |+|---|---|---|+| tab | `name` | Stable identity. Emitted as `tab_<i>` when omitted — see *editing an existing form* below. |+| tab | `label` | Tab title. |+| tab | `expanded` | `false` collapses the tab on open (default `true`). |+| tab | `visible` | `false` hides the tab (default `true`). |+| tab | `sections[]` | Shorthand for **one full-width form-column**. |+| tab | `columns[]` | The multi-column form: each entry is `{ "width": "60%", "sections": [...] }`. |+| form-column | `width` | Percentage string (`"60%"`). Omitted widths split evenly (3 columns → 34/33/33). |+| section | `name` | Stable identity, `section_<tab>_<i>` when omitted. |+| section | `label`, `showLabel`, `visible` | Section heading, whether it renders, whether the section shows. |+| section | `columns` | `1`–`4` grid columns. |+| section | `fields[]` | Column logical names, or `{ "name": …, … }` entries. |+| field entry | `colspan`, `rowspan` | Whole numbers ≥ 1. A cell wider than its section is clamped to it — the clamp reaches the deployed cell, not just the row packing. `rowspan` is valid only on the **last** field of a section (see below). |++A tab declares **either** `sections` **or** `columns`, never both. `columns` on a **tab** is the list+of form-columns; `columns` on a **section** is its 1–4 grid width — a number on a tab is rejected+rather than silently discarded. Any other key is **rejected** — including `showLabel`/`labelPosition`+on a tab and `labelPosition`/`locked` on a section, which the SDK's serializer silently discards, so+accepting them would promise a layout Dataverse never renders.++**Names are identity, and a field is placed once per form.** Two tabs — or two sections — on one+form may not share a `name`, and a column may not be placed twice, whether in two different sections+or twice in the same one (matching is case-insensitive, and applies to both the string and the+`{ "name": … }` entry shape). All three are rejected at author time.++The reason is that create and rebuild would otherwise disagree. The compiler emits **one cell per+entry**, so a fresh build deploys a duplicated field twice, while every reconcile path resolves a+field to its **first** placement — the second cell would appear on the initial create and then vanish+on the next build of the same spec. Duplicate container names fail the same way: `name` is what the+build matches a deployed tab or section by, so two declarations sharing one would target the same+live container. A second form on the same table may of course place the same column — identity is+per form.++**`rowspan` must be the last field in its section.** A cell that spans down reserves its column in+the rows beneath it, and the cells of the following row fill the section left to right — so a field+declared after a spanning one would land in the reserved slot. Every stock Dataverse form that uses+`rowspan` puts it on the last cell of its section, so that is the shape this plugin emits.++This is a **compiler limitation, not a platform one.** Positioning a field beside a vertical span+requires emitting an empty *spacer* cell to occupy the reserved slot, which the SDK serializes+correctly; the compiler does not emit one yet. The restriction can be lifted once it does — tracked+in [#581](https://github.com/microsoft/power-platform-skills/issues/581).++**Editing an existing form.** An explicit layout is converged onto the deployed form rather than+flattened into its first section: missing tabs, form-columns and sections are **created**, a+section's `columns`/`label`/`showLabel`/`visible` are **updated in place**, and a field sitting in+the wrong section is **moved** (never duplicated — the cell keeps its id and any control state a+maker edited). Containers are matched by `name`, then `label`, then position, so a form built by an+earlier `auto` layout — or by hand in Maker — converges instead of gaining a duplicate tab. Nothing+is renamed, because form scripts and business rules can reference a section by name.++Two rules keep that matching from claiming the wrong container. An index an earlier tab or section+already matched is **not reused**, because an unlabeled container compiles to a default label+(`General` for a tab, `Details` for a section) and several of them would otherwise all match the+first one. And sections the **engine** owns — a sub-grid host, the notes/timeline section — are+matched only by `name`: a label or a position is not evidence about what a container *is*, and+matching one positionally would relabel a sub-grid and place fields in the row holding its grid.++⚠ Containers are only ever added or updated, never removed. Moving a section between form-columns or+tabs while letting its `name` be generated therefore leaves the original behind as an **empty+section with the same label** — generated names encode position (`section_<tab>_<column>_<index>`),+so the moved section is a different identity. Give a section an explicit `name` when you intend to+move it, and delete a section you no longer want in Maker.++⚠ Declaring explicit `tabs` also switches **pruning** on: a field the deployed form carries and the+layout does not list is removed (never the primary field). Set `"prune": false` to restyle or+reorder a subset without re-declaring every other field.+### Per-field control options — `readOnly`, `hidden`, `after`A form field can carry three per-control options. Declare them **form-level** in `fieldOptions`diff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.mdindex c8bd5c318..57cb6c0ed 100644--- a/plugins/model-apps/references/authoring-flow.md+++ b/plugins/model-apps/references/authoring-flow.md@@ -336,8 +336,10 @@ columns that complement rather than duplicate what's already there. Build**By default, give every _custom_ table you create a meaningful table icon** so the app nav shows arecognizable glyph instead of the generic Dataverse table cube. This is the default authoringbehavior — only skip it if the user declines. (A model-driven app's nav icon for an `entity`-subarea comes from the **table's own icon**, not the sitemap subarea — a subarea `vectorIcon` is-ignored for entity subareas.)+subarea normally comes from the **table's own icon**, so leaving the subarea's icon unset is the+right default. A subarea `vectorIcon` is honoured on an entity subarea when it is a resolvable+path or `$webresource:` reference; only a bare Fluent **token** is dropped there, because that+shape breaks the modern app designer's property pane.)**Propose the icon in words FIRST, before you author any SVG.** For each custom table, say what theglyph will **depict** — "a briefcase", "an outlined clipboard with a checkmark", "a laptop with a@@ -430,6 +432,23 @@ is optional — omit it to title the grid with the child entity's `pluralName` (supply it to override. To ship only your form and hide the blank stock "Information" form, set`"deactivateOtherMainForms": true` on the form (opt-in; only affects tables this build owns).+**Choosing auto vs an explicit layout.** `auto` is the right default and already adapts: it puts+the primary field first and switches to **two columns above six fields** (Quick Create stays one+column, which Dataverse requires). What it cannot do is *group by task*.++So prefer an **explicit** layout — tabs and sections named for the work — once a Main form is+field-heavy or the fields fall into obviously different jobs (execution vs estimates vs approval).+Group by what the user is doing, put the record's name and its most decision-relevant status or+lookup first, and use `colspan` for a field that reads badly in a narrow cell (a long description,+a full-width summary). This is a **default, not a rule**: a short form, a Quick Create, or a single+coherent group is genuinely better as one column, and `auto` remains a correct answer.++⚠ **When EDITING a deployed form, an explicit layout also switches pruning on** — a field the form+carries that your `tabs` do not list is removed. Either re-declare the full field set, or set+`"prune": false` to restructure a subset safely. Tabs and sections themselves now converge (they+are created, patched and have fields moved into them), so the layout you show in the wireframe is+the layout that lands.+**Show the form wireframe.** After writing the proposed forms to `app-spec.json`, render anASCII wireframe so the user can *see* each form's tabs, sections, fields, the Notes block, andsub-grids before approving — then ask for changes:@@ -474,6 +493,20 @@ Propose one active-records view per entity. Include the primary attribute plusthe 2–4 most useful columns for quick scanning. Set `"activeOnly": true` andprovide a sensible `sort`.+Then add a **task-oriented view** wherever a persona's job implies a question the+default view cannot answer — *My Active Work Items*, *Blocked Work Items*,+*High-Severity Open Risks*. Name it for the decision it supports, and sort by the+field the user actually prioritizes by. Direct-column filters on the view's own+table are supported, including current-user (`ownerid` / `eq-userid`) and relative+dates; a filter **through a related table** is not expressible and must not be+faked — say so and propose a supported alternative.++Two edit-time limits worth stating up front, because both bite silently:+an authored view whose name collides with the table's stock default view MERGES+onto that default (its filters and sort are ignored), and an **existing** view's+filters/sort are not reapplied on a rebuild — only its columns and description+converge. Prefer a distinct name for anything you want filtered your way.+#### ChartsAuto-suggest **one chart per Choice column on the primary entity**, alternating@@ -563,8 +596,20 @@ Author the intent shape — **not `.tsx`**:#### App shellAlso propose the `appShell` block — the sitemap areas, groups, and subAreas that-wire each entity into the app's navigation. Keep it simple: one area, one group,-one subArea per entity.+wire each entity into the app's navigation.++Group by the **workflow** a user is in, not by "one group per table". A handful of+named groups that read like the jobs from Level (a) — e.g. *Delivery* (Projects,+Work Items, Sprints), *Tracking* (Risks, Issues), *Customers* (Accounts, Contacts) —+is what separates a polished app from a flat list, and the builder already emits+groups and subAreas in the order you author them. For a small app (roughly four+tables or fewer) one group is genuinely the right answer; above that, say which+workflow each group serves.++Leave a table **out** of the nav when users never start a task there — a junction+or configuration table reached only through a parent form or a sub-grid. A table+with no subarea still works everywhere it is referenced (verification deliberately+allows supporting tables without navigation).#### Shippable-defaults notediff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex 5bd33e557..9712903ee 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -17,7 +17,7 @@ const { parseManifestBase64, manifestResourceName, reconcilePageIds } = require(const { reverseResolveNavIds } = require('./lib/pageref-resolver.js');const { fetchSitemap, sitemapGenPages } = require('./lib/sitemap-pages.js');const { isRestrictedSolution } = require('./lib/system-solutions.js');-const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, ambiguousChoiceAliases } = require('./lib/app-spec.js');+const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, ambiguousChoiceAliases, relationshipSchemaName } = require('./lib/app-spec.js');const { odataGuid } = require('./lib/ai-app-settings.js');// webresourcetype (int) -> app-spec web-resource type.@@ -63,10 +63,43 @@ async function readDashboards(sdk, app, warn) {const p = c.parameters || {};const entity = p.TargetEntityType;const viewId = strip(p.ViewId);- if (c.type === 'chart' && viewId) tiles.push({ type: 'chart', name: c.name, entity, viewId, visualizationId: strip(p.VisualizationId) });- else if (c.type === 'list' && viewId) tiles.push({ type: 'list', name: c.name, entity, viewId });+ if (c.type === 'chart' || c.type === 'list') {+ // The two id-passthrough tile shapes, gated together because they share their required+ // parameters. EVERY one of these ids is load-bearing: a chart renders a visualization OVER a+ // view, so it needs both ids, and `entity` is required by both spec gates for either shape.+ // Emitting a tile missing any of them hands back a spec that fails its own lint — the exact+ // #572 defect class — so name the missing parameter and omit the tile rather than shipping+ // one a rebuild cannot honour.+ //+ // Collected as a LIST rather than reported one-at-a-time so a component missing several+ // parameters says so once, and — the reason this is not an `&& viewId` guard — so a tile+ // with no ViewId is reported too. Falling through to the unsupported-type branch would have+ // dropped it with no stated cause, which is the untraceability this whole block exists to end.+ const visualizationId = c.type === 'chart' ? strip(p.VisualizationId) : undefined;+ const missing = [];+ if (!entity) missing.push('TargetEntityType');+ if (!viewId) missing.push('ViewId');+ if (c.type === 'chart' && !visualizationId) missing.push('VisualizationId');+ if (!missing.length) {+ tiles.push(c.type === 'chart'+ ? { type: 'chart', name: c.name, entity, viewId, visualizationId }+ : { type: 'list', name: c.name, entity, viewId });+ } else if (typeof warn === 'function') {+ warn(`dashboard '${name}' ${c.type} tile '${c.name || viewId || '(unnamed)'}' carries no ${missing.join(' or ')}, so it cannot be rebuilt; it is omitted from dashboards[].`);+ }+ }else if (c.type === 'iframe' && p.Url) tiles.push({ type: 'iframe', name: c.name, url: p.Url });else if (c.type === 'webresource' && p.WebResourceName) tiles.push({ type: 'webresource', name: c.name, webResource: p.WebResourceName });+ // Everything else a dashboard can hold. Reported for the same reason as the branches above: the+ // dashboard-level "no recognizable tiles" warning below only fires when NOTHING survives, so a+ // dashboard with one good tile would otherwise drop its siblings in silence.+ else if (typeof warn === 'function') {+ const missingParam = c.type === 'iframe' ? 'Url' : c.type === 'webresource' ? 'WebResourceName' : null;+ warn(`dashboard '${name}' tile '${c.name || '(unnamed)'}' of type '${c.type}' `+ + (missingParam+ ? `carries no ${missingParam}, so it cannot be rebuilt; it is omitted from dashboards[].`+ : `is not a tile type the App Spec can express, so it is omitted from dashboards[].`));+ }}// A dashboard that read cleanly but yielded no usable tile is ALSO a silent drop — the subarea// disappears with nothing said. Distinguish it from the unreadable case above.@@ -79,6 +112,202 @@ async function readDashboards(sdk, app, warn) {return out;}+// Reconstruct relationships[] from live metadata (#567).+//+// Derived from the CHILD ("referencing") side via `ManyToOneRelationships`, because that is how App+// Spec indexes a 1:N: `referencing` is the table that carries the lookup column. Reading from the+// parent side instead would miss the documented "bridge to a standard table" pattern — where the+// parent is `systemuser`/`account` and is therefore never one of the downloaded entities, so its+// metadata is never read — which references/app-spec-schema.md explicitly supports.+//+// This deliberately does NOT use the SDK's `fetchEntityMetadata().relationships` projection, which+// LIVE-MEASURED returns entries shaped:+// {"schemaName":"cfo_workorder_SyncErrors","type":"OneToMany","relatedEntity":"syncerror","relatedAttribute":"regardingobjectid"}+// and is missing all three facts this needs: (1) no `IsCustomRelationship`, and on a 3-table app 20+// of 22 entries per table were platform plumbing (SyncErrors, AsyncOperations,+// MailboxTrackingFolders, BulkDeleteFailures, …) that must not become spec relationships; (2) no+// properly-cased lookup `SchemaName` — App Spec wants `cfo_CustomerId`, the projection lowercases+// to `cfo_customerid`; and (3) no ManyToMany entries.+//+// Returns { relationships, skipped } — `skipped` feeds the not-round-tripped report so a+// relationship this cannot express is DECLARED missing rather than silently absent, which was the+// whole complaint in #567.+async function readRelationships(sdk, logicals, publisherPrefix, warn) {+ const inApp = new Set((logicals || []).map((l) => String(l).toLowerCase()));+ const lc = (s) => String(s || '').toLowerCase();+ const relationships = [];+ const skipped = [];+ const seen = new Set(); // relationship SchemaName (lower) — a 1:N read from both ends, and every N:N, appears twice+ const parentOk = new Map(); // logical -> can a rebuild target be relied on to have this table?+ const note = (name, entity, reason) => {+ skipped.push({ name, entity, reason });+ if (typeof warn === 'function') warn(`relationship '${name}' on '${entity}' is not carried into the spec: ${reason}`);+ };++ // A parent OUTSIDE the app is only safe to declare when a fresh rebuild target is guaranteed to+ // have it — i.e. it is a stock table. A CUSTOM table this app does not include would not exist+ // there, so declaring the relationship would turn a silent omission into a failed build.+ // Three OUTCOMES, deliberately kept apart: the parent is in the app or is a stock table+ // ('rebuildable'); it is a confirmed custom table this app omits ('custom'); or its metadata could+ // not be read ('unknown'). Collapsing the last two into `false` made a transient 403/503 report+ // the confident and possibly wrong diagnosis "is a custom table this app does not include".+ const referencedRebuildability = async (logical) => {+ const key = lc(logical);+ if (inApp.has(key)) return 'rebuildable';+ if (parentOk.has(key)) return parentOk.get(key);+ let state = 'unknown';+ try {+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}?$select=IsCustomEntity`);+ if (res && res.status >= 200 && res.status < 300 && res.body) {+ state = res.body.IsCustomEntity === false ? 'rebuildable' : 'custom';+ }+ } catch { state = 'unknown'; }+ parentOk.set(key, state);+ return state;+ };++ for (const logical of logicals || []) {+ let rows = null;+ try {+ // `dataverse.get` RESOLVES on a non-2xx rather than throwing, so the status must be checked+ // explicitly — a bare try/catch would turn a 403 into "this table has no relationships".+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/ManyToOneRelationships`+ + '?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,IsCustomRelationship');+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);+ rows = ((res.body && res.body.value) || []).filter((r) => r && r.IsCustomRelationship);+ } catch (e) {+ // Report rather than swallow: "no relationships" and "the query failed" must not look alike.+ // `rows` stays null so the 1:N block below is skipped, but the N:N read still runs — an+ // earlier version `continue`d here, which meant a failed 1:N read ALSO skipped the N:N read+ // silently, leaving any N:N both unreconstructed and unmentioned.+ note('(all)', lc(logical), `their metadata could not be read (${e && e.message})`);+ }++ if (rows === null) rows = [];+ // Properly-cased lookup SchemaName + label. Best-effort: on failure the relationship still+ // round-trips using the lowercase logical name, which produces the same Dataverse column.+ // Skipped entirely when there is no relationship to label, so a table whose 1:N read failed+ // does not also pay for an attribute read whose result nothing would consume.+ const lookups = new Map();+ if (rows.length) {+ try {+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata`+ + '?$select=LogicalName,SchemaName,DisplayName,Targets');+ for (const a of ((res && res.body && res.body.value) || [])) lookups.set(lc(a.LogicalName), a);+ } catch { /* fall back to the relationship's own ReferencingAttribute */ }+ }++ // POLYMORPHIC lookups. One lookup column that targets several tables surfaces as SEVERAL+ // relationships sharing ONE ReferencingAttribute — LIVE-MEASURED, `cfo_billto` with+ // Targets ["account","contact"] produced BOTH `cfo_cfo_workorder_account` and+ // `cfo_cfo_workorder_contact`. relationships[] has exactly one `referenced` per lookup, so+ // emitting both would declare the same lookup schema name twice and the rebuild would fail+ // creating the second. Skip the whole group and say so.+ const byAttr = new Map();+ for (const r of rows) {+ const k = lc(r.ReferencingAttribute);+ if (!byAttr.has(k)) byAttr.set(k, []);+ byAttr.get(k).push(r);+ }++ for (const [attr, group] of byAttr) {+ if (group.length > 1) {+ note(group.map((g) => g.SchemaName).sort().join(' + '), lc(logical),+ `lookup '${attr}' is polymorphic (targets ${group.map((g) => lc(g.ReferencedEntity)).sort().join(', ')}) and relationships[] declares exactly one referenced table per lookup`);+ continue;+ }+ const r = group[0];+ const key = lc(r.SchemaName);+ if (seen.has(key)) continue;+ const referenced = lc(r.ReferencedEntity);+ const referencing = lc(r.ReferencingEntity);+ const rebuildability = await referencedRebuildability(referenced);+ if (rebuildability !== 'rebuildable') {+ note(r.SchemaName, referencing, rebuildability === 'custom'+ ? `its parent table '${referenced}' is a custom table this app does not include, so a rebuild target would not have it`+ : `its parent table '${referenced}' could not be read, so whether a rebuild target would have it could not be determined`);+ continue;+ }+ seen.add(key);+ const a = lookups.get(attr);+ const lookup = { schemaName: (a && a.SchemaName) || r.ReferencingAttribute };+ const displayName = a && labelFromDataverse(a.DisplayName);+ if (displayName) lookup.displayName = displayName;+ // The deployed schema name is emitted ONLY when it differs from the one the build would+ // generate anyway AND it satisfies the publisher-prefix rule the lint enforces+ // (spec-lint.js "must start with the publisher prefix"). Emitting a foreign-prefix name would+ // hand back a spec that fails its own lint — the exact defect #572 is about — while omitting a+ // DIVERGENT name would make a rebuild into this same environment create a second relationship+ // beside the existing one instead of matching it.+ const auto = relationshipSchemaName({ referenced, referencing }, publisherPrefix);+ const deployed = r.SchemaName;+ const prefixOk = !publisherPrefix || lc(deployed).startsWith(`${lc(publisherPrefix)}_`);+ const rel = { type: 'OneToMany', referenced, referencing, lookup };+ if (deployed && lc(deployed) !== lc(auto)) {+ if (prefixOk) rel.schemaName = deployed;+ else if (typeof warn === 'function') {+ // RENAMED, not skipped. This relationship IS pushed below, so recording it in `skipped`+ // made the summary claim it was "absent from the rebuildable spec" — the opposite of what+ // happens. Warn through the plain channel so the rename stays visible without being+ // counted as a loss.+ warn(`relationship '${deployed}' on '${referencing}' does not start with this solution's publisher prefix '${publisherPrefix}_', so the spec rebuilds it under the generated name '${auto}' instead`);+ }+ }+ relationships.push(rel);+ }++ // Many-to-many. Both ends must be in the app: the intersect table is created by the platform,+ // so there is nothing to declare for a partner table a rebuild target would not have.+ // Attempted INDEPENDENTLY of the 1:N read above: a failed 1:N read says nothing about whether+ // N:N metadata is readable.+ try {+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/ManyToManyRelationships`+ + '?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IsCustomRelationship');+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);+ for (const r of ((res.body && res.body.value) || []).filter((x) => x && x.IsCustomRelationship)) {+ const key = lc(r.SchemaName);+ if (seen.has(key)) continue;+ seen.add(key);+ const e1 = lc(r.Entity1LogicalName);+ const e2 = lc(r.Entity2LogicalName);+ if (!inApp.has(e1) || !inApp.has(e2)) {+ note(r.SchemaName, lc(logical), `it links '${e1}' to '${e2}' and this app does not include both tables`);+ continue;+ }+ relationships.push({ type: 'ManyToMany', entity1: e1, entity2: e2 });+ }+ } catch (e) {+ note('(many-to-many)', lc(logical), `their metadata could not be read (${e && e.message})`);+ }+ }++ // Deterministic order: the metadata endpoints carry no ordering guarantee, and this block is+ // written to a file that operators diff between runs, so an unstable order reads as a change that+ // did not happen.+ relationships.sort((x, y) => JSON.stringify(x).localeCompare(JSON.stringify(y)));+ skipped.sort((x, y) => (x.entity + x.name).localeCompare(y.entity + y.name));+ return { relationships, skipped };+}++// Render the relationships this download could NOT express in relationships[] (#567).+//+// Deliberately NOT folded into `notRoundTrippedSummary`. That report describes classes this download+// does not reconstruct AT ALL and whose members are all recorded under `descriptionInventory` — both+// of its standing sentences ("this download does not reconstruct …", "They are NOT lost: every one+// is listed under descriptionInventory") would be FALSE for relationships, which are now+// reconstructed apart from specific, individually-explained exceptions. A report whose value is that+// its claims are true cannot be extended with a claim that is not.+function relationshipsSkippedWarning(skipped) {+ if (!skipped || !skipped.length) return '';+ const lines = [+ `NOTE: ${skipped.length} relationship(s) could not be expressed in relationships[] and are absent from the rebuildable spec.`,+ ' They remain on the deployed app, so rebuilding into THIS environment leaves them untouched. Rebuilding into a',+ ' DIFFERENT environment will NOT recreate them — re-declare or re-create the ones you need there.',+ ];+ for (const s of skipped) lines.push(` - ${s.entity}: ${s.name} — ${s.reason}`);+ return `${lines.join('\n')}\n`;+}+function makeProvision(env, workspaceDir) {const { createMakerSdk } = require('./vendor/cds-maker-sdk.cjs');const httpClient = createAzHttpClient(env);@@ -983,6 +1212,40 @@ function entityFromMetadata(meta, logical) {// label-read warning now names that consequence explicitly.const isLogical = a.IsLogical !== undefined ? a.IsLogical : a.isLogical;if (isLogical === true && a.optionSet === undefined && choiceTypeFromTypeName(a) === undefined) return false;+ // SHADOW-OF, the precise form of the same rule. `AttributeOf` names the attribute this one is a+ // projection of, so a non-empty value is positive proof the column was never authored — no type+ // inference and no relationship context needed.+ //+ // This is not redundant with the `IsLogical` rule above. LIVE-MEASURED on a polymorphic+ // (`Customer`-type) lookup `cfo_billto` targeting account + contact:+ // cfo_billtoname AttributeOf=cfo_billto IsLogical=FALSE AttributeType=String+ // cfo_billtoyominame AttributeOf=cfo_billto IsLogical=FALSE AttributeType=String+ // cfo_customeridname AttributeOf=cfo_customerid IsLogical=TRUE (single-target — already caught)+ // The polymorphic shadows are physically stored, so `IsLogical` is false and the rule above+ // cannot see them; they were emitted as real Text columns and a fresh-environment rebuild+ // invented two text fields where a lookup used to be (#574). A real column — including the+ // lookup itself — reports `AttributeOf: null`, so nothing authored is at risk.+ //+ // Absent KEEPS the attribute, matching every other rule here: when the label read fails no+ // attribute carries `AttributeOf`, and "we could not look" must not become a column deletion.+ if (a.AttributeOf) return false;+ // BASE-CURRENCY TWIN. Dataverse generates a `<money>_base` column beside every Money column. It+ // carries no `AttributeOf`, is not logical, and reports `IsCustomAttribute: true`, so every rule+ // above is blind to it — and emitting it meant a rebuild tried to CREATE a column the platform+ // generates for itself.+ //+ // `IsBaseCurrency` is the ONLY unambiguous signal. `IsValidForCreate: false` is NOT a substitute:+ // it is a per-column write capability this spec deliberately supports on authored columns+ // (`isValidForCreate` in app-spec-schema.md), so filtering on it turns a round-trip into a+ // deletion of a legitimately read-only column. LIVE-MEASURED on stock `opportunity`:+ // estimatedvalue IsBaseCurrency=false IsValidForCreate=true+ // estimatedvalue_base IsBaseCurrency=TRUE IsValidForCreate=false+ // totalamount IsBaseCurrency=false IsValidForCreate=FALSE <- real column, must KEEP+ // `totalamount` is exactly the column the capability flag would have wrongly deleted.+ //+ // Absent KEEPS the attribute, like every other rule here: `IsBaseCurrency` only rides along when+ // the Money cast read succeeded, and "we could not look" must never become a column deletion.+ if (a.IsBaseCurrency === true) return false;// Keep only attribute types the App Spec can declare (see the map above), PLUS any attribute the// option-set read matched, PLUS any attribute `AttributeTypeName` proves is a choice. That last// clause is what keeps a MultiChoice when the cast read failed or came back empty: its@@ -1156,7 +1419,10 @@ async function readEntityWithDescriptions(sdk, logical) {// `IsLogical` rides along for the synthetic-shadow filter in entityFromMetadata: a lookup's// formatted-name attribute (`<lookup>name`) reports IsCustomAttribute TRUE and AttributeType// String, so nothing else distinguishes it from a real Text column the author wrote.- const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description,DisplayName,IsLogical,AttributeTypeName`);+ // `AttributeOf` rides along for the same filter and is the STRONGER signal: it names the+ // attribute a shadow belongs to, and a POLYMORPHIC lookup's shadows report `IsLogical: false`+ // (live-measured), so `IsLogical` alone cannot see them.+ const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName`);if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');const rows = res.body.value;@@ -1164,7 +1430,7 @@ async function readEntityWithDescriptions(sdk, logical) {meta.attributes = (meta.attributes || []).map((a) => {const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();const row = byLogical.get(key);- return row ? { ...a, Description: row.Description, DisplayName: row.DisplayName, IsLogical: row.IsLogical, AttributeTypeName: row.AttributeTypeName } : a;+ return row ? { ...a, Description: row.Description, DisplayName: row.DisplayName, IsLogical: row.IsLogical, AttributeOf: row.AttributeOf, AttributeTypeName: row.AttributeTypeName } : a;});} catch (err) {// Recorded, not swallowed — and it does NOT overwrite a table-level failure already recorded@@ -1174,6 +1440,33 @@ async function readEntityWithDescriptions(sdk, logical) {meta.labelReadFailed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';}}+ try {+ // Base-currency twins. `IsBaseCurrency` lives on MoneyAttributeMetadata, not on the base+ // attribute type, so it needs its own CAST read — the same shape the option-set reads below use.+ //+ // This is the only unambiguous way to recognise the `<money>_base` column Dataverse generates+ // beside every Money column. It reports no `AttributeOf`, is not logical, and is+ // `IsCustomAttribute: true`, so nothing else in the projection distinguishes it from a column the+ // author wrote — and emitting it made a rebuild try to create a column the platform owns.+ //+ // Best-effort on purpose: a failure leaves `IsBaseCurrency` absent on every attribute, and the+ // filter KEEPS an attribute whose flag it could not read. The cost of a failed read is the twin+ // reappearing, never a real column disappearing.+ const res = await sdk.dataverse.get(`${entityPath}/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency`);+ if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {+ const baseCurrency = new Set(res.body.value+ .filter((r) => r && r.LogicalName && r.IsBaseCurrency === true)+ .map((r) => String(r.LogicalName).toLowerCase()));+ if (baseCurrency.size) {+ meta.attributes = (meta.attributes || []).map((a) => {+ const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();+ return baseCurrency.has(key) ? { ...a, IsBaseCurrency: true } : a;+ });+ }+ }+ } catch {+ /* best-effort: absent IsBaseCurrency keeps the column, which is the safe direction */+ }try {// Choice / MultiChoice option sets (#564). A SEPARATE read from the attribute one above, and it// has to be: `OptionSet` can only be `$expand`ed through a type CAST, which the heterogeneous@@ -1712,6 +2005,24 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosprocess.stderr.write(`(dashboards reconstruction skipped: ${e.message})\n`);}+ // Relationships (#567). Reconstructed from live metadata; anything that cannot be expressed in+ // relationships[] is collected in `relationshipsSkipped` and reported with the other+ // not-round-tripped classes, so an omission is stated rather than left to be discovered.+ let relationships = [];+ let relationshipsSkipped = [];+ try {+ const rel = await readRelationships(sdk, allLogicals, solution.publisherPrefix, (m) => {+ process.stderr.write(`WARNING: ${m}\n`);+ });+ relationships = rel.relationships;+ relationshipsSkipped = rel.skipped;+ } catch (e) {+ // A total failure must not sink the download, but it must not masquerade as "this app has no+ // relationships" either — that is precisely the silent absence #567 was filed about.+ relationshipsSkipped = [{ name: '(all)', entity: 'unknown', reason: `relationship metadata could not be read (${e && e.message})` }];+ process.stderr.write(`WARNING: relationships could not be reconstructed: ${e && e.message}\n`);+ }+// Captured by the descriptionInventory accessor below so the role-restriction warning can read it// without making a second query.let capturedInventory;@@ -1723,6 +2034,7 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosapp: async () => ({ ...app, uniquename: (app && app.uniquename) || appUnique, ...(await readAppShellSettings(sdk, appId)) }),pages: async () => pages,entities: async () => entities,+ relationships: async () => relationships,webResources: async () => webResources,dashboards: async () => dashboards,solution: async () => solution,@@ -1757,9 +2069,10 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos// from "this download does not carry views".const notRoundTripped = notRoundTrippedSummary(roundTrippedAware(capturedInventory, globalChoiceDecls));if (notRoundTripped) process.stderr.write(notRoundTrippedWarning(notRoundTripped));+ if (relationshipsSkipped.length) process.stderr.write(relationshipsSkippedWarning(relationshipsSkipped));const droppedSubareas = typeof spec.droppedSubareas === 'number' ? spec.droppedSubareas : droppedSubareaCount(app, spec);const droppedSubareaDetails = Array.isArray(spec.droppedSubareaDetails) ? spec.droppedSubareaDetails : [];- return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped };+ return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, relationships, relationshipsSkipped };}async function main() {@@ -1899,4 +2212,4 @@ if (require.main === module) {main().catch((err) => emitResult(false, err));}-module.exports = { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };+module.exports = { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex 977f02121..633abc717 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -1110,6 +1110,286 @@ function validateFormSecurityRoles(f, spec, errors) {}}+// Allow-listed keys for an explicit form layout, with the reason each rejection exists.+//+// `tabs[]`/`sections[]` had no allow-list at all, so an invented or misspelled key validated clean+// and then vanished — the same class of silent loss that let `entities[].localizedLabels` ship as a+// no-op. Worse here, several plausible keys are accepted by the SDK's normalizers and then DROPPED+// by its serializer: measured against the vendored bundle, a tab emits only name/expanded/visible+// + label, and a section only name/showlabel/visible/columns + label. Anything else never reaches+// the FormXml, so accepting it would promise a layout Dataverse will not render.+const FORM_TAB_KEYS = new Set(['name', 'label', 'expanded', 'visible', 'sections', 'columns']);+const FORM_TAB_COLUMN_KEYS = new Set(['width', 'sections']);+const FORM_SECTION_KEYS = new Set(['name', 'label', 'columns', 'showLabel', 'visible', 'fields']);+const FORM_FIELD_ENTRY_KEYS = new Set(['name', 'readOnly', 'hidden', 'after', 'colspan', 'rowspan']);+// Identity of a sample-data `matchOn` value, shared by the author-time gate in `validateAppSpec` and+// the loader's own refusal in `chooseMatchOn`/`firstDuplicateNonEmpty` (entity-provision.js).+//+// It lives here because entity-provision.js already requires this module, so one definition can feed+// both without a cycle — and the two MUST agree: the gate exists only to move the loader's refusal+// earlier, so a gate that decides "duplicate" differently either rejects a spec that would build or+// passes one that would not.+//+// Type-sensitive because the loader is: `1` and `'1'` are distinct keys. Dataverse would coerce both+// to "1" in a text column, so a spec mixing the two still has a latent collision the loader does not+// catch either — that is a shared limitation, deliberately not papered over on one side only.+function sampleKeyIdentity(v) {+ return JSON.stringify([typeof v, v]);+}++// The names the form compiler generates for an UNNAMED tab/section, shared with artifact-intent.js+// so the spec gate and the compiler cannot disagree about what a container will actually be called.+//+// This matters because the generated name is a real identity, not a placeholder: the topology+// reconcile matches a deployed container by name, so an authored `name: "section_0_0"` and an+// unnamed first section are the SAME container to every rebuild path even though the create path+// emits two. Uniqueness therefore has to be checked on the EFFECTIVE name, which means the gate has+// to know these formulas exactly.+//+// The `ci` segment is appended only for ci > 0, and that asymmetry is load-bearing: adding it+// unconditionally would rename every section on every already-deployed single-column form, and each+// rebuild would then create a duplicate section beside the original instead of converging onto it.+function generatedTabName(ti) {+ return 'tab_' + ti;+}++function generatedSectionName(ti, ci, si) {+ return 'section_' + ti + (ci > 0 ? '_' + ci : '') + '_' + si;+}++// The form-columns a tab declares, in the shape the compiler reads them: `columns[]` is the explicit+// multi-column form, and `sections[]` is the single-full-width-column shorthand. Shared for the same+// reason as the name helpers — the section index that feeds `generatedSectionName` is the index+// WITHIN a form-column, so anything computing an effective name has to walk the same structure.+function formColumnsOf(tab) {+ if (!tab || typeof tab !== 'object') return [];+ if (Array.isArray(tab.columns)) return tab.columns;+ return [{ width: '100%', sections: Array.isArray(tab.sections) ? tab.sections : [] }];+}++// Keys an author reasonably reaches for that the serializer silently discards. Naming the real+// mechanism is the difference between an actionable error and a scavenger hunt.+const FORM_LAYOUT_KEY_HINTS = {+ showLabel: " — a TAB has no label toggle in FormXml; use the tab's `label`, or move the toggle to a section's `showLabel`",+ labelPosition: ' — label position is not expressible per tab/section through this SDK',+ locked: ' — section locking is not expressible through this SDK',+ column: " — did you mean 'columns'?",+ field: " — did you mean 'fields'?",+ title: " — did you mean 'label'?",+ visibility: " — did you mean 'visible'?",+ colSpan: " — did you mean 'colspan'?",+ rowSpan: " — did you mean 'rowspan'?",+ readonly: " — did you mean 'readOnly'?",+};++// Sections a tab declares, from EITHER shape: directly on `sections` (the single-full-width-column+// shorthand) or nested inside `columns[]` (the multi-column form). Every raw-spec reader must go+// through this — reading `tab.sections` alone silently skips every check for a multi-column tab,+// which is how a lint rule came to report such a tab as having no sections at all.+function formSectionsOf(tab) {+ if (!tab || typeof tab !== 'object') return [];+ if (Array.isArray(tab.columns)) return tab.columns.flatMap((c) => (c && Array.isArray(c.sections) ? c.sections : []));+ return Array.isArray(tab.sections) ? tab.sections : [];+}++function validateFormLayoutKeys(f, errors) {+ if (!f || !Array.isArray(f.tabs)) return;+ const label = `form '${f.name || f.entity}'`;+ // An explicit layout has to supply real structure, and this is the gate that decides: the BUILD+ // runs `validateAppSpec` only — it never calls the standalone lint — so a rule that lives only in+ // `spec-lint.js` does not stop a deploy.+ //+ // MEASURED before this check, all with `validate.ok === true`:+ // tabs: [] -> compiled 0 tabs, 0 sections, 0 bound cells+ // tab with sections: [] -> compiled 1 tab, 0 sections, 0 bound cells+ // tab with columns: [] -> same+ // tab with columns:[{sections:[]}]-> same+ // Every declared field was silently dropped, because there is nowhere to place one+ // (`firstSectionRowsPointer` returns ''). `tabs: []` is worse still: with notes enabled the+ // compiler throws a raw `Cannot read properties of undefined (reading 'columns')` rather than+ // reporting anything an author can act on.+ //+ // `layout: 'explicit'` with no `tabs` key at all is already rejected elsewhere, so only the+ // present-but-empty shapes are handled here.+ if (f.tabs.length === 0) {+ errors.push(`${label}: uses an explicit layout but declares no tabs — add at least one tab with a section, or use layout:'auto'`);+ }+ const unknown = (where, obj, allowed) => {+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return;+ for (const k of Object.keys(obj)) {+ if (allowed.has(k)) continue;+ errors.push(`${label}: unknown key '${k}' on ${where}${FORM_LAYOUT_KEY_HINTS[k] || ''} (allowed: ${[...allowed].join(', ')})`);+ }+ };+ const checkSpan = (where, entry) => {+ for (const key of ['colspan', 'rowspan']) {+ const v = entry[key];+ if (v === undefined) continue;+ if (!Number.isInteger(v) || v < 1) errors.push(`${label}: ${where} has ${key} '${v}' — it must be a whole number of ${key === 'colspan' ? 'columns' : 'rows'}, 1 or greater`);+ }+ };+ // A tab/section/form-column entry the compiler will DEREFERENCE. `unknown` deliberately ignores a+ // non-object, so `tabs: [null]` used to reach compileFormIntent — which reads `t.columns` — as a raw+ // TypeError instead of a structural validation error.+ const mustBeObject = (where, v) => {+ if (v && typeof v === 'object' && !Array.isArray(v)) return true;+ errors.push(`${label}: ${where} must be an object, got ${Array.isArray(v) ? 'an array' : JSON.stringify(v)}`);+ return false;+ };+ // `expanded`/`visible`/`showLabel` are only ever truth-tested by the compiler (`!== false`), so a+ // STRING "false" compiles as true and silently deploys the opposite of what was authored — the same+ // silent-no-op class the allow-list exists to end.+ const checkBooleans = (where, o, keys) => {+ for (const k of keys) {+ if (o[k] === undefined) continue;+ if (typeof o[k] !== 'boolean') errors.push(`${label}: ${where} has ${k} '${o[k]}' — it must be true or false, not a ${typeof o[k]}`);+ }+ };+ // Names are IDENTITY for the build's topology reconcile (it matches a deployed container by name,+ // and keys its placement targets by name), so two containers sharing one name make both+ // declarations resolve to the same live container.+ //+ // Checked on the EFFECTIVE name — the authored one, or the compiler's generated fallback — because+ // a generated name is just as real an identity. An unnamed first section and an explicit+ // `name: "section_0_0"` both compile to `section_0_0`, so create emits two sections while+ // `declaredSectionByField`/`sectionTargets` route both their fields to one. MEASURED before this+ // gate: the compiled intent carried two sections named `section_0_0`.+ //+ // Reserving the generated namespace instead would be wrong: a spec DOWNLOADED from a deployed app+ // carries the real deployed section names, which for an app this compiler built are exactly these+ // generated ones — rejecting them would break every download → rebuild round-trip.+ const seenTabNames = new Map();+ const seenSectionNames = new Map();+ const checkUniqueName = (where, authored, effective, seen, kind) => {+ if (effective === undefined || effective === null || effective === '') return;+ const key = String(effective).toLowerCase();+ if (seen.has(key)) {+ const prev = seen.get(key);+ // Name the generated side explicitly — an author who wrote only one of the two names would+ // otherwise get an error about a name they cannot find anywhere in their spec.+ const origin = (!authored || !prev.authored)+ ? ` — an unnamed ${kind} is given the generated name '${effective}', so this collides with it`+ : '';+ errors.push(`${label}: ${where} reuses the ${kind} name '${effective}', already used by ${prev.where}${origin} — a ${kind} name is its identity on a rebuild, so duplicates make both declarations target the same deployed ${kind}. Give one of them a different \`name\`.`);+ return;+ }+ seen.set(key, { where, authored: !!authored });+ };+ // A FIELD is identity too, and form-wide. The create path emits one cell per entry, but every+ // reconcile path keys placement by logical name and takes the FIRST: `declaredSectionByField`+ // resolves a field to one section, `findFieldCellPointer` targets the first matching cell, and+ // `formFieldLogicals` de-duplicates. So a field listed twice deploys TWO cells on a fresh create+ // and ONE on a rebuild — the same spec producing two different forms, which is the silent+ // disagreement this whole gate exists to end.+ //+ // MEASURED on a two-section form listing `contoso_name` in both: the compiled intent carries 2+ // bound cells while declaredSectionByField resolves the field to the first section only.+ //+ // Rejecting rather than implementing multi-placement because one-cell-per-field is what the rest+ // of the pipeline is built on; supporting a second placement would mean teaching the reconcile,+ // the prune and the verifier oracle to carry a set of pointers per field.+ const seenFieldNames = new Map();+ const checkUniqueField = (where, name) => {+ if (typeof name !== 'string' || !name) return;+ const key = name.toLowerCase();+ if (seenFieldNames.has(key)) {+ errors.push(`${label}: ${where} places field '${name}' again — it is already placed by ${seenFieldNames.get(key)}. A form places each field once: a rebuild resolves the field to its first placement, so the second cell would deploy on a fresh create and then vanish on the next build. Remove the duplicate, or move the field to the section you want it in.`);+ return;+ }+ seenFieldNames.set(key, where);+ };+ f.tabs.forEach((t, ti) => {+ const where = `tab ${t && t.label ? `'${t.label}'` : `#${ti + 1}`}`;+ if (!mustBeObject(where, t)) return;+ unknown(where, t, FORM_TAB_KEYS);+ checkBooleans(where, t, ['expanded', 'visible']);+ checkUniqueName(where, t.name, t.name || generatedTabName(ti), seenTabNames, 'tab');+ // Section names are checked COLUMN-AWARE, because the index that feeds the generated name is the+ // section's position within its form-column — not its position in the flattened list the+ // per-section checks below walk. Done in its own pass so those checks keep their existing+ // flattened numbering, and their messages do not churn.+ formColumnsOf(t).forEach((c, ci) => {+ const colSections = (c && Array.isArray(c.sections)) ? c.sections : [];+ colSections.forEach((s, si) => {+ if (!s || typeof s !== 'object' || Array.isArray(s)) return;+ const nwhere = `${where} section ${s.label ? `'${s.label}'` : `#${si + 1}`}${ci > 0 ? ` (column #${ci + 1})` : ''}`;+ checkUniqueName(nwhere, s.name, s.name || generatedSectionName(ti, ci, si), seenSectionNames, 'section');+ });+ });+ // A tab is EITHER the single-full-width-column shorthand or the explicit multi-column shape.+ // Accepting both would leave the compiler to pick one and silently discard the other's sections.+ if (t && Array.isArray(t.columns) && Array.isArray(t.sections)) {+ errors.push(`${label}: ${where} declares both 'sections' and 'columns' — 'sections' is the shorthand for one full-width column, so use one or the other (move those sections into columns[0].sections).`);+ }+ // `columns` means an INTEGER grid width on a section but an ARRAY of form-columns on a tab — the+ // single most confusable key in this schema. A non-array tab `columns` used to validate clean and+ // then be discarded by the compiler (which reads `Array.isArray(t.columns)`), so `"columns": 2`+ // on a tab silently produced a one-column form: exactly the silent no-op this allow-list exists+ // to end.+ if (t && t.columns !== undefined && !Array.isArray(t.columns)) {+ errors.push(`${label}: ${where} has columns '${t.columns}' — on a TAB, 'columns' is the list of form-columns ([{ "width": "60%", "sections": [...] }]). To give a SECTION a multi-column grid, put 'columns': ${t.columns} on the section instead.`);+ }+ const columns = (t && Array.isArray(t.columns)) ? t.columns : [];+ columns.forEach((c, ci) => {+ const cwhere = `${where} column #${ci + 1}`;+ if (!mustBeObject(cwhere, c)) return;+ unknown(cwhere, c, FORM_TAB_COLUMN_KEYS);+ // Dataverse omits an undefined width from columnToRaw and then rejects the push, and a width+ // that is not a percentage does not lay out at all.+ if (c && c.width !== undefined && !/^\d{1,3}%$/.test(String(c.width))) {+ errors.push(`${label}: ${where} column #${ci + 1} has width '${c.width}' — a form-column width must be a percentage such as '60%'`);+ }+ // A non-array `sections` is treated as absent by formSectionsOf, so the column's whole layout+ // would be silently dropped rather than rejected.+ if (c && c.sections !== undefined && !Array.isArray(c.sections)) {+ errors.push(`${label}: ${where} column #${ci + 1} has a non-array 'sections' — it must be a list of sections`);+ }+ });+ const sections = formSectionsOf(t);+ // A tab with no section has nowhere to place a field, a sub-grid or a quick-view, so everything+ // the author declared for it is dropped in silence. Checked against the FLATTENED list, so the+ // multi-column shape counts too — looking at `t.sections` alone would report every multi-column+ // tab as empty, which is the same silent disagreement in the other direction.+ if (sections.length === 0) {+ errors.push(`${label}: ${where} has no sections — add at least one section with fields, or drop the tab.`);+ }+ sections.forEach((s, si) => { const swhere = `${where} section ${s && s.label ? `'${s.label}'` : `#${si + 1}`}`;+ if (!mustBeObject(swhere, s)) return;+ unknown(swhere, s, FORM_SECTION_KEYS);+ checkBooleans(swhere, s, ['showLabel', 'visible']);+ if (s && s.columns !== undefined && (!Number.isInteger(s.columns) || s.columns < 1 || s.columns > 4)) {+ errors.push(`${label}: ${swhere} has columns '${s.columns}' — a section may span 1 to 4 columns`);+ }+ const entries = (s && Array.isArray(s.fields) ? s.fields : []);+ entries.forEach((entry, fi) => {+ // Runs for BOTH entry shapes — a bare logical-name string and a `{ name, ... }` object —+ // because either one places a cell, so either one can be the duplicate.+ checkUniqueField(swhere, typeof entry === 'string'+ ? entry+ : (entry && typeof entry === 'object' && !Array.isArray(entry) ? entry.name : undefined));+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return;+ const fwhere = `${swhere} field '${entry.name || '?'}'`;+ unknown(fwhere, entry, FORM_FIELD_ENTRY_KEYS);+ checkSpan(fwhere, entry);+ // A cell that spans DOWN reserves its column in the rows beneath it, and the following row's+ // cells fill the section left to right — so a field declared after a spanning one lands in+ // the reserved slot. Every stock Dataverse form that uses `rowspan` puts it on the LAST cell+ // of its section (measured on the account and contact Main forms), so that is the shape this+ // compiler emits.+ //+ // This is a COMPILER limitation, not a platform one: an empty SPACER cell occupies the+ // reserved slot and the SDK serializes it correctly (measured against the vendored bundle —+ // `{}` pushes as `<cell … colspan="1" rowspan="1" />`). Emitting spacers would lift this+ // restriction; until the compiler does, rejecting is better than silently mispositioning a+ // control. Tracked in #581.+ if (Number.isInteger(entry.rowspan) && entry.rowspan > 1 && fi !== entries.length - 1) {+ errors.push(`${label}: ${fwhere} has rowspan ${entry.rowspan} but is not the last field in its section — a cell that spans rows reserves its column underneath, and this compiler does not yet emit the spacer cell needed to place a field beside it. Move this field to the end of the section, or drop the rowspan.`);+ }+ });+ });+ });+}+function validateFormFieldOptions(f, entityByLower, errors, warnings) {const label = `form '${f.name || f.entity}'`;const entity = entityByLower.get(String(f.entity || '').toLowerCase());@@ -1127,7 +1407,7 @@ function validateFormFieldOptions(f, entityByLower, errors, warnings) {const listedByLayout = new Set();for (const t of (Array.isArray(f.tabs) ? f.tabs : [])) {- for (const s of ((t && t.sections) || [])) {+ for (const s of formSectionsOf(t)) {if (s && s.fields !== undefined && !Array.isArray(s.fields)) {// Guard the compiler, which does `(s.fields || []).map(...)`. A string is ITERABLE and every// character of it IS a string, so a `fields: "new_name"` typo would pass a naive per-entry@@ -1246,7 +1526,7 @@ function validateFormFieldOptions(f, entityByLower, errors, warnings) {// warning, not an error: the author asked for it by name and may be pairing it with a custom control.if (explicit) {for (const t of (Array.isArray(f.tabs) ? f.tabs : [])) {- for (const s of ((t && t.sections) || [])) {+ for (const s of formSectionsOf(t)) {// Re-guard: the array check in the first loop `continue`s that loop only. Without repeating// it here a non-iterable `fields` (e.g. `{}` or `3`) throws a raw TypeError out of// validateAppSpec — discarding the correct finding the first loop already pushed.@@ -1652,6 +1932,7 @@ function validateAppSpec(spec, opts = {}) {}}validateFormFieldOptions(f, entityByLower, errors, warnings);+ validateFormLayoutKeys(f, errors);validateFormSecurityRoles(f, spec, errors);// `layout: 'explicit'` with no `tabs[]` is a spec that asks for one thing and builds another.// `compileFormIntent` takes the explicit path only when `tabs` is an ARRAY, so this combination@@ -2015,10 +2296,16 @@ function validateAppSpec(spec, opts = {}) {if (!t || !DASH_TILE_TYPES.has(t.type)) { errors.push(`dashboard '${d.name}': tile type must be chart|list|iframe|webresource`); continue; }// ID-passthrough tiles (from a round-tripped/downloaded app) carry the deployed view/chart ids// + entity directly instead of names — they bind to existing artifacts, so skip the name checks.- const byId = t.viewId || t.visualizationId;+ // `visualizationId` identifies a CHART and means nothing on a list tile; sharing one id test+ // across both let a list tile with a stray visualizationId skip its viewId requirement.+ const byId = t.type === 'chart' ? (t.viewId || t.visualizationId) : t.viewId;if (t.type === 'chart') {if (byId) {+ // BOTH ids are load-bearing: a chart renders a visualization OVER a view. This mirrors+ // spec-lint exactly — the two gates disagreeing meant a spec could validate clean and then+ // fail its own structural lint.if (!t.viewId) errors.push(`dashboard '${d.name}': chart tile with visualizationId also needs viewId`);+ if (!t.visualizationId) errors.push(`dashboard '${d.name}': id-based chart tile with viewId also needs visualizationId`);if (!t.entity) errors.push(`dashboard '${d.name}': id-based chart tile needs entity`);else badEntityRef(t.entity, `dashboard '${d.name}': chart tile`);} else {@@ -2392,6 +2679,54 @@ function validateAppSpec(spec, opts = {}) {const ent = lower.has(k.toLowerCase())? (spec.entities || []).find((e) => String(e.schemaName).toLowerCase() === k.toLowerCase()): null;+ // Mirror chooseMatchOn (entity-provision.js): with no safe single-column alternate key the+ // loader falls back to the primary NAME column as `matchOn`, and duplicate names would let+ // Dataverse resolve or deduplicate the wrong row — so the seeder refuses. That refusal lands+ // in the sample-data phase, i.e. AFTER tables, forms and views are already deployed, which+ // turns ordinary sample data (two tickets both called 'Printer issue') into a spec that+ // validates clean and then stops building halfway. Caught here instead, at author time.+ //+ // Values are read case-insensitively because a sample record is keyed by the column name as+ // the author wrote it, while the runtime compares the resolved lowercase logical name.+ if (ent && ent.primaryAttribute && ent.primaryAttribute.schemaName) {+ const valueOf = (rec, col) => {+ if (!rec || typeof rec !== 'object') return undefined;+ const want = String(col).toLowerCase();+ for (const key of Object.keys(rec)) if (key.toLowerCase() === want) return rec[key];+ return undefined;+ };+ const filled = (col) => v.length > 0 && v.every((r) => {+ const x = valueOf(r, col);+ return x !== undefined && x !== null && x !== '';+ });+ // An alternate key is enforced-unique by Dataverse, so it is preferred and makes the+ // primary-name fallback irrelevant.+ const hasSafeKey = (ent.alternateKeys || []).some((key) => (key.columns || []).length === 1 && filled(key.columns[0]));+ // Whichever column becomes `matchOn` is the one duplicates break, so check THAT column.+ // Checking only the primary-name fallback left `{ code: 'A' }, { code: 'A' }` passing the+ // gate and then failing during sample-data provisioning — after tables, forms and views+ // were already deployed, which is the whole failure this gate exists to move earlier.+ const altKeyCol = (ent.alternateKeys || [])+ .map((key) => ((key.columns || []).length === 1 ? key.columns[0] : null))+ .find((c) => c && filled(c));+ const matchOnCol = altKeyCol || (!hasSafeKey && filled(ent.primaryAttribute.schemaName) ? ent.primaryAttribute.schemaName : null);+ if (matchOnCol) {+ const seen = new Set();+ for (const r of v) {+ const raw = valueOf(r, matchOnCol);+ // Keyed through the SHARED `sampleKeyIdentity` the loader uses, so this gate cannot+ // decide "duplicate" differently from the code that actually refuses the seed. A+ // plain `String(...)` key made `1` and `'1'` collide here while the loader treats them+ // as distinct — rejecting, at author time, a spec that builds.+ const key = sampleKeyIdentity(raw);+ if (seen.has(key)) {+ errors.push(`sampleData['${k}']: duplicate ${String(matchOnCol).toLowerCase()} value '${String(raw)}'. ${altKeyCol ? `${String(matchOnCol).toLowerCase()} is the single-column alternate key used as matchOn` : `With no single-column alternate key, ${String(matchOnCol).toLowerCase()} is used as matchOn`}, so Dataverse could resolve or deduplicate the wrong row. Make ${String(matchOnCol).toLowerCase()} unique across the sample rows.`);+ break;+ }+ seen.add(key);+ }+ }+ }for (const rec of v) {for (const { field, token } of invalidChoiceSampleTokens(spec, ent, rec)) {errors.push(`sampleData['${k}']: value '${token}' for choice column '${field}' is not a declared option label`);@@ -2399,6 +2734,14 @@ function validateAppSpec(spec, opts = {}) {if (!rec || typeof rec !== 'object') {continue;}+ // `_seedKey` is not a loader sentinel and never has been: only `$parent`, `$parents` and+ // `statusReason` are stripped before a record body is sent, so a `_seedKey` reaches+ // Dataverse as an attribute no table has. Rejected rather than silently stripped because+ // an author writing one is asking for dedupe/identity behavior that does not exist — the+ // real mechanism is a single-column alternate key, which `matchOn` resolves.+ if (Object.prototype.hasOwnProperty.call(rec, '_seedKey')) {+ errors.push(`sampleData['${k}']: '_seedKey' is not a supported sample-record key — it is sent to Dataverse as an unknown attribute. Declare a single-column alternate key on the table for identity/dedupe instead.`);+ }// #1: validate the parent bind(s) — one `$parent` (singular) and/or many `$parents` (a// junction row binding multiple sides). Each must name a known parent entity, carry a// non-empty match, have an existing OneToMany relationship, AND a match that resolves to@@ -2928,6 +3271,10 @@ function migrateAppSpec(spec) {module.exports = {rejectLocalizedGlobalChoice,+ sampleKeyIdentity,+ generatedTabName,+ generatedSectionName,+ formColumnsOf,validateAppSpec,normalizePageSource,normalizeLanguageCode,@@ -2977,6 +3324,11 @@ module.exports = {relationshipFor,resolveParentRelationship,lookupColumnsFor,+ // Exported so every raw-spec form reader — including the offline eval harness — goes through the+ // one helper that understands BOTH tab shapes. A reader that opens `tab.sections` directly silently+ // skips every multi-column tab, which is exactly how a lint rule came to report such a tab as+ // having no sections at all.+ formSectionsOf,childRelationshipsFor,relationshipSchemaName,prefixedRelationshipName,diff --git a/plugins/model-apps/scripts/lib/artifact-intent.js b/plugins/model-apps/scripts/lib/artifact-intent.jsindex 9b9780fd1..133d3e087 100644--- a/plugins/model-apps/scripts/lib/artifact-intent.js+++ b/plugins/model-apps/scripts/lib/artifact-intent.js@@ -11,7 +11,7 @@// the SDK's generic mutation surface without hardcoding form-model logic everywhere.const { entityByLogical } = require('./_graph.js');-const { lookupColumnsFor } = require('./app-spec.js');+const { lookupColumnsFor, generatedTabName, generatedSectionName, formColumnsOf } = require('./app-spec.js');const { SDK_COLUMN_TYPE } = require('./entity-provision.js');// Arrange field cells into `columns` cells-per-row.@@ -20,12 +20,49 @@ const { SDK_COLUMN_TYPE } = require('./entity-provision.js');function rowsFromCells(cells, columns) {const cols = Math.max(1, Math.min(4, columns || 1));const rows = [];- for (let i = 0; i < cells.length; i += cols) {- rows.push({ cells: cells.slice(i, i + cols) });+ // Pack by the WIDTH each cell occupies, not by cell count: a `colspan: 2` cell fills two of the+ // section's columns, so counting cells would put 2 cells in a 2-column row whose first cell+ // already spans it and push the second into an overflowing row. A span wider than the section is+ // clamped, because Dataverse renders a cell that overruns its section unpredictably and the+ // author's intent ("as wide as possible") is preserved by the clamp.+ let current = [];+ let used = 0;+ for (const cell of cells) {+ const declared = Math.max(1, Number(cell && cell.colspan) || 1);+ const span = Math.min(cols, declared);+ if (used + span > cols && current.length) {+ rows.push({ cells: current });+ current = [];+ used = 0;+ }+ // The clamp has to reach the EMITTED cell, not just the row arithmetic. Packing a `colspan: 4`+ // cell as width 2 while still serializing `colspan="4"` produces exactly the overrunning cell+ // this clamp exists to prevent, and contradicts the documented behaviour. A span clamped back+ // down to 1 drops the attribute entirely, matching fieldCellIntent's omit-the-default rule.+ let out = cell;+ if (span !== declared) {+ out = Object.assign({}, cell);+ if (span > 1) out.colspan = span; else delete out.colspan;+ }+ current.push(out);+ used += span;}+ if (current.length) rows.push({ cells: current });return rows;}+// Widths for a tab's FormColumns when the author did not set them explicitly.+//+// A single column is '100%' EXACTLY — that literal is what every previously generated form carries,+// and changing it would make each rebuild look like a width edit. Remaining columns split evenly with+// the first absorbing the rounding remainder, so three columns are 34/33/33 rather than 99% total.+function equalColumnWidths(n) {+ const count = Math.max(1, n || 1);+ if (count === 1) return ['100%'];+ const base = Math.floor(100 / count);+ return Array.from({ length: count }, (_, i) => (i === 0 ? 100 - base * (count - 1) : base) + '%');+}+// Minimal push-ready bound-field cell.//// SDK T4 tenet: mutations express intent; the adapter applies defaults. The SDK@@ -64,6 +101,12 @@ function fieldCellIntent(logical, opts) {// Same asymmetry, same reason: only `visible: false` is written. An explicit `true` would// un-hide a control someone deliberately hid outside the spec.if (opts.hidden) cell.visible = false;+ // Spans are written only when they are NOT the adapter's default of 1, for the same reason+ // `isReadOnly: false` is never written: emitting the default on every ordinary cell would+ // overwrite a span a maker widened by hand on a form the spec never claimed to own that of.+ // Both serialize to real `colspan`/`rowspan` attributes (verified against the vendored bundle).+ if (opts.colspan > 1) cell.colspan = opts.colspan;+ if (opts.rowspan > 1) cell.rowspan = opts.rowspan;return cell;}@@ -85,19 +128,24 @@ const NON_FORM_RENDERABLE_TYPES = new Set(['BigInt']);// { "name": "co_ticketnumber", "readOnly": true }// { "name": "co_storypoints", "hidden": true }// { "name": "co_daysremaining", "after": "co_duedate" }-// Returns a canonical { name, readOnly, hidden, after } with `name`/`after` lower-cased, because-// every downstream comparison (form field logicals, cell pointers, Dataverse attribute logical-// names) is lower-case.+// { "name": "co_description", "colspan": 2 }+// Returns a canonical { name, readOnly, hidden, after, colspan, rowspan } with `name`/`after`+// lower-cased, because every downstream comparison (form field logicals, cell pointers, Dataverse+// attribute logical names) is lower-case. Spans normalize to `undefined` rather than 1 so the cell+// builder can distinguish "author asked for the default" from "author said nothing".function normalizeFieldEntry(entry) {+ const span = (v) => (Number.isFinite(Number(v)) && Number(v) > 1 ? Math.floor(Number(v)) : undefined);if (entry && typeof entry === 'object' && !Array.isArray(entry)) {return {name: String(entry.name || '').toLowerCase(),readOnly: entry.readOnly === true,hidden: entry.hidden === true,after: entry.after ? String(entry.after).toLowerCase() : undefined,+ colspan: span(entry.colspan),+ rowspan: span(entry.rowspan),};}- return { name: String(entry || '').toLowerCase(), readOnly: false, hidden: false, after: undefined };+ return { name: String(entry || '').toLowerCase(), readOnly: false, hidden: false, after: undefined, colspan: undefined, rowspan: undefined };}// Form-level per-field control options, keyed by column logical name:@@ -118,6 +166,8 @@ function fieldOptionsMap(formSpec) {readOnly: v.readOnly === true,hidden: v.hidden === true,after: v.after ? String(v.after).toLowerCase() : undefined,+ colspan: Number(v.colspan) > 1 ? Math.floor(Number(v.colspan)) : undefined,+ rowspan: Number(v.rowspan) > 1 ? Math.floor(Number(v.rowspan)) : undefined,};}return map;@@ -387,45 +437,56 @@ function compileFormIntent(spec, formSpec, opts) {readOnly: inline.readOnly || base.readOnly,hidden: inline.hidden || base.hidden,after: inline.after !== undefined ? inline.after : base.after,+ colspan: inline.colspan !== undefined ? inline.colspan : base.colspan,+ rowspan: inline.rowspan !== undefined ? inline.rowspan : base.rowspan,};};let tabs;if (explicit && Array.isArray(formSpec.tabs)) {- // Honor the authored layout verbatim. Wrap each tab's sections in a single FormColumn- // (the new topology requires it; old tabs had sections directly without a column layer).+ // Honor the authored layout verbatim. A tab is one or more FormColumns: `tabs[].sections` is+ // the single-full-width-column shorthand, `tabs[].columns[]` the explicit multi-column shape.+ // Declaring both is rejected at the spec gate, so reading `columns` first cannot mask `sections`.tabs = formSpec.tabs.map(function (t, ti) {+ const authoredColumns = formColumnsOf(t);+ const defaultWidths = equalColumnWidths(authoredColumns.length);return {- name: t.name || ('tab_' + ti),+ name: t.name || generatedTabName(ti),label: t.label || 'General',- expanded: true,- visible: true,- // Each tab is one FormColumn. width is set explicitly ('100%') for exact control; as of- // hardening-3 the SDK's normalizeColumn ALSO defaults a synthesized column's width to '100%'- // (a belt-and-suspenders safety net), but we keep setting it here so the value is never left to- // an implicit default and older bundles that don't default it still produce valid formxml- // (columnToRaw omits an undefined width, which makes Dataverse reject the push).- columns: [{- width: '100%',- sections: (t.sections || []).map(function (s, si) {- const cells = (s.fields || []).map(function (fl) {- const inline = normalizeFieldEntry(fl);- const opt = optionsFor(inline.name, inline);- recordPosition(opt);- return fieldCellIntent(inline.name, { isRequired: requiredFor(inline.name), readOnly: opt.readOnly, hidden: opt.hidden });- });- const secCols = Math.min(s.columns || 1, maxCols);- return {- name: s.name || ('section_' + ti + '_' + si),- label: s.label || 'Details',- visible: true,- showLabel: s.showLabel !== false,- columns: secCols,- rows: rowsFromCells(cells, secCols)- };- })- }]+ // Only an explicit `false` collapses/hides a tab; anything else keeps the previous+ // always-visible, always-expanded behavior, so existing specs compile unchanged.+ expanded: t.expanded !== false,+ visible: t.visible !== false,+ columns: authoredColumns.map(function (c, ci) {+ return {+ // width is set explicitly for exact control; the SDK's normalizeColumn also defaults a+ // synthesized column's width to '100%', but keeping it explicit works on every bundle+ // (an undefined width is omitted by columnToRaw and Dataverse would reject it).+ width: c.width || defaultWidths[ci],+ sections: (c.sections || []).map(function (s, si) {+ const cells = (s.fields || []).map(function (fl) {+ const inline = normalizeFieldEntry(fl);+ const opt = optionsFor(inline.name, inline);+ recordPosition(opt);+ return fieldCellIntent(inline.name, { isRequired: requiredFor(inline.name), readOnly: opt.readOnly, hidden: opt.hidden, colspan: opt.colspan, rowspan: opt.rowspan });+ });+ const secCols = Math.min(s.columns || 1, maxCols);+ return {+ // The generated fallback name is the form's identity for this section on a REBUILD+ // (topology reconcile matches deployed sections by name). Shared with the spec gate+ // via `generatedSectionName` so the two cannot disagree about what an unnamed+ // section will be called — see that helper for why the ci segment is conditional.+ name: s.name || generatedSectionName(ti, ci, si),+ label: s.label || 'Details',+ visible: s.visible !== false,+ showLabel: s.showLabel !== false,+ columns: secCols,+ rows: rowsFromCells(cells, secCols)+ };+ })+ };+ })};});} else {@@ -437,7 +498,7 @@ function compileFormIntent(spec, formSpec, opts) {const autoCell = function (logical, extra) {const opt = optionsFor(logical, null);recordPosition(opt);- return fieldCellIntent(logical, Object.assign({ readOnly: opt.readOnly, hidden: opt.hidden }, extra || {}));+ return fieldCellIntent(logical, Object.assign({ readOnly: opt.readOnly, hidden: opt.hidden, colspan: opt.colspan, rowspan: opt.rowspan }, extra || {}));};if (entity) {cells.push(autoCell(entity.primaryAttribute.schemaName.toLowerCase(), { isRequired: true }));@@ -679,6 +740,56 @@ function findFieldCellLocation(formJson, logical) {return null;}+// A deployed section, located by NAME (case-insensitive) across the WHOLE form, or null.+//+// The search is form-wide rather than scoped to the expected tab on purpose: section names are+// unique per form in Dataverse, and a section a maker dragged to another tab is still THAT section.+// Scoping the lookup to the tab the spec now names would miss it and create a duplicate beside it.+function findSectionLocation(formJson, sectionName) {+ const want = String(sectionName || '').toLowerCase();+ if (!want) return null;+ const tabs = formJson.tabs || [];+ for (let ti = 0; ti < tabs.length; ti++) {+ const cols = tabs[ti].columns || [];+ for (let ci = 0; ci < cols.length; ci++) {+ const sections = cols[ci].sections || [];+ for (let si = 0; si < sections.length; si++) {+ if (String(sections[si].name || '').toLowerCase() !== want) continue;+ const pointer = '/tabs/' + ti + '/columns/' + ci + '/sections/' + si;+ return { pointer, rowsPointer: pointer + '/rows', tabIndex: ti, columnIndex: ci, sectionIndex: si, section: sections[si] };+ }+ }+ }+ return null;+}++// Where the COMPILED layout says each bound field belongs: logical name -> section name.+//+// Derived from the compiled intent rather than the raw spec so it cannot disagree with the tree the+// create path builds (the compiler is what resolves generated section names, shorthand columns and+// field-entry objects). The first placement wins — and that is safe only because the spec gate+// rejects a field placed twice on one form (`checkUniqueField` in validateFormLayoutKeys). Without+// that gate this would silently diverge from the create path, which emits one cell per entry: a+// duplicated field would deploy two cells on a fresh build and one on a rebuild.+function declaredSectionByField(intentTabs) {+ const out = {};+ for (const t of intentTabs || []) {+ for (const col of t.columns || []) {+ for (const s of col.sections || []) {+ for (const r of s.rows || []) {+ for (const c of r.cells || []) {+ const fn = c.control && c.control.fieldName;+ if (!fn || isNonFieldControl(c.control)) continue;+ const logical = String(fn).toLowerCase();+ if (out[logical] === undefined) out[logical] = s.name;+ }+ }+ }+ }+ }+ return out;+}+// JsonPointer to the cell hosting the BOUND field `logical`, or null if not present.// Used by the engine's field-removal reconcile (removeElement(pointer) on the SDK). Non-field// controls are skipped even if their fieldName matches, so a prune never targets a quick-view whose@@ -704,6 +815,9 @@ module.exports = {sectionRowsPointer,findFieldCellPointer,findFieldCellLocation,+ findSectionLocation,+ declaredSectionByField,+ equalColumnWidths,normalizeFieldEntry,fieldOptionsMap,NON_FORM_RENDERABLE_TYPESdiff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex 82fdce83b..0d946b543 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -17,6 +17,7 @@ const {labelText,isLocalizedLabelMap,localizedLabelLcids,+ sampleKeyIdentity,} = require('./app-spec.js');const { topoOrderEntities, entityByLogical } = require('./_graph.js');// OData string-literal escaping for spec-controlled values interpolated into $filter (a solution@@ -1101,14 +1102,29 @@ function matchesRecord(rec, match) {// relationship's lookup nav property, and resolve a custom statusReason into statuscode/statecode// (halting if its option value wasn't captured during the data-model phase). The SDK's// seedRecordGraph owns the @odata.bind URL formation and resolve-by-name idempotency.+function firstDuplicateNonEmpty(seedRecords, attr) {+ const seen = new Set();+ for (const r of seedRecords) {+ const v = r.body[attr];+ if (v === undefined || v === null || v === '') continue;+ // SHARED with validateAppSpec's author-time gate (app-spec.js) so the two cannot drift: that+ // gate exists only to move this refusal earlier, and a different notion of "duplicate" there+ // would reject a spec this accepts, or accept one this refuses.+ const key = sampleKeyIdentity(v);+ if (seen.has(key)) return v;+ seen.add(key);+ }+ return undefined;+}+// Choose the seedRecordGraph idempotency key (matchOn) for an entity's sample rows. The SDK dedups /// reuses an existing row ONLY when matchOn is supplied, and it NEVER falls back to the primary// display name — Dataverse permits duplicate names, so name-based resolve is a silent-wrong-id bug// (see types/recordGraph.ts `SeedEntityGroup.matchOn`). To keep the old resolve-by-name idempotency// WITHOUT regressing correctness:// 1. prefer a single-column ALTERNATE KEY (Dataverse enforces its uniqueness — a safe key);-// 2. else fall back to the primary NAME column (the key the retired `primaryAttribute` used), which-// carries the documented duplicate-name risk but preserves prior behavior;+// 2. else fall back to the primary NAME column (the key the retired `primaryAttribute` used), but+// only if the sample rows are unique on that column;// and in BOTH cases only when EVERY seeded record has a non-empty value for the chosen key — otherwise// omit matchOn (insert every record, no dedup) rather than resolve on a partially-empty key, which// would collapse or mis-bind rows. `body` values are the resolved Web-API values the SDK will filter on.@@ -1118,10 +1134,26 @@ function chooseMatchOn(e, seedRecords) {seedRecords.every((r) => { const v = r.body[attr]; return v !== undefined && v !== null && v !== ''; });for (const k of e.alternateKeys || []) {const cols = (k.columns || []).map((c) => String(c).toLowerCase());- if (cols.length === 1 && hasNonEmpty(cols[0])) return cols[0];+ // An alternate key is enforced-unique by Dataverse, but the SAMPLE ROWS are not checked by+ // anything before they are sent. Two rows sharing the key value resolve to the same record — the+ // same wrong-row resolve the primary-name fallback below rejects — and the failure would land+ // mid-seed rather than here. So the duplicate rule applies to whichever column becomes matchOn.+ if (cols.length === 1 && hasNonEmpty(cols[0])) {+ const duplicate = firstDuplicateNonEmpty(seedRecords, cols[0]);+ if (duplicate !== undefined) {+ throw new Error(`sample data for '${e.schemaName}' has duplicate ${cols[0]} value '${String(duplicate)}'; ${cols[0]} is the single-column alternate key used as matchOn, so Dataverse could resolve or deduplicate the wrong row. Make ${cols[0]} unique across the sample rows.`);+ }+ return cols[0];+ }}const primary = e.primaryAttribute.schemaName.toLowerCase();- if (hasNonEmpty(primary)) return primary;+ if (hasNonEmpty(primary)) {+ const duplicate = firstDuplicateNonEmpty(seedRecords, primary);+ if (duplicate !== undefined) {+ throw new Error(`sample data for '${e.schemaName}' has duplicate ${primary} value '${String(duplicate)}'; without a single-column alternate key, ${primary} would be used as matchOn and Dataverse could resolve or deduplicate the wrong row. Add a single-column alternate key with unique values, or make ${primary} unique across the sample rows.`);+ }+ return primary;+ }return undefined;}@@ -1139,6 +1171,13 @@ function buildSeedGroup({ spec, e, records, statusReasonValues }) {const seedRecords = [];for (let i = 0; i < resolved.length; i++) {const raw = records[i];+ // Sample rows are otherwise free-form Dataverse attribute bags, so an undocumented sentinel-like+ // key is more likely an authoring mistake than a safe instruction. Rejecting it prevents a+ // payload like `{ "new_name": "T1", "_seedKey": "ticket-1" }` from reaching Dataverse+ // as a non-existent attribute while avoiding a silent drop of data the author may expect to use.+ if (raw && Object.prototype.hasOwnProperty.call(raw, '_seedKey')) {+ throw new Error(`sample data for '${e.schemaName}' record ${i} uses _seedKey, but _seedKey is not supported by this App Spec version. Remove it, or declare a real single-column alternate key and put the stable seed identifier in that column.`);+ }const body = Object.assign({}, resolved[i]);delete body.$parent; delete body.$parents; delete body.statusReason;// Parent lookups — one (`$parent`) or many (`$parents`, e.g. a junction row binding both@@ -1157,10 +1196,18 @@ function buildSeedGroup({ spec, e, records, statusReasonValues }) {if (!rel || !parentEntity) {throw new Error(`sample data for '${e.schemaName}' declares a parent on '${parent.entity}' with no OneToMany relationship to it — fix the spec's $parent/$parents`);}- const parentIndex = sampleRecordsFor(spec, parentEntity).findIndex((pr) => matchesRecord(pr, parent.match));- if (parentIndex < 0) {+ const parentRecords = sampleRecordsFor(spec, parentEntity);+ const matchingParentIndexes = [];+ for (let j = 0; j < parentRecords.length; j++) {+ if (matchesRecord(parentRecords[j], parent.match)) matchingParentIndexes.push(j);+ }+ if (matchingParentIndexes.length === 0) {throw new Error(`sample data for '${e.schemaName}': parent match ${JSON.stringify(parent.match)} found no '${String(parent.entity).toLowerCase()}' sample record — the '${rel.lookup.schemaName}' lookup would be left unset`);}+ if (matchingParentIndexes.length > 1) {+ throw new Error(`sample data for '${e.schemaName}': parent match ${JSON.stringify(parent.match)} matched ${matchingParentIndexes.length} '${String(parent.entity).toLowerCase()}' sample records, so '${rel.lookup.schemaName}' is ambiguous. Make the match unique (for example by matching an alternate-key column) or change the sample data.`);+ }+ const parentIndex = matchingParentIndexes[0];binds.push({ navProperty: rel.lookup.schemaName, parentEntity: parent.entity.toLowerCase(), parentIndex });}// Custom status reason -> statecode + the captured statuscode option value. The value isdiff --git a/plugins/model-apps/scripts/lib/form-preview.js b/plugins/model-apps/scripts/lib/form-preview.jsindex 193c7517f..b74e14a8b 100644--- a/plugins/model-apps/scripts/lib/form-preview.js+++ b/plugins/model-apps/scripts/lib/form-preview.js@@ -97,16 +97,30 @@ function renderFormWireframe(spec, f) {}for (const tab of def.tabs) {- if (tabLabels.length > 1) lines.push(row(`▾ ${tab.label || 'General'}`));+ // The banner carries the tab's authored STATE, so it must render whenever that state is not the+ // default — not only when there are several tabs to tell apart. A single tab that is collapsed or+ // hidden would otherwise preview as an ordinary open tab, and the wireframe IS the approval gate:+ // silently dropping "(collapsed)" or "(hidden)" has the maker approve a different form.+ const annotated = tab.expanded === false || tab.visible === false;+ if (tabLabels.length > 1 || annotated) lines.push(row(`${tab.expanded === false ? '▸' : '▾'} ${tab.label || 'General'}${tab.visible === false ? ' (hidden)' : ''}${tab.expanded === false ? ' (collapsed)' : ''}`));// New topology inserts a FormColumn layer between tab and section.- for (const col of tab.columns || []) {+ const cols = tab.columns || [];+ for (let ci = 0; ci < cols.length; ci++) {+ const col = cols[ci];+ // Name the form-column when a tab has more than one, so a two-column tab is visibly two+ // columns rather than sections stacked in sequence. Rendering them truly side by side would+ // need column-aware wrapping of every section; naming the split keeps the preview honest+ // about the structure without pretending to be a pixel layout.+ if (cols.length > 1) lines.push(row(` ╷ column ${ci + 1} of ${cols.length}${col.width ? ` (${col.width})` : ''}`));for (const sec of col.sections || []) {if (sec.name === 'section_notes') {lines.push(rule('▤ Notes / Timeline'));lines.push(row(' (activity timeline + notes — type to add a note)'));continue;}- lines.push(rule(sec.label || 'Details'));+ // `showLabel: false` means Dataverse renders NO section heading, so showing one here would+ // have the approval preview promise a heading the deployed form does not have.+ lines.push(rule(`${sec.showLabel === false ? '(no heading)' : (sec.label || 'Details')}${sec.visible === false ? ' (hidden)' : ''}`));for (const r of sec.rows || []) {// A bound field cell has control.fieldName; the notes control has none.const cells = (r.cells || []).filter((c) => c.control && c.control.fieldName);diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.jsindex 0d859df47..a20746415 100644--- a/plugins/model-apps/scripts/lib/hydrate-spec.js+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js@@ -110,6 +110,12 @@ async function hydrateSpec(read) {return withDescription({ ...(e || {}), columns }, e && (e.description !== undefined ? e.description : e.Description));});const webResources = ((await read.webResources()) || []).map((wr) => withDescription(wr || {}, wr && (wr.description !== undefined ? wr.description : wr.Description)));+ // Optional accessor: hydrateSpec has callers that predate relationship reconstruction (#567) and+ // pass no `relationships`. The two states are kept APART rather than both collapsing to `[]`:+ // · `undefined` — nobody could look, so the key is OMITTED rather than asserting an absence,+ // which is the silent-absence problem the feature exists to end;+ // · `[]` — a real read proved there are none, which is a fact worth recording.+ const relationships = read.relationships ? ((await read.relationships()) || []) : undefined;const dashboards = ((read.dashboards ? await read.dashboards() : []) || []).map((d) => withDescription(d || {}, d && (d.description !== undefined ? d.description : d.Description)));// `prefixResolved` is a TRANSIENT download-time signal (whether recoverAppSolution trusted the publisher@@ -210,6 +216,7 @@ async function hydrateSpec(read) {...(typeof app.headerNavigationRefresh === 'boolean' ? { headerNavigationRefresh: app.headerNavigationRefresh } : {}),},entities,+ ...(relationships ? { relationships } : {}),...(globalChoices.length ? { globalChoices } : {}),webResources,views: [],diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 1561750a1..8e9bf8676 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -64,6 +64,8 @@ const {firstSectionRowsPointer,findFieldCellPointer,findFieldCellLocation,+ findSectionLocation,+ declaredSectionByField,subgridCellIntent,subgridSectionIntent,quickViewCellIntent,@@ -1773,6 +1775,287 @@ async function runSdkBuild(spec, opts = {}) {}};+ // After a whole tab or form-column is appended, record where each of its sections landed, so the+ // field pass places into them through the same locator the converge path produces. A freshly+ // added container's sections occupy indices 0..n-1 in declaration order.+ const recordColumnSectionTargets = (out, wantColumn, tabIndex, columnIndex, liveColumns) => {+ const live = ((liveColumns || [])[columnIndex] || {}).sections || [];+ (wantColumn.sections || []).forEach((s, si) => {+ out[s.name] = { pointer: '/tabs/' + tabIndex + '/columns/' + columnIndex + '/sections/' + si, name: (live[si] || {}).name };+ });+ };++ const recordSectionTargets = (out, wantTab, tabIndex, liveTab) => {+ (wantTab.columns || []).forEach((c, ci) => recordColumnSectionTargets(out, c, tabIndex, ci, (liveTab || {}).columns));+ };++ // Identity of a deployed tab/section across rebuilds, in descending order of confidence:+ // 1. NAME — what the compiler emits, so a form this plugin created matches itself exactly.+ // 2. LABEL — what the author sees and types; survives a name this plugin did not choose+ // (a form built in Maker, or by a much older version).+ // 3. POSITION — last resort, and the one that makes an AUTO -> EXPLICIT migration converge.+ // The auto layout emits `tab_general`/`section_general`, while an explicit layout with no+ // authored names emits `tab_0`/`section_0_0` — so name matching alone would append a second+ // tab to every form this plugin had already built, on every single rebuild.+ // A container is CREATED only when all three miss, which is what stops a rebuild duplicating one.+ //+ // `claimed` carries the indices an EARLIER want already took. Without it every want is matched+ // independently, and because the compiler substitutes a DEFAULT label for an unlabeled container+ // ('General' for a tab, 'Details' for a section), an author who labels nothing produces several+ // wants with an identical label — the label pass then returns index 0 for all of them and the+ // whole layout collapses into one container. Position has the same failure with repeated indices.+ //+ // `skip` hides containers the weaker passes must not claim. Only NAME may match them, because a+ // name is positive evidence and a label/position is not.+ const matchContainer = (list, want, wantIndex, opts) => {+ const items = list || [];+ const claimed = (opts && opts.claimed) || null;+ const skip = (opts && opts.skip) || (() => false);+ const eq = (a, b) => a !== undefined && a !== null && String(a).toLowerCase() === String(b || '').toLowerCase();+ const free = (i) => !claimed || !claimed.has(i);+ let idx = items.findIndex((x, i) => free(i) && want.name && eq(x.name, want.name));+ if (idx < 0) idx = items.findIndex((x, i) => free(i) && !skip(x) && want.label && eq(x.label, want.label));+ if (idx < 0 && wantIndex < items.length && free(wantIndex) && !skip(items[wantIndex])) idx = wantIndex;+ return idx < 0 ? null : { index: idx, item: items[idx] };+ };++ // A section the ENGINE owns rather than one the author laid out: a sub-grid host, or the+ // notes/timeline section. `addSubgrids` appends one such section per authored sub-grid on EVERY+ // layout (auto included), and `compileFormIntent` appends the notes section — so they sit in the+ // same `sections[]` array as the author's own, just after them.+ //+ // They must be invisible to the LABEL and POSITION passes. Otherwise, as soon as an explicit+ // layout declares as many sections as the index of the first appended one, the positional fallback+ // claims the sub-grid: it gets relabelled to the author's section title, bound field controls are+ // injected into the row holding the grid control, and the author's section is never created. The+ // build is green and a rebuild converges on the same wrong shape, so nothing downstream reports it.+ //+ // Detected structurally (every cell carries a control with no `fieldName`) rather than by name, so+ // it holds for a sub-grid whose section the author renamed in Maker. An EMPTY section has no cells+ // and is deliberately NOT engine-owned — it stays matchable so a vacated section can be reused.+ const isEngineOwnedSection = (s) => {+ const cells = ((s && s.rows) || []).flatMap((r) => (r && r.cells) || []);+ return cells.length > 0 && cells.every((c) => c && c.control && !c.control.fieldName);+ };++ // Send only the keys that actually differ, so a rebuild that changes nothing issues no writes.+ const diffPatch = (live, want, keys) => {+ const patch = {};+ for (const k of keys) if (want[k] !== undefined && live[k] !== want[k]) patch[k] = want[k];+ return patch;+ };++ // Converge an EXISTING form's CONTAINER topology (tabs, form-columns, sections) onto the spec's+ // explicit layout, before any field is placed.+ //+ // Why this exists: the reconcile used to flatten an explicit layout entirely — every field was+ // appended to `firstSectionRowsPointer`, i.e. the first section of the first tab, and no tab or+ // section was ever created or reshaped. Because declaring explicit `tabs` ALSO switches pruning+ // on, an author who moved to an explicit two-column layout to reorganize a deployed form got the+ // old topology, minus any field they had not re-declared, and a successful build (#575).+ //+ // Containers are created EMPTY (`rows: []`) and every field is placed by the single pass that+ // follows. Adding a tab with its compiled cells intact would duplicate any field already on the+ // form elsewhere, and would leave two code paths that can each place a control.+ //+ // Existing containers are UPDATED IN PLACE rather than replaced, so ids — and any control a maker+ // added to a section by hand — survive. `updateElement` merges when both sides are objects, so+ // patching only the differing keys preserves everything else in the container.+ //+ // Returns the desired-section-name -> deployed-section locator map the field pass places through.+ // It cannot re-derive this by name: a position-matched section keeps its own deployed name (it is+ // deliberately NOT renamed, because form scripts and business rules can reference a section name).+ const reconcileFormTopology = async (formId, def) => {+ // An engine-owned section carries its rows INTACT when created: the field pass places only bound+ // fields, so a notes/timeline section created empty would deploy a visible section header+ // promising a control that nothing ever adds.+ const stripRows = (section) => (isEngineOwnedSection(section) ? Object.assign({}, section) : Object.assign({}, section, { rows: [] }));+ const sectionTargets = {};+ const wantTabs = def.tabs || [];+ // Indices already taken by an earlier want, so two wants can never converge on one container.+ const claimedTabs = new Set();+ const claimedSections = new Map(); // column pointer -> Set(index)+ const claimedIn = (key) => { if (!claimedSections.has(key)) claimedSections.set(key, new Set()); return claimedSections.get(key); };+ for (let ti = 0; ti < wantTabs.length; ti++) {+ const wantTab = wantTabs[ti];+ // Re-read before every mutation: addElement appends and shifts sibling indices, so a pointer+ // computed against an earlier snapshot can address the wrong container.+ let form = await provision.getArtifact('form', formId) || {};+ const tabMatch = matchContainer(form.tabs, wantTab, ti, { claimed: claimedTabs });+ if (!tabMatch) {+ await provision.addElement('form', formId, '/tabs', Object.assign({}, wantTab, {+ columns: (wantTab.columns || []).map((c) => Object.assign({}, c, { sections: (c.sections || []).map(stripRows) })),+ }));+ form = await provision.getArtifact('form', formId) || {};+ const added = matchContainer(form.tabs, wantTab, (form.tabs || []).length - 1, { claimed: claimedTabs });+ if (added) { claimedTabs.add(added.index); recordSectionTargets(sectionTargets, wantTab, added.index, added.item); }+ continue;+ }+ claimedTabs.add(tabMatch.index);+ const tabPointer = '/tabs/' + tabMatch.index;+ const tabPatch = diffPatch(tabMatch.item, wantTab, ['label', 'expanded', 'visible']);+ if (Object.keys(tabPatch).length) await provision.updateElement('form', formId, tabPointer, tabPatch);++ const wantColumns = wantTab.columns || [];+ for (let ci = 0; ci < wantColumns.length; ci++) {+ form = await provision.getArtifact('form', formId) || {};+ const liveTab = (form.tabs || [])[tabMatch.index];+ if (!liveTab) break; // defensive: the tab vanished mid-reconcile+ const liveColumns = liveTab.columns || [];+ if (ci >= liveColumns.length) {+ // A tab that gained a form-column — e.g. a single-column form widened into two.+ await provision.addElement('form', formId, tabPointer + '/columns', Object.assign({}, wantColumns[ci], {+ sections: (wantColumns[ci].sections || []).map(stripRows),+ }));+ form = await provision.getArtifact('form', formId) || {};+ recordColumnSectionTargets(sectionTargets, wantColumns[ci], tabMatch.index, ci, ((form.tabs || [])[tabMatch.index] || {}).columns);+ continue;+ }+ if (wantColumns[ci].width && liveColumns[ci].width !== wantColumns[ci].width) {+ await provision.updateElement('form', formId, tabPointer + '/columns/' + ci, { width: wantColumns[ci].width });+ }+ const wantSections = wantColumns[ci].sections || [];+ for (let si = 0; si < wantSections.length; si++) {+ const wantSection = wantSections[si];+ form = await provision.getArtifact('form', formId) || {};+ const columnPointer = tabPointer + '/columns/' + ci;+ const liveSections = (((form.tabs || [])[tabMatch.index] || {}).columns || [])[ci];+ // A section may have been dragged to a different tab in Maker; it is still THAT section,+ // so a form-wide name hit outranks a positional one inside this column.+ const global = wantSection.name ? findSectionLocation(form, wantSection.name) : null;+ const claimedHere = claimedIn(columnPointer);+ const local = global ? null : matchContainer((liveSections || {}).sections, wantSection, si, { claimed: claimedHere, skip: isEngineOwnedSection });+ if (!global && !local) {+ await provision.addElement('form', formId, columnPointer + '/sections', stripRows(wantSection));+ form = await provision.getArtifact('form', formId) || {};+ const addedList = ((((form.tabs || [])[tabMatch.index] || {}).columns || [])[ci] || {}).sections || [];+ const addedIdx = addedList.length - 1;+ claimedHere.add(addedIdx);+ sectionTargets[wantSection.name] = { pointer: columnPointer + '/sections/' + addedIdx, name: (addedList[addedIdx] || {}).name };+ continue;+ }+ if (local) claimedHere.add(local.index);+ else if (global && global.pointer.startsWith(columnPointer + '/sections/')) {+ // A form-wide NAME hit inside THIS column still consumes that index. Without this, a+ // later want in the same column could match the very section the name hit already took+ // (by label or position), routing two authored sections onto one deployed section.+ const idx = Number(global.pointer.slice((columnPointer + '/sections/').length));+ if (Number.isInteger(idx)) claimedHere.add(idx);+ }+ const pointer = global ? global.pointer : columnPointer + '/sections/' + local.index;+ const live = global ? global.section : local.item;+ sectionTargets[wantSection.name] = { pointer, name: live.name };+ // `columns` is the key that matters most: it is what makes a section render as two+ // columns rather than one, and it was previously unreachable on an existing form.+ const patch = diffPatch(live, wantSection, ['columns', 'label', 'showLabel', 'visible']);+ if (Object.keys(patch).length) await provision.updateElement('form', formId, pointer, patch);+ }+ }+ }+ return sectionTargets;+ };++ // Resolve a section target recorded during the topology pass back to a live pointer.+ // Prefer the deployed NAME (stable across the row-level mutations the field pass makes) and fall+ // back to the recorded pointer for a section that carries no name at all.+ const resolveSectionPointer = (form, target) => {+ if (!target) return null;+ if (target.name) {+ const loc = findSectionLocation(form, target.name);+ if (loc) return loc.pointer;+ }+ return target.pointer || null;+ };++ const sectionAt = (form, pointer) => {+ const t = String(pointer || '').split('/').filter(Boolean);+ if (t.length !== 6) return null;+ const tab = (form.tabs || [])[Number(t[1])];+ const col = tab && (tab.columns || [])[Number(t[3])];+ return (col && (col.sections || [])[Number(t[5])]) || null;+ };++ // Write an authored `colspan`/`rowspan` onto a cell that is already on the form. Only a span the+ // author explicitly declared is sent, and only when the deployed value differs, so a rebuild that+ // changes nothing issues no writes.+ const convergeCellSpans = async (formId, form, location, wantCell) => {+ if (!location || !wantCell) return;+ const live = cellAt(form, location);+ if (!live) return;+ const patch = {};+ for (const key of ['colspan', 'rowspan']) {+ const want = wantCell[key];+ if (want === undefined) continue; // no opinion — never overwrite a maker's hand-set span+ const current = live[key] === undefined ? 1 : live[key];+ if (current !== want) patch[key] = want;+ }+ if (Object.keys(patch).length) await provision.updateElement('form', formId, location.cellPointer, patch);+ };++ // The live cell a findFieldCellLocation result points at.+ const cellAt = (form, location) => {+ const section = sectionAt(form, location.sectionPointer);+ const row = section && (section.rows || [])[location.rowIndex];+ return (row && (row.cells || [])[location.cellIndex]) || null;+ };++ // Place one field in the section the layout declares, whether it is absent or merely misplaced.+ //+ // A field whose declared section could not be resolved falls back to the form's first section —+ // exactly the pre-existing behavior. A layout the topology pass could not materialize must still+ // never lose a field.+ const placeFieldInSection = async (formId, logical, wantCell, target) => {+ let form = await provision.getArtifact('form', formId) || {};+ const targetPointer = resolveSectionPointer(form, target);+ const existing = findFieldCellLocation(form, logical);++ if (!existing) {+ const rowsPtr = targetPointer ? targetPointer + '/rows' : firstSectionRowsPointer(form);+ if (!rowsPtr) return;+ await provision.addElement('form', formId, rowsPtr, { cells: [wantCell] });+ return;+ }+ // Converge the cell SHAPE even when the cell is already where it belongs. `colspan`/`rowspan`+ // used to be create-only on an existing form: an author who widened a field to `colspan: 2` on a+ // deployed form got a green build and an unchanged cell.+ //+ // Only spans the author EXPLICITLY set are written. `fieldCellIntent` omits a span of 1, so an+ // absent span means "no opinion" and leaves a cell a maker widened by hand alone — the same rule+ // that keeps `isReadOnly: false` from ever being written.+ await convergeCellSpans(formId, form, existing, wantCell);++ // Already on the form and already in the right section (or we have no opinion) — leave it be,+ // so a rebuild converges instead of reshuffling the form on every run.+ if (!targetPointer || existing.sectionPointer === targetPointer) return;++ // Misplaced: relocate the CELL rather than delete-and-recreate it, so its id and any+ // adapter-derived or maker-edited control state survive the move.+ let rowIndex = ((sectionAt(form, targetPointer) || {}).rows || []).length - 1;+ if (rowIndex < 0) {+ // A section this run just created has no row to move into. The SDK accepts a row with an+ // empty cells array and serializes it correctly, so seed one and target that.+ await provision.addElement('form', formId, targetPointer + '/rows', { cells: [] });+ rowIndex = 0;+ }+ form = await provision.getArtifact('form', formId) || {};+ const from = findFieldCellLocation(form, logical);+ const liveTarget = resolveSectionPointer(form, target);+ if (!from || !liveTarget) return;+ const row = ((sectionAt(form, liveTarget) || {}).rows || [])[rowIndex];+ if (!row) return;+ await provision.moveElement('form', formId, from.cellPointer, liveTarget + '/rows/' + rowIndex + '/cells', { index: (row.cells || []).length });+ // Moving the only cell out of a row leaves an empty `<row/>` that renders as a blank line and+ // would accumulate one per relocated field. Row indices are unchanged by a cell move, so the+ // source row is still where it was.+ if (from.rowCellCount === 1) {+ const after = await provision.getArtifact('form', formId) || {};+ const stranded = jsonPointerRow(after, from.rowPointer);+ if (stranded && (stranded.cells || []).length === 0) {+ await provision.removeElement('form', formId, from.rowPointer);+ }+ }+ };+const reconcileForm = async (formId, def) => {await provision.fetchArtifact('form', formId);// The def's field cells are already push-ready ({ control: { fieldName, isRequired? } }); index by@@ -1783,13 +2066,18 @@ async function runSdkBuild(spec, opts = {}) {if (fn) wantCellByLogical[String(fn).toLowerCase()] = c;}const want = formFieldLogicals(def);- const have = new Set(formFieldLogicals(await provision.getArtifact('form', formId) || {}));+ // An EXPLICIT layout is author-controlled topology, so converge the containers first and then+ // place every field into the section that layout names. An AUTO layout has exactly one section+ // and no authored structure to honor, so it keeps the additive first-section behavior —+ // reshaping a form a maker built by hand is not something an auto layout ever asked for.+ let declaredSection = {};+ let sectionTargets = {};+ if (def.__explicitLayout) {+ declaredSection = declaredSectionByField(def.tabs);+ sectionTargets = await reconcileFormTopology(formId, def);+ }for (const logical of want) {- if (have.has(logical)) continue; // idempotent: already on the form- const rowsPtr = firstSectionRowsPointer(await provision.getArtifact('form', formId) || {});- if (!rowsPtr) break;- await provision.addElement('form', formId, rowsPtr, { cells: [wantCellByLogical[logical]] });- have.add(logical);+ await placeFieldInSection(formId, logical, wantCellByLogical[logical], sectionTargets[declaredSection[logical]]);}await addSubgrids(formId, def.__subgrids);// Re-assert per-control attributes (read-only / hidden) on fields that were ALREADY on the form.@@ -1829,7 +2117,7 @@ async function runSdkBuild(spec, opts = {}) {// Reconcile an EXISTING author view: fetch it, UNION its current columns with the spec's (so a// manual column add in Maker is preserved AND the spec's new lookup columns land), set, push,// publish. Editing a view's column set (e.g. to surface a parent lookup) now takes effect.- const reconcileView = async (viewId, def) => {+ const reconcileView = async (viewId, def, authoredQuery) => {await provision.fetchArtifact('view', viewId);const current = await provision.getArtifact('view', viewId) || {};const have = new Set((current.columns || []).map((c) => String(c.name).toLowerCase()));@@ -1856,6 +2144,20 @@ async function runSdkBuild(spec, opts = {}) {if (wantDescription && wantDescription !== String(current.description || '')) {await provision.updateElement('view', viewId, '/description', wantDescription);}+ // An EXISTING view's FetchXML (filters + sort) is not reapplied here — only columns and the+ // description converge. Silence made an authored filter edit look applied when it was not, so+ // the no-op is reported instead. It is a warning rather than a failure because the common way to+ // hit it is entirely benign: the build reconciles onto the platform's auto-generated+ // "Active <Plural>" view, which every table already has.+ //+ // `authoredQuery` is passed in rather than derived from `def`, because `viewDef` folds the+ // implicit `statecode eq 0` of `activeOnly` into the same `filters.conditions` array as the+ // author's own — so a non-empty array does not mean the author declared anything, and warning+ // off it would fire on every rebuild of every view. `--verify` proves the deployed fetchxml+ // separately and FAILS on a divergence; this explains what verification will report.+ if (authoredQuery && typeof opts.warn === 'function') {+ opts.warn(`view '${def.name}' already exists — its columns and description were updated, but authored filters/sort are NOT reapplied to an existing view. Rename the view to author a separate one, or adjust its filters in Maker.`);+ }requireSuccessfulPush(await provision.pushArtifact('view', viewId), `view ${def.name}`, opts.warn);reportPartialPush(await provision.publishArtifact('view', viewId), `view ${def.name}`, opts.warn);await provision.addSolutionComponent({ componentId: viewId, componentType: COMPONENT_TYPE.view, solutionUniqueName: sol.uniqueName });@@ -1887,11 +2189,17 @@ async function runSdkBuild(spec, opts = {}) {try {await provision.updateRecord('systemform', formId, { isdefault: true });promoted = true;- } catch {- /* best-effort — leave promoted=false so we skip the destructive deactivation below */+ } catch (err) {+ // Best-effort for the BUILD (leave promoted=false so the destructive deactivation below is+ // skipped), but no longer SILENT. Swallowing this outright let a build record a selected+ // default form it had not actually promoted, and report success — the exact silent-partial+ // class `--verify` exists to catch. Verification now proves `systemform.isdefault`+ // independently, so this warning is the signal that explains the failure it will report.+ const reason = (err && err.message) ? String(err.message).slice(0, 200) : 'unknown error';+ if (typeof opts.warn === 'function') opts.warn(`could not make form the default for '${entityLogical}': ${reason} — the table keeps its previous default form`);}- if (!deactivateOthers || !promoted) return;- if (typeof provision.queryRecords !== 'function') return;+ if (!deactivateOthers || !promoted) return promoted;+ if (typeof provision.queryRecords !== 'function') return promoted;try {// Main forms only (systemform.type == 2). Every other ACTIVE main form is deactivated// (formactivationstate 1 -> 0); ours is skipped by id. A form already inactive@@ -1915,10 +2223,11 @@ async function runSdkBuild(spec, opts = {}) {} catch {/* best-effort */}+ return promoted;};// helper: create an artifact — or UPDATE it in place if it already exists — then add to the solution.- const buildArtifact = (type, def) => runner.run(`${type}s`, `${type} "${def.name}"`, async () => {+ const buildArtifact = (type, def, meta) => runner.run(`${type}s`, `${type} "${def.name}"`, async () => {// Update-in-place: editing a deployed spec must land, so a form is reconciled (fields +// sub-grids) and a view has its columns reconciled, instead of the artifact being reused// unchanged (the old behavior silently dropped every edit while still reporting success).@@ -1932,7 +2241,7 @@ async function runSdkBuild(spec, opts = {}) {if (existingId) return reconcileForm(existingId, def);} else if (type === 'view') {const existingId = await provision.findArtifact('view', { name: def.name, entity: def.entityLogicalName });- if (existingId) return reconcileView(existingId, def);+ if (existingId) return reconcileView(existingId, def, !!(meta && meta.authoredQuery));}// A form cannot be created from a full authored definition (the adapter's createDefault// serializes authored tabs BEFORE minting ids and throws on the id-less cells); build its body@@ -1952,7 +2261,7 @@ async function runSdkBuild(spec, opts = {}) {// 4. Views (independent -> parallel).if (has('views')) {- const ids = await runner.mapLimit(spec.views || [], concurrency, (v) => buildArtifact('view', viewDef(spec, v)));+ const ids = await runner.mapLimit(spec.views || [], concurrency, (v) => buildArtifact('view', viewDef(spec, v), { authoredQuery: !!((v.filters || []).length || (v.sort || []).length) }));// Key by `entity|name` (matching identityOf.view + the snapshot canonical id). View names are unique// only PER ENTITY, so a name-only key lets a same-named view on another entity OVERWRITE this id and// cross-wire dashboards / sub-grids / AI-summaries to the wrong entity's view.@@ -2153,9 +2462,11 @@ async function runSdkBuild(spec, opts = {}) {const isOwnCustomTable = !!(entSpec && entSpec.existing !== true && prefix &&String(entSpec.schemaName).toLowerCase().startsWith(String(prefix).toLowerCase() + '_'));if (!isOwnCustomTable) continue;- // Serialized deliberately: two promotions racing is the bug being fixed.- await promoteDefaultForm(chosen.id, entityLogical, chosen.f.deactivateOtherMainForms === true);- promotedEntities.add(entityLogical);+ // Serialized deliberately: two promotions racing is the bug being fixed. `promoted` gates the+ // bookkeeping below — a build that could not set the flag must not report a default form it+ // did not set, which is what `result.created.defaultForms` claims.+ const promoted = await promoteDefaultForm(chosen.id, entityLogical, chosen.f.deactivateOtherMainForms === true);+ if (promoted) promotedEntities.add(entityLogical);}if (promotedEntities.size) result.created.defaultForms = Object.fromEntries([...mainByEntity].filter(([k]) => promotedEntities.has(k)).map(([k, v]) => [k, v.id])diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.jsindex e8a45638f..795eb2291 100644--- a/plugins/model-apps/scripts/lib/spec-lint.js+++ b/plugins/model-apps/scripts/lib/spec-lint.js@@ -205,7 +205,21 @@ function lintAppSpec(spec) {if (isExplicit) {if (!Array.isArray(f.tabs) || f.tabs.length === 0) E(`Form ${f.entity} uses an explicit layout but declares no tabs — add at least one tab with a section, or use layout:'auto'`);else for (const t of f.tabs) {- if (!Array.isArray(t.sections) || t.sections.length === 0) E(`Form ${f.entity} explicit tab '${t.label || t.name || ''}' has no sections — add at least one section with fields`);+ // A malformed entry (`tabs: [null]`, a string, an array) would throw from this linter rather+ // than be reported as a lint error — the validator rejects it, but the standalone lint has to+ // survive the same input.+ if (!t || typeof t !== 'object' || Array.isArray(t)) {+ E(`Form ${f.entity} has a tab entry that is not an object — each tab must be { label, sections|columns }`);+ continue;+ }+ // A tab holds sections either directly (the single-full-width-column shorthand) or inside+ // `columns[]` (the multi-column form). Checking only `t.sections` reported every+ // multi-column tab as empty, which is the exact silent-disagreement this lint exists to+ // prevent — the compiler and validator both accept the `columns[]` shape.+ const sections = Array.isArray(t.columns)+ ? t.columns.flatMap((c) => (c && Array.isArray(c.sections) ? c.sections : []))+ : t.sections;+ if (!Array.isArray(sections) || sections.length === 0) E(`Form ${f.entity} explicit tab '${t.label || t.name || ''}' has no sections — add at least one section with fields`);}}for (const sg of f.subgrids || []) {@@ -267,6 +281,16 @@ function lintAppSpec(spec) {}// Dashboards — chart/list tiles must reference a declared chart/view; webresource a web resource.+ //+ // ID PASSTHROUGH: a tile from a downloaded/round-tripped app carries the deployed view/chart ids+ // (+ target entity) instead of names, binding to artifacts that ALREADY exist rather than to+ // anything the spec declares. `validateAppSpec` (app-spec.js, "ID-passthrough tiles") and the+ // build (sdk-build.js `dashboardTileOpts`, "ID passthrough (round-tripped dashboards)") have both+ // always accepted that form, and `download-model-app.js readDashboards` deliberately emits it —+ // this lint was the only stage that did not know about it, so a freshly downloaded spec failed+ // its OWN structural lint. Because such a tile has no `chart`/`view` key at all, the old check+ // also interpolated `undefined` into the message and reported a chart literally named+ // 'undefined'. See #572.const DASH_TILE_TYPES = new Set(['chart', 'list', 'iframe', 'webresource']);const viewNames = new Set((spec.views || []).map((v) => lc(v.name)));const chartNames = new Set((spec.charts || []).map((c) => lc(c.name)));@@ -275,8 +299,29 @@ function lintAppSpec(spec) {if (!(d.tiles && d.tiles.length)) W(`Dashboard '${d.name}' has no tiles`);for (const t of d.tiles || []) {if (!DASH_TILE_TYPES.has(t.type)) { E(`Dashboard '${d.name}' has a tile with invalid type '${t.type}' (chart/list/iframe/webresource)`); continue; }- if (t.type === 'chart' && (!t.chart || !chartNames.has(lc(t.chart)))) E(`Dashboard '${d.name}' chart tile references unknown chart '${t.chart}'`);- if ((t.type === 'chart' || t.type === 'list') && (!t.view || !viewNames.has(lc(t.view)))) E(`Dashboard '${d.name}' ${t.type} tile references unknown view '${t.view}'`);+ // `visualizationId` identifies a CHART; it means nothing on a list tile. One shared id test let+ // a list tile carrying a stray visualizationId take the id path and skip the viewId requirement+ // altogether, so the tile deployed with no view to list.+ const byId = t.type === 'chart' ? (t.viewId || t.visualizationId) : t.viewId;+ if (t.type === 'chart') {+ if (byId) {+ // A chart tile renders a visualization over a view, so BOTH halves are load-bearing: a+ // visualizationId alone has no data to plot, and a viewId alone has nothing to plot with.+ if (!t.viewId) E(`Dashboard '${d.name}' chart tile with visualizationId also needs viewId`);+ if (!t.visualizationId) E(`Dashboard '${d.name}' id-based chart tile with viewId also needs visualizationId`);+ if (!t.entity) E(`Dashboard '${d.name}' id-based chart tile needs entity`);+ } else {+ if (!t.chart) E(`Dashboard '${d.name}' chart tile needs a chart (by name) or viewId+visualizationId (id passthrough)`);+ else if (!chartNames.has(lc(t.chart))) E(`Dashboard '${d.name}' chart tile references unknown chart '${t.chart}'`);+ if (!t.view) E(`Dashboard '${d.name}' chart tile needs a view (by name) or viewId+visualizationId (id passthrough)`);+ else if (!viewNames.has(lc(t.view))) E(`Dashboard '${d.name}' chart tile references unknown view '${t.view}'`);+ }+ } else if (t.type === 'list') {+ if (byId) {+ if (!t.entity) E(`Dashboard '${d.name}' id-based list tile needs entity`);+ } else if (!t.view) E(`Dashboard '${d.name}' list tile needs a view (by name) or a viewId (id passthrough)`);+ else if (!viewNames.has(lc(t.view))) E(`Dashboard '${d.name}' list tile references unknown view '${t.view}'`);+ }if (t.type === 'iframe' && !t.url) E(`Dashboard '${d.name}' iframe tile needs a url`);if (t.type === 'webresource' && (!t.webResource || !webResourceNames.has(lc(t.webResource)))) E(`Dashboard '${d.name}' webresource tile references undeclared web resource '${t.webResource}'`);}diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex 469717147..9fd1b1ef1 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -6,7 +6,7 @@const { odataLit } = require('./odata.js');const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName, bpfUniqueName, BPF_ROLE_ACCESS } = require('./app-spec.js');-const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter } = require('./sdk-build.js');+const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef } = require('./sdk-build.js');const { extractNavTargets } = require('./pageref-resolver.js');const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');const { declaredPrivileges, compareRolePrivileges } = require('./role-privileges.js');@@ -50,6 +50,26 @@ async function verifySpec(spec, read, opts = {}) {const environmentSkipped = [];const phaseSkipped = [];+ const selectedDefaultForms = new Map();+ for (const f of spec.forms || []) {+ const formType = f.formType || 'Main';+ if (formType !== 'Main') continue;+ const entity = String(f.entity || '').toLowerCase();+ if (!entity) continue;+ // Mirror the BUILD's promotion guard exactly (sdk-build.js `isOwnCustomTable`): the build+ // refuses to re-point the default form of a reused or stock table, because that is an+ // environment-wide side effect on a table the spec does not own. Asserting `isdefault` for a+ // table the build deliberately never promotes makes `--verify` permanently unsatisfiable for any+ // spec that puts a Main form on `account`, `contact`, or an `existing: true` table.+ const entSpec = (spec.entities || []).find((e) => e && String(e.schemaName || '').toLowerCase() === entity);+ const prefix = spec.solution && spec.solution.publisherPrefix;+ const isOwnCustomTable = !!(entSpec && entSpec.existing !== true && prefix &&+ String(entSpec.schemaName).toLowerCase().startsWith(String(prefix).toLowerCase() + '_'));+ if (!isOwnCustomTable) continue;+ const current = selectedDefaultForms.get(entity);+ if (!current || (f.isDefault === true && current.isDefault !== true)) selectedDefaultForms.set(entity, f);+ }+// Entities + their declared columns.for (const e of spec.entities || []) {const logical = e.schemaName.toLowerCase();@@ -98,7 +118,7 @@ async function verifySpec(spec, read, opts = {}) {let rows = [];let readError = null;try {- rows = await read.queryRecords('savedquery', { select: ['savedqueryid', 'layoutxml'], filter: `returnedtypecode eq '${String(v.entity).toLowerCase()}' and name eq '${odataLit(v.name)}'`, top: 1 });+ rows = await read.queryRecords('savedquery', { select: ['savedqueryid', 'layoutxml', 'fetchxml'], filter: `returnedtypecode eq '${String(v.entity).toLowerCase()}' and name eq '${odataLit(v.name)}'`, top: 1 });} catch (error) {readError = error;}@@ -113,6 +133,43 @@ async function verifySpec(spec, read, opts = {}) {const missingCols = specCols.filter((c) => !deployed.has(c));add('view-columns', viewName, missingCols.length === 0, missingCols.length ? `missing column(s): ${missingCols.join(', ')}` : '');}+ if (row && Object.prototype.hasOwnProperty.call(row, 'fetchxml')) {+ const expected = expectedViewFetchParts(spec, v);+ // Dataverse stores savedquery.fetchxml as the authoritative query content for a system view, so+ // the verifier proves the DEPLOYED predicates/orders rather than trusting the build's intended+ // view definition. Subset semantics are deliberate: Dataverse may add platform-owned predicates+ // that the App Spec never authored, and those must not block a good app.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/savedquery+ if (!row.fetchxml && (expected.conditions.length || expected.orders.length)) {+ if (expected.conditions.length) add('view-filters', viewName, false, 'could not read deployed savedquery.fetchxml to prove authored filters');+ if (expected.orders.length) add('view-sort', viewName, false, 'could not read deployed savedquery.fetchxml to prove authored sort');+ continue;+ }+ const actual = parseFetchXml(row.fetchxml);+ if (expected.conditions.length) {+ const missing = expected.conditions.filter((want) => !actual.conditions.some((got) => conditionMatches(want, got)));+ add('view-filters', viewName, missing.length === 0, missing.length ? `missing filter(s): ${missing.map(formatCondition).join('; ')}` : '');+ }+ if (expected.orders.length) {+ // Sort PRECEDENCE is the whole point of a sort, so membership is not enough: a deployed+ // `[name asc, createdon desc]` would satisfy an authored `[createdon desc, name asc]` under a+ // per-order `some(...)`, even though the two views return rows in different orders.+ //+ // Authored orders must therefore appear as an ordered SUBSEQUENCE of the deployed ones.+ // Extra platform-owned orders are still tolerated (same subset rule as the filters above),+ // but the authored ones may not be reordered relative to each other.+ let ei = 0;+ for (const got of actual.orders) {+ if (ei < expected.orders.length && orderMatches(expected.orders[ei], got)) ei++;+ }+ const satisfied = ei === expected.orders.length;+ const absent = expected.orders.filter((want) => !actual.orders.some((got) => orderMatches(want, got)));+ add('view-sort', viewName, satisfied, satisfied ? ''+ : absent.length+ ? `missing sort(s): ${absent.map(formatOrder).join('; ')}`+ : `deployed sort order does not match the authored precedence ${expected.orders.map(formatOrder).join(', ')} (deployed: ${actual.orders.map(formatOrder).join(', ')})`);+ }+ }}for (const ch of spec.charts || []) {const rows = await read.queryRecords('savedqueryvisualization', { select: ['savedqueryvisualizationid'], filter: `primaryentitytypecode eq '${String(ch.entity).toLowerCase()}' and name eq '${odataLit(ch.name)}'`, top: 1 });@@ -130,6 +187,21 @@ async function verifySpec(spec, read, opts = {}) {id = await resolveExistingFormId(read, { entityLogicalName: String(f.entity).toLowerCase(), name, formType: f.formType, formId: f.formId });} catch { id = null; }add('form', name, id);+ const entityLogical = String(f.entity || '').toLowerCase();+ if (id && selectedDefaultForms.get(entityLogical) === f && typeof read.formDefaultState === 'function') {+ let state = null;+ let readError = null;+ try { state = await read.formDefaultState(entityLogical, id); } catch (e) { readError = (e && e.message) || String(e); }+ // Default-form promotion is a stored systemform flag, not a property of the App Spec or the+ // build result. A form can exist with the right name/type while still not being the table's+ // default, so this proves the platform row the model-driven runtime uses.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/systemform+ const present = !!(state && state.isDefault === true);+ add('form-default', `${entityLogical}.${name}`, present, present ? '' :+ readError+ ? `could not read deployed systemform.isdefault: ${readError}`+ : `expected this Main form to be the table default, but deployed systemform.isdefault is ${state && state.isDefault === false ? 'false' : 'unreadable'}`);+ }}// Relationships (existence) — currently a build can declare a relationship that silently fails to@@ -463,6 +535,11 @@ async function verifySpec(spec, read, opts = {}) {// therefore verify the role exists AND carries the SDK ownership marker (a same-name role someone// else built would pass a bare existence check but is NOT the role the security phase authored).const roleBuCache = {}; // memoize the root-BU lookup across personas in this verify pass+ let appRoleIdsP;+ const appRoleIds = async () => {+ if (!appRoleIdsP) appRoleIdsP = read.appRoleIds();+ return appRoleIdsP;+ };for (const p of spec.personas || []) {const roleName = canonicalPersonaName(p); // trimmed — matches the SDK's created nameif (!roleName) continue;@@ -481,6 +558,18 @@ async function verifySpec(spec, read, opts = {}) {} catch { row = undefined; }add('role', roleName, row, row ? '' : 'persona security role not found (or its business unit could not be resolved)');+ if (row && p.appAccess !== false && typeof read.appRoleIds === 'function') {+ let res = null;+ try { res = await appRoleIds(); } catch (e) { res = { ok: false, reason: (e && e.message) || String(e) }; }+ if (!res || res.ok !== true) {+ add('app-role', roleName, false, `could not read appmoduleroles_association rows: ${(res && res.reason) || 'unknown'}`);+ } else {+ const ids = new Set((res.roleIds || []).map((id) => String(id).toLowerCase()));+ add('app-role', roleName, ids.has(String(row.roleid).toLowerCase()),+ ids.has(String(row.roleid).toLowerCase()) ? '' : 'persona role is not associated to the app module, so the app may not appear for users with this role');+ }+ }+// Privilege depth check — reader-gated (see `entityRelationships` / `commandBar` above for the// same pattern), so an existence-only reader behaves exactly as before. Proving the role ROW// exists says nothing about what it GRANTS: a role created with the wrong access, or one whose@@ -842,6 +931,158 @@ function escapeRe(s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');}+function expectedViewFetchParts(spec, view) {+ const def = viewDef(spec, view);+ const conditions = [];+ const walk = (group) => {+ for (const c of (group && group.conditions) || []) {+ conditions.push({+ attribute: String(c.attribute || '').toLowerCase(),+ operator: String(c.operator || 'eq').toLowerCase(),+ value: c.value === undefined ? undefined : String(c.value),+ });+ }+ for (const child of (group && group.groups) || []) walk(child);+ };+ walk(def.filters);+ const orders = (def.sort || []).map((s) => ({+ attribute: String(s.attribute || '').toLowerCase(),+ descending: s.descending === true,+ }));+ return { conditions: conditions.filter((c) => c.attribute && c.operator), orders };+}++function xmlDecode(value) {+ return String(value || '')+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/&/g, '&');+}++function tagAttrs(tag) {+ const attrs = {};+ const re = /\b([A-Za-z_][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;+ let m;+ while ((m = re.exec(String(tag || ''))) !== null) attrs[String(m[1]).toLowerCase()] = xmlDecode(m[2] != null ? m[2] : m[3]);+ return attrs;+}++// Parse only the FetchXML facts the App Spec authors and the verifier must prove. Raw deployed+// shape, with the platform quirks that matter:+// <fetch><entity name="new_ticket">+// <filter type="and">+// <condition attribute="ownerid" operator="eq-userid" />+// <condition attribute="modifiedon" operator="this-week"></condition>+// <condition attribute="new_priority" operator="ne" value="100000000" />+// </filter>+// <order attribute="createdon" descending="true" />+// </entity></fetch>+// Current-user and relative-date operators serialize with NO `value` attribute; that is a correct+// deployed condition, not malformed XML. Attribute order and quote style vary, and Dataverse may add+// extra filters, so callers compare for presence rather than byte equality.+// Strip every `<link-entity>` subtree, leaving only what belongs to the view's ROOT `<entity>`.+//+// FetchXML puts a joined table's own predicates and ordering inside `<link-entity>`:+// <entity name="account">+// <filter><condition attribute="statecode" operator="eq" value="0" /></filter>+// <link-entity name="contact" from="parentcustomerid" to="accountid">+// <filter><condition attribute="statecode" operator="eq" value="0" /></filter>+// </link-entity>+// </entity>+// Both conditions read `statecode eq 0`, but only the first is a predicate on `account`. Scanning the+// whole document let the linked one satisfy an authored base-entity condition by coincidence — a+// verifier reporting PASS on a view that does not filter the way the spec says, which is the one+// outcome an oracle must never produce.+//+// Written as a depth scanner rather than a regex because link-entities NEST, and `<link-entity ... />`+// may also be self-closing (a join used only for its column projection) — a non-greedy regex would+// stop at the first `</link-entity>` and let an outer subtree leak back in.+function baseEntityFetchXml(xml) {+ const s = String(xml || '');+ const re = /<(\/?)link-entity\b([^>]*)>/gi;+ let out = '';+ let last = 0;+ let depth = 0;+ let m;+ while ((m = re.exec(s)) !== null) {+ if (m[1] === '/') {+ if (depth > 0) depth -= 1;+ if (depth === 0) last = re.lastIndex;+ continue;+ }+ if (depth === 0) out += s.slice(last, m.index);+ // A self-closing start tag opens nothing, so only its own text is dropped.+ if (!/\/\s*$/.test(m[2])) depth += 1;+ last = re.lastIndex;+ }+ // An unbalanced document (depth still open) contributes no trailing text rather than guessing.+ if (depth === 0) out += s.slice(last);+ return out;+}++function parseFetchXml(xml) {+ // Both scans are scoped to the root entity — see baseEntityFetchXml. Orders are scoped for the+ // same reason as conditions: an `<order>` inside a link-entity sorts the joined table, and letting+ // it into this list would satisfy — or break — the authored sort precedence with a foreign order.+ const scoped = baseEntityFetchXml(xml);+ const conditions = [];+ const conditionRe = /<condition\b[^>]*?(?:\/>|>[\s\S]*?<\/condition>)/gi;+ let m;+ while ((m = conditionRe.exec(scoped)) !== null) {+ const tag = m[0];+ const attrs = tagAttrs(tag);+ if (!attrs.attribute || !attrs.operator) continue;+ // `in`/`not-in`/`between` serialize their operands as SIBLING <value> elements:+ // <condition attribute="statuscode" operator="in"><value>1</value><value>2</value></condition>+ // Reading only the first made an authored `in 2` unprovable against a view that really does+ // filter on it. Single-operand conditions use the `value` ATTRIBUTE instead, which wins when+ // present; an operator with no operand at all (`eq-userid`, `last-x-days`) yields [undefined],+ // which conditionMatches treats as "attribute+operator is the whole claim".+ const inner = [];+ const valueRe = /<value\b[^>]*>([\s\S]*?)<\/value>/gi;+ let vm;+ while ((vm = valueRe.exec(tag)) !== null) inner.push(xmlDecode(vm[1].trim()));+ const values = attrs.value !== undefined ? [attrs.value] : (inner.length ? inner : [undefined]);+ for (const value of values) {+ conditions.push({+ attribute: String(attrs.attribute).toLowerCase(),+ operator: String(attrs.operator).toLowerCase(),+ value: value === undefined ? undefined : String(value),+ });+ }+ }+ const orders = [];+ const orderRe = /<order\b[^>]*>/gi;+ while ((m = orderRe.exec(scoped)) !== null) {+ const attrs = tagAttrs(m[0]);+ if (!attrs.attribute) continue;+ orders.push({+ attribute: String(attrs.attribute).toLowerCase(),+ descending: String(attrs.descending || 'false').toLowerCase() === 'true',+ });+ }+ return { conditions, orders };+}++function conditionMatches(want, got) {+ if (want.attribute !== got.attribute || want.operator !== got.operator) return false;+ return want.value === undefined || String(want.value) === String(got.value);+}++function orderMatches(want, got) {+ return want.attribute === got.attribute && want.descending === got.descending;+}++function formatCondition(c) {+ return `${c.attribute} ${c.operator}${c.value === undefined ? '' : ` ${c.value}`}`;+}++function formatOrder(o) {+ return `${o.attribute} ${o.descending ? 'desc' : 'asc'}`;+}+// Extract the deployed column logical names from a saved view's layoutxml. Shape (Dataverse grid// layout), e.g.:// <grid name='resultset' ...><row ...><cell name='new_name' width='200' /><cell name='new_status' /></row></grid>@@ -904,4 +1145,4 @@ function appShellReferencesPage(spec, key) {return false;}-module.exports = { verifySpec, hasElement, subareaHasDashboard, subareaHasGenPage, appShellReferencesPage, layoutColumnNames };+module.exports = { verifySpec, hasElement, subareaHasDashboard, subareaHasGenPage, appShellReferencesPage, layoutColumnNames, parseFetchXml };diff --git a/plugins/model-apps/scripts/tests/app-spec-keys.test.js b/plugins/model-apps/scripts/tests/app-spec-keys.test.jsindex 611ad40c1..243e10444 100644--- a/plugins/model-apps/scripts/tests/app-spec-keys.test.js+++ b/plugins/model-apps/scripts/tests/app-spec-keys.test.js@@ -398,3 +398,348 @@ test('#537 review follow-up: a NON-STRING schemaName is an error, not a crash',// means resolving the name ONCE into a local and threading it through every site, which is its own// change with its own tests. Unlike the non-string case above, this shape cannot come from// `JSON.parse` — only a programmatic caller can build it — so it is not on any real input path.++// --- explicit form layout: unknown/unserializable keys (#575 follow-on) ---+// tabs[]/sections[] had NO allow-list, so an invented key validated clean and vanished. Several+// plausible keys are also accepted by the SDK normalizers and then dropped by its serializer.++function withForm(tabs) {+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_amount', type: 'Text' }];+ s.forms = [{ entity: 'contoso_order', name: 'Order', layout: 'explicit', tabs }];+ return s;+}+const errsFor = (tabs) => validateAppSpec(withForm(tabs), { profile: 'plan' }).errors;++test('form layout: an unknown key on a tab, section or field entry is rejected', () => {+ assert.ok(errsFor([{ label: 'G', bogusTabKey: 1, sections: [{ label: 'S', fields: [] }] }])+ .some((e) => /unknown key \x27bogusTabKey\x27 on tab/.test(e)), 'tab key');+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'S', bogusSectionKey: 1, fields: [] }] }])+ .some((e) => /unknown key \x27bogusSectionKey\x27 on tab .* section/.test(e)), 'section key');+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'S', fields: [{ name: 'contoso_amount', bogusFieldKey: 1 }] }] }])+ .some((e) => /unknown key \x27bogusFieldKey\x27 on tab .* field/.test(e)), 'field entry key');+});++test('form layout: keys the SDK serializer DROPS are rejected with the real mechanism named', () => {+ // Measured against the vendored bundle: a tab serializes only name/expanded/visible + label.+ const tabShowLabel = errsFor([{ label: 'G', showLabel: true, sections: [{ label: 'S', fields: [] }] }]);+ assert.ok(tabShowLabel.some((e) => /unknown key \x27showLabel\x27 on tab/.test(e)));+ assert.ok(tabShowLabel.some((e) => /a TAB has no label toggle in FormXml/.test(e)), 'names what to use instead');+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'S', labelPosition: 'Top', fields: [] }] }])+ .some((e) => /unknown key \x27labelPosition\x27 on tab .* section/.test(e)));+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'S', locked: true, fields: [] }] }])+ .some((e) => /unknown key \x27locked\x27/.test(e)));+});++test('form layout: a tab cannot declare both sections and columns', () => {+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'A', fields: [] }], columns: [{ sections: [{ label: 'B', fields: [] }] }] }])+ .some((e) => /declares both \x27sections\x27 and \x27columns\x27/.test(e)));+});++// `columns` is an INTEGER grid width on a section but an ARRAY of form-columns on a tab. A non-array+// tab `columns` used to validate clean and then be dropped by the compiler (which reads+// `Array.isArray(t.columns)`), so `"columns": 2` on a tab silently shipped a one-column form — the+// exact silent no-op this allow-list exists to end, on the schema's most confusable key. The+// "declares both" rule above cannot catch it: that too requires Array.isArray.+// A cell that spans DOWN reserves its column in the rows beneath it, and FormXml fills a row's cells+// left to right with no way to skip a reserved slot. Measured on the stock account/contact Main+// forms: every section using rowspan puts it on the LAST cell, precisely because nothing can be+// positioned beside it.+test('form layout: a rowspan is rejected unless it is the last field in its section', () => {+ const bad = errsFor([{ label: 'G', sections: [{ label: 'S', columns: 2, fields: [{ name: 'a', rowspan: 2 }, 'b'] }] }]);+ assert.ok(bad.some((e) => /rowspan 2 but is not the last field in its section/.test(e)), `expected a rowspan placement error; got ${JSON.stringify(bad)}`);++ const ok = errsFor([{ label: 'G', sections: [{ label: 'S', columns: 2, fields: ['b', { name: 'a', rowspan: 2 }] }] }]);+ assert.ok(!ok.some((e) => /rowspan/.test(e)), `a terminal rowspan must stay valid; got ${JSON.stringify(ok)}`);+});++// formSectionsOf treats a non-array `sections` as absent, so a typo silently dropped the whole+// form-column's layout instead of failing.+test('form layout: a non-array sections inside a form-column is rejected', () => {+ const errs = errsFor([{ label: 'G', columns: [{ width: '50%', sections: {} }] }]);+ assert.ok(errs.some((e) => /non-array 'sections'/.test(e)), `expected a non-array sections error; got ${JSON.stringify(errs)}`);+});++// The compiler dereferences every tab/column/section entry. Tabs and sections had partial pre-existing+// guards; a malformed FORM-COLUMN was entirely unguarded and reached compileFormIntent, which reads+// `c.width`/`c.sections`, as a raw TypeError.+test('form layout: a non-object tab, form-column or section is rejected, not dereferenced', () => {+ assert.ok(errsFor([null]).some((e) => /tabs\[0\] must be an object/.test(e)), 'a null tab is rejected');+ assert.ok(errsFor(['nope']).some((e) => /tab #1 must be an object/.test(e)), 'a primitive tab is rejected');+ assert.ok(errsFor([{ label: 'G', sections: [null] }]).some((e) => /sections\[0\] must be an object/.test(e)), 'a null section is rejected');+ // The gap this closes:+ assert.ok(errsFor([{ label: 'G', columns: [null] }]).some((e) => /column #1 must be an object, got null/.test(e)), 'a null form-column is rejected');+ assert.ok(errsFor([{ label: 'G', columns: ['x'] }]).some((e) => /column #1 must be an object/.test(e)), 'a primitive form-column is rejected');+});++// compileFormIntent only truth-tests these (`!== false`), so a STRING "false" compiles as true and+// deploys the opposite of what was authored.+test('form layout: expanded / visible / showLabel must be real booleans', () => {+ assert.ok(errsFor([{ label: 'G', expanded: 'false', sections: [{ label: 'S', fields: [] }] }])+ .some((e) => /has expanded 'false' — it must be true or false/.test(e)));+ assert.ok(errsFor([{ label: 'G', visible: 0, sections: [{ label: 'S', fields: [] }] }])+ .some((e) => /has visible '0'/.test(e)));+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'S', showLabel: 'false', fields: [] }] }])+ .some((e) => /has showLabel 'false'/.test(e)));+ // A real boolean still passes.+ assert.ok(!errsFor([{ label: 'G', expanded: false, sections: [{ label: 'S', showLabel: true, fields: [] }] }])+ .some((e) => /must be true or false/.test(e)));+});++// A name is the container's IDENTITY on a rebuild — the topology reconcile matches deployed+// containers by name and keys its placement targets by name — so duplicates make two authored+// declarations resolve to the same deployed container.+test('form layout: duplicate tab or section names are rejected (a name is identity on rebuild)', () => {+ assert.ok(errsFor([+ { name: 'tab_a', label: 'A', sections: [{ label: 'S1', fields: [] }] },+ { name: 'TAB_A', label: 'B', sections: [{ label: 'S2', fields: [] }] },+ ]).some((e) => /reuses the tab name 'TAB_A'/.test(e)), 'duplicate tab names are caught case-insensitively');++ assert.ok(errsFor([{ label: 'G', sections: [+ { name: 'sec_x', label: 'S1', fields: [] },+ { name: 'sec_x', label: 'S2', fields: [] },+ ] }]).some((e) => /reuses the section name 'sec_x'/.test(e)));+});++test('form layout: a tab columns that is a NUMBER is rejected and points at the section key', () => {+ const errs = errsFor([{ label: 'G', columns: 2, sections: [{ label: 'S', fields: [] }] }]);+ assert.ok(errs.some((e) => /has columns \x272\x27/.test(e)), `expected a tab-columns error; got ${JSON.stringify(errs)}`);+ assert.ok(errs.some((e) => /put \x27columns\x27: 2 on the section instead/.test(e)), 'the message must name the fix');+});++test('form layout: out-of-range spans, section columns and column widths are rejected', () => {+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'S', columns: 9, fields: [] }] }])+ .some((e) => /may span 1 to 4 columns/.test(e)), 'section columns');+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'S', fields: [{ name: 'contoso_amount', colspan: 0 }] }] }])+ .some((e) => /has colspan \x270\x27/.test(e)), 'colspan 0');+ assert.ok(errsFor([{ label: 'G', sections: [{ label: 'S', fields: [{ name: 'contoso_amount', rowspan: 1.5 }] }] }])+ .some((e) => /has rowspan \x271.5\x27/.test(e)), 'fractional rowspan');+ assert.ok(errsFor([{ label: 'G', columns: [{ width: '60px', sections: [{ label: 'S', fields: [] }] }] }])+ .some((e) => /width \x2760px\x27 .* must be a percentage/.test(e)), 'non-percentage width');+});++test('form layout: a valid explicit layout with spans and multi-column tabs passes clean', () => {+ const errs = errsFor([{ name: 'tab_g', label: 'G', expanded: false, visible: true, columns: [+ { width: '60%', sections: [{ name: 's1', label: 'S1', columns: 2, showLabel: true, visible: true, fields: [{ name: 'contoso_amount', colspan: 2 }] }] },+ { width: '40%', sections: [{ name: 's2', label: 'S2', columns: 1, fields: ['contoso_name'] }] },+ ] }]);+ assert.deepStrictEqual(errs.filter((e) => /unknown key|must be a percentage|may span|has colspan|has rowspan/.test(e)), []);+});++// A field placed twice on one form is a CREATE-vs-REBUILD divergence, not a cosmetic slip: the+// compiler emits one cell per entry, so a fresh build deploys two cells, while every reconcile path+// keys placement by logical name and takes the first (`declaredSectionByField`, `findFieldCellPointer`,+// and `formFieldLogicals`, which de-duplicates). The second cell would appear on create and vanish on+// the next build. MEASURED before this gate existed: the same spec compiled to 2 bound cells while+// declaredSectionByField resolved the field to the first section only.+test('form layout: a field placed twice is rejected, because create and rebuild would disagree', () => {+ const mk = (secA, secB) => {+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_amount', displayName: 'Amount', type: 'Decimal' }];+ s.forms = [{ entity: 'contoso_order', layout: 'explicit', tabs: [{ label: 'General', sections: [+ { label: 'A', name: 'sec_a', fields: secA },+ { label: 'B', name: 'sec_b', fields: secB },+ ] }] }];+ return s;+ };+ const dupErrors = (s) => validateAppSpec(s, { profile: 'plan' }).errors.filter((e) => /places field/.test(e));++ assert.strictEqual(dupErrors(mk(['contoso_name', 'contoso_amount'], ['contoso_name'])).length, 1,+ 'the same field in two sections must be rejected');+ assert.strictEqual(dupErrors(mk(['contoso_name', 'contoso_name'], ['contoso_amount'])).length, 1,+ 'the same field twice in ONE section must be rejected too');+ // Dataverse logical names are case-insensitive, so a casing difference is the same cell.+ assert.strictEqual(dupErrors(mk([{ name: 'contoso_name' }], [{ name: 'CONTOSO_NAME' }])).length, 1,+ 'duplicate detection must be case-insensitive and must see field-entry objects');+ assert.strictEqual(dupErrors(mk(['contoso_name'], [{ name: 'contoso_name' }])).length, 1,+ 'a string entry and an object entry naming the same field are still one field twice');++ // The gate must not fire on an ordinary form — that would make every explicit layout unbuildable.+ assert.deepStrictEqual(dupErrors(mk(['contoso_name'], ['contoso_amount'])), [],+ 'distinct fields must stay valid');++ // Identity is per FORM, so two forms on the same table may each place the same column.+ const twoForms = mk(['contoso_name'], ['contoso_amount']);+ twoForms.forms.push({ entity: 'contoso_order', name: 'Second', layout: 'explicit', tabs: [{ label: 'General', sections: [+ { label: 'A', name: 'other_a', fields: ['contoso_name'] },+ ] }] });+ assert.deepStrictEqual(dupErrors(twoForms), [], 'a second form may place the same field');+});++// The gate exists only to move the loader's refusal earlier, so the two must agree EXACTLY. The+// loader keys on `JSON.stringify([typeof v, v])`, so `1` and `'1'` are distinct rows; a plain+// `String(...)` key here made them collide and rejected, at author time, a spec that builds. Both+// sides now call the shared `sampleKeyIdentity`, so they cannot drift apart again.+test('sampleData: duplicate detection keys values exactly the way the loader does', () => {+ const withKey = (rows) => {+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_code', displayName: 'Code', type: 'Text' }];+ s.entities[0].alternateKeys = [{ name: 'k', columns: ['contoso_code'] }];+ s.sampleData = { contoso_order: rows };+ return validateAppSpec(s, { profile: 'plan' }).errors.filter((e) => /duplicate contoso_code/.test(e));+ };++ assert.deepStrictEqual(withKey([{ contoso_name: 'A', contoso_code: 1 }, { contoso_name: 'B', contoso_code: '1' }]), [],+ 'the loader treats 1 and "1" as distinct, so this gate must not reject them');+ assert.strictEqual(withKey([{ contoso_name: 'A', contoso_code: '1' }, { contoso_name: 'B', contoso_code: '1' }]).length, 1,+ 'two identical strings are still a duplicate');+ assert.strictEqual(withKey([{ contoso_name: 'A', contoso_code: 1 }, { contoso_name: 'B', contoso_code: 1 }]).length, 1,+ 'and so are two identical numbers');+});++// A generated fallback name is a REAL identity, not a placeholder: the reconcile matches a deployed+// container by name. So an unnamed section and an explicit `name: "section_0_0"` are the same+// container to every rebuild path, while create emits two. MEASURED before this gate: the compiled+// intent carried two sections both named `section_0_0`, and declaredSectionByField routed both+// sections' fields to that one target. Uniqueness is therefore checked on the EFFECTIVE name.+test('form layout: an explicit name that collides with a generated one is rejected', () => {+ const form = (tabs) => { const s = base(); s.entities[0].columns = [{ schemaName: 'contoso_amount', displayName: 'Amt', type: 'Decimal' }]; s.forms = [{ entity: 'contoso_order', layout: 'explicit', tabs }]; return s; };+ const nameErrors = (s) => validateAppSpec(s, { profile: 'plan' }).errors.filter((e) => /reuses the (tab|section) name/.test(e));++ const secCollision = form([{ label: 'G', sections: [+ { label: 'A', fields: ['contoso_name'] }, // unnamed -> section_0_0+ { label: 'B', name: 'section_0_0', fields: ['contoso_amount'] }, // explicit, same identity+ ] }]);+ assert.strictEqual(nameErrors(secCollision).length, 1, 'an unnamed section and an explicit section_0_0 are one container');+ assert.match(nameErrors(secCollision)[0], /generated name/, 'the message must explain where the other name came from');++ const tabCollision = form([+ { label: 'A', sections: [{ label: 'S', name: 's1', fields: ['contoso_name'] }] }, // unnamed -> tab_0+ { label: 'B', name: 'tab_0', sections: [{ label: 'T', name: 's2', fields: ['contoso_amount'] }] },+ ]);+ assert.strictEqual(nameErrors(tabCollision).length, 1, 'tabs collide the same way');++ // The generated section name carries its FORM-COLUMN index for ci > 0, so the gate has to walk+ // columns rather than the flattened section list to compute it.+ const multiColumn = form([{ label: 'G', columns: [+ { width: '50%', sections: [{ label: 'L', name: 'section_0_1_0', fields: ['contoso_name'] }] },+ { width: '50%', sections: [{ label: 'R', fields: ['contoso_amount'] }] }, // -> section_0_1_0+ ] }]);+ assert.strictEqual(nameErrors(multiColumn).length, 1, 'a collision with a column-scoped generated name must be caught');++ // Ordinary multi-column layouts generate distinct names and must stay valid.+ const ok = form([{ label: 'G', columns: [+ { width: '50%', sections: [{ label: 'L', fields: ['contoso_name'] }] },+ { width: '50%', sections: [{ label: 'R', fields: ['contoso_amount'] }] },+ ] }]);+ assert.deepStrictEqual(nameErrors(ok), [], 'unnamed sections in different form-columns are distinct');+});++// Reserving the generated namespace instead would break the round trip: a DOWNLOADED spec carries+// the real deployed names, which for an app this compiler built are exactly the generated ones. They+// must stay valid when they are the only declaration of that container.+test('form layout: a downloaded spec that names its containers explicitly stays valid', () => {+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_amount', displayName: 'Amt', type: 'Decimal' }];+ s.forms = [{ entity: 'contoso_order', layout: 'explicit', tabs: [+ { label: 'General', name: 'tab_0', sections: [+ { label: 'A', name: 'section_0_0', fields: ['contoso_name'] },+ { label: 'B', name: 'section_0_1', fields: ['contoso_amount'] },+ ] },+ ] }];+ assert.deepStrictEqual(+ validateAppSpec(s, { profile: 'plan' }).errors.filter((e) => /reuses the (tab|section) name/.test(e)),+ [], 'round-tripping a built app must not be rejected by its own generated names');+});++// An explicit layout that supplies no structure used to pass `validateAppSpec` — and that is the+// gate that matters, because `build-model-app.js` runs the validator and never the standalone lint.+// MEASURED before this check, every one with `validate.ok === true`: `tabs: []` compiled to 0 tabs /+// 0 sections / 0 bound cells, and a tab with empty `sections`/`columns` compiled to 1 tab and 0+// sections — every declared field silently dropped. With notes enabled, `tabs: []` did not even+// fail cleanly: the compiler threw `Cannot read properties of undefined (reading 'columns')`.+test('form layout: an explicit layout with no place to put a field is rejected', () => {+ const form = (tabs) => {+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_amount', displayName: 'Amt', type: 'Decimal' }];+ s.forms = [{ entity: 'contoso_order', layout: 'explicit', tabs }];+ return s;+ };+ const emptyErrors = (s) => validateAppSpec(s, { profile: 'plan' }).errors.filter((e) => /no tabs|has no sections/.test(e));++ assert.strictEqual(emptyErrors(form([])).length, 1, 'tabs: [] declares no structure at all');+ assert.strictEqual(emptyErrors(form([{ label: 'G', sections: [] }])).length, 1, 'a tab with no sections has nowhere to place a field');+ assert.strictEqual(emptyErrors(form([{ label: 'G', columns: [] }])).length, 1, 'nor does a tab with no form-columns');+ assert.strictEqual(emptyErrors(form([{ label: 'G', columns: [{ width: '100%', sections: [] }] }])).length, 1,+ 'nor one whose only form-column is empty');++ // The emptiness test is on the FLATTENED section list, so an empty form-column BESIDE a populated+ // one is still a legitimate layout — checking `t.sections` alone would have reported every+ // multi-column tab as empty, the same silent disagreement in the other direction.+ assert.deepStrictEqual(emptyErrors(form([{ label: 'G', columns: [+ { width: '50%', sections: [] },+ { width: '50%', sections: [{ label: 'S', fields: ['contoso_name'] }] },+ ] }])), [], 'an empty form-column beside a populated one is allowed');++ // A section with no fields is NOT rejected: a section may legitimately carry only a sub-grid or a+ // quick-view, neither of which is declared in `fields[]`.+ assert.deepStrictEqual(emptyErrors(form([{ label: 'G', sections: [{ label: 'S', fields: [] }] }])), [],+ 'an empty section is legal — it may host a sub-grid or quick-view');++ assert.deepStrictEqual(emptyErrors(form([{ label: 'G', sections: [{ label: 'S', fields: ['contoso_name'] }] }])), [],+ 'an ordinary layout stays valid');+});++// The seeder refuses to use a duplicated primary name as `matchOn` (Dataverse could resolve or+// deduplicate the wrong row). That refusal happens in the sample-data phase — after tables, forms and+// views are already deployed — so ordinary sample data used to validate clean and then stop the build+// halfway. The gate mirrors chooseMatchOn exactly, including both of its escape hatches.+test('sampleData: duplicate primary-name values are rejected at author time, not mid-build', () => {+ const dup = base();+ dup.sampleData = { contoso_order: [{ contoso_name: 'Printer issue' }, { contoso_name: 'Printer issue' }] };+ assert.ok(validateAppSpec(dup, { profile: 'plan' }).errors.some((e) => /duplicate contoso_name value 'Printer issue'/.test(e)));++ const unique = base();+ unique.sampleData = { contoso_order: [{ contoso_name: 'A' }, { contoso_name: 'B' }] };+ assert.ok(!validateAppSpec(unique, { profile: 'plan' }).errors.some((e) => /duplicate contoso_name/.test(e)), 'unique names must stay valid');++ // A single-column alternate key is enforced-unique by Dataverse, so it is what matchOn uses and+ // the primary name never comes into it.+ const keyed = base();+ keyed.entities[0].alternateKeys = [{ name: 'k', columns: ['contoso_code'] }];+ keyed.sampleData = { contoso_order: [{ contoso_name: 'X', contoso_code: '1' }, { contoso_name: 'X', contoso_code: '2' }] };+ assert.ok(!validateAppSpec(keyed, { profile: 'plan' }).errors.some((e) => /duplicate contoso_name/.test(e)), 'a safe alternate key makes the primary irrelevant');++ // A safe alternate key is what matchOn USES, so duplicates in it break the same way — and used to+ // pass this gate and fail during sample-data provisioning instead.+ const dupKey = base();+ dupKey.entities[0].alternateKeys = [{ name: 'k', columns: ['contoso_code'] }];+ dupKey.sampleData = { contoso_order: [{ contoso_name: 'A', contoso_code: 'DUP' }, { contoso_name: 'B', contoso_code: 'DUP' }] };+ assert.ok(validateAppSpec(dupKey, { profile: 'plan' }).errors.some((e) => /duplicate contoso_code value 'DUP'/.test(e)),+ 'duplicates in the alternate key that matchOn selects must be caught at author time');++ // A partially/entirely empty primary means matchOn is omitted altogether, so there is no wrong-row+ // resolve to guard against.+ const empty = base();+ empty.sampleData = { contoso_order: [{ contoso_name: '' }, { contoso_name: '' }] };+ assert.ok(!validateAppSpec(empty, { profile: 'plan' }).errors.some((e) => /duplicate contoso_name/.test(e)));+});++test('sampleData: _seedKey is rejected because it reaches Dataverse as an unknown attribute', () => {+ const s = base();+ s.sampleData = { contoso_order: [{ contoso_name: 'A', _seedKey: 'order-1' }] };+ const errs = validateAppSpec(s, { profile: 'plan' }).errors;+ assert.ok(errs.some((e) => /_seedKey. is not a supported sample-record key/.test(e)));+ assert.ok(errs.some((e) => /single-column alternate key/.test(e)), 'points at the real mechanism');+});++// A multi-column tab nests its sections inside columns[]. Every raw-spec reader must see them, or+// section-level validation silently stops running for exactly the richer layouts it should police.+test('form layout: sections nested in columns[] are still validated', () => {+ const badKey = errsFor([{ label: 'G', columns: [{ width: '50%', sections: [{ label: 'S', locked: true, fields: [] }] }] }]);+ assert.ok(badKey.some((e) => /unknown key .locked./.test(e)), `nested section keys must be checked; got ${JSON.stringify(badKey)}`);+ const badCols = errsFor([{ label: 'G', columns: [{ width: '50%', sections: [{ label: 'S', columns: 9, fields: [] }] }] }]);+ assert.ok(badCols.some((e) => /may span 1 to 4 columns/.test(e)), 'nested section column counts must be checked');+ const badSpan = errsFor([{ label: 'G', columns: [{ width: '50%', sections: [{ label: 'S', fields: [{ name: 'contoso_amount', colspan: 0 }] }] }] }]);+ assert.ok(badSpan.some((e) => /has colspan .0./.test(e)), 'nested field spans must be checked');+});++test('form layout: a non-array fields inside columns[] is caught, not thrown on', () => {+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_amount', type: 'Text' }];+ s.forms = [{ entity: 'contoso_order', name: 'O', layout: 'explicit',+ tabs: [{ label: 'G', columns: [{ width: '100%', sections: [{ label: 'S', fields: 'contoso_amount' }] }] }] }];+ // A string is ITERABLE, so a naive per-entry loop would walk its characters instead of failing.+ const errs = validateAppSpec(s, { profile: 'plan' }).errors;+ assert.ok(errs.some((e) => /fields must be an array/.test(e)), `got ${JSON.stringify(errs)}`);+});diff --git a/plugins/model-apps/scripts/tests/artifact-intent.test.js b/plugins/model-apps/scripts/tests/artifact-intent.test.jsindex cf061730f..5c2bf4075 100644--- a/plugins/model-apps/scripts/tests/artifact-intent.test.js+++ b/plugins/model-apps/scripts/tests/artifact-intent.test.js@@ -689,3 +689,65 @@ test('form event parameters accepts an explicit empty string and ignores null',// Dataverse writes parameters="" itself, so an absent value is the empty string, not a dropped attribute.assert.strictEqual(attrsOf({ event: 'onsave', library: 'l.js', function: 'f', parameters: null }).parameters, '');});++test('explicit layout: colspan/rowspan are emitted only when they exceed the adapter default', () => {+ const spec = makeSpec();+ const form = { entity: 'new_item', name: 'Item', layout: 'explicit', tabs: [{ label: 'General', sections: [+ { label: 'Details', columns: 2, fields: [{ name: 'new_name', colspan: 2 }, 'new_status', { name: 'new_cost', rowspan: 2 }] },+ ] }] };+ const intent = compileFormIntent(spec, form);+ const cells = intent.tabs[0].columns[0].sections[0].rows.flatMap((r) => r.cells);+ const byField = Object.fromEntries(cells.map((c) => [c.control.fieldName, c]));+ assert.strictEqual(byField.new_name.colspan, 2, 'an authored colspan reaches the cell');+ assert.strictEqual(byField.new_cost.rowspan, 2, 'an authored rowspan reaches the cell');+ // An ordinary cell must carry NO span key: emitting the default would overwrite a span a maker+ // widened by hand on a form the spec never claimed to own that of.+ assert.ok(!('colspan' in byField.new_status), 'no colspan is written for a field that did not ask');+ assert.ok(!('rowspan' in byField.new_status), 'no rowspan is written for a field that did not ask');+});++test('explicit layout: a colspan cell consumes its full width when packing rows', () => {+ const spec = makeSpec();+ const form = { entity: 'new_item', name: 'Item', layout: 'explicit', tabs: [{ label: 'G', sections: [+ { label: 'D', columns: 2, fields: [{ name: 'new_name', colspan: 2 }, 'new_status', 'new_cost'] },+ ] }] };+ const rows = compileFormIntent(spec, form).tabs[0].columns[0].sections[0].rows;+ // Packing by cell COUNT would put new_name and new_status in row 0, even though new_name already+ // spans the whole 2-column section.+ assert.deepStrictEqual(rows.map((r) => r.cells.map((c) => c.control.fieldName)), [['new_name'], ['new_status', 'new_cost']]);+});++test('explicit layout: tab expanded/visible and section visible are author-controlled', () => {+ const spec = makeSpec();+ const form = { entity: 'new_item', name: 'Item', layout: 'explicit', tabs: [+ { label: 'Collapsed', expanded: false, sections: [{ label: 'A', fields: ['new_name'] }] },+ { label: 'Hidden', visible: false, sections: [{ label: 'B', visible: false, fields: ['new_status'] }] },+ ] };+ const intent = compileFormIntent(spec, form);+ assert.strictEqual(intent.tabs[0].expanded, false, 'expanded: false collapses the tab');+ assert.strictEqual(intent.tabs[0].visible, true, 'and leaves visibility alone');+ assert.strictEqual(intent.tabs[1].visible, false);+ assert.strictEqual(intent.tabs[1].columns[0].sections[0].visible, false);+});++test('explicit layout: multi-column tabs split width evenly unless authored', () => {+ const spec = makeSpec();+ const form = { entity: 'new_item', name: 'Item', layout: 'explicit', tabs: [{ label: 'G', columns: [+ { sections: [{ label: 'L', fields: ['new_name'] }] },+ { sections: [{ label: 'M', fields: ['new_status'] }] },+ { sections: [{ label: 'R', fields: ['new_cost'] }] },+ ] }] };+ const cols = compileFormIntent(spec, form).tabs[0].columns;+ assert.deepStrictEqual(cols.map((c) => c.width), ['34%', '33%', '33%'], 'widths total exactly 100');+ // Generated section names stay collision-free across columns while column 0 keeps the legacy+ // `section_<tab>_<i>` form, so already-deployed single-column forms still match themselves.+ assert.deepStrictEqual(cols.map((c) => c.sections[0].name), ['section_0_0', 'section_0_1_0', 'section_0_2_0']);+});++test('fieldCellIntent writes a span only ABOVE the adapter default, even when handed the default', () => {+ // normalizeFieldEntry already folds <=1 to undefined, so this guards the OTHER callers: emitting+ // colspan="1" on every ordinary cell would overwrite a span widened by hand in the designer.+ assert.ok(!('colspan' in fieldCellIntent('new_name', { colspan: 1 })), 'colspan 1 is the default and must not be written');+ assert.ok(!('rowspan' in fieldCellIntent('new_name', { rowspan: 1 })), 'rowspan 1 is the default and must not be written');+ assert.strictEqual(fieldCellIntent('new_name', { colspan: 3 }).colspan, 3);+});diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.jsindex c7c9d14a4..76f6fcaee 100644--- a/plugins/model-apps/scripts/tests/download-model-app.test.js+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js@@ -249,7 +249,7 @@ test('readEntityWithDescriptions reads descriptions through the RAW dataverse cl// The $select also carries the DISPLAY labels now, so a table/column labelled in more than one// language round-trips (AB#6686428). The SDK's flattened `displayName` keeps only one.assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\?\$select=LogicalName,Description,DisplayName,DisplayCollectionName$/.test(u)), `table read URL wrong: ${gets.join(' | ')}`);- assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\/Attributes\?\$select=LogicalName,Description,DisplayName,IsLogical,AttributeTypeName$/.test(u)), `attribute read URL wrong: ${gets.join(' | ')}`);+ assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\/Attributes\?\$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName$/.test(u)), `attribute read URL wrong: ${gets.join(' | ')}`);assert.strictEqual(e.description, 'Order table purpose.');const status = e.columns.find((c) => c.schemaName === 'new_status');assert.strictEqual(status.description, 'State shown to dispatchers.');@@ -651,8 +651,122 @@ test('readDashboards reconstructs supported tile shapes and skips unreadable das]);});-test('readDashboards omits a null dashboard description instead of emitting a blank string', async () => {+// A chart tile renders a visualization OVER a view. A deployed component that carries a ViewId but no+// VisualizationId therefore has nothing to plot, and emitting it anyway hands back a spec that fails+// its own lint ("id-based chart tile with viewId also needs visualizationId") — the exact #572 defect+// class this download path exists to prevent.+test('readDashboards omits a chart tile with no VisualizationId (and says so) rather than emitting a half-tile', async () => {+ const warnings = [];const sdk = {+ fetchArtifact: async () => ({ components: [+ { type: 'chart', name: 'Plotless', parameters: { TargetEntityType: 'account', ViewId: '{11111111-0000-4000-8000-000000000001}' } },+ { type: 'list', name: 'Open', parameters: { TargetEntityType: 'account', ViewId: '{33333333-0000-4000-8000-000000000003}' } },+ ] }),+ queryRecords: async () => [{ name: 'Operations', description: null }],+ };+ const dashboards = await readDashboards(sdk, {+ siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: 'dash-1', title: 'Operations' }] }] }] },+ }, (m) => warnings.push(m));++ assert.deepStrictEqual(dashboards[0].tiles, [+ { type: 'list', name: 'Open', entity: 'account', viewId: '33333333-0000-4000-8000-000000000003' },+ ], 'the plotless chart tile must not be emitted');+ assert.ok(warnings.some((w) => /VisualizationId/.test(w)), `the omission must be reported; got ${JSON.stringify(warnings)}`);+});++// `entity` is required by BOTH spec gates for any id-passthrough tile, so a component with no+// TargetEntityType produces `entity: undefined` — which JSON drops — and the downloaded spec then+// fails its own lint. Same class as the missing-VisualizationId case above.+test('readDashboards omits an id-passthrough tile with no TargetEntityType (and says so)', async () => {+ const warnings = [];+ const sdk = {+ fetchArtifact: async () => ({ components: [+ { type: 'chart', name: 'NoEntity', parameters: { ViewId: '{11111111-0000-4000-8000-000000000001}', VisualizationId: '{22222222-0000-4000-8000-000000000002}' } },+ { type: 'list', name: 'AlsoNoEntity', parameters: { ViewId: '{33333333-0000-4000-8000-000000000003}' } },+ { type: 'list', name: 'Good', parameters: { TargetEntityType: 'account', ViewId: '{44444444-0000-4000-8000-000000000004}' } },+ ] }),+ queryRecords: async () => [{ name: 'Operations', description: null }],+ };+ const dashboards = await readDashboards(sdk, {+ siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: 'dash-1', title: 'Operations' }] }] }] },+ }, (m) => warnings.push(m));++ assert.deepStrictEqual(dashboards[0].tiles, [+ { type: 'list', name: 'Good', entity: 'account', viewId: '44444444-0000-4000-8000-000000000004' },+ ], 'only the tile carrying an entity may be emitted');+ assert.strictEqual(warnings.filter((w) => /TargetEntityType/.test(w)).length, 2, `both omissions must be reported; got ${JSON.stringify(warnings)}`);+});++// The silent-drop hole the two tests above did NOT cover. `chart`/`list` used to be matched with an+// `&& viewId` guard, so a component of a supported type carrying no ViewId matched no branch at all+// and vanished with nothing said — and the dashboard-level "no recognizable tiles" warning cannot+// catch it, because that only fires when EVERY tile fails. Same untraceability as #572, reached from+// the one direction the omission warnings missed.+test('readDashboards reports a supported tile dropped for a missing ViewId instead of dropping it silently', async () => {+ const warnings = [];+ const sdk = {+ fetchArtifact: async () => ({ components: [+ { type: 'chart', name: 'NoView', parameters: { TargetEntityType: 'account', VisualizationId: '{22222222-0000-4000-8000-000000000002}' } },+ { type: 'list', name: 'AlsoNoView', parameters: { TargetEntityType: 'account' } },+ { type: 'list', name: 'Good', parameters: { TargetEntityType: 'account', ViewId: '{44444444-0000-4000-8000-000000000004}' } },+ ] }),+ queryRecords: async () => [{ name: 'Operations', description: null }],+ };+ const dashboards = await readDashboards(sdk, {+ siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: 'dash-1', title: 'Operations' }] }] }] },+ }, (m) => warnings.push(m));++ assert.deepStrictEqual(dashboards[0].tiles, [+ { type: 'list', name: 'Good', entity: 'account', viewId: '44444444-0000-4000-8000-000000000004' },+ ], 'only the tile carrying a ViewId may be emitted');+ assert.ok(/NoView/.test(warnings.join('\n')) && /AlsoNoView/.test(warnings.join('\n')),+ `both ViewId-less tiles must be named; got ${JSON.stringify(warnings)}`);+ assert.strictEqual(warnings.filter((w) => /ViewId/.test(w)).length, 2, `both omissions must cite ViewId; got ${JSON.stringify(warnings)}`);+});++// A component missing SEVERAL required parameters must say so once, naming each — reporting only the+// first would send a maker back for a second round trip to discover the rest.+test('readDashboards names every missing parameter on one tile in a single warning', async () => {+ const warnings = [];+ const sdk = {+ fetchArtifact: async () => ({ components: [{ type: 'chart', name: 'Empty', parameters: {} }] }),+ queryRecords: async () => [{ name: 'Operations', description: null }],+ };+ await readDashboards(sdk, {+ siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: 'dash-1', title: 'Operations' }] }] }] },+ }, (m) => warnings.push(m));++ const tileWarning = warnings.find((w) => /Empty/.test(w));+ assert.ok(tileWarning, `the tile omission must be reported; got ${JSON.stringify(warnings)}`);+ for (const param of ['TargetEntityType', 'ViewId', 'VisualizationId']) {+ assert.ok(tileWarning.includes(param), `'${param}' must be named in "${tileWarning}"`);+ }+});++// An unsupported component type is a silent drop too, for the same reason: a dashboard with one good+// tile never reaches the dashboard-level catch-all.+test('readDashboards reports a tile type the App Spec cannot express', async () => {+ const warnings = [];+ const sdk = {+ fetchArtifact: async () => ({ components: [+ { type: 'organizationinsights', name: 'Insights', parameters: {} },+ { type: 'iframe', name: 'NoUrl', parameters: {} },+ { type: 'list', name: 'Good', parameters: { TargetEntityType: 'account', ViewId: '{44444444-0000-4000-8000-000000000004}' } },+ ] }),+ queryRecords: async () => [{ name: 'Operations', description: null }],+ };+ const dashboards = await readDashboards(sdk, {+ siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: 'dash-1', title: 'Operations' }] }] }] },+ }, (m) => warnings.push(m));++ assert.strictEqual(dashboards[0].tiles.length, 1, 'only the rebuildable tile may be emitted');+ assert.ok(warnings.some((w) => /Insights/.test(w) && /organizationinsights/.test(w)),+ `the unsupported type must be named; got ${JSON.stringify(warnings)}`);+ assert.ok(warnings.some((w) => /NoUrl/.test(w) && /Url/.test(w)),+ `the iframe missing its Url must be reported; got ${JSON.stringify(warnings)}`);+});++test('readDashboards omits a null dashboard description instead of emitting a blank string', async () => { const sdk = {fetchArtifact: async () => ({ components: [{ type: 'iframe', name: 'Portal', parameters: { Url: 'https://contoso.example' } }] }),queryRecords: async (_set, opts) => {assert.ok(opts.select.includes('description'), 'dashboard name lookup also requests description');@@ -2209,4 +2323,174 @@ test('REVIEW-B cast membership still keeps a column when the ATTRIBUTE read alsoconst e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_t'), 'pp_t');assert.ok(e.columns.find((c) => c.schemaName === 'pp_tags'), 'cast membership must keep the column when nothing else can');assert.deepStrictEqual(untypedColumnNames([e]), ['pp_t.pp_tags']);-});\ No newline at end of file+});++test('#574 a POLYMORPHIC lookup shadow is filtered out via AttributeOf, even though IsLogical is false', async () => {+ // LIVE-MEASURED on a Customer-type lookup `cfo_billto` targeting account + contact. Dataverse+ // creates THREE shadows for it, and unlike a single-target lookup they are physically stored:+ // cfo_billtoname AttributeOf=cfo_billto IsLogical=FALSE AttributeType=String+ // cfo_billtoyominame AttributeOf=cfo_billto IsLogical=FALSE AttributeType=String+ // cfo_billtoidtype AttributeOf=cfo_billto IsLogical=FALSE AttributeType=EntityName+ // vs a single-target lookup, whose shadow IS logical:+ // cfo_customeridname AttributeOf=cfo_customerid IsLogical=TRUE+ // So the IsLogical rule cannot see the polymorphic ones: they were emitted as real Text columns+ // and a fresh-environment rebuild invented two text fields where a lookup used to be.+ const e = entityFromMetadata({+ schemaName: 'cfo_workorder', displayName: 'Work Order', primaryNameAttribute: 'cfo_name',+ attributes: [+ { logicalName: 'cfo_name', attributeType: 'String', IsCustomAttribute: true },+ { logicalName: 'cfo_intakeref', attributeType: 'String', IsCustomAttribute: true },+ { logicalName: 'cfo_billtoname', attributeType: 'String', IsCustomAttribute: true, IsLogical: false, AttributeOf: 'cfo_billto' },+ { logicalName: 'cfo_billtoyominame', attributeType: 'String', IsCustomAttribute: true, IsLogical: false, AttributeOf: 'cfo_billto' },+ { logicalName: 'cfo_customeridname', attributeType: 'String', IsCustomAttribute: true, IsLogical: true, AttributeOf: 'cfo_customerid' },+ ],+ }, 'cfo_workorder');+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['cfo_intakeref'],+ `only the authored column survives; got ${JSON.stringify(e.columns.map((c) => c.schemaName))}`);+});++test('#574 a REAL column is never dropped by the AttributeOf rule (AttributeOf is null on authored columns)', async () => {+ // The lookup itself, and every ordinary column, report AttributeOf: null -- so nothing authored+ // is at risk. Guards the rule against becoming a silent column deletion.+ const e = entityFromMetadata({+ schemaName: 'cfo_workorder', displayName: 'Work Order', primaryNameAttribute: 'cfo_name',+ attributes: [+ { logicalName: 'cfo_intakeref', attributeType: 'String', IsCustomAttribute: true, AttributeOf: null },+ { logicalName: 'cfo_resolution', attributeType: 'Memo', IsCustomAttribute: true, AttributeOf: null },+ { logicalName: 'cfo_onsiteduration', attributeType: 'Integer', IsCustomAttribute: true },+ ],+ }, 'cfo_workorder');+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['cfo_intakeref', 'cfo_resolution', 'cfo_onsiteduration']);+});++test('#574 an attribute whose AttributeOf could not be read is KEPT, not dropped', async () => {+ // When the label read fails NO attribute carries AttributeOf. Dropping on absent would empty the+ // table\u0027s columns[] entirely -- the same direction every other rule here takes: "we could not+ // look" must never become a deletion.+ const e = entityFromMetadata({+ schemaName: 'cfo_workorder', displayName: 'Work Order', primaryNameAttribute: 'cfo_name',+ attributes: [{ logicalName: 'cfo_intakeref', attributeType: 'String', IsCustomAttribute: true }],+ }, 'cfo_workorder');+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['cfo_intakeref']);+});++test('#574 AttributeOf survives the description merge, so the shadow is dropped through the REAL read path', async () => {+ // The unit tests above hand AttributeOf straight to entityFromMetadata. This one drives the+ // integration seam: the SDK metadata has NO AttributeOf (it is not in its projection), so the+ // value only reaches the filter if readEntityWithDescriptions merges it off the label read.+ // Dropping that one field from the merge silently re-enables the leak.+ const sdk = {+ fetchEntityMetadata: async (logical) => ({+ logicalName: logical, schemaName: 'cfo_workorder', displayName: 'Work Order', primaryNameAttribute: 'cfo_name',+ attributes: [+ { logicalName: 'cfo_intakeref', attributeType: 'String', IsCustomAttribute: true },+ { logicalName: 'cfo_billtoname', attributeType: 'String', IsCustomAttribute: true },+ { logicalName: 'cfo_billtoyominame', attributeType: 'String', IsCustomAttribute: true },+ ],+ }),+ queryRecords: async (set) => { throw new Error(`queryRecords must not be used for metadata paths (got \u0027${set}\u0027)`); },+ dataverse: {+ get: async (url) => {+ if (/\/Attributes\?/.test(url)) {+ // Exactly the live shape: polymorphic shadows are NOT logical, so only AttributeOf marks them.+ return { status: 200, headers: {}, body: { value: [+ { LogicalName: 'cfo_intakeref', IsLogical: false, AttributeOf: null },+ { LogicalName: 'cfo_billtoname', IsLogical: false, AttributeOf: 'cfo_billto' },+ { LogicalName: 'cfo_billtoyominame', IsLogical: false, AttributeOf: 'cfo_billto' },+ ] } };+ }+ return { status: 200, headers: {}, body: {} };+ },+ },+ };+ const meta574 = await readEntityWithDescriptions(sdk, 'cfo_workorder');+ const e574 = entityFromMetadata(meta574, 'cfo_workorder');+ assert.deepStrictEqual(e574.columns.map((c) => c.schemaName), ['cfo_intakeref'],+ `the polymorphic shadows must not survive the real read path; got ${JSON.stringify(e574.columns.map((c) => c.schemaName))}`);+});++// A platform-generated companion that carries NO AttributeOf, is not logical, and reports+// IsCustomAttribute true slips past every rule above. `<money>_base` is the canonical case.+test('#574 follow-up: the base-currency twin is dropped via IsBaseCurrency, and the real Money column is kept', async () => {+ // LIVE-MEASURED on stock `opportunity`:+ // estimatedvalue IsBaseCurrency=false IsValidForCreate=true+ // estimatedvalue_base IsBaseCurrency=TRUE IsValidForCreate=false+ const e = entityFromMetadata({+ primaryNameAttribute: 'cfo_name',+ attributes: [+ { SchemaName: 'cfo_name', LogicalName: 'cfo_name', AttributeType: 'String', IsCustomAttribute: true, IsLogical: false, AttributeOf: null },+ { SchemaName: 'cfo_budget', LogicalName: 'cfo_budget', AttributeType: 'Money', IsCustomAttribute: true, IsLogical: false, AttributeOf: null },+ { SchemaName: 'cfo_budget_base', LogicalName: 'cfo_budget_base', AttributeType: 'Money', IsCustomAttribute: true, IsLogical: false, AttributeOf: null, IsBaseCurrency: true },+ ],+ }, 'cfo_rtproject');+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['cfo_budget'],+ `the base-currency twin must not be emitted as an authored column; got ${JSON.stringify(e.columns.map((c) => c.schemaName))}`);+});++// The capability flag is NOT a substitute for IsBaseCurrency. This spec deliberately supports+// authored columns with `isValidForCreate: false` (app-spec-schema.md), so filtering on it turns a+// round-trip into a DELETION of a legitimately read-only column. Live-measured counter-example:+// stock `opportunity.totalamount` has IsValidForCreate=false and IsBaseCurrency=false.+test('#574 follow-up: a real column that is merely NOT CREATABLE is kept, not mistaken for a generated twin', async () => {+ const e = entityFromMetadata({+ primaryNameAttribute: 'cfo_name',+ attributes: [+ { SchemaName: 'cfo_name', LogicalName: 'cfo_name', AttributeType: 'String', IsCustomAttribute: true },+ { SchemaName: 'cfo_rollup', LogicalName: 'cfo_rollup', AttributeType: 'Money', IsCustomAttribute: true, IsValidForCreate: false, IsBaseCurrency: false },+ ],+ }, 'cfo_rtproject');+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['cfo_rollup'],+ 'a read-only authored column must survive a download');+});++test('#574 follow-up: an attribute whose IsBaseCurrency could not be read is KEPT, not dropped', async () => {+ // Same fail-open direction as every other rule: when the Money cast read fails, no attribute+ // carries IsBaseCurrency, and "we could not look" must never become a column deletion.+ const e = entityFromMetadata({+ primaryNameAttribute: 'cfo_name',+ attributes: [+ { SchemaName: 'cfo_name', LogicalName: 'cfo_name', AttributeType: 'String', IsCustomAttribute: true },+ { SchemaName: 'cfo_budget', LogicalName: 'cfo_budget', AttributeType: 'Money', IsCustomAttribute: true },+ ],+ }, 'cfo_rtproject');+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['cfo_budget']);+});++test('#574 follow-up: IsBaseCurrency is read through the Money CAST and drops the twin on the REAL read path', async () => {+ // IsBaseCurrency lives on MoneyAttributeMetadata, not the base attribute type, so it needs its own+ // cast read. Dropping that read silently re-enables the leak.+ let castRequested = false;+ const sdk = {+ fetchEntityMetadata: async (logical) => ({+ logicalName: logical, schemaName: 'cfo_rtproject', displayName: 'RT Project', primaryNameAttribute: 'cfo_name',+ attributes: [+ { logicalName: 'cfo_budget', attributeType: 'Money', IsCustomAttribute: true },+ { logicalName: 'cfo_budget_base', attributeType: 'Money', IsCustomAttribute: true },+ ],+ }),+ queryRecords: async (set) => { throw new Error(`queryRecords must not be used for metadata paths (got \u0027${set}\u0027)`); },+ dataverse: {+ get: async (url) => {+ if (/MoneyAttributeMetadata/.test(url)) {+ castRequested = true;+ return { status: 200, headers: {}, body: { value: [+ { LogicalName: 'cfo_budget', IsBaseCurrency: false },+ { LogicalName: 'cfo_budget_base', IsBaseCurrency: true },+ ] } };+ }+ if (/\/Attributes\?/.test(url)) {+ return { status: 200, headers: {}, body: { value: [+ { LogicalName: 'cfo_budget', IsLogical: false, AttributeOf: null },+ { LogicalName: 'cfo_budget_base', IsLogical: false, AttributeOf: null },+ ] } };+ }+ return { status: 200, headers: {}, body: {} };+ },+ },+ };+ const meta = await readEntityWithDescriptions(sdk, 'cfo_rtproject');+ assert.ok(castRequested, 'the Money cast read must be issued');+ const e = entityFromMetadata(meta, 'cfo_rtproject');+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['cfo_budget'],+ `the base-currency twin must not survive the real read path; got ${JSON.stringify(e.columns.map((c) => c.schemaName))}`);+});diff --git a/plugins/model-apps/scripts/tests/download-relationships.test.js b/plugins/model-apps/scripts/tests/download-relationships.test.jsnew file mode 100644index 000000000..cb076d98a--- /dev/null+++ b/plugins/model-apps/scripts/tests/download-relationships.test.js@@ -0,0 +1,205 @@+'use strict';+// Relationship reconstruction on download (#567). The shapes asserted here were LIVE-MEASURED+// against a Dataverse organization; see the comment on `readRelationships` for the raw payloads.+const { test } = require('node:test');+const assert = require('node:assert');+const { readRelationships, relationshipsSkippedWarning } = require('../download-model-app.js');++const label = (s) => ({ LocalizedLabels: [{ Label: s, LanguageCode: 1033 }] });++// Routes the four metadata reads `readRelationships` performs. Anything not supplied answers with+// an empty collection, so a test only declares the reads it cares about.+function makeSdk({ m2o = {}, m2m = {}, lookups = {}, custom = {}, fail = {} } = {}) {+ const ofEntity = (p) => (p.match(/LogicalName='([^']+)'/) || [])[1];+ return {+ dataverse: {+ get: async (p) => {+ const e = ofEntity(p);+ if (fail[e] && (!fail.only || p.includes(fail.only))) throw new Error(fail[e]);+ if (/\/ManyToOneRelationships/.test(p)) return { status: 200, body: { value: m2o[e] || [] } };+ if (/\/ManyToManyRelationships/.test(p)) return { status: 200, body: { value: m2m[e] || [] } };+ if (/LookupAttributeMetadata/.test(p)) return { status: 200, body: { value: lookups[e] || [] } };+ if (/\?\$select=IsCustomEntity/.test(p)) return { status: 200, body: { IsCustomEntity: custom[e] !== false } };+ return { status: 404, body: null };+ },+ },+ };+}++const rel = (o) => ({ IsCustomRelationship: true, ...o });++test('reconstructs a 1:N between two app tables with the properly-cased lookup name (#567)', async () => {+ const sdk = makeSdk({+ m2o: { new_ticket: [rel({ SchemaName: 'new_customer_new_ticket', ReferencedEntity: 'new_customer', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_customerid' })] },+ lookups: { new_ticket: [{ LogicalName: 'new_customerid', SchemaName: 'new_CustomerId', DisplayName: label('Customer'), Targets: ['new_customer'] }] },+ });+ const { relationships, skipped } = await readRelationships(sdk, ['new_customer', 'new_ticket'], 'new');+ assert.deepStrictEqual(skipped, []);+ assert.deepStrictEqual(relationships, [{+ type: 'OneToMany',+ referenced: 'new_customer',+ referencing: 'new_ticket',+ // Cased as deployed — the SDK's own projection lowercases this to `new_customerid`.+ lookup: { schemaName: 'new_CustomerId', displayName: 'Customer' },+ }]);+});++test('drops platform relationships rather than declaring them as app relationships (#567)', async () => {+ // LIVE-MEASURED: a 3-table app carried 20 of 22 entries per table as platform plumbing.+ const sdk = makeSdk({+ m2o: {+ new_ticket: [+ { IsCustomRelationship: false, SchemaName: 'new_ticket_SyncErrors', ReferencedEntity: 'syncerror', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'regardingobjectid' },+ { IsCustomRelationship: false, SchemaName: 'new_ticket_AsyncOperations', ReferencedEntity: 'asyncoperation', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'regardingobjectid' },+ ],+ },+ });+ const { relationships, skipped } = await readRelationships(sdk, ['new_ticket'], 'new');+ assert.deepStrictEqual(relationships, []);+ assert.deepStrictEqual(skipped, []); // not app relationships at all, so nothing to report as lost+});++test('skips AND reports a polymorphic lookup, which relationships[] cannot express (#567)', async () => {+ // LIVE-MEASURED: `cfo_billto` targeting account+contact produced TWO relationships sharing ONE+ // ReferencingAttribute. Emitting both would declare the same lookup schema name twice.+ const sdk = makeSdk({+ m2o: {+ new_ticket: [+ rel({ SchemaName: 'new_new_ticket_account', ReferencedEntity: 'account', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_billto' }),+ rel({ SchemaName: 'new_new_ticket_contact', ReferencedEntity: 'contact', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_billto' }),+ ],+ },+ });+ const { relationships, skipped } = await readRelationships(sdk, ['new_ticket'], 'new');+ assert.deepStrictEqual(relationships, []);+ assert.strictEqual(skipped.length, 1);+ assert.match(skipped[0].reason, /polymorphic/i);+ assert.match(skipped[0].reason, /account, contact/);+});++test('keeps a bridge to a standard table but drops a custom parent outside the app (#567)', async () => {+ const sdk = makeSdk({+ m2o: {+ new_ticket: [+ rel({ SchemaName: 'new_systemuser_new_ticket', ReferencedEntity: 'systemuser', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_agentid' }),+ rel({ SchemaName: 'new_other_new_ticket', ReferencedEntity: 'new_other', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_otherid' }),+ ],+ },+ // A rebuild target always has systemuser; it would NOT have a custom table this app excludes.+ custom: { systemuser: false, new_other: true },+ });+ const { relationships, skipped } = await readRelationships(sdk, ['new_ticket'], 'new');+ assert.strictEqual(relationships.length, 1);+ assert.strictEqual(relationships[0].referenced, 'systemuser');+ assert.strictEqual(skipped.length, 1);+ assert.strictEqual(skipped[0].name, 'new_other_new_ticket');+ assert.match(skipped[0].reason, /custom table this app does not include/i);+});++test('emits an explicit schemaName only when it diverges from the generated default (#567)', async () => {+ const mk = (deployed) => makeSdk({+ m2o: { new_ticket: [rel({ SchemaName: deployed, ReferencedEntity: 'new_customer', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_customerid' })] },+ });+ // Matches `prefixedRelationshipName('new_customer','new_ticket','new')` — omitted, so the build+ // regenerates the same name.+ const same = await readRelationships(mk('new_customer_new_ticket'), ['new_customer', 'new_ticket'], 'new');+ assert.strictEqual(same.relationships[0].schemaName, undefined);+ // Divergent: must be carried, or a rebuild into THIS environment creates a second relationship+ // beside the existing one instead of matching it.+ const diff = await readRelationships(mk('new_CustomerTicketLink'), ['new_customer', 'new_ticket'], 'new');+ assert.strictEqual(diff.relationships[0].schemaName, 'new_CustomerTicketLink');+});++// An unreadable parent and a confirmed-custom parent are different facts. Collapsing them made a+// transient 403/503 report the confident (and possibly wrong) diagnosis "is a custom table this app+// does not include", sending the author to fix a modelling problem that may not exist.+test('an unreadable parent table is reported as undetermined, not as a confirmed custom table (#567)', async () => {+ const sdk = makeSdk({+ m2o: { new_ticket: [rel({ SchemaName: 'new_foo_new_ticket', ReferencedEntity: 'foo_parent', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_fooid' })] },+ });+ // Make the IsCustomEntity probe fail the way a throttled or forbidden metadata read does.+ const inner = sdk.dataverse.get;+ sdk.dataverse.get = async (url) => (/IsCustomEntity/.test(url) ? { status: 503, body: null } : inner(url));++ const { relationships, skipped } = await readRelationships(sdk, ['new_customer', 'new_ticket'], 'new');+ assert.strictEqual(relationships.length, 0, 'an undetermined parent is still not declared');+ assert.strictEqual(skipped.length, 1);+ assert.match(skipped[0].reason, /could not be read/i);+ assert.doesNotMatch(skipped[0].reason, /is a custom table/i, 'a read failure must not be stated as a fact about the table');+});++test('a divergent schemaName under a foreign prefix is reported as a RENAME, not as a loss (#567)', async () => {+ const sdk = makeSdk({+ m2o: { new_ticket: [rel({ SchemaName: 'zzz_LegacyLink', ReferencedEntity: 'new_customer', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_customerid' })] },+ });+ const warnings = [];+ const { relationships, skipped } = await readRelationships(sdk, ['new_customer', 'new_ticket'], 'new', (m) => warnings.push(m));+ assert.strictEqual(relationships.length, 1);+ assert.strictEqual(relationships[0].schemaName, undefined, 'a foreign-prefix name would fail the publisher-prefix lint');+ // It IS carried into the spec, just under the generated name — so reporting it as skipped made the+ // summary say it was "absent from the rebuildable spec", the opposite of what happens.+ assert.deepStrictEqual(skipped, [], 'an emitted relationship must not be counted as skipped');+ assert.ok(warnings.some((w) => /publisher prefix/i.test(w) && /generated name/i.test(w)), `the rename must still be reported; got ${JSON.stringify(warnings)}`);+});++test('reconstructs N:N only when both ends are in the app, and reports the rest (#567)', async () => {+ const sdk = makeSdk({+ m2m: {+ new_ticket: [+ rel({ SchemaName: 'new_ticket_new_tag', Entity1LogicalName: 'new_ticket', Entity2LogicalName: 'new_tag' }),+ rel({ SchemaName: 'new_ticket_new_absent', Entity1LogicalName: 'new_ticket', Entity2LogicalName: 'new_absent' }),+ ],+ },+ });+ const { relationships, skipped } = await readRelationships(sdk, ['new_ticket', 'new_tag'], 'new');+ assert.deepStrictEqual(relationships, [{ type: 'ManyToMany', entity1: 'new_ticket', entity2: 'new_tag' }]);+ assert.strictEqual(skipped.length, 1);+ assert.match(skipped[0].reason, /does not include both tables/i);+});++test('a relationship reachable from both ends is emitted exactly once (#567)', async () => {+ const r = rel({ SchemaName: 'new_customer_new_ticket', ReferencedEntity: 'new_customer', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_customerid' });+ const sdk = makeSdk({ m2o: { new_ticket: [r], new_customer: [r] } });+ const { relationships } = await readRelationships(sdk, ['new_customer', 'new_ticket'], 'new');+ assert.strictEqual(relationships.length, 1);+});++test('an N:N is emitted once even though it appears on BOTH tables metadata (#567)', async () => {+ // Dataverse reports a ManyToMany from each participating table, so without a cross-end dedupe the+ // same link is declared twice and the rebuild tries to create the intersect table a second time.+ const r = rel({ SchemaName: 'new_ticket_new_tag', Entity1LogicalName: 'new_ticket', Entity2LogicalName: 'new_tag' });+ const sdk = makeSdk({ m2m: { new_ticket: [r], new_tag: [r] } });+ const { relationships } = await readRelationships(sdk, ['new_ticket', 'new_tag'], 'new');+ assert.deepStrictEqual(relationships, [{ type: 'ManyToMany', entity1: 'new_ticket', entity2: 'new_tag' }]);+});++test('a failed relationship read is REPORTED, not silently read as "this table has none" (#567)', async () => {+ const sdk = makeSdk({ fail: { new_ticket: 'network down' } });+ const { relationships, skipped } = await readRelationships(sdk, ['new_ticket'], 'new');+ assert.deepStrictEqual(relationships, []);+ assert.ok(skipped.some((s) => /could not be read/i.test(s.reason)), JSON.stringify(skipped));+});++test('a non-2xx status is treated as a failure, not as an empty collection (#567)', async () => {+ // `dataverse.get` RESOLVES on a non-2xx rather than throwing, so a bare try/catch would turn a+ // 403 into "this table has no relationships" — the exact silent absence #567 was filed about.+ // Both the 1:N and the N:N read are asserted SEPARATELY and by name: asserting only that some+ // entry mentions "HTTP 403" passed even with one of the two status checks removed, because the+ // other read's failure satisfied it.+ const sdk = { dataverse: { get: async () => ({ status: 403, body: null }) } };+ const { relationships, skipped } = await readRelationships(sdk, ['new_ticket'], 'new');+ assert.deepStrictEqual(relationships, []);+ const byName = Object.fromEntries(skipped.map((s) => [s.name, s.reason]));+ assert.match(byName['(all)'] || '', /HTTP 403/, `1:N read not reported: ${JSON.stringify(skipped)}`);+ assert.match(byName['(many-to-many)'] || '', /HTTP 403/, `N:N read not reported: ${JSON.stringify(skipped)}`);+});++test('the skipped-relationship warning names each one and its reason (#567)', () => {+ assert.strictEqual(relationshipsSkippedWarning([]), '');+ const out = relationshipsSkippedWarning([{ name: 'new_a_new_b', entity: 'new_b', reason: 'because' }]);+ assert.match(out, /1 relationship\(s\) could not be expressed/);+ assert.match(out, /new_b: new_a_new_b — because/);+ // It must NOT repeat notRoundTrippedSummary's claim that everything omitted is recorded under+ // descriptionInventory — skipped relationships are not.+ assert.ok(!/descriptionInventory/.test(out));+});diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.jsindex e4cfaa515..1ac6a86c0 100644--- a/plugins/model-apps/scripts/tests/entity-provision.test.js+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js@@ -491,6 +491,15 @@ test('buildSeedGroup translates $parent.match into a lookup bind (parentIndex) aassert.strictEqual(group.records[0].body.$parent, undefined, 'sentinel stripped from body');assert.strictEqual(group.records[0].body['[email protected]'], undefined, 'no @odata.bind baked in (SDK forms it)');});++test('buildSeedGroup rejects unsupported _seedKey before it reaches the outbound body', () => {+ const spec = seedSpec();+ spec.sampleData.new_ticket[0]._seedKey = 'ticket-1';+ assert.throws(+ () => buildSeedGroup({ spec, e: spec.entities[1], records: spec.sampleData.new_ticket, statusReasonValues: {} }),+ /_seedKey[\s\S]*not supported[\s\S]*alternate key/,+ );+});test('#1 buildSeedGroup THROWS (not silently drops) when a $parent.match resolves to no parent row', () => {const spec = seedSpec();@@ -502,6 +511,19 @@ test('#1 buildSeedGroup THROWS (not silently drops) when a $parent.match resolve/found no 'new_customer' sample record|left unset/,);});++test('buildSeedGroup THROWS when a $parent.match resolves to more than one parent row', () => {+ const spec = seedSpec();+ spec.sampleData.new_customer = [+ { new_name: 'Same', new_tier: 'Free' },+ { new_name: 'Same', new_tier: 'Pro' },+ ];+ spec.sampleData.new_ticket[0].$parent.match = { new_name: 'Same' };+ assert.throws(+ () => buildSeedGroup({ spec, e: spec.entities[1], records: spec.sampleData.new_ticket, statusReasonValues: {} }),+ /parent match[\s\S]*matched 2 'new_customer' sample records[\s\S]*new_CustomerId/,+ );+});test('#1 buildSeedGroup THROWS when a declared $parent has no OneToMany relationship to the child', () => {const spec = seedSpec();@@ -539,6 +561,35 @@ test('buildSeedGroup prefers a single-column alternate key as matchOn over the pconst group = buildSeedGroup({ spec, e: spec.entities[0], records: spec.sampleData.new_customer, statusReasonValues: {} });assert.strictEqual(group.matchOn, 'new_code', 'alt-key column wins over primary name');});++test('buildSeedGroup rejects duplicate primary-name values when matchOn would fall back to name', () => {+ const spec = seedSpec();+ spec.sampleData.new_customer = [+ { new_name: 'Same', new_tier: 'Free' },+ { new_name: 'Same', new_tier: 'Pro' },+ ];+ assert.throws(+ () => buildSeedGroup({ spec, e: spec.entities[0], records: spec.sampleData.new_customer, statusReasonValues: {} }),+ /duplicate new_name value 'Same'[\s\S]*single-column alternate key/,+ );+});++// An alternate key is enforced-unique by Dataverse, but the SAMPLE ROWS are not checked by anything+// before they are sent — so duplicate key values resolve two authored records to the same row, the+// same wrong-row resolve the primary-name rule rejects. The rule must follow whichever column+// actually becomes matchOn.+test('buildSeedGroup rejects duplicate values in the single-column alternate key it selects as matchOn', () => {+ const spec = seedSpec();+ spec.entities[0].alternateKeys = [{ schemaName: 'new_codekey', columns: ['new_code'] }];+ spec.sampleData.new_customer = [+ { new_name: 'A', new_code: 'DUP', new_tier: 'Free' },+ { new_name: 'B', new_code: 'DUP', new_tier: 'Pro' },+ ];+ assert.throws(+ () => buildSeedGroup({ spec, e: spec.entities[0], records: spec.sampleData.new_customer, statusReasonValues: {} }),+ /duplicate new_code value 'DUP'/,+ );+});test('buildSeedGroup omits matchOn (no dedup) when the key value is empty in a record', () => {const spec = seedSpec();diff --git a/plugins/model-apps/scripts/tests/form-field-options.test.js b/plugins/model-apps/scripts/tests/form-field-options.test.jsindex 4c79602b9..214152465 100644--- a/plugins/model-apps/scripts/tests/form-field-options.test.js+++ b/plugins/model-apps/scripts/tests/form-field-options.test.js@@ -178,8 +178,19 @@ test('an inline entry OVERRIDES the form-level fieldOptions default for the same});test('normalizeFieldEntry lower-cases both name and anchor (every downstream compare is lower-case)', () => {- assert.deepStrictEqual(normalizeFieldEntry('New_Name'), { name: 'new_name', readOnly: false, hidden: false, after: undefined });- assert.deepStrictEqual(normalizeFieldEntry({ name: 'New_B', after: 'New_A' }), { name: 'new_b', readOnly: false, hidden: false, after: 'new_a' });+ assert.deepStrictEqual(normalizeFieldEntry('New_Name'), { name: 'new_name', readOnly: false, hidden: false, after: undefined, colspan: undefined, rowspan: undefined });+ assert.deepStrictEqual(normalizeFieldEntry({ name: 'New_B', after: 'New_A' }), { name: 'new_b', readOnly: false, hidden: false, after: 'new_a', colspan: undefined, rowspan: undefined });+});++test('normalizeFieldEntry keeps a span only when it exceeds the adapter default of 1', () => {+ // A colspan of 1 IS the default, so recording it would make the cell builder emit an explicit+ // attribute for every ordinary field and overwrite a span widened by hand in the designer.+ assert.strictEqual(normalizeFieldEntry({ name: 'a', colspan: 1 }).colspan, undefined);+ assert.strictEqual(normalizeFieldEntry({ name: 'a', colspan: 2 }).colspan, 2);+ assert.strictEqual(normalizeFieldEntry({ name: 'a', rowspan: 3 }).rowspan, 3);+ // Non-numeric and fractional values must not reach the serializer as-is.+ assert.strictEqual(normalizeFieldEntry({ name: 'a', colspan: 'wide' }).colspan, undefined);+ assert.strictEqual(normalizeFieldEntry({ name: 'a', colspan: 2.7 }).colspan, 2);});test('fieldOptionsMap ignores a non-object entry rather than throwing on a half-typed spec', () => {diff --git a/plugins/model-apps/scripts/tests/form-preview.test.js b/plugins/model-apps/scripts/tests/form-preview.test.jsindex 674f4dcd6..94dd46267 100644--- a/plugins/model-apps/scripts/tests/form-preview.test.js+++ b/plugins/model-apps/scripts/tests/form-preview.test.js@@ -88,3 +88,70 @@ test('renderFormWireframe shows multi-tab forms, truncates wide labels, and fallassert.match(w, /\[text area\]/, 'Memo columns keep their multiline widget hint');assert.match(w, /new_missinglookupid\s+\[lookup\]/, 'unknown fields are treated as relationship lookups');});++test('the wireframe shows a multi-column tab as columns, and a collapsed tab as collapsed', () => {+ const s = spec();+ s.forms = [{ entity: 'new_wo', name: 'WO', layout: 'explicit', tabs: [+ { name: 't1', label: 'Main', columns: [+ { width: '65%', sections: [{ name: 'a', label: 'Left', columns: 1, fields: ['new_status'] }] },+ { width: '35%', sections: [{ name: 'b', label: 'Right', columns: 1, fields: ['new_cost'] }] },+ ] },+ { name: 't2', label: 'Extra', expanded: false, sections: [{ name: 'c', label: 'More', columns: 1, fields: ['new_number'] }] },+ ] }];+ const out = renderFormWireframe(s, s.forms[0]);+ // The wireframe IS the approval gate: showing two form-columns stacked as one, or a collapsed+ // tab as open, promises a layout the build does not deploy.+ assert.match(out, /column 1 of 2.*65%/, `multi-column split not shown:\n${out}`);+ assert.match(out, /column 2 of 2.*35%/);+ assert.match(out, /Extra.*\(collapsed\)/, `collapsed state not shown:\n${out}`);+});++// The wireframe IS the layout approval gate, so anything it omits is something the user approves+// without seeing. Two states were invisible: a hidden tab when it is the ONLY tab (the banner was+// gated on tab count), and a section whose heading Dataverse will not render at all.+test('the wireframe shows a hidden single tab, and a showLabel:false section as having no heading', () => {+ const s = spec();+ s.forms = [{ entity: 'new_wo', name: 'WO', layout: 'explicit', tabs: [+ { name: 't1', label: 'Only', visible: false,+ sections: [{ name: 'a', label: 'Suppressed Heading', showLabel: false, columns: 1, fields: ['new_status'] }] },+ ] }];+ const out = renderFormWireframe(s, s.forms[0]);+ assert.match(out, /\(hidden\)/, `a hidden tab must be shown even as the only tab:\n${out}`);+ assert.ok(!/Suppressed Heading/.test(out), `a showLabel:false section must not promise a heading:\n${out}`);+ assert.match(out, /no heading/, 'and the preview should say so explicitly');+});++// The same hole as the hidden-single-tab case above, reached through the OTHER state flag: the+// banner was gated on `tabLabels.length > 1 || tab.visible === false`, so a lone COLLAPSED tab+// rendered no banner at all and previewed exactly like an ordinary open one — even though the+// comment above the line said collapsed state must be shown because this is the approval gate.+test('the wireframe shows a collapsed tab even when it is the only tab', () => {+ const s = spec();+ s.forms = [{ entity: 'new_wo', name: 'WO', layout: 'explicit', tabs: [+ { name: 't1', label: 'Only', expanded: false,+ sections: [{ name: 'a', label: 'Details', columns: 1, fields: ['new_status'] }] },+ ] }];+ const out = renderFormWireframe(s, s.forms[0]);+ assert.match(out, /\(collapsed\)/, `a collapsed tab must be shown even as the only tab:\n${out}`);+ assert.match(out, /▸/, 'and it must render with the collapsed marker, not the open one');+});++// The negative half of the rule: a lone tab in its DEFAULT state still gets no banner, so the+// common case stays uncluttered. Without this, "always show the banner" would pass the two tests+// above while making every single-tab wireframe noisier.+test('the wireframe still omits the banner for a single tab in its default state', () => {+ const s = spec();+ s.forms = [{ entity: 'new_wo', name: 'WO', layout: 'explicit', tabs: [+ { name: 't1', label: 'Only', sections: [{ name: 'a', label: 'Details', columns: 1, fields: ['new_status'] }] },+ ] }];+ const out = renderFormWireframe(s, s.forms[0]);+ assert.ok(!/▾ Only/.test(out), `an ordinary single tab needs no state banner:\n${out}`);+});++test('a single-column tab shows no column banner (the common case stays clean)', () => {+ const s = spec();+ s.forms = [{ entity: 'new_wo', name: 'WO', layout: 'explicit', tabs: [+ { name: 't1', label: 'Main', sections: [{ name: 'a', label: 'Only', columns: 1, fields: ['new_status'] }] },+ ] }];+ assert.doesNotMatch(renderFormWireframe(s, s.forms[0]), /column 1 of/);+});diff --git a/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js b/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.jsindex b85ecc1d3..c6793bf38 100644--- a/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js@@ -225,3 +225,79 @@ test('412 conflict: pushArtifact resolves to { success:false, error } (the signaassert.strictEqual(result.saved !== undefined ? result.saved : result.success, false, 'a 412 is signalled by a failed PushResult, NOT a thrown error');assert.ok(result.error, 'the conflict carries an error the engine reports');});++// ---------------------------------------------------------------------------+// TOPOLOGY primitives (#575). The engine converges an existing form onto an explicit layout by+// appending tabs/columns/sections, patching a section in place and moving cells between sections.+// sdk-build.test.js covers the ORCHESTRATION against a mock; these lock the four SDK behaviors+// that orchestration assumes, against the REAL bundle -- a mock proves only self-consistency.+// ---------------------------------------------------------------------------++const secIntent = (name, label, columns, cells) => ({ name, label, visible: true, showLabel: true, columns, rows: cells.length ? [{ cells }] : [] });+const fcell = (fn) => ({ control: { fieldName: fn, isRequired: false } });+const META3 = { new_customer: { new_name: 'String', new_tier: 'Picklist', new_note: 'Memo', new_amt: 'Money' } };++async function seedTwoSectionForm(sdk) {+ const art = sdk.createArtifact('form', { name: 'T', entityLogicalName: 'new_customer', formType: 'Main' });+ await sdk.addElement('form', art.id, '/tabs', { name: 'tab_general', label: 'General', expanded: true, visible: true,+ columns: [{ width: '100%', sections: [+ secIntent('section_general', 'General', 1, [fcell('new_name'), fcell('new_tier')]),+ secIntent('section_more', 'More', 1, []),+ ] }] });+ await sdk.removeElement('form', art.id, '/tabs/0');+ return art.id;+}++test('REAL BUNDLE topology: an existing form gains a tab and a section, and a section widens in place', async () => {+ const sdk = freshSdk(null, META3);+ const id = await seedTwoSectionForm(sdk);+ await sdk.addElement('form', id, '/tabs', { name: 'tab_audit', label: 'Audit', expanded: true, visible: true,+ columns: [{ width: '100%', sections: [secIntent('section_audit', 'Audit', 2, [])] }] });+ await sdk.addElement('form', id, '/tabs/0/columns/0/sections', secIntent('section_added', 'Added', 2, []));+ await sdk.updateElement('form', id, '/tabs/0/columns/0/sections/0', { columns: 2 });+ const form = await sdk.getArtifact('form', id);+ assert.deepStrictEqual((form.tabs || []).map((x) => x.name), ['tab_general', 'tab_audit'], 'the tab is appended, not replaced');+ const sections = form.tabs[0].columns[0].sections;+ assert.deepStrictEqual(sections.map((s) => s.name), ['section_general', 'section_more', 'section_added']);+ assert.strictEqual(sections[0].columns, 2, 'an EXISTING section is widened in place');+ assert.strictEqual((sections[0].rows || []).length, 1, 'and keeps its rows -- updateElement MERGES');+});++test('REAL BUNDLE topology: a field cell moves between sections and serializes under the new one', async () => {+ const cap = [];+ const sdk = freshSdk(cap, META3);+ const id = await seedTwoSectionForm(sdk);+ // section_more is deployed EMPTY, so a row must be seeded before a cell can move into it.+ await sdk.addElement('form', id, '/tabs/0/columns/0/sections/1/rows', { cells: [] });+ let form = await sdk.getArtifact('form', id);+ const from = ai.findFieldCellLocation(form, 'new_tier');+ assert.strictEqual(from.sectionPointer, '/tabs/0/columns/0/sections/0', 'precondition: it starts in section_general');+ await sdk.moveElement('form', id, from.cellPointer, '/tabs/0/columns/0/sections/1/rows/0/cells', { index: 0 });+ form = await sdk.getArtifact('form', id);+ assert.strictEqual(ai.findFieldCellLocation(form, 'new_tier').sectionPointer, '/tabs/0/columns/0/sections/1', 'it now lives in section_more');+ assert.strictEqual(ai.findFieldCellLocation(form, 'new_name').sectionPointer, '/tabs/0/columns/0/sections/0', 'and its neighbour did not follow it');+ const res = await sdk.pushArtifact('form', id);+ assert.notStrictEqual(res && res.success, false, 'the restructured form still pushes');+ const formxml = (cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml;+ const more = /<section[^>]*name="section_more"[\s\S]*?<\/section>/.exec(formxml);+ assert.ok(more && /datafieldname="new_tier"/.test(more[0]), 'new_tier serializes INSIDE section_more');+});++test('REAL BUNDLE layout: multi-column tabs and cell spans reach the serialized formxml', async () => {+ const cap = [];+ const sdk = freshSdk(cap, META3);+ const art = sdk.createArtifact('form', { name: 'W', entityLogicalName: 'new_customer', formType: 'Main' });+ await sdk.addElement('form', art.id, '/tabs', { name: 'tab_w', label: 'W', expanded: true, visible: true, columns: [+ { width: '60%', sections: [secIntent('sec_l', 'L', 2, [Object.assign(fcell('new_name'), { colspan: 2 }), fcell('new_tier')])] },+ { width: '40%', sections: [secIntent('sec_r', 'R', 1, [Object.assign(fcell('new_note'), { rowspan: 2 })])] },+ ] });+ await sdk.removeElement('form', art.id, '/tabs/0');+ await sdk.pushArtifact('form', art.id);+ const formxml = (cap.find((c) => /systemforms/.test(c.url)) || {}).body.formxml;+ assert.ok(/<column width="60%">/.test(formxml) && /<column width="40%">/.test(formxml), 'both form-columns carry their authored width');+ // The SDK encodes an N-column section as N repeated "1"s, so columns:2 serializes as columns="11".+ assert.ok(/name="sec_l"[^>]*columns="11"/.test(formxml), 'a 2-column section serializes as columns="11"');+ const nameCell = /<cell[^>]*colspan="2"[^>]*>[\s\S]*?datafieldname="new_name"/.exec(formxml);+ assert.ok(nameCell, 'an authored colspan reaches the cell attribute');+ assert.ok(/<cell[^>]*rowspan="2"[^>]*>[\s\S]*?datafieldname="new_note"/.test(formxml), 'an authored rowspan reaches the cell attribute');+});diff --git a/plugins/model-apps/scripts/tests/hydrate-spec.test.js b/plugins/model-apps/scripts/tests/hydrate-spec.test.jsindex c522ea0af..0e4a49451 100644--- a/plugins/model-apps/scripts/tests/hydrate-spec.test.js+++ b/plugins/model-apps/scripts/tests/hydrate-spec.test.js@@ -41,6 +41,24 @@ function deployedRead() {};}+// "Nobody could look" and "we looked and there are none" are different facts, and collapsing both to+// `[]` meant the omit-the-key rule could not tell them apart. A reader that predates relationship+// reconstruction (#567) must not have an absence asserted on its behalf; a reader that really read+// zero relationships should record that.+test('hydrateSpec keeps "no relationships reader" apart from "a read that found none" (#567)', async () => {+ const noReader = await hydrateSpec(deployedRead());+ assert.ok(!('relationships' in noReader), 'with no reader the key must be OMITTED, not asserted empty');++ const readEmpty = await hydrateSpec({ ...deployedRead(), relationships: async () => [] });+ assert.deepStrictEqual(readEmpty.relationships, [], 'a real read proving none is a fact worth recording');++ const readSome = await hydrateSpec({+ ...deployedRead(),+ relationships: async () => [{ type: 'OneToMany', referenced: 'new_order', referencing: 'new_line', lookup: { schemaName: 'new_OrderId' } }],+ });+ assert.strictEqual(readSome.relationships.length, 1);+});+test('hydrateSpec reconstructs a valid, complete spec (entities + appShell + pages)', async () => {const spec = await hydrateSpec(deployedRead());const r = validateAppSpec(spec);diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex f8ed0761e..006e62f87 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js@@ -199,7 +199,11 @@ function mockSdk(opts = {}) {calls.push({ name: 'fetchArtifact', args: [t, id] });// Seed the store to mimic a fetched, deployed artifact so reconcile can read + mutate it.if (!store[`${t}:${id}`]) {- if (t === 'form') store[`${t}:${id}`] = seedForm(id, opts.existingFormFields || []);+ // `existingFormJson` overrides the single-tab default so a test can seed a deployed form+ // with real topology (several tabs/sections) — the shape a topology reconcile must converge+ // onto rather than flatten. Deep-cloned so a shared fixture object cannot leak mutations+ // from one build into the next.+ if (t === 'form') store[`${t}:${id}`] = opts.existingFormJson ? Object.assign(JSON.parse(JSON.stringify(opts.existingFormJson)), { id }) : seedForm(id, opts.existingFormFields || []);// `description` is seeded UNCONDITIONALLY (default '') because the real ViewAdapter always// emits `description: t.description ?? ''`. A view artifact with no `description` key is a// shape production never produces — and the real `updateElement` THROWS PathNotFoundError@@ -1658,6 +1662,374 @@ test('form reconcile: an AUTO layout is additive — a deployed field not in theassert.strictEqual(find(calls, 'removeElement').length, 0, 'auto layout never removes fields');});+// ---------------------------------------------------------------------------+// Explicit-layout TOPOLOGY reconcile (#575).+//+// The reconcile used to flatten an explicit layout: every field was appended to the first section+// of the first tab and no tab/section was ever created or reshaped — while declaring explicit tabs+// simultaneously switched PRUNING on. An author reorganizing a deployed form therefore got the old+// layout, minus the fields they had not re-declared, and a green build.+// ---------------------------------------------------------------------------++// A deployed form with real topology: two tabs, the first holding two sections.+function twoTabForm() {+ const cell = (fn) => ({ cells: [{ control: { fieldName: fn } }] });+ return { id: 'f1', tabs: [+ { id: 't0', name: 'tab_general', label: 'General', expanded: true, visible: true,+ columns: [{ width: '100%', sections: [+ { id: 's0', name: 'section_general', label: 'General', visible: true, showLabel: false, columns: 1, rows: [cell('new_name'), cell('new_tier')] },+ { id: 's1', name: 'section_more', label: 'More', visible: true, showLabel: true, columns: 1, rows: [cell('new_obsolete')] },+ ] }] },+ { id: 't1', name: 'tab_extra', label: 'Extra', expanded: true, visible: true,+ columns: [{ width: '100%', sections: [{ id: 's2', name: 'section_extra', label: 'Extra', visible: true, showLabel: true, columns: 1, rows: [] }] }] },+ ], bag: { a: [], c: [] } };+}++const explicitForm = (tabs) => [{ entity: 'new_customer', name: 'Customer', layout: 'explicit', tabs }];++test('form topology: a section the deployed form lacks is CREATED, not flattened into the first one', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', columns: 2, fields: ['new_name'] },+ { name: 'section_brandnew', label: 'Brand New', columns: 2, fields: ['new_tier'] },+ ] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const added = find(calls, 'addElement').filter((c) => /\/sections$/.test(String(c.args[2])));+ assert.strictEqual(added.length, 1, `exactly one section added; saw ${added.map((c) => c.args[2]).join(', ')}`);+ assert.strictEqual(added[0].args[3].name, 'section_brandnew');+ assert.deepStrictEqual(added[0].args[3].rows, [], 'a new section is created EMPTY — the field pass places controls, so a field already on the form is moved rather than duplicated');+});++// --- container identity: two wants must never converge on one live container -------------------++// `addSubgrids` appends a sub-grid host section to tabs[0].columns[0].sections on EVERY layout, so+// it sits in the same array as the author's own sections, just after them. The positional fallback+// has no notion of "this is not a field section", so the moment an explicit layout declares as many+// sections as the sub-grid's index, it claimed the sub-grid: relabelled it to the author's title and+// injected bound controls into the row holding the grid. The author's section was never created and+// the build was green — and because it converges on the same wrong shape, a rebuild and --verify+// both agree with it.+function formWithSubgrid() {+ const cell = (fn) => ({ cells: [{ control: { fieldName: fn } }] });+ return { id: 'f1', tabs: [+ { id: 't0', name: 'tab_general', label: 'General', expanded: true, visible: true,+ columns: [{ width: '100%', sections: [+ { id: 's0', name: 'section_general', label: 'General', visible: true, showLabel: false, columns: 1, rows: [cell('new_name')] },+ { id: 's1', name: 'section_grid_tickets', label: 'Tickets', visible: true, showLabel: true, columns: 1,+ rows: [{ cells: [{ control: { parameters: { RelationshipName: 'new_customer_new_ticket' } } }] }] },+ ] }] },+ ], bag: { a: [], c: [] } };+}++test('form topology: an engine-owned sub-grid section is not seized by the positional fallback', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', columns: 1, fields: ['new_name'] },+ { name: 'section_brandnew', label: 'Brand New', columns: 1, fields: ['new_tier'] },+ ] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: formWithSubgrid() });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });++ const added = find(calls, 'addElement').filter((c) => /\/sections$/.test(String(c.args[2])));+ assert.strictEqual(added.length, 1, `the author's section must be CREATED, not taken from the sub-grid; saw ${added.map((c) => c.args[2]).join(', ')}`);+ assert.strictEqual(added[0].args[3].name, 'section_brandnew');+ const relabelled = find(calls, 'updateElement').filter((c) => c.args[2] === '/tabs/0/columns/0/sections/1' && c.args[3] && c.args[3].label !== undefined);+ assert.deepStrictEqual(relabelled, [], 'the sub-grid section must keep its own label');+});++// The compiler substitutes a DEFAULT label for an unlabeled container — 'General' for a tab,+// 'Details' for a section (artifact-intent.js). So an author who labels nothing produces several+// wants carrying the same label, and a label pass with no memory of what an earlier want already+// took returns index 0 for every one of them.+test('form topology: two unlabeled sections do not collapse onto the same live section', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([{ sections: [+ { fields: ['new_name'] },+ { fields: ['new_tier'] },+ ] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });++ const added = find(calls, 'addElement').filter((c) => /\/sections$/.test(String(c.args[2])));+ assert.strictEqual(added.length, 1, 'the second unlabeled section must be created, not merged into the first');+ assert.strictEqual(added[0].args[3].name, 'section_0_1');+});++test('form topology: two unlabeled tabs do not collapse onto the same live tab', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([+ { sections: [{ fields: ['new_name'] }] },+ { sections: [{ fields: ['new_tier'] }] },+ ]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });++ const addedTabs = find(calls, 'addElement').filter((c) => c.args[2] === '/tabs');+ assert.strictEqual(addedTabs.length, 1, 'the second unlabeled tab must be created, not merged into the first');+ assert.strictEqual(addedTabs[0].args[3].name, 'tab_1');+});++// The field pass places only BOUND fields. A notes/timeline section holds one non-field control, so+// creating it with `rows: []` like an ordinary section deployed a visible "Notes" header promising a+// timeline that nothing ever adds — and the build was green.+// A form-wide NAME hit resolves a section that may sit anywhere on the form. If its index is not+// claimed, a LATER want in the same column can match that very section by label or position, so two+// authored sections converge on one and fields are routed to the wrong target.+test('form topology: a section matched globally by name claims its index, so a later section cannot reuse it', async () => {+ const spec = makeSpec();+ // Two sections: the first names the deployed section explicitly (a form-wide name hit), the second+ // is unlabeled/unnamed and would otherwise fall through to the same index positionally.+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'Details', columns: 1, fields: ['new_name'] },+ { columns: 1, fields: ['new_tier'] },+ ] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });++ const added = find(calls, 'addElement').filter((c) => /\/sections$/.test(String(c.args[2])));+ assert.strictEqual(added.length, 1, `the second section must be CREATED, not resolved onto the globally named one; saw ${added.map((c) => JSON.stringify(c.args[3] && c.args[3].name)).join(', ')}`);+});++test('form topology: a created notes section keeps its timeline row instead of deploying empty', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', columns: 1, fields: ['new_name'] },+ ] }]);+ spec.forms[0].notes = true;+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });++ const notes = find(calls, 'addElement').filter((c) => /\/sections$/.test(String(c.args[2])) && c.args[3] && c.args[3].name === 'section_notes');+ assert.strictEqual(notes.length, 1, 'the notes section must be created');+ assert.ok((notes[0].args[3].rows || []).length >= 1, 'the notes section must carry its timeline row, not be created empty');+});++// The clamp has to reach the emitted cell. Packing a `colspan: 4` cell as width 2 while still+// serializing colspan="4" produces the overrunning cell the clamp exists to prevent, and contradicts+// the documented behaviour ("a cell wider than its section is clamped to it").+test('form topology: a colspan wider than the section is clamped in the EMITTED cell, not just in row packing', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', columns: 2, fields: [{ name: 'new_name', colspan: 4 }, 'new_tier'] },+ ] }]);+ const intent = compileFormIntent(spec, spec.forms[0], {});+ const rows = intent.tabs[0].columns[0].sections[0].rows;+ assert.strictEqual(rows[0].cells[0].colspan, 2, `a colspan of 4 in a 2-column section must serialize as 2; got ${JSON.stringify(rows)}`);+});++// `colspan`/`rowspan` used to be create-only on an existing form: an author who widened a field on a+// deployed form got a green build and an unchanged cell.+test('form topology: an authored colspan converges on a field already in the right section', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', columns: 2, fields: [{ name: 'new_name', colspan: 2 }, 'new_tier'] },+ ] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const spanPatch = find(calls, 'updateElement').filter((c) => /\/cells\/\d+$/.test(String(c.args[2])) && c.args[3] && c.args[3].colspan === 2);+ assert.strictEqual(spanPatch.length, 1, `the authored colspan must be written to the deployed cell; saw ${JSON.stringify(find(calls, 'updateElement').map((c) => [c.args[2], c.args[3]]))}`);+});++// A span the author did NOT declare must never be written, or a rebuild would flatten a cell a maker+// widened by hand — the same rule that keeps `isReadOnly: false` from ever being sent.+test('form topology: a field with no authored span leaves the deployed cell alone', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', columns: 2, fields: ['new_name', 'new_tier'] },+ ] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const spanPatch = find(calls, 'updateElement').filter((c) => c.args[3] && (c.args[3].colspan !== undefined || c.args[3].rowspan !== undefined));+ assert.deepStrictEqual(spanPatch, [], 'no span may be written when the author declared none');+});++// A build that could not set `isdefault` must not report a default form it did not set.+test('default form: a failed promotion is not recorded in result.created.defaultForms', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', formType: 'Main', layout: 'auto' }];+ const { sdk } = mockSdk({ artifactsExist: false });+ const original = sdk.updateRecord;+ sdk.updateRecord = async (entity, id, data) => {+ if (entity === 'systemform' && data && data.isdefault === true) throw new Error('privilege denied');+ return original(entity, id, data);+ };+ const warnings = [];+ const result = await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], warn: (m) => warnings.push(m) });+ assert.deepStrictEqual(result.created.defaultForms, undefined, 'a failed promotion must not be reported as a set default form');+ assert.ok(warnings.some((w) => /could not make form the default/i.test(w)), `the failure must be warned; got ${JSON.stringify(warnings)}`);+});++test('form topology: a section column count is converged on an EXISTING section (1 -> 2 columns)', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', columns: 2, fields: ['new_name', 'new_tier'] },+ ] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: twoTabForm() });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const patch = find(calls, 'updateElement').find((c) => String(c.args[2]) === '/tabs/0/columns/0/sections/0');+ assert.ok(patch, `no section patch issued; updateElement pointers: ${find(calls, 'updateElement').map((c) => c.args[2]).join(', ')}`);+ assert.strictEqual(patch.args[3].columns, 2, 'the section is widened to two columns in place');+});++test('form topology: a field is added to its DECLARED section, not the first section', async () => {+ const spec = makeSpec();+ // new_extra is absent from the deployed form and declared in the SECOND tab's section.+ spec.entities[0].columns.push({ schemaName: 'new_extra', displayName: 'Extra', type: 'Text' });+ spec.forms = explicitForm([+ { name: 'tab_general', label: 'General', sections: [{ name: 'section_general', label: 'General', columns: 1, fields: ['new_name', 'new_tier'] }] },+ { name: 'tab_extra', label: 'Extra', sections: [{ name: 'section_extra', label: 'Extra', columns: 1, fields: ['new_extra'] }] },+ ]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: twoTabForm() });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const rowAdds = find(calls, 'addElement').filter((c) => /\/rows$/.test(String(c.args[2])));+ const extra = rowAdds.find((c) => ((c.args[3].cells || [])[0] || {}).control && c.args[3].cells[0].control.fieldName === 'new_extra');+ assert.ok(extra, `new_extra was never added; row adds: ${rowAdds.map((c) => c.args[2]).join(', ')}`);+ assert.strictEqual(extra.args[2], '/tabs/1/columns/0/sections/0/rows', 'lands in tab_extra/section_extra, NOT /tabs/0/columns/0/sections/0/rows');+});++test('form topology: a field sitting in the wrong section is MOVED, never duplicated', async () => {+ const spec = makeSpec();+ // new_tier is deployed in section_general but the spec now declares it in section_more.+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', columns: 1, fields: ['new_name'] },+ { name: 'section_more', label: 'More', columns: 1, fields: ['new_tier'] },+ ] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: twoTabForm() });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const moves = find(calls, 'moveElement');+ assert.strictEqual(moves.length, 1, `exactly one move; saw ${moves.map((c) => `${c.args[2]} -> ${c.args[3]}`).join(', ')}`);+ assert.strictEqual(moves[0].args[3], '/tabs/0/columns/0/sections/1/rows/0/cells', 'moved INTO section_more');+ const dupAdds = find(calls, 'addElement').filter((c) => /\/rows$/.test(String(c.args[2])) && ((c.args[3].cells || [])[0] || {}).control && c.args[3].cells[0].control.fieldName === 'new_tier');+ assert.strictEqual(dupAdds.length, 0, 'a relocated field must never be re-added as a second control');+});++test('form topology: an auto->explicit migration converges onto the deployed tab instead of appending a duplicate', async () => {+ // THE regression this guards: the auto layout emits `tab_general`/`section_general`, but an+ // explicit layout with no authored names emits `tab_0`/`section_0_0`. Matching on name alone+ // appended a second tab to every form this plugin had already built, on every rebuild.+ const spec = makeSpec();+ spec.forms = explicitForm([{ label: 'General', sections: [{ label: 'Details', columns: 2, fields: ['new_name', 'new_tier'] }] }]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const tabAdds = find(calls, 'addElement').filter((c) => String(c.args[2]) === '/tabs');+ assert.strictEqual(tabAdds.length, 0, `no tab may be appended to an existing form here; saw ${tabAdds.length}`);+ const secAdds = find(calls, 'addElement').filter((c) => /\/sections$/.test(String(c.args[2])));+ assert.strictEqual(secAdds.length, 0, 'the deployed section is matched positionally, not duplicated');+ const patch = find(calls, 'updateElement').find((c) => String(c.args[2]) === '/tabs/0/columns/0/sections/0');+ assert.strictEqual(patch && patch.args[3].columns, 2, 'and it is still widened to two columns');+});++test('form topology: a rebuild that changes nothing issues no topology writes (idempotent)', async () => {+ const spec = makeSpec();+ // Declare EXACTLY what twoTabForm already deploys, so every container already matches.+ spec.forms = explicitForm([+ { name: 'tab_general', label: 'General', sections: [+ { name: 'section_general', label: 'General', showLabel: false, columns: 1, fields: ['new_name', 'new_tier'] },+ ] },+ ]);+ spec.forms[0].prune = false; // isolate the topology pass from the pruning pass+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: twoTabForm() });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ assert.strictEqual(find(calls, 'addElement').filter((c) => /\/(tabs|sections|rows)$/.test(String(c.args[2]))).length, 0, 'nothing is created');+ assert.strictEqual(find(calls, 'moveElement').length, 0, 'nothing is moved');+ const structural = find(calls, 'updateElement').filter((c) => /\/(tabs\/\d+|sections\/\d+)$/.test(String(c.args[2])));+ assert.deepStrictEqual(structural.map((c) => c.args[2]), [], 'and no container is patched');+});++test('form topology: an AUTO layout never reshapes a deployed form', async () => {+ // makeSpec's form is layout:auto. Auto has one section and no authored structure to honor, so a+ // form a maker reorganized by hand must come back untouched.+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: twoTabForm() });+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ // Sub-grids are excluded deliberately: `addSubgrids` gives each related list its own full-width+ // section on EVERY layout, auto included. That is a separate, pre-existing mechanism — the claim+ // under test is that auto never reshapes the FIELD topology.+ const isSubgridSection = (el) => (((el || {}).rows || [])[0] || {}).cells &&+ el.rows[0].cells.some((c) => c.control && c.control.parameters && c.control.parameters.RelationshipName);+ const containerAdds = find(calls, 'addElement')+ .filter((c) => /\/(tabs|sections)$/.test(String(c.args[2])))+ .filter((c) => !isSubgridSection(c.args[3]));+ assert.strictEqual(containerAdds.length, 0, `auto creates no field containers; saw ${JSON.stringify(containerAdds.map((c) => ({ ptr: c.args[2], name: c.args[3] && c.args[3].name })))}`);+ assert.strictEqual(find(calls, 'moveElement').length, 0, 'auto moves no fields between sections');+});++test('form topology: a tab the deployed form lacks is CREATED with empty sections', async () => {+ const spec = makeSpec();+ spec.entities[0].columns.push({ schemaName: 'new_extra', displayName: 'Extra', type: 'Text' });+ spec.forms = explicitForm([+ { name: 'tab_general', label: 'General', sections: [{ name: 'section_general', label: 'General', columns: 1, fields: ['new_name', 'new_tier'] }] },+ { name: 'tab_audit', label: 'Audit', sections: [{ name: 'section_audit', label: 'Audit', columns: 1, fields: ['new_extra'] }] },+ ]);+ // The deployed form has ONE tab, so the second has no name, label or position to match.+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const tabAdds = find(calls, 'addElement').filter((c) => String(c.args[2]) === '/tabs');+ assert.strictEqual(tabAdds.length, 1, `exactly one tab added; saw ${tabAdds.length}`);+ assert.strictEqual(tabAdds[0].args[3].name, 'tab_audit');+ assert.deepStrictEqual(tabAdds[0].args[3].columns[0].sections[0].rows, [], 'its sections arrive EMPTY so the field pass owns every control');+ // And the field it declares still lands inside the new tab rather than back in the first section.+ const extra = find(calls, 'addElement').find((c) => /\/rows$/.test(String(c.args[2])) && (((c.args[3] || {}).cells || [])[0] || {}).control && c.args[3].cells[0].control.fieldName === 'new_extra');+ assert.ok(extra && extra.args[2].startsWith('/tabs/1/'), `new_extra should land in the new tab, landed at ${extra && extra.args[2]}`);+});++test('form topology: a tab that gains a second form-column has the column ADDED (multi-column layout)', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit', tabs: [{+ name: 'tab_general', label: 'General',+ columns: [+ { width: '60%', sections: [{ name: 'section_general', label: 'General', columns: 1, fields: ['new_name'] }] },+ { width: '40%', sections: [{ name: 'section_side', label: 'Side', columns: 1, fields: ['new_tier'] }] },+ ],+ }] }];+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormFields: ['new_name', 'new_tier'] });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const colAdds = find(calls, 'addElement').filter((c) => /\/columns$/.test(String(c.args[2])));+ assert.strictEqual(colAdds.length, 1, `exactly one form-column added; saw ${colAdds.map((c) => c.args[2]).join(', ')}`);+ assert.strictEqual(colAdds[0].args[2], '/tabs/0/columns');+ assert.strictEqual(colAdds[0].args[3].width, '40%', 'the authored width is carried onto the new column');+ assert.deepStrictEqual(colAdds[0].args[3].sections[0].rows, [], 'and its sections arrive empty');+});++test('form topology: a field moving into an EMPTY section gets a row seeded for it first', async () => {+ const spec = makeSpec();+ // twoTabForm's section_extra is deployed with rows: [] — there is nothing to move a cell into.+ spec.forms = explicitForm([+ { name: 'tab_general', label: 'General', sections: [{ name: 'section_general', label: 'General', columns: 1, fields: ['new_name'] }] },+ { name: 'tab_extra', label: 'Extra', sections: [{ name: 'section_extra', label: 'Extra', columns: 1, fields: ['new_tier'] }] },+ ]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: twoTabForm() });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ const seeded = find(calls, 'addElement').find((c) => String(c.args[2]) === '/tabs/1/columns/0/sections/0/rows' && Array.isArray(c.args[3].cells) && c.args[3].cells.length === 0);+ assert.ok(seeded, `an empty row must be seeded in the empty target section; row adds: ${find(calls, 'addElement').filter((c) => /\/rows$/.test(String(c.args[2]))).map((c) => c.args[2]).join(', ')}`);+ const moves = find(calls, 'moveElement');+ assert.strictEqual(moves.length, 1, 'and the field is then moved into it');+ assert.strictEqual(moves[0].args[3], '/tabs/1/columns/0/sections/0/rows/0/cells');+});++test('form topology: a tab renamed in the spec is matched by LABEL, not by position', async () => {+ const spec = makeSpec();+ // Deployed: tab0 = tab_general/"General", tab1 = tab_extra/"Extra".+ // The spec's ONLY tab carries an unknown name but the label of the SECOND tab, so a name match+ // misses and a positional match would wrongly seize tab 0.+ spec.forms = explicitForm([{ name: 'tab_renamed', label: 'Extra', sections: [+ { name: 'section_extra', label: 'Extra Details', columns: 1, fields: ['new_name'] },+ ] }]);+ spec.forms[0].prune = false;+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: twoTabForm() });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });+ assert.strictEqual(find(calls, 'addElement').filter((c) => String(c.args[2]) === '/tabs').length, 0, 'a label hit must not create a second tab');+ // The decisive assertion: sections are matched by name across the WHOLE form, so section_extra+ // resolves under tab 1 no matter which tab matched. Only the TAB patch distinguishes a label hit+ // from a positional one — a positional match would seize tab 0 and relabel "General" to "Extra".+ const tabZeroPatch = find(calls, 'updateElement').find((c) => String(c.args[2]) === '/tabs/0');+ assert.ok(!tabZeroPatch, `tab 0 must not be seized by a positional match; got patch ${JSON.stringify(tabZeroPatch && tabZeroPatch.args[3])}`);+ const secPatch = find(calls, 'updateElement').find((c) => String(c.args[2]) === '/tabs/1/columns/0/sections/0');+ assert.ok(secPatch, `section_extra (under tab 1) should be patched; updateElement pointers: ${find(calls, 'updateElement').map((c) => c.args[2]).join(', ')}`);+ assert.strictEqual(secPatch.args[3].label, 'Extra Details');+});++// ---------------------------------------------------------------------------// Per-field control options on a DEPLOYED form (ADO 6648516 / 6651241 / 6651439 / 6651696).//@@ -3738,3 +4110,39 @@ test('a flyout ANCHOR has no action at all', () => {const def = commandDef('new_t', cmds, { 'x.js': 'wr-1' });assert.strictEqual(def.commandBars[0].groups[0].controls[0].action, undefined);});++// --- silent no-ops are now REPORTED (#575 follow-on) ---++test('an existing view REPORTS that authored filters/sort are not reapplied', async () => {+ const spec = makeSpec();+ spec.views = [{ entity: 'new_customer', name: 'Active Customers', columns: ['new_name'], filters: [{ attr: 'new_tier', op: 'eq', value: 'Gold' }] }];+ const warnings = [];+ const { sdk } = mockSdk({ artifactsExist: true });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'views'], warn: (m) => warnings.push(m) });+ assert.ok(warnings.some((w) => /Active Customers/.test(w) && /filters\/sort are NOT reapplied/.test(w)),+ `expected an unconverged-query warning; got ${JSON.stringify(warnings)}`);+});++test('a view with NO authored filters/sort stays quiet on rebuild', async () => {+ const spec = makeSpec();+ spec.views = [{ entity: 'new_customer', name: 'Active Customers', columns: ['new_name'] }];+ const warnings = [];+ const { sdk } = mockSdk({ artifactsExist: true });+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'views'], warn: (m) => warnings.push(m) });+ // viewDef folds activeOnly's implicit `statecode eq 0` into the same conditions array, so a+ // naive non-empty check here would warn on every rebuild of every view.+ assert.deepStrictEqual(warnings.filter((w) => /filters\/sort are NOT reapplied/.test(w)), []);+});++test('a failed default-form promotion WARNS instead of reporting a silent success', async () => {+ const warnings = [];+ const { sdk } = mockSdk({ artifactsExist: true });+ const realUpdate = sdk.updateRecord;+ sdk.updateRecord = async (entity, id, patch) => {+ if (entity === 'systemform' && patch && patch.isdefault === true) throw new Error('privilege check failed');+ return realUpdate(entity, id, patch);+ };+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], warn: (m) => warnings.push(m) });+ assert.ok(warnings.some((w) => /could not make form the default/.test(w) && /privilege check failed/.test(w)),+ `expected a promotion-failure warning naming the reason; got ${JSON.stringify(warnings)}`);+});diff --git a/plugins/model-apps/scripts/tests/spec-lint.test.js b/plugins/model-apps/scripts/tests/spec-lint.test.jsindex edc737a4b..d5e803fe3 100644--- a/plugins/model-apps/scripts/tests/spec-lint.test.js+++ b/plugins/model-apps/scripts/tests/spec-lint.test.js@@ -441,6 +441,23 @@ test('accepts a command bound to a declared web resource + function', () => {assert.strictEqual(r.ok, true, JSON.stringify(r.errors));});+test('lint: a malformed tab entry is reported, not thrown on', () => {+ const s = base();+ s.forms = [{ entity: 'new_ticket', name: 'T', layout: 'explicit', tabs: [null] }];+ // The linter dereferences each tab (`t.columns`/`t.sections`). Through the public entry point+ // migrateAppSpec normalises a null entry to `{}` first, so the crash is not reachable there — but+ // the loop now guards the entry anyway, because lintAppSpec is also called on raw specs.+ let r;+ assert.doesNotThrow(() => { r = lintAppSpec(s); }, 'lintAppSpec must not throw on a malformed tab');+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((m) => /tab/i.test(m)), `expected a structural tab error; got ${JSON.stringify(r.errors)}`);++ // And a genuinely raw null tab, bypassing migration, is reported rather than thrown on.+ const raw = { ...base(), forms: [{ entity: 'new_ticket', name: 'T', layout: 'explicit', tabs: [null] }] };+ raw.schemaVersion = undefined;+ assert.doesNotThrow(() => lintAppSpec(raw));+});+test('errors on a dashboard tile referencing an unknown view', () => {const s = base();s.views = [{ entity: 'new_ticket', name: 'Active', columns: ['new_name'] }];@@ -449,6 +466,84 @@ test('errors on a dashboard tile referencing an unknown view', () => {assert.ok(!r.ok && r.errors.some((m) => /references unknown view/i.test(m)));});+// #572 — a downloaded app's dashboards carry ID-PASSTHROUGH tiles (the deployed view/chart ids ++// entity, no names) because the artifacts already exist. `validateAppSpec` and the build both+// accept that form; this lint did not, so `download-model-app.js` produced a spec that failed its+// own structural lint with "references unknown chart 'undefined'".+test('accepts id-passthrough dashboard tiles with no declared views[]/charts[] (#572)', () => {+ const s = base();+ s.views = [];+ s.charts = [];+ s.dashboards = [{+ name: 'Field Ops Overview',+ tiles: [+ { type: 'chart', name: 'By Priority', entity: 'new_ticket', viewId: '11111111-1111-1111-1111-111111111111', visualizationId: '22222222-2222-2222-2222-222222222222' },+ { type: 'list', name: 'Open', entity: 'new_ticket', viewId: '33333333-3333-3333-3333-333333333333' },+ ],+ }];+ const r = lintAppSpec(s);+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++test('an id-passthrough chart tile still needs entity and viewId (#572)', () => {+ const noEntity = base();+ noEntity.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', name: 'X', viewId: 'v1', visualizationId: 'c1' }] }];+ assert.ok(lintAppSpec(noEntity).errors.some((m) => /id-based chart tile needs entity/i.test(m)));++ // A visualization with no view has nothing to plot, so the view id is the load-bearing half.+ const noView = base();+ noView.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', name: 'X', entity: 'new_ticket', visualizationId: 'c1' }] }];+ assert.ok(lintAppSpec(noView).errors.some((m) => /also needs viewId/i.test(m)));++ const noListEntity = base();+ noListEntity.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', name: 'X', viewId: 'v1' }] }];+ assert.ok(lintAppSpec(noListEntity).errors.some((m) => /id-based list tile needs entity/i.test(m)));+});++// `visualizationId` identifies a CHART and means nothing on a list tile, but one shared id test was+// applied to both. A list tile carrying a stray visualizationId therefore took the id path and+// escaped the viewId requirement, and a chart tile with only a viewId had nothing to plot.+test('id-passthrough tiles: visualizationId is chart-only, and a chart needs BOTH ids (#572 follow-up)', () => {+ // A list tile with only a visualizationId must not be treated as id-based.+ const strayViz = base();+ strayViz.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', name: 'X', entity: 'new_ticket', visualizationId: 'c1' }] }];+ assert.ok(lintAppSpec(strayViz).errors.some((m) => /list tile needs a view/i.test(m)),+ `a list tile without a viewId must be rejected; got ${JSON.stringify(lintAppSpec(strayViz).errors)}`);++ // A chart tile with a viewId but no visualizationId has no visualization to render.+ const noViz = base();+ noViz.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', name: 'X', entity: 'new_ticket', viewId: 'v1' }] }];+ assert.ok(lintAppSpec(noViz).errors.some((m) => /also needs visualizationId/i.test(m)),+ `a chart tile without a visualizationId must be rejected; got ${JSON.stringify(lintAppSpec(noViz).errors)}`);++ // …and validateAppSpec must agree, or a spec validates clean and then fails its own lint.+ const { validateAppSpec } = require('../lib/app-spec.js');+ assert.ok(validateAppSpec(noViz, { profile: 'plan' }).errors.some((m) => /also needs visualizationId/i.test(m)),+ 'the validator and the lint must enforce the same chart-ID contract');+});++test('a tile with neither a name nor an id reports the absence, not a chart called undefined (#572)', () => {+ const s = base();+ s.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', name: 'X' }] }];+ const r = lintAppSpec(s);+ assert.strictEqual(r.ok, false);+ // The old check interpolated a missing key straight into the message.+ assert.ok(!r.errors.some((m) => /'undefined'/.test(m)), `leaked undefined: ${JSON.stringify(r.errors)}`);+ assert.ok(r.errors.some((m) => /chart tile needs a chart \(by name\) or viewId\+visualizationId/i.test(m)));+});++test('name-based dashboard tiles are still validated against declared views/charts (#572)', () => {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Active', columns: ['new_name'] }];+ s.charts = [{ entity: 'new_ticket', name: 'By Priority', groupBy: 'new_priority' }];+ // Correct names pass...+ s.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', chart: 'By Priority', view: 'Active' }] }];+ assert.strictEqual(lintAppSpec(s).ok, true, JSON.stringify(lintAppSpec(s).errors));+ // ...and a wrong one is still caught, so the id branch did not disable the name branch.+ s.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', chart: 'Nope', view: 'Active' }] }];+ assert.ok(lintAppSpec(s).errors.some((m) => /references unknown chart 'Nope'/i.test(m)));+});+test('warns on prefix drift', () => {const s = base();s.entities[1].schemaName = 'cr123_ticket';@@ -553,3 +648,26 @@ test('lint accepts a v2 page subarea referenced by KEY when key !== name (no falbad.appShell.areas[0].groups[0].subAreas[0].page = 'nope-not-a-page';assert.ok(lintAppSpec(bad).errors.some((e) => /unknown page/i.test(e)), 'an unknown page ref still errors');});++// A multi-column tab holds its sections inside `columns[]`, not directly on `sections`. Reading+// only `t.sections` reported EVERY multi-column tab as empty -- found by linting a real spec, not+// by a unit test, which is why this guard exists.+test('a multi-column tab is not reported as having no sections', () => {+ const s = base();+ s.forms = [{ entity: 'new_ticket', name: 'Ticket', layout: 'explicit', tabs: [{+ name: 'tab_g', label: 'G', columns: [+ { width: '60%', sections: [{ name: 's1', label: 'S1', columns: 1, fields: ['new_name'] }] },+ { width: '40%', sections: [{ name: 's2', label: 'S2', columns: 1, fields: ['new_priority'] }] },+ ] }] }];+ const out = lintAppSpec(migrateAppSpec(s));+ assert.deepStrictEqual(out.errors.filter((e) => /has no sections/.test(e)), []);+});++test('a tab that genuinely declares no sections in EITHER shape is still an error', () => {+ const s = base();+ s.forms = [{ entity: 'new_ticket', name: 'Ticket', layout: 'explicit', tabs: [{ label: 'Empty' }] }];+ assert.ok(lintAppSpec(migrateAppSpec(s)).errors.some((e) => /has no sections/.test(e)));+ const s2 = base();+ s2.forms = [{ entity: 'new_ticket', name: 'T', layout: 'explicit', tabs: [{ label: 'E', columns: [{ width: '100%', sections: [] }] }] }];+ assert.ok(lintAppSpec(migrateAppSpec(s2)).errors.some((e) => /has no sections/.test(e)));+});diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.jsindex fb7a50b89..39ecc02aa 100644--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js@@ -6,6 +6,7 @@ const fs = require('node:fs');const path = require('node:path');const vm = require('node:vm');const { readerFor, appIdFor } = require('../verify-model-app.js');+const { verifySpec } = require('../lib/verify-spec.js');const { validateFlagsFromParsed } = require('./helpers/fake-auth.js');const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';@@ -186,6 +187,46 @@ test('readerFor base readers normalize exact identities for tables, relationshipassert.ok(calls.some((c) => c.method === 'retrieveSetting' && c.opts && Object.keys(c.opts).length === 0));});+test('readerFor + verifySpec reads deployed fetchxml and systemform.isdefault through the real reader seam', async () => {+ const calls = [];+ const sdk = {+ findTables: async () => [],+ findColumns: async () => [],+ queryRecords: async (set, opts) => {+ calls.push({ set, opts });+ if (set === 'savedquery') {+ return [{+ savedqueryid: 'view-1',+ layoutxml: '<grid><row><cell name="new_subject"/></row></grid>',+ fetchxml: '<fetch><entity name="new_ticket"><filter><condition attribute="ownerid" operator="eq-userid"/></filter></entity></fetch>',+ }];+ }+ if (set === 'systemform') return [{ formid: 'form-1', isdefault: false }];+ return [];+ },+ fetchEntityMetadata: async () => ({ Relationships: [] }),+ resolveArtifact: async () => [],+ retrieveSetting: async () => null,+ };+ const spec = {+ solution: { publisherPrefix: 'new' },+ app: { name: 'Support Desk', uniqueName: 'new_supportdesk' },+ entities: [{ schemaName: 'new_ticket', columns: [] }], charts: [], appShell: { areas: [] },+ views: [{ entity: 'new_ticket', name: 'My Tickets', columns: ['new_subject'], activeOnly: false, filters: [{ attr: 'modifiedon', op: 'this-week' }] }],+ forms: [{ entity: 'new_ticket', name: 'Main', formType: 'Main', isDefault: true }],+ };++ const r = await verifySpec(spec, readerFor(sdk, 'new_supportdesk', {}));++ assert.ok(r.missing.some((m) => m.kind === 'view-filters' && /modifiedon this-week/.test(m.detail)), 'the real reader must surface fetchxml to the filter oracle');+ assert.ok(r.missing.some((m) => m.kind === 'form-default' && /isdefault is false/.test(m.detail)), 'the real reader must surface systemform.isdefault to the default-form oracle');+ const viewQuery = calls.find((c) => c.set === 'savedquery');+ assert.ok(viewQuery.opts.select.includes('fetchxml'), 'view reads must request savedquery.fetchxml');+ const formDefaultQuery = calls.find((c) => c.set === 'systemform' && /formid eq form-1/.test(c.opts.filter));+ assert.ok(formDefaultQuery, 'default-form proof must read the deployed form row by id');+ assert.ok(formDefaultQuery.opts.select.includes('isdefault'), 'default-form proof must request systemform.isdefault');+});+test('appIdFor returns the deployed app id or undefined when the app is already gone', async () => {const filters = [];const sdk = {@@ -200,6 +241,49 @@ test('appIdFor returns the deployed app id or undefined when the app is alreadyassert.ok(filters.every((f) => /uniquename eq '/.test(f)), 'app lookup stays name-scoped');});+test('readerFor.appRoleIds reads the deployed appmoduleroles_association rows', async () => {+ const calls = [];+ const sdk = {+ queryRecords: async (set, opts) => {+ calls.push({ set, opts });+ if (set === 'appmodule') return [{ appmoduleid: 'app-id-1' }];+ return [];+ },+ findTables: async () => [],+ findColumns: async () => [],+ dataverse: {+ get: async (url) => {+ calls.push({ url });+ return {+ status: 200,+ headers: {},+ body: { value: [{ roleid: 'role-agent' }, { roleid: 'ROLE-MANAGER' }] },+ };+ },+ },+ };++ const res = await readerFor(sdk, 'contoso_app', {}).appRoleIds();++ assert.strictEqual(res.ok, true);+ assert.deepStrictEqual(res.roleIds, ['role-agent', 'role-manager']);+ assert.ok(calls.some((c) => c.url && /appmodules\(app-id-1\)\/appmoduleroles_association/.test(c.url)), 'must read the actual app-role association navigation property');+});++test('readerFor.appRoleIds fails closed when the association rows cannot be read', async () => {+ const sdk = {+ queryRecords: async (set) => (set === 'appmodule' ? [{ appmoduleid: 'app-id-1' }] : []),+ findTables: async () => [],+ findColumns: async () => [],+ dataverse: { get: async () => ({ status: 403, headers: {}, body: { error: { message: 'forbidden' } } }) },+ };++ const res = await readerFor(sdk, 'contoso_app', {}).appRoleIds();++ assert.strictEqual(res.ok, false);+ assert.match(res.reason, /403/);+});+function loadVerifyCli({ parseResult, validateResult = { ok: true }, verifyResult = { ok: true, checks: [], missing: [] }, sdkThrows = null, invokeAsMain = false }) {const scriptPath = path.join(__dirname, '..', 'verify-model-app.js');const source = `${fs.readFileSync(scriptPath, 'utf8')}\nmodule.exports.__mainForTest = main;\n`;diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.jsindex ea1ed5d23..8d3a9df39 100644--- a/plugins/model-apps/scripts/tests/verify-spec.test.js+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js@@ -1,7 +1,7 @@'use strict';const { test } = require('node:test');const assert = require('node:assert');-const { verifySpec, hasElement } = require('../lib/verify-spec.js');+const { verifySpec, hasElement, parseFetchXml } = require('../lib/verify-spec.js');const { sitemapXmlFor } = require('../verify-model-app.js');const { SDK_ROLE_MARKER } = require('../lib/app-spec.js');@@ -471,6 +471,276 @@ test('verifySpec: view-columns check is SKIPPED when the reader gives no layoutxassert.ok(!r.checks.some((c) => c.kind === 'view-columns'), 'no layoutxml -> no view-columns check (best-effort)');});+// Sort PRECEDENCE decides what a view returns, so proving each authored order merely EXISTS+// somewhere is not proof: a deployed [name asc, createdon desc] would satisfy an authored+// [createdon desc, name asc] under a per-order membership test.+test('verifySpec: view-sort fails when the deployed sort has the authored orders in the WRONG precedence', async () => {+ const spec = { solution: { publisherPrefix: 'new' }, entities: [], charts: [], appShell: { areas: [] }, forms: [],+ views: [{ entity: 'new_ticket', name: 'Ordered', columns: ['new_name'], activeOnly: false,+ sort: [{ attr: 'createdon', dir: 'desc' }, { attr: 'new_name', dir: 'asc' }] }] };+ const fetchxml = '<fetch><entity name="new_ticket">'+ + '<order attribute="new_name" descending="false"/>'+ + '<order attribute="createdon" descending="true"/>'+ + '</entity></fetch>';+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'savedquery'+ ? [{ savedqueryid: 'v1', layoutxml: '<grid><row><cell name="new_name"/></row></grid>', fetchxml }]+ : []),+ };++ const r = await verifySpec(spec, read);+ const c = r.checks.find((x) => x.kind === 'view-sort');+ assert.ok(c, 'a view-sort check must be emitted');+ assert.strictEqual(c.present, false, 'reversed precedence must not pass');+ assert.match(c.detail, /precedence/i);+});++test('verifySpec: view-sort passes when the authored orders keep their relative order among extras', async () => {+ const spec = { solution: { publisherPrefix: 'new' }, entities: [], charts: [], appShell: { areas: [] }, forms: [],+ views: [{ entity: 'new_ticket', name: 'Ordered', columns: ['new_name'], activeOnly: false,+ sort: [{ attr: 'createdon', dir: 'desc' }, { attr: 'new_name', dir: 'asc' }] }] };+ // A platform-owned order appended after the authored ones must still pass (subset semantics).+ const fetchxml = '<fetch><entity name="new_ticket">'+ + '<order attribute="createdon" descending="true"/>'+ + '<order attribute="new_name" descending="false"/>'+ + '<order attribute="modifiedon" descending="true"/>'+ + '</entity></fetch>';+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'savedquery'+ ? [{ savedqueryid: 'v1', layoutxml: '<grid><row><cell name="new_name"/></row></grid>', fetchxml }]+ : []),+ };++ const r = await verifySpec(spec, read);+ const c = r.checks.find((x) => x.kind === 'view-sort');+ assert.ok(c && c.present === true, `authored precedence preserved must pass; got ${JSON.stringify(c)}`);+});++test('verifySpec: default-form — the selected Main form must read back systemform.isdefault=true', async () => {+ // The owning table must be declared, and declared as one this solution OWNS: the build only+ // promotes a default form for its own custom tables, so verify only asserts it for those.+ const spec = { solution: { publisherPrefix: 'new' },+ entities: [{ schemaName: 'new_ticket', columns: [] }], views: [], charts: [], appShell: { areas: [] },+ forms: [+ { entity: 'new_ticket', name: 'Agent Form', formType: 'Main' },+ { entity: 'new_ticket', name: 'Manager Form', formType: 'Main', isDefault: true },+ ] };+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set, opts) => {+ if (set !== 'systemform') return [];+ if (/name eq 'Agent Form'/.test(opts.filter)) return [{ formid: 'agent-form-id' }];+ if (/name eq 'Manager Form'/.test(opts.filter)) return [{ formid: 'manager-form-id' }];+ return [];+ },+ formDefaultState: async (entity, formId) => ({ isDefault: formId === 'agent-form-id' }),+ };++ const r = await verifySpec(spec, read);++ assert.ok(r.checks.some((c) => c.kind === 'form' && c.name === 'Manager Form' && c.present), 'the selected form exists');+ const c = r.checks.find((x) => x.kind === 'form-default' && x.name === 'new_ticket.Manager Form');+ assert.ok(c && c.present === false, 'the actual isdefault flag, not form existence, decides the default-form check');+ assert.match(c.detail, /isdefault is false/);+ assert.strictEqual(r.ok, false);+});++// The build refuses to re-point the default form of a reused or stock table (sdk-build.js+// `isOwnCustomTable`) because that is an environment-wide side effect on a table the spec does not+// own. A verifier that asserts `isdefault` anyway makes --verify permanently unsatisfiable: the+// author is told the build failed to do something it deliberately never attempts.+test('verifySpec: no default-form check is emitted for a reused or stock table the build never promotes', async () => {+ const spec = { solution: { publisherPrefix: 'new' },+ entities: [{ schemaName: 'account', existing: true, columns: [] }, { schemaName: 'new_ticket', columns: [] }],+ views: [], charts: [], appShell: { areas: [] },+ forms: [+ { entity: 'account', name: 'Account Main', formType: 'Main' },+ { entity: 'new_ticket', name: 'Ticket Main', formType: 'Main' },+ ] };+ const read = {+ findTable: async (l) => ({ logicalName: l }), findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set, opts) => {+ if (set !== 'systemform') return [];+ if (/name eq 'Account Main'/.test(opts.filter)) return [{ formid: 'account-form-id' }];+ if (/name eq 'Ticket Main'/.test(opts.filter)) return [{ formid: 'ticket-form-id' }];+ return [];+ },+ // Dataverse's own stock Account form holds the default slot, so the reused table reads false.+ formDefaultState: async (entity, formId) => ({ isDefault: formId === 'ticket-form-id' }),+ };++ const r = await verifySpec(spec, read);++ assert.ok(!r.checks.some((c) => c.kind === 'form-default' && /^account\./.test(c.name)),+ 'a reused table must not be asserted to hold the default form');+ assert.ok(r.checks.some((c) => c.kind === 'form-default' && c.name === 'new_ticket.Ticket Main' && c.present),+ "the solution's own custom table is still checked");+});++test('verifySpec: default-form check is reader-gated for existence-only callers', async () => { const spec = { entities: [], views: [], charts: [], appShell: { areas: [] },+ forms: [{ entity: 'new_ticket', name: 'Agent Form', formType: 'Main', isDefault: true }] };+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'systemform' ? [{ formid: 'agent-form-id' }] : []),+ };++ const r = await verifySpec(spec, read);++ assert.ok(r.checks.some((c) => c.kind === 'form' && c.present));+ assert.ok(!r.checks.some((c) => c.kind === 'form-default'), 'no formDefaultState reader -> no content check');+ assert.strictEqual(r.ok, true);+});++test('verifySpec: view-filters — every authored condition must be present in deployed fetchxml', async () => {+ const spec = { entities: [], charts: [], forms: [], appShell: { areas: [] },+ views: [{ entity: 'new_ticket', name: 'My Open', columns: ['new_subject'], activeOnly: true,+ filters: [+ { attr: 'ownerid', op: 'eq-userid' },+ { attr: 'new_priority', op: 'not-in', values: ['100000000'] },+ { attr: 'modifiedon', op: 'this-week' },+ ],+ sort: [{ attr: 'createdon', dir: 'desc' }] }] };+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'savedquery' ? [{+ savedqueryid: 'v1',+ layoutxml: '<grid><row><cell name="new_subject"/></row></grid>',+ fetchxml: '<fetch><entity name="new_ticket"><attribute name="new_subject"/>' ++ '<filter type="and"><condition attribute="statecode" operator="eq" value="0"/>' ++ '<condition attribute="ownerid" operator="eq-userid"/>' ++ '<condition attribute="modifiedon" operator="this-week"/>' ++ '<filter type="and"><condition attribute="new_priority" operator="ne" value="100000000"/></filter>' ++ '</filter><order attribute="createdon" descending="true"/></entity></fetch>',+ }] : []),+ };++ const r = await verifySpec(spec, read);++ assert.ok(r.checks.some((c) => c.kind === 'view-filters' && c.present), JSON.stringify(r.missing));+ assert.ok(r.checks.some((c) => c.kind === 'view-sort' && c.present), JSON.stringify(r.missing));+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));+});++test('verifySpec: view-filters — value-less operators missing value are correct, missing operator is a failure', async () => {+ const spec = { entities: [], charts: [], forms: [], appShell: { areas: [] },+ views: [{ entity: 'new_ticket', name: 'This Week', columns: ['new_subject'], activeOnly: false,+ filters: [{ attr: 'modifiedon', op: 'this-week' }] }] };+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'savedquery' ? [{+ savedqueryid: 'v1',+ layoutxml: '<grid><row><cell name="new_subject"/></row></grid>',+ fetchxml: '<fetch><entity name="new_ticket"><filter><condition attribute="createdon" operator="this-week"/></filter></entity></fetch>',+ }] : []),+ };++ const r = await verifySpec(spec, read);++ const c = r.checks.find((x) => x.kind === 'view-filters');+ assert.ok(c && c.present === false, 'omitting value is fine; the wrong attribute is not');+ assert.match(c.detail, /modifiedon this-week/);+ assert.strictEqual(r.ok, false);+});++test('verifySpec: view-sort — a missing authored order fails without demanding FetchXML byte equality', async () => {+ const spec = { entities: [], charts: [], forms: [], appShell: { areas: [] },+ views: [{ entity: 'new_ticket', name: 'Sorted', columns: ['new_subject'], activeOnly: false,+ sort: [{ attr: 'createdon', dir: 'desc' }] }] };+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'savedquery' ? [{+ savedqueryid: 'v1',+ layoutxml: '<grid><row><cell name="new_subject"/></row></grid>',+ fetchxml: '<fetch><entity name="new_ticket"><filter><condition attribute="ownerid" operator="eq-userid"/></filter><order attribute="new_subject" descending="false"/></entity></fetch>',+ }] : []),+ };++ const r = await verifySpec(spec, read);++ assert.ok(!r.checks.some((c) => c.kind === 'view-filters'), 'platform-added undeclared filters are tolerated');+ const c = r.checks.find((x) => x.kind === 'view-sort');+ assert.ok(c && c.present === false);+ assert.match(c.detail, /createdon desc/);+ assert.strictEqual(r.ok, false);+});++test('verifySpec: view-filters fail closed when the reader supplied an unreadable fetchxml value', async () => {+ const spec = { entities: [], charts: [], forms: [], appShell: { areas: [] },+ views: [{ entity: 'new_ticket', name: 'Mine', columns: ['new_subject'], activeOnly: false,+ filters: [{ attr: 'ownerid', op: 'eq-userid' }] }] };+ const read = {+ findTable: async () => null, findColumns: async () => [], sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'savedquery' ? [{+ savedqueryid: 'v1',+ layoutxml: '<grid><row><cell name="new_subject"/></row></grid>',+ fetchxml: null,+ }] : []),+ };++ const r = await verifySpec(spec, read);++ const c = r.checks.find((x) => x.kind === 'view-filters');+ assert.ok(c && c.present === false);+ assert.match(c.detail, /could not read deployed savedquery.fetchxml/);+ assert.strictEqual(r.ok, false);+});++test('verifySpec: app-role association — app access personas must be linked to the app module', async () => {+ const spec = {+ entities: [{ schemaName: 'new_ticket', columns: [] }],+ views: [], charts: [], forms: [], appShell: { areas: [] },+ personas: [+ { persona: 'Agent', jobs: [{ name: 'work', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] },+ { persona: 'Auditor', appAccess: false, jobs: [{ name: 'audit', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] },+ ],+ };+ const read = {+ findTable: async () => ({ logicalName: 'new_ticket' }),+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set, opts) => {+ if (set === 'businessunit') return [{ businessunitid: '00000000-0000-0000-0000-000000000001' }];+ if (set === 'role' && /Agent/.test(opts.filter)) return [{ roleid: 'role-agent', description: SDK_ROLE_MARKER, ismanaged: false }];+ if (set === 'role' && /Auditor/.test(opts.filter)) return [{ roleid: 'role-auditor', description: SDK_ROLE_MARKER, ismanaged: false }];+ return [];+ },+ appRoleIds: async () => ({ ok: true, roleIds: ['role-other'] }),+ };++ const r = await verifySpec(spec, read);++ const c = r.checks.find((x) => x.kind === 'app-role' && x.name === 'Agent');+ assert.ok(c && c.present === false, 'existing role is not enough; the actual association row must exist');+ assert.ok(!r.checks.some((x) => x.kind === 'app-role' && x.name === 'Auditor'), 'appAccess:false personas should not require an app association');+ assert.strictEqual(r.ok, false);+});++test('verifySpec: app-role association read failures fail closed', async () => {+ const spec = {+ entities: [{ schemaName: 'new_ticket', columns: [] }],+ views: [], charts: [], forms: [], appShell: { areas: [] },+ personas: [{ persona: 'Agent', jobs: [{ name: 'work', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] }],+ };+ const read = {+ findTable: async () => ({ logicalName: 'new_ticket' }),+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set) => (set === 'businessunit'+ ? [{ businessunitid: '00000000-0000-0000-0000-000000000001' }]+ : [{ roleid: 'role-agent', description: SDK_ROLE_MARKER, ismanaged: false }]),+ appRoleIds: async () => ({ ok: false, reason: 'HTTP 403' }),+ };++ const r = await verifySpec(spec, read);++ const c = r.checks.find((x) => x.kind === 'app-role');+ assert.ok(c && c.present === false);+ assert.match(c.detail, /could not read.*403/);+ assert.strictEqual(r.ok, false);+});+test('verifySpec: relationship existence — a declared relationship absent from the child metadata FAILS (F5)', async () => {const spec = { entities: [{ schemaName: 'new_o' }], views: [], charts: [], forms: [], appShell: { areas: [] },relationships: [{ type: 'OneToMany', referenced: 'new_customer', referencing: 'new_o', lookup: { schemaName: 'new_CustomerId' } }] };@@ -886,4 +1156,59 @@ test('app table membership: only SITEMAP-visible tables are required to be compoconst res = await verifySpec(spec, membershipRead(async () => ({ ok: true, present: ['new_order', 'new_line'] })));assert.strictEqual(checkFor(res, 'new_audit'), undefined, 'a table with no subarea must not be required');assert.ok(res.checks.filter((c) => c.kind === 'app-table-component').every((c) => c.present));+});++// --- parseFetchXml scoping and multi-operand conditions ---------------------------------------+//+// This parser is a verifier ORACLE, so a false PASS is its worst failure: it would report that a+// deployed view filters the way the spec says when it does not.++// FetchXML puts a joined table's predicates inside <link-entity>. Collecting conditions from the+// whole document let a condition on the JOINED table satisfy an authored base-entity condition by+// attribute/operator coincidence — the two read identically (`statecode eq 0`) but constrain+// different tables.+test('parseFetchXml ignores conditions and orders that belong to a link-entity', () => {+ const xml = `<fetch><entity name="account">`+ + `<link-entity name="contact"><filter><condition attribute="statecode" operator="eq" value="0"/></filter>`+ + `<order attribute="fullname"/></link-entity></entity></fetch>`;+ const r = parseFetchXml(xml);+ assert.deepStrictEqual(r.conditions, [], 'a linked table predicate is not the base entity one');+ assert.deepStrictEqual(r.orders, [], 'and a linked table sort is not the base entity one either');+});++// link-entities NEST, and a join used only for projection is self-closing. A non-greedy regex would+// stop at the first </link-entity> and let the outer subtree leak back in, so the scanner tracks+// depth. Base-entity content on BOTH sides of the subtree has to survive.+test('parseFetchXml keeps base-entity content around nested and self-closing link-entities', () => {+ const nested = `<fetch><entity name="a"><condition attribute="base" operator="eq" value="1"/>`+ + `<link-entity name="b"><link-entity name="c"><condition attribute="deep" operator="eq" value="9"/>`+ + `</link-entity></link-entity><order attribute="baseorder"/></entity></fetch>`;+ const n = parseFetchXml(nested);+ assert.deepStrictEqual(n.conditions.map((c) => c.attribute), ['base'], 'a doubly-nested condition must not leak');+ assert.deepStrictEqual(n.orders.map((o) => o.attribute), ['baseorder'], 'the base order after the subtree must survive');++ const selfClosing = `<fetch><entity name="a"><link-entity name="b" from="x" to="y" />`+ + `<condition attribute="base" operator="eq" value="1"/><order attribute="o1"/></entity></fetch>`;+ const s = parseFetchXml(selfClosing);+ assert.deepStrictEqual(s.conditions.map((c) => c.attribute), ['base'], 'a self-closing join opens no subtree');+ assert.deepStrictEqual(s.orders.map((o) => o.attribute), ['o1']);+});++// `in`/`not-in`/`between` serialize their operands as sibling <value> elements. Reading only the+// first made an authored `in 2` unprovable against a view that really does filter on it.+test('parseFetchXml reads every <value> of a multi-operand condition', () => {+ const xml = `<fetch><entity name="a"><filter><condition attribute="statuscode" operator="in">`+ + `<value>1</value><value>2</value><value>3</value></condition></filter></entity></fetch>`;+ assert.deepStrictEqual(parseFetchXml(xml).conditions.map((c) => c.value), ['1', '2', '3']);+});++// The single-operand shape (a `value` ATTRIBUTE) still wins over any child element, and an operator+// that takes no operand at all stays `undefined` — that is how conditionMatches knows the authored+// claim is just attribute+operator.+test('parseFetchXml keeps the value attribute authoritative, and no-operand operators undefined', () => {+ const attrWins = `<fetch><entity name="a"><condition attribute="x" operator="eq" value="7"><value>ignored</value></condition></entity></fetch>`;+ assert.deepStrictEqual(parseFetchXml(attrWins).conditions.map((c) => c.value), ['7']);++ const noOperand = `<fetch><entity name="a"><condition attribute="ownerid" operator="eq-userid"/></entity></fetch>`;+ assert.deepStrictEqual(parseFetchXml(noOperand).conditions, [{ attribute: 'ownerid', operator: 'eq-userid', value: undefined }]);});\ No newline at end of filediff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex 4f9820b06..0ff97c2df 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -52,6 +52,30 @@ async function appIdFor(sdk, appUnique) {return rows && rows[0] && rows[0].appmoduleid;}+async function appRoleIdsFor(sdk, appUnique) {+ try {+ const appId = await appIdFor(sdk, appUnique);+ if (!appId) return { ok: false, reason: `app '${appUnique}' could not be resolved` };+ if (!sdk.dataverse || typeof sdk.dataverse.get !== 'function') return { ok: false, reason: 'SDK dataverse reader is unavailable' };+ // The SDK has associate/disassociate helpers for `appmoduleroles_association`, but no modeled+ // read for that N:N membership. Read the relationship navigation property directly so verify+ // proves the deployed app<->role rows the model-driven app launcher uses, rather than inferring+ // access from role existence or from the build result.+ // See appmodule relationships: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule+ const res = await sdk.dataverse.get(`/appmodules(${appId})/appmoduleroles_association?$select=roleid`);+ if (!res || res.status < 200 || res.status >= 300) return { ok: false, reason: `HTTP ${res && res.status}` };+ return {+ ok: true,+ roleIds: ((res.body && res.body.value) || [])+ .map((r) => r && r.roleid)+ .filter(Boolean)+ .map((id) => String(id).toLowerCase()),+ };+ } catch (err) {+ return { ok: false, reason: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' };+ }+}+// Which of `wanted` (table logical names) are real TABLE components of the app// (`appmodulecomponent` componenttype 1), plus whether the app carries an `entity` PLACEHOLDER row.//@@ -197,6 +221,20 @@ function readerFor(sdk, appUnique, opts) {// feature and reports the read failure as a not-present check, which is the fail-closed direction —// a verify that cannot prove a feature is in effect must not claim it is.retrieveSetting: async (name, opts) => sdk.retrieveSetting(name, opts || {}),+ // formDefaultState(entity, formId): the selected Main form's actual default flag. The identity+ // check in verify-spec proves the form row exists; this separate read proves the platform state+ // that chooses which form opens by default. Errors propagate to verify-spec as a fail-closed+ // finding, because a missing proof is not evidence that promotion succeeded.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/systemform+ formDefaultState: async (_entity, formId) => {+ const rows = await sdk.queryRecords('systemform', {+ select: ['formid', 'isdefault'],+ filter: `formid eq ${formId}`,+ top: 1,+ });+ const row = rows && rows[0];+ return row ? { isDefault: row.isdefault === true } : null;+ },// sitemapXml (string, fail-closed '') for entity/icon hasElement checks — from the discriminated sitemap// read. Returning '' on failure suppresses entity/icon checks without aborting the whole verify.sitemapXml: async () => { const r = await memoSitemap(); return r.ok ? r.xml : ''; },@@ -207,6 +245,7 @@ function readerFor(sdk, appUnique, opts) {if (!appComponentsP.has(key)) appComponentsP.set(key, appEntityComponentsFor(sdk, appUnique, wanted));return appComponentsP.get(key);},+ appRoleIds: () => appRoleIdsFor(sdk, appUnique),};// entityPrivileges(logical): the privilege set a table exposes, as [{ PrivilegeId, PrivilegeType, ... }].@@ -344,4 +383,4 @@ if (require.main === module) {main().catch((err) => emitResult(false, err));}-module.exports = { sitemapXmlFor, readerFor, appIdFor };+module.exports = { sitemapXmlFor, readerFor, appIdFor, appRoleIdsFor };